From 00a190b0a6098918a916b4c1315704613b703e59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Fri, 20 Feb 2015 00:35:01 -0500 Subject: [PATCH] Just another update --- Conf/task.yaml | 2 +- Lang/360-Assembly/00DESCRIPTION | 19 +- Lang/360-Assembly/Conditional-structures | 1 + Lang/360-Assembly/Empty-program | 1 + Lang/360-Assembly/Factorial | 1 + Lang/360-Assembly/Fibonacci-sequence | 1 + Lang/360-Assembly/Gamma-function | 1 + Lang/360-Assembly/Integer-comparison | 1 + Lang/360-Assembly/Loops-Do-while | 1 + Lang/360-Assembly/Loops-Infinite | 1 + Lang/360-Assembly/Loops-While | 1 + Lang/360-Assembly/Lucas-Lehmer-test | 1 + Lang/360-Assembly/Sieve-of-Eratosthenes | 1 + Lang/360-Assembly/Sleep | 1 + .../Sorting-algorithms-Bubble-sort | 1 + Lang/360-Assembly/Spiral-matrix | 1 + Lang/360-Assembly/Standard-deviation | 1 + Lang/360-Assembly/Variable-size-Set | 1 + Lang/6502-Assembly/Even-or-odd | 1 + Lang/ABAP/N-queens-problem | 1 + Lang/ACL2/00DESCRIPTION | 1 + Lang/ALGOL-60/Comments | 1 + Lang/ALGOL-60/Empty-program | 1 + Lang/ALGOL-60/Hello-world-Text | 1 + Lang/ALGOL-60/Loops-For | 1 + Lang/ALGOL-60/Loops-While | 1 + Lang/ALGOL-60/Sieve-of-Eratosthenes | 1 + Lang/ALGOL-68/Call-a-function | 1 + Lang/ALGOL-68/Count-the-coins | 1 + Lang/ALGOL-68/Entropy | 1 + Lang/ALGOL-68/Even-or-odd | 1 + Lang/ALGOL-68/Floyds-triangle | 1 + Lang/ALGOL-68/Function-prototype | 1 + Lang/ALGOL-68/Guess-the-number-With-feedback | 1 + Lang/ALGOL-68/Knights-tour | 1 + Lang/ALGOL-68/Mad-Libs | 1 + Lang/ALGOL-68/Middle-three-digits | 1 + .../ALGOL-68/Parsing-RPN-calculator-algorithm | 1 + Lang/ALGOL-68/Pick-random-element | 1 + .../ALGOL-68/Read-a-specific-line-from-a-file | 1 + Lang/ALGOL-68/Return-multiple-values | 1 + Lang/ALGOL-68/Rock-paper-scissors | 1 + Lang/ALGOL-68/Sleep | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/ALGOL-68/Sum-digits-of-an-integer | 1 + Lang/ALGOL-W/Comments | 1 + Lang/APL/Fibonacci-sequence | 1 + Lang/APL/Longest-common-subsequence | 1 + Lang/ATS/00DESCRIPTION | 2 +- Lang/ATS/100-doors | 1 + Lang/ATS/Balanced-ternary | 1 + Lang/ATS/Fibonacci-sequence | 1 + Lang/ATS/Greatest-subsequential-sum | 1 + Lang/ATS/Hamming-numbers | 1 + Lang/ATS/Haversine-formula | 1 + Lang/ATS/Higher-order-functions | 1 + Lang/ATS/Identity-matrix | 1 + Lang/ATS/Repeat-a-string | 1 + Lang/ATS/Reverse-a-string | 1 + Lang/ATS/Roots-of-a-function | 1 + Lang/ATS/Sierpinski-triangle | 1 + Lang/ATS/Sum-digits-of-an-integer | 1 + Lang/AWK/00DESCRIPTION | 20 +- Lang/AWK/Anagrams-Deranged-anagrams | 1 + Lang/AWK/Combinations-with-repetitions | 1 + Lang/AWK/File-modification-time | 1 + Lang/AWK/File-size | 1 + Lang/AWK/Five-weekends | 1 + Lang/AWK/Hello-world-Graphical | 1 + Lang/AWK/Knights-tour | 1 + Lang/AWK/Langtons-ant | 1 + Lang/AWK/Modular-inverse | 1 + Lang/AWK/Operator-precedence | 1 + Lang/AWK/Order-two-numerical-lists | 1 + Lang/AWK/Sieve-of-Eratosthenes | 1 + Lang/AWK/Stem-and-leaf-plot | 1 + Lang/Ada/Extend-your-language | 1 + Lang/Ada/Set-puzzle | 1 + Lang/Ada/Visualize-a-tree | 1 + Lang/Aime/Generic-swap | 1 + Lang/Aime/Hailstone-sequence | 1 + Lang/Aime/String-comparison | 1 + Lang/Aime/Sum-of-squares | 1 + Lang/AppleScript/Accumulator-factory | 1 + Lang/AppleScript/Apply-a-callback-to-an-array | 1 + Lang/AppleScript/First-class-functions | 1 + Lang/AppleScript/Function-composition | 1 + Lang/AppleScript/Higher-order-functions | 1 + Lang/AppleScript/Hostname | 1 + Lang/Applesoft-BASIC/Loops-Continue | 1 + .../Terminal-control-Dimensions | 1 + Lang/Applesoft-BASIC/Video-display-modes | 1 + Lang/Assembly/00DESCRIPTION | 11 +- Lang/AutoHotkey/Continued-fraction | 1 + Lang/AutoHotkey/Narcissist | 1 + Lang/AutoHotkey/Polymorphism | 1 + Lang/AutoHotkey/Xiaolin-Wus-line-algorithm | 1 + ...ical-integration-Gauss-Legendre-Quadrature | 1 + Lang/Axiom/Quaternion-type | 1 + Lang/BASIC/00DESCRIPTION | 1 + Lang/Babel/00DESCRIPTION | 2 +- Lang/Babel/Apply-a-callback-to-an-array | 1 + Lang/Babel/Arrays | 1 + Lang/Babel/Associative-array-Creation | 1 + Lang/Babel/Associative-array-Iteration | 1 + Lang/Babel/Averages-Arithmetic-mean | 1 + Lang/Babel/Bitwise-operations | 1 + Lang/Babel/Caesar-cipher | 1 + Lang/Babel/Character-codes | 1 + Lang/Babel/Conditional-structures | 1 + Lang/Babel/Copy-a-string | 1 + Lang/Babel/Deepcopy | 1 + Lang/Batch-File/24-game | 1 + .../Bitmap-Bresenhams-line-algorithm | 1 + Lang/Batch-File/Conditional-structures | 1 + .../Determine-if-a-string-is-numeric | 1 + .../Batch-File/Guess-the-number-With-feedback | 1 + Lang/Batch-File/Hostname | 1 + Lang/Batch-File/Palindrome-detection | 1 + Lang/Batch-File/Sieve-of-Eratosthenes | 1 + Lang/Batch-File/Sorting-algorithms-Gnome-sort | 1 + Lang/Bc/00DESCRIPTION | 35 +- Lang/Bc/Non-decimal-radices-Output | 1 + Lang/Befunge/Factors-of-an-integer | 1 + Lang/Boo/Arrays | 1 + Lang/Bracmat/Apply-a-callback-to-an-array | 1 + Lang/Bracmat/Arithmetic-Complex | 1 + Lang/Bracmat/Arrays | 1 + Lang/Bracmat/Averages-Simple-moving-average | 1 + Lang/Bracmat/Combinations-with-repetitions | 1 + Lang/Bracmat/Day-of-the-week | 1 + Lang/Bracmat/Factors-of-a-Mersenne-number | 1 + .../Bracmat/Fibonacci-n-step-number-sequences | 1 + Lang/Bracmat/First-class-functions | 1 + Lang/Bracmat/Hofstadter-Q-sequence | 1 + Lang/Bracmat/Input-loop | 1 + Lang/Bracmat/JSON | 1 + Lang/Bracmat/Knapsack-problem-Continuous | 1 + Lang/Bracmat/Look-and-say-sequence | 1 + Lang/Bracmat/Loops-While | 1 + Lang/Bracmat/N-queens-problem | 1 + Lang/Bracmat/Optional-parameters | 1 + Lang/Bracmat/Palindrome-detection | 1 + Lang/Bracmat/Partial-function-application | 1 + Lang/Bracmat/Permutations-Derangements | 1 + Lang/Bracmat/Queue-Definition | 1 + Lang/Bracmat/Queue-Usage | 1 + Lang/Bracmat/Rosetta-Code-Count-examples | 1 + .../Rosetta-Code-Rank-languages-by-popularity | 1 + .../Runtime-evaluation-In-an-environment | 1 + Lang/Bracmat/Simple-database | 1 + Lang/Bracmat/Sum-and-product-of-an-array | 1 + Lang/Bracmat/Sum-of-squares | 1 + Lang/Bracmat/Time-a-function | 1 + Lang/Bracmat/Variables | 1 + Lang/Bracmat/Zebra-puzzle | 1 + Lang/Brainf---/00DESCRIPTION | 53 +- Lang/Brat/Integer-comparison | 1 + Lang/C++/00DESCRIPTION | 3 +- Lang/C++/24-game-Solve | 1 + Lang/C++/Closest-pair-problem | 1 + Lang/C++/Count-in-factors | 1 + Lang/C++/Function-prototype | 1 + Lang/C++/Greatest-common-divisor | 1 + Lang/C++/Here-document | 1 + Lang/C++/Inverted-syntax | 1 + Lang/C++/Leap-year | 1 + Lang/C++/Longest-common-subsequence | 1 + Lang/C++/Minesweeper-game | 1 + Lang/C++/Non-continuous-subsequences | 1 + Lang/C++/Record-sound | 1 + Lang/C++/Sorting-algorithms-Sleep-sort | 1 + Lang/C++/Terminal-control-Hiding-the-cursor | 1 + Lang/C++/Topological-sort | 1 + Lang/C++/Zebra-puzzle | 1 + Lang/C-sharp/Averages-Mean-time-of-day | 1 + Lang/C-sharp/Empty-directory | 1 + Lang/C-sharp/Entropy | 1 + .../C-sharp/Fibonacci-n-step-number-sequences | 1 + Lang/C-sharp/Floyds-triangle | 1 + Lang/C-sharp/Gamma-function | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/C-sharp/Hello-world-Line-printer | 1 + Lang/C-sharp/Kaprekar-numbers | 1 + Lang/C-sharp/Mad-Libs | 1 + Lang/C-sharp/Narcissist | 1 + Lang/C-sharp/Non-decimal-radices-Output | 1 + Lang/C-sharp/Pick-random-element | 1 + Lang/C-sharp/Pinstripe-Display | 1 + Lang/C-sharp/Priority-queue | 1 + .../Sutherland-Hodgman-polygon-clipping | 1 + Lang/C-sharp/Synchronous-concurrency | 1 + Lang/C-sharp/Van-der-Corput-sequence | 1 + Lang/C-sharp/Zeckendorf-number-representation | 1 + Lang/C/Carmichael-3-strong-pseudoprimes | 1 + Lang/CMake/00DESCRIPTION | 18 +- Lang/COBOL/Create-a-file-on-magnetic-tape | 1 + Lang/COBOL/Range-expansion | 1 + Lang/Chapel/Numerical-integration | 1 + Lang/Chef/00DESCRIPTION | 13 +- Lang/Clojure/Break-OO-privacy | 1 + Lang/Clojure/Call-an-object-method | 1 + Lang/Clojure/Classes | 1 + Lang/Clojure/Count-the-coins | 1 + Lang/Clojure/Create-a-file-on-magnetic-tape | 1 + Lang/Clojure/Create-an-HTML-table | 1 + Lang/Clojure/Define-a-primitive-data-type | 1 + Lang/Clojure/Discordian-date | 1 + Lang/Clojure/Draw-a-cuboid | 1 + Lang/Clojure/Draw-a-sphere | 1 + Lang/Clojure/Extreme-floating-point-values | 1 + Lang/Clojure/Function-prototype | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Clojure/Hello-world-Web-server | 1 + Lang/Clojure/History-variables | 1 + Lang/Clojure/Knapsack-problem-Continuous | 1 + Lang/Clojure/Last-Friday-of-each-month | 1 + Lang/Clojure/MD4 | 1 + Lang/Clojure/Plot-coordinate-pairs | 1 + Lang/Clojure/Price-fraction | 1 + Lang/Clojure/Priority-queue | 1 + Lang/Clojure/RIPEMD-160 | 1 + Lang/Clojure/Read-a-configuration-file | 1 + Lang/Clojure/Read-a-specific-line-from-a-file | 1 + Lang/Clojure/Rock-paper-scissors | 1 + Lang/Clojure/SEDOLs | 1 + Lang/Clojure/SHA-256 | 1 + Lang/Clojure/Send-email | 1 + Lang/Clojure/Set-of-real-numbers | 1 + .../Singly-linked-list-Element-definition | 1 + Lang/Clojure/Sort-disjoint-sublist | 1 + Lang/Clojure/Sorting-algorithms-Sleep-sort | 1 + Lang/Clojure/Special-variables | 1 + Lang/Clojure/Speech-synthesis | 1 + Lang/Clojure/Stack-traces | 1 + ...odes-and-extended-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Clojure/Substring-Top-and-tail | 1 + Lang/Clojure/Sum-digits-of-an-integer | 1 + Lang/Clojure/Temperature-conversion | 1 + ...inal-control-Display-an-extended-character | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/Clojure/Terminal-control-Unicode-output | 1 + Lang/Clojure/Topic-variable | 1 + Lang/Clojure/URL-encoding | 1 + Lang/Clojure/Unicode-variable-names | 1 + Lang/Clojure/Write-language-name-in-3D-ASCII | 1 + Lang/Clojure/Write-to-Windows-event-log | 1 + Lang/Clojure/XML-DOM-serialization | 1 + Lang/CoffeeScript/Filter | 1 + Lang/CoffeeScript/Haversine-formula | 1 + Lang/CoffeeScript/Interactive-programming | 1 + Lang/CoffeeScript/Sum-and-product-of-an-array | 1 + Lang/ColdFusion/Active-Directory-Connect | 1 + Lang/ColdFusion/Even-or-odd | 1 + Lang/ColdFusion/Evolutionary-algorithm | 1 + Lang/ColdFusion/FizzBuzz | 1 + Lang/ColdFusion/Greatest-element-of-a-list | 1 + Lang/ColdFusion/Harshad-or-Niven-series | 1 + Lang/ColdFusion/Loops-Break | 1 + .../Loops-For-with-a-specified-step | 1 + Lang/ColdFusion/Loops-Foreach | 1 + Lang/ColdFusion/Loops-Nested | 1 + Lang/ColdFusion/Repeat-a-string | 1 + Lang/ColdFusion/Stable-marriage-problem | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Common-Lisp/Animate-a-pendulum | 1 + Lang/Common-Lisp/Bulls-and-cows-Player | 1 + .../Fibonacci-n-step-number-sequences | 1 + Lang/Common-Lisp/Harshad-or-Niven-series | 1 + Lang/Common-Lisp/Last-Friday-of-each-month | 1 + Lang/Common-Lisp/Modular-inverse | 1 + Lang/Common-Lisp/OpenGL | 1 + .../Common-Lisp/Sorting-algorithms-Sleep-sort | 1 + Lang/Common-Lisp/Special-variables | 1 + Lang/Common-Lisp/String-comparison | 1 + Lang/Common-Lisp/Temperature-conversion | 1 + Lang/Common-Lisp/Tic-tac-toe | 1 + Lang/Common-Lisp/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Common-Lisp/Truncatable-primes | 1 + Lang/Common-Lisp/Twelve-statements | 1 + Lang/Common-Lisp/Universal-Turing-machine | 1 + Lang/Common-Lisp/Variables | 1 + .../Greatest-subsequential-sum | 1 + Lang/Curry/Pascals-triangle-Puzzle | 1 + Lang/Curry/Solve-a-Hidato-puzzle | 1 + Lang/Curry/Zebra-puzzle | 1 + Lang/D/Averages-Mean-time-of-day | 1 + Lang/D/Call-a-function | 1 + Lang/D/MD4 | 1 + Lang/D/Program-termination | 1 + Lang/DCL/00DESCRIPTION | 1 + Lang/Dart/Sorting-algorithms-Sleep-sort | 1 + Lang/Dc/00DESCRIPTION | 9 +- Lang/Delphi/Bitmap-Bresenhams-line-algorithm | 1 + Lang/Delphi/SEDOLs | 1 + Lang/Delphi/Sieve-of-Eratosthenes | 1 + Lang/Delphi/String-interpolation--included- | 1 + Lang/Delphi/Take-notes-on-the-command-line | 1 + Lang/Delphi/Temperature-conversion | 1 + Lang/Delphi/Truncate-a-file | 1 + Lang/Dylan/Man-or-boy-test | 1 + Lang/Eiffel/Binary-search | 1 + Lang/Eiffel/Caesar-cipher | 1 + Lang/Eiffel/Catalan-numbers | 1 + Lang/Eiffel/Character-codes | 1 + Lang/Eiffel/Combinations | 1 + Lang/Eiffel/Count-in-factors | 1 + Lang/Eiffel/Digital-root | 1 + Lang/Eiffel/Dot-product | 1 + Lang/Eiffel/Ethiopian-multiplication | 1 + Lang/Eiffel/Extreme-floating-point-values | 1 + Lang/Eiffel/FizzBuzz | 1 + Lang/Eiffel/Function-definition | 1 + Lang/Eiffel/Guess-the-number | 1 + Lang/Eiffel/Happy-numbers | 1 + Lang/Eiffel/Harshad-or-Niven-series | 1 + Lang/Eiffel/Hofstadter-Q-sequence | 1 + Lang/Eiffel/Huffman-coding | 1 + Lang/Eiffel/Identity-matrix | 1 + Lang/Eiffel/Increment-a-numerical-string | 1 + Lang/Eiffel/Knuth-shuffle | 1 + Lang/Eiffel/Letter-frequency | 1 + Lang/Eiffel/Literals-Floating-point | 1 + Lang/Eiffel/Literals-Integer | 1 + Lang/Eiffel/N-queens-problem | 1 + Lang/Eiffel/Null-object | 1 + Lang/Eiffel/Number-reversal-game | 1 + Lang/Eiffel/Palindrome-detection | 1 + Lang/Eiffel/Perfect-numbers | 1 + Lang/Eiffel/Permutations | 1 + Lang/Eiffel/Pig-the-dice-game | 1 + Lang/Eiffel/Prime-decomposition | 1 + Lang/Eiffel/Pythagorean-triples | 1 + Lang/Eiffel/Range-extraction | 1 + Lang/Eiffel/Repeat-a-string | 1 + Lang/Eiffel/Return-multiple-values | 1 + Lang/Eiffel/Roman-numerals-Decode | 1 + Lang/Eiffel/Roman-numerals-Encode | 1 + Lang/Eiffel/Scope-Function-names-and-labels | 1 + Lang/Eiffel/Scope-modifiers | 1 + Lang/Eiffel/Semordnilap | 1 + Lang/Eiffel/Sequence-of-non-squares | 1 + Lang/Eiffel/Sorting-algorithms-Bead-sort | 1 + Lang/Eiffel/Sorting-algorithms-Bogosort | 1 + Lang/Eiffel/Sorting-algorithms-Cocktail-sort | 1 + Lang/Eiffel/Sorting-algorithms-Comb-sort | 1 + Lang/Eiffel/Sorting-algorithms-Counting-sort | 1 + Lang/Eiffel/Sorting-algorithms-Gnome-sort | 1 + Lang/Eiffel/Sorting-algorithms-Merge-sort | 1 + Lang/Eiffel/Sorting-algorithms-Pancake-sort | 1 + Lang/Eiffel/Sorting-algorithms-Selection-sort | 1 + Lang/Eiffel/Sorting-algorithms-Stooge-sort | 1 + Lang/Eiffel/Sum-and-product-of-an-array | 1 + Lang/Eiffel/Topswops | 1 + Lang/Eiffel/Towers-of-Hanoi | 1 + Lang/Eiffel/Variables | 1 + Lang/Elena/00DESCRIPTION | 222 ++++- Lang/Elixir/00DESCRIPTION | 3 +- Lang/Elixir/Ackermann-function | 1 + Lang/Elixir/Averages-Arithmetic-mean | 1 + Lang/Elixir/Averages-Median | 1 + Lang/Elixir/Averages-Pythagorean-means | 1 + Lang/Elixir/Averages-Root-mean-square | 1 + Lang/Elixir/Case-sensitivity-of-identifiers | 1 + Lang/Elixir/Comments | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Elixir/Empty-string | 1 + Lang/Elixir/Factorial | 1 + Lang/Elixir/Flatten-a-list | 1 + Lang/Elixir/Guess-the-number | 1 + Lang/Elixir/Guess-the-number-With-feedback | 1 + Lang/Elixir/Hello-world-Newline-omission | 1 + Lang/Elixir/Hello-world-Text | 1 + Lang/Elixir/Mutual-recursion | 1 + Lang/Elixir/Palindrome-detection | 1 + Lang/Elixir/Perfect-numbers | 1 + Lang/Elixir/Pick-random-element | 1 + .../Elixir/Random-number-generator--included- | 1 + Lang/Elixir/Random-numbers | 1 + Lang/Elixir/Repeat-a-string | 1 + Lang/Elixir/Reverse-a-string | 1 + Lang/Elixir/String-case | 1 + Lang/Elixir/String-concatenation | 1 + Lang/Elixir/String-interpolation--included- | 1 + Lang/Elixir/String-length | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/Elixir/Terminal-control-Unicode-output | 1 + Lang/Elixir/Tokenize-a-string | 1 + Lang/Elixir/Unbias-a-random-generator | 1 + Lang/Emacs-Lisp/Associative-array-Creation | 1 + Lang/Emacs-Lisp/Averages-Root-mean-square | 1 + Lang/Emacs-Lisp/Check-that-file-exists | 1 + Lang/Emacs-Lisp/Detect-division-by-zero | 1 + Lang/Emacs-Lisp/Documentation | 1 + Lang/Emacs-Lisp/Dynamic-variable-names | 1 + Lang/Emacs-Lisp/File-modification-time | 1 + Lang/Emacs-Lisp/Function-composition | 1 + Lang/Emacs-Lisp/Function-definition | 1 + Lang/Emacs-Lisp/Generic-swap | 1 + Lang/Emacs-Lisp/Literals-String | 1 + Lang/Emacs-Lisp/Loops-Do-while | 1 + Lang/Emacs-Lisp/Loops-Foreach | 1 + Lang/Emacs-Lisp/Loops-While | 1 + Lang/Emacs-Lisp/Primality-by-trial-division | 1 + Lang/Emacs-Lisp/Program-termination | 1 + Lang/Emacs-Lisp/Range-extraction | 1 + Lang/Emacs-Lisp/Read-entire-file | 1 + Lang/Emacs-Lisp/SHA-256 | 1 + Lang/Emacs-Lisp/Secure-temporary-file | 1 + Lang/Emacs-Lisp/Sieve-of-Eratosthenes | 1 + Lang/Emacs-Lisp/Unicode-variable-names | 1 + Lang/Erlang/Pattern-matching | 1 + Lang/Erlang/Probabilistic-choice | 1 + Lang/Euphoria/Averages-Mean-angle | 1 + Lang/Euphoria/Averages-Mean-time-of-day | 1 + Lang/Euphoria/Compound-data-type | 1 + Lang/Euphoria/Execute-a-system-command | 1 + Lang/Euphoria/Horizontal-sundial-calculations | 1 + Lang/Euphoria/Letter-frequency | 1 + Lang/Euphoria/Literals-Floating-point | 1 + Lang/Euphoria/Literals-Integer | 1 + Lang/Euphoria/Loops-Do-while | 1 + Lang/Euphoria/Loops-Foreach | 1 + Lang/Euphoria/OpenGL | 1 + Lang/Euphoria/Sierpinski-carpet | 1 + Lang/Euphoria/Temperature-conversion | 1 + Lang/Euphoria/Tic-tac-toe | 1 + Lang/Excel/Arithmetic-Integer | 1 + Lang/Excel/Averages-Root-mean-square | 1 + Lang/Excel/Integer-comparison | 1 + Lang/Excel/Logical-operations | 1 + Lang/Excel/Temperature-conversion | 1 + Lang/F-Sharp/Gamma-function | 1 + Lang/F-Sharp/Sieve-of-Eratosthenes | 1 + Lang/FBSL/00DESCRIPTION | 2 +- Lang/Factor/Colour-bars-Display | 1 + Lang/Factor/Here-document | 1 + Lang/Factor/Parallel-calculations | 1 + Lang/Factor/Price-fraction | 1 + Lang/Factor/Sum-digits-of-an-integer | 1 + Lang/Factor/XML-XPath | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Falcon/Hello-world-Newline-omission | 1 + Lang/Falcon/Pick-random-element | 1 + Lang/Fexl/00DESCRIPTION | 28 +- Lang/Forth/Call-a-function | 1 + Lang/Forth/Named-parameters | 1 + Lang/Forth/Top-rank-per-group | 1 + Lang/Forth/Vector-products | 1 + Lang/Fortran/00DESCRIPTION | 8 +- Lang/Fortran/Animate-a-pendulum | 1 + Lang/Fortran/Call-a-function | 1 + Lang/Fortran/Deal-cards-for-FreeCell | 1 + Lang/Fortran/Digital-root | 1 + Lang/Fortran/Enforced-immutability | 1 + .../Fortran/Fibonacci-n-step-number-sequences | 1 + Lang/Fortran/Langtons-ant | 1 + Lang/Fortran/Random-number-generator--device- | 1 + Lang/Fortran/Subtractive-generator | 1 + Lang/Fortran/Temperature-conversion | 1 + Lang/Fortran/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Frink/Factors-of-an-integer | 1 + Lang/Frink/Greyscale-bars-Display | 1 + Lang/Frink/Hello-world-Standard-error | 1 + Lang/Frink/Knuth-shuffle | 1 + Lang/Frink/Remove-lines-from-a-file | 1 + Lang/Frink/Return-multiple-values | 1 + Lang/Frink/Runtime-evaluation | 1 + Lang/Frink/Sort-an-integer-array | 1 + Lang/Frink/String-interpolation--included- | 1 + Lang/Frink/Window-creation | 1 + Lang/GML/Hello-world-Text | 1 + Lang/GUISS/00DESCRIPTION | 2 +- Lang/Gema/A+B | 1 + Lang/Gentee/Hello-world-Text | 1 + Lang/Gnuplot/Function-definition | 1 + Lang/Gnuplot/Program-termination | 1 + Lang/Go/00DESCRIPTION | 22 +- Lang/Go/Arena-storage-pool | 1 + Lang/Go/Break-OO-privacy | 1 + Lang/Go/Call-a-function | 1 + Lang/Go/Create-a-file-on-magnetic-tape | 1 + Lang/Go/Cut-a-rectangle | 1 + .../Keyboard-input-Flush-the-keyboard-buffer | 1 + Lang/Go/Keyboard-input-Keypress-check | 1 + .../Keyboard-input-Obtain-a-Y-or-N-response | 1 + Lang/Go/Metronome | 1 + Lang/Go/Parametrized-SQL-statement | 1 + Lang/Go/Partial-function-application | 1 + Lang/Go/SQL-based-authentication | 1 + Lang/Go/Scope-Function-names-and-labels | 1 + Lang/Go/Set-of-real-numbers | 1 + Lang/Go/Terminal-control-Coloured-text | 1 + Lang/Go/Terminal-control-Cursor-movement | 1 + Lang/Go/Terminal-control-Cursor-positioning | 1 + Lang/Go/Terminal-control-Dimensions | 1 + Lang/Go/Terminal-control-Hiding-the-cursor | 1 + Lang/Go/Terminal-control-Inverse-video | 1 + Lang/Go/Universal-Turing-machine | 1 + Lang/Go/Zebra-puzzle | 1 + Lang/Groovy/Anagrams-Deranged-anagrams | 1 + Lang/Groovy/Arithmetic-geometric-mean | 1 + Lang/Groovy/Delete-a-file | 1 + Lang/Groovy/Happy-numbers | 1 + Lang/Groovy/Huffman-coding | 1 + Lang/Groovy/Least-common-multiple | 1 + Lang/Groovy/Optional-parameters | 1 + Lang/Groovy/Parametric-polymorphism | 1 + Lang/Groovy/Polymorphic-copy | 1 + Lang/Groovy/Pythagorean-triples | 1 + Lang/Groovy/Respond-to-an-unknown-method-call | 1 + Lang/Groovy/Sorting-algorithms-Sleep-sort | 1 + Lang/Haskell/Average-loop-length | 1 + Lang/Haskell/Calendar | 1 + Lang/Haskell/Color-quantization | 1 + Lang/Haskell/Element-wise-operations | 1 + Lang/Haskell/Honeycombs | 1 + Lang/Haskell/Hough-transform | 1 + Lang/Haskell/Image-noise | 1 + Lang/Haskell/Last-Friday-of-each-month | 1 + Lang/Haskell/Mad-Libs | 1 + Lang/Haskell/Multisplit | 1 + Lang/Haskell/Narcissist | 1 + Lang/Haskell/Nautical-bell | 1 + Lang/Haskell/Optional-parameters | 1 + .../Percentage-difference-between-images | 1 + Lang/Haskell/Rate-counter | 1 + Lang/Haskell/SHA-1 | 1 + Lang/Haskell/Sokoban | 1 + Lang/Haskell/String-comparison | 1 + Lang/Haskell/Temperature-conversion | 1 + .../Haskell/Terminal-control-Clear-the-screen | 1 + Lang/Haskell/URL-decoding | 1 + Lang/Haskell/URL-encoding | 1 + Lang/Haxe/Execute-HQ9+ | 1 + Lang/Haxe/Hello-world-Text | 1 + Lang/Icon/Balanced-ternary | 1 + Lang/Icon/Carmichael-3-strong-pseudoprimes | 1 + Lang/Icon/Create-a-file-on-magnetic-tape | 1 + Lang/Icon/Fibonacci-n-step-number-sequences | 1 + Lang/Icon/Hello-world-Line-printer | 1 + Lang/Icon/Keyboard-macros | 1 + Lang/Icon/Permutations-by-swapping | 1 + Lang/Icon/Reduced-row-echelon-form | 1 + Lang/Icon/Roots-of-a-function | 1 + Lang/Icon/Secure-temporary-file | 1 + Lang/Icon/Test-a-function | 1 + Lang/Icon/Video-display-modes | 1 + Lang/Intercal/Loops-Infinite | 1 + Lang/Io/Man-or-boy-test | 1 + Lang/Iptscrae/00DESCRIPTION | 7 +- Lang/J/00DESCRIPTION | 8 +- Lang/J/Date-manipulation | 1 + Lang/J/Execute-SNUSP | 1 + Lang/J/Fork | 1 + Lang/J/Nautical-bell | 1 + Lang/J/Send-an-unknown-method-call | 1 + Lang/J/Sieve-of-Eratosthenes | 1 + Lang/J/Synchronous-concurrency | 1 + Lang/Java/24-game | 1 + Lang/Java/24-game-Solve | 1 + Lang/Java/Bitmap-Bresenhams-line-algorithm | 1 + Lang/Java/Calendar | 1 + Lang/Java/Colour-pinstripe-Display | 1 + Lang/Java/Discordian-date | 1 + Lang/Java/Draw-a-cuboid | 1 + Lang/Java/Dutch-national-flag-problem | 1 + Lang/Java/Execute-a-Markov-algorithm | 1 + Lang/Java/GUI-Maximum-window-dimensions | 1 + Lang/Java/Holidays-related-to-Easter | 1 + Lang/Java/Honeycombs | 1 + Lang/Java/Longest-string-challenge | 1 + Lang/Java/Multifactorial | 1 + Lang/Java/Multisplit | 1 + Lang/Java/Nautical-bell | 1 + Lang/Java/Non-continuous-subsequences | 1 + Lang/Java/Parallel-calculations | 1 + Lang/Java/Parsing-RPN-to-infix-conversion | 1 + Lang/Java/Parsing-Shunting-yard-algorithm | 1 + Lang/Java/Pinstripe-Display | 1 + Lang/Java/Self-referential-sequence | 1 + Lang/Java/Sierpinski-triangle-Graphical | 1 + Lang/Java/Simple-database | 1 + Lang/Java/Solve-a-Hidato-puzzle | 1 + Lang/Java/String-comparison | 1 + ...odes-and-extended-characters-from-a-string | 1 + Lang/Java/Sutherland-Hodgman-polygon-clipping | 1 + Lang/Java/Terminal-control-Clear-the-screen | 1 + Lang/Java/Text-processing-1 | 1 + Lang/Java/Top-rank-per-group | 1 + Lang/Java/Update-a-configuration-file | 1 + Lang/Java/Visualize-a-tree | 1 + Lang/Java/Window-management | 1 + Lang/Java/Zebra-puzzle | 1 + Lang/JavaScript/Death-Star | 1 + Lang/JavaScript/Digital-root | 1 + Lang/JavaScript/Draw-a-sphere | 1 + Lang/JavaScript/Empty-string | 1 + Lang/JavaScript/Entropy | 1 + Lang/JavaScript/Euler-method | 1 + Lang/JavaScript/Fast-Fourier-transform | 1 + Lang/JavaScript/Gamma-function | 1 + Lang/JavaScript/Handle-a-signal | 1 + Lang/JavaScript/Haversine-formula | 1 + Lang/JavaScript/Identity-matrix | 1 + Lang/JavaScript/Knapsack-problem-0-1 | 1 + .../Parsing-Shunting-yard-algorithm | 1 + Lang/JavaScript/Roots-of-a-function | 1 + Lang/JavaScript/Unicode-variable-names | 1 + Lang/JavaScript/Web-scraping | 1 + Lang/Jcon/00DESCRIPTION | 28 - Lang/Julia/Arithmetic-Integer | 1 + Lang/Julia/Associative-array-Creation | 1 + Lang/Julia/Averages-Pythagorean-means | 1 + Lang/Julia/Averages-Simple-moving-average | 1 + Lang/Julia/Combinations-with-repetitions | 1 + Lang/Julia/Conways-Game-of-Life | 1 + Lang/Julia/Entropy | 1 + Lang/Julia/Ethiopian-multiplication | 1 + Lang/Julia/Generator-Exponential | 1 + Lang/Julia/Hamming-numbers | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/Julia/Integer-comparison | 1 + Lang/Julia/Introspection | 1 + Lang/Julia/Kaprekar-numbers | 1 + Lang/Julia/Letter-frequency | 1 + Lang/Julia/Levenshtein-distance | 1 + Lang/Julia/Literals-Integer | 1 + Lang/Julia/Loops-N-plus-one-half | 1 + Lang/Julia/Minesweeper-game | 1 + Lang/Julia/Parsing-RPN-calculator-algorithm | 1 + .../Seven-sided-dice-from-five-sided-dice | 1 + Lang/Julia/Sierpinski-carpet | 1 + Lang/Julia/Special-variables | 1 + Lang/Julia/Truncate-a-file | 1 + Lang/Julia/Y-combinator | 1 + Lang/Kotlin/00DESCRIPTION | 2 +- Lang/LOLCODE/Loops-Infinite | 1 + Lang/Liberty-BASIC/LZW-compression | 1 + Lang/Logo/Averages-Mean-angle | 1 + Lang/Logo/Langtons-ant | 1 + Lang/Logo/Sum-digits-of-an-integer | 1 + Lang/Lua/00DESCRIPTION | 10 +- Lang/Lua/Arithmetic-geometric-mean | 1 + Lang/Lua/Call-a-foreign-language-function | 1 + Lang/Lua/Combinations-with-repetitions | 1 + Lang/Lua/Digital-root | 1 + Lang/Lua/Forest-fire | 1 + Lang/Lua/JSON | 1 + Lang/Lua/Langtons-ant | 1 + Lang/Lua/Largest-int-from-concatenated-ints | 1 + Lang/Lua/Longest-string-challenge | 1 + Lang/Lua/Maze-generation | 1 + Lang/Lua/Order-two-numerical-lists | 1 + Lang/Lua/Partial-function-application | 1 + Lang/Lua/Priority-queue | 1 + Lang/Lua/Range-expansion | 1 + Lang/Lua/Read-a-specific-line-from-a-file | 1 + Lang/Lua/Sorting-algorithms-Sleep-sort | 1 + Lang/Lua/Special-variables | 1 + Lang/Lua/Standard-deviation | 1 + Lang/Lua/String-concatenation | 1 + Lang/Lua/Sum-digits-of-an-integer | 1 + Lang/Lua/Temperature-conversion | 1 + Lang/Lua/Van-der-Corput-sequence | 1 + Lang/Lua/Word-wrap | 1 + Lang/Lush/Fibonacci-sequence | 1 + Lang/M4/A+B | 1 + Lang/M4/Even-or-odd | 1 + Lang/M4/Read-entire-file | 1 + Lang/MATLAB/00DESCRIPTION | 6 + Lang/MATLAB/Bulls-and-cows | 1 + Lang/MATLAB/Bulls-and-cows-Player | 1 + Lang/MATLAB/Element-wise-operations | 1 + Lang/MATLAB/Gray-code | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/MATLAB/Hamming-numbers | 1 + Lang/MATLAB/Handle-a-signal | 1 + Lang/MATLAB/Happy-numbers | 1 + Lang/MATLAB/Hash-from-two-arrays | 1 + Lang/MATLAB/Honeycombs | 1 + Lang/MATLAB/Image-convolution | 1 + Lang/MATLAB/Minesweeper-game | 1 + Lang/MATLAB/Number-reversal-game | 1 + Lang/MATLAB/Perfect-numbers | 1 + Lang/MATLAB/Probabilistic-choice | 1 + Lang/MATLAB/Runtime-evaluation | 1 + .../Runtime-evaluation-In-an-environment | 1 + Lang/MATLAB/Tic-tac-toe | 1 + Lang/MAXScript/Animation | 1 + Lang/MAXScript/Averages-Root-mean-square | 1 + Lang/MAXScript/Bulls-and-cows | 1 + Lang/MAXScript/Factors-of-an-integer | 1 + Lang/MAXScript/Greyscale-bars-Display | 1 + Lang/MAXScript/Guess-the-number | 1 + Lang/MAXScript/Guess-the-number-With-feedback | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/MAXScript/Happy-numbers | 1 + Lang/MAXScript/Image-noise | 1 + Lang/MAXScript/Knapsack-problem-0-1 | 1 + Lang/MAXScript/Loops-Break | 1 + .../MAXScript/Loops-For-with-a-specified-step | 1 + Lang/MAXScript/Loops-Nested | 1 + Lang/MAXScript/Mouse-position | 1 + Lang/MAXScript/Regular-expressions | 1 + Lang/MAXScript/Sorting-algorithms-Comb-sort | 1 + .../Sorting-algorithms-Counting-sort | 1 + Lang/MAXScript/Sorting-algorithms-Gnome-sort | 1 + Lang/MAXScript/Sorting-algorithms-Heapsort | 1 + .../Sorting-algorithms-Insertion-sort | 1 + Lang/MAXScript/Sorting-algorithms-Merge-sort | 1 + .../MAXScript/Sorting-algorithms-Pancake-sort | 1 + .../Sorting-algorithms-Permutation-sort | 1 + Lang/MAXScript/Sorting-algorithms-Stooge-sort | 1 + Lang/MAXScript/Sorting-algorithms-Strand-sort | 1 + Lang/MS-SQL/00DESCRIPTION | 1 - Lang/MSSQL/00DESCRIPTION | 1 - Lang/Make/00DESCRIPTION | 17 +- Lang/Make/Environment-variables | 1 + Lang/Make/Read-entire-file | 1 + Lang/Maple/Averages-Mode | 1 + Lang/Maple/Averages-Pythagorean-means | 1 + Lang/Maple/Averages-Root-mean-square | 1 + Lang/Maple/Call-a-function | 1 + Lang/Maple/Call-an-object-method | 1 + Lang/Maple/Catalan-numbers | 1 + Lang/Maple/Collections | 1 + Lang/Maple/Combinations | 1 + .../Constrained-random-points-on-a-circle | 1 + Lang/Maple/Create-a-file | 1 + Lang/Maple/Delete-a-file | 1 + Lang/Maple/Empty-string | 1 + Lang/Maple/Even-or-odd | 1 + Lang/Maple/FizzBuzz | 1 + Lang/Maple/HTTPS | 1 + Lang/Maple/Hash-from-two-arrays | 1 + Lang/Maple/Loops-N-plus-one-half | 1 + Lang/Maple/MD5 | 1 + Lang/Maple/Memory-allocation | 1 + Lang/Maple/Multiplicative-order | 1 + Lang/Maple/Optional-parameters | 1 + Lang/Maple/Roman-numerals-Encode | 1 + Lang/Maple/Shell-one-liner | 1 + Lang/Maple/Stem-and-leaf-plot | 1 + Lang/Maple/String-length | 1 + Lang/Maple/Strip-comments-from-a-string | 1 + Lang/Maple/Substring | 1 + Lang/Maple/Symmetric-difference | 1 + Lang/Maple/Ternary-logic | 1 + Lang/Maple/Trigonometric-functions | 1 + Lang/Maple/URL-decoding | 1 + Lang/Maple/URL-encoding | 1 + Lang/Mathematica/00DESCRIPTION | 4 +- Lang/Mathematica/Abstract-type | 1 + .../Globally-replace-text-in-several-files | 1 + Lang/Mathematica/Huffman-coding | 1 + Lang/Mathematica/K-means++-clustering | 1 + .../Largest-int-from-concatenated-ints | 1 + Lang/Mathematica/Mad-Libs | 1 + Lang/Mathematica/Metaprogramming | 1 + Lang/Mathematica/One-of-n-lines-in-a-file | 1 + .../Random-number-generator--device- | 1 + Lang/Mathematica/Rate-counter | 1 + Lang/Mathematica/Read-a-configuration-file | 1 + Lang/Mathematica/Remove-lines-from-a-file | 1 + .../Rosetta-Code-Find-unimplemented-tasks | 1 + Lang/Mathematica/Send-an-unknown-method-call | 1 + Lang/Mathematica/Set-of-real-numbers | 1 + Lang/Mathematica/Set-puzzle | 1 + .../Mathematica/Sorting-algorithms-Radix-sort | 1 + Lang/Mathematica/String-comparison | 1 + Lang/Mathematica/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Mathematica/Universal-Turing-machine | 1 + Lang/Mathematica/Vampire-number | 1 + Lang/Mathematica/Window-management | 1 + Lang/Mathematica/Word-wrap | 1 + Lang/Mathematica/Zebra-puzzle | 1 + Lang/Maxima/Pick-random-element | 1 + Lang/Mercury/Averages-Arithmetic-mean | 1 + Lang/Mercury/Factorial | 1 + Lang/Mercury/Flatten-a-list | 1 + Lang/Mercury/Greatest-common-divisor | 1 + Lang/Mercury/Happy-numbers | 1 + Lang/Mercury/Literals-Integer | 1 + Lang/Mercury/Miller-Rabin-primality-test | 1 + Lang/Mercury/Program-name | 1 + Lang/Mercury/String-length | 1 + Lang/Mercury/Synchronous-concurrency | 1 + Lang/Neko/Increment-a-numerical-string | 1 + Lang/NewLISP/Associative-array-Iteration | 1 + Lang/NewLISP/Check-that-file-exists | 1 + Lang/NewLISP/Delete-a-file | 1 + Lang/NewLISP/Even-or-odd | 1 + Lang/NewLISP/Execute-a-system-command | 1 + Lang/NewLISP/File-modification-time | 1 + Lang/NewLISP/File-size | 1 + Lang/NewLISP/FizzBuzz | 1 + Lang/NewLISP/Fork | 1 + Lang/NewLISP/Generic-swap | 1 + Lang/NewLISP/Handle-a-signal | 1 + Lang/NewLISP/Include-a-file | 1 + Lang/NewLISP/Increment-a-numerical-string | 1 + Lang/NewLISP/Integer-sequence | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/NewLISP/Loops-Break | 1 + Lang/NewLISP/Loops-Continue | 1 + Lang/NewLISP/Loops-Do-while | 1 + Lang/NewLISP/Loops-Downward-for | 1 + Lang/NewLISP/Loops-For-with-a-specified-step | 1 + Lang/NewLISP/Loops-Foreach | 1 + Lang/NewLISP/Loops-Infinite | 1 + Lang/NewLISP/Loops-N-plus-one-half | 1 + Lang/NewLISP/Loops-Nested | 1 + Lang/NewLISP/Loops-While | 1 + Lang/NewLISP/MD5 | 1 + Lang/NewLISP/Nth-root | 1 + Lang/NewLISP/Rot-13 | 1 + Lang/NewLISP/SHA-1 | 1 + Lang/NewLISP/SHA-256 | 1 + Lang/NewLISP/Singly-linked-list-Traversal | 1 + Lang/NewLISP/String-concatenation | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + ...trip-whitespace-from-a-string-Top-and-tail | 1 + Lang/NewLISP/Substring-Top-and-tail | 1 + Lang/NewLISP/Sum-and-product-of-an-array | 1 + Lang/NewLISP/Sum-of-a-series | 1 + Lang/NewLISP/System-time | 1 + Lang/NewLISP/Tokenize-a-string | 1 + Lang/NewLISP/URL-decoding | 1 + Lang/NewLISP/URL-encoding | 1 + Lang/Nimrod/00DESCRIPTION | 14 +- Lang/OCaml/Box-the-compass | 1 + Lang/OCaml/Entropy | 1 + Lang/OCaml/Pig-the-dice-game | 1 + Lang/OCaml/Temperature-conversion | 1 + Lang/OOC/99-Bottles-of-Beer | 1 + Lang/OOC/Ackermann-function | 1 + Lang/OOC/Arithmetic-geometric-mean | 1 + Lang/OOC/Caesar-cipher | 1 + Lang/OOC/Empty-program | 1 + Lang/OOC/Even-or-odd | 1 + Lang/OOC/Function-definition | 1 + Lang/OOC/Hello-world-Newline-omission | 1 + Lang/OOC/Logical-operations | 1 + Lang/OOC/Loops-While | 1 + Lang/OOC/Reverse-a-string | 1 + Lang/OOC/String-interpolation--included- | 1 + Lang/Oberon-2/Abstract-type | 1 + Lang/Oberon-2/Align-columns | 1 + Lang/Oberon-2/Array-concatenation | 1 + Lang/Oberon-2/Arrays | 1 + Lang/Oberon-2/Associative-array-Creation | 1 + Lang/Oberon-2/Associative-array-Iteration | 1 + Lang/Oberon-2/Binary-digits | 1 + Lang/Oberon-2/Boolean-values | 1 + Lang/Oberon-2/CRC-32 | 1 + Lang/Oberon-2/CSV-to-HTML-translation | 1 + Lang/Oberon-2/Caesar-cipher | 1 + Lang/Oberon-2/Case-sensitivity-of-identifiers | 1 + Lang/Oberon-2/Comments | 1 + Lang/Oberon-2/Compile-time-calculation | 1 + Lang/Oberon-2/Greatest-common-divisor | 1 + Lang/Oberon-2/Greatest-element-of-a-list | 1 + Lang/Oberon-2/Greatest-subsequential-sum | 1 + Lang/Oberon-2/Guess-the-number | 1 + Lang/Oberon-2/Hash-from-two-arrays | 1 + Lang/Oberon-2/Haversine-formula | 1 + Lang/Oberon-2/Hello-world-Newline-omission | 1 + Lang/Oberon-2/Higher-order-functions | 1 + Lang/Oberon-2/Hofstadter-Q-sequence | 1 + Lang/Oberon-2/Hostname | 1 + Lang/Oberon-2/Inheritance-Single | 1 + Lang/Oberon-2/Input-loop | 1 + Lang/Oberon-2/Integer-sequence | 1 + .../Loop-over-multiple-arrays-simultaneously | 1 + Lang/Oberon-2/Loops-Break | 1 + Lang/Oberon-2/Loops-Do-while | 1 + Lang/Oberon-2/Loops-For | 1 + Lang/Oberon-2/Loops-For-with-a-specified-step | 1 + Lang/Oberon-2/Loops-Infinite | 1 + Lang/Oberon-2/Program-name | 1 + Lang/Oberon-2/Program-termination | 1 + Lang/Objeck/00DESCRIPTION | 4 +- Lang/Objeck/Averages-Pythagorean-means | 1 + Lang/Objeck/Levenshtein-distance | 1 + Lang/Objeck/Nth-root | 1 + Lang/Objeck/Rosetta-Code-Count-examples | 1 + .../Rosetta-Code-Rank-languages-by-popularity | 1 + Lang/Objeck/SQL-based-authentication | 1 + Lang/Objeck/Sierpinski-carpet | 1 + Lang/Objective-C/00DESCRIPTION | 2 + Lang/Objective-C/100-doors | 1 + Lang/Objective-C/Enumerations | 1 + Lang/Objective-C/Knuth-shuffle | 1 + Lang/Objective-C/Number-names | 1 + Lang/Objective-C/Range-extraction | 1 + .../Sorting-algorithms-Bubble-sort | 1 + Lang/Octave/Resistor-mesh | 1 + Lang/OoRexx/00DESCRIPTION | 3 +- Lang/OoRexx/Box-the-compass | 1 + Lang/OoRexx/Evolutionary-algorithm | 1 + Lang/OoRexx/Loops-Nested | 1 + Lang/Opa/00DESCRIPTION | 4 +- Lang/OpenEdge-Progress/Loops-Do-while | 1 + .../Luhn-test-of-credit-card-numbers | 1 + Lang/OpenEdge-Progress/Rename-a-file | 1 + Lang/Oz/Miller-Rabin-primality-test | 1 + Lang/Oz/Primality-by-trial-division | 1 + Lang/PARI-GP/00DESCRIPTION | 12 +- Lang/PARI-GP/Anonymous-recursion | 1 + Lang/PARI-GP/Check-Machin-like-formulas | 1 + Lang/PARI-GP/Count-occurrences-of-a-substring | 1 + Lang/PARI-GP/Dragon-curve | 1 + Lang/PARI-GP/Variable-length-quantity | 1 + Lang/PARI-GP/Y-combinator | 1 + Lang/PHP/Self-describing-numbers | 1 + ...Terminal-control-Ringing-the-terminal-bell | 1 + Lang/PHP/Tree-traversal | 1 + Lang/PHP/Zeckendorf-number-representation | 1 + Lang/PL-I/00DESCRIPTION | 17 +- Lang/PL-I/Arithmetic-Rational | 1 + Lang/PL-I/Averages-Mean-time-of-day | 1 + Lang/PL-I/Enforced-immutability | 1 + Lang/PL-I/Entropy | 1 + Lang/PL-I/Knapsack-problem-Continuous | 1 + Lang/PL-I/Levenshtein-distance | 1 + Lang/PL-I/Modular-inverse | 1 + Lang/PL-I/Order-two-numerical-lists | 1 + Lang/PL-I/Sorting-algorithms-Bogosort | 1 + Lang/PL-I/Sudoku | 1 + Lang/PL-I/Take-notes-on-the-command-line | 1 + Lang/Pascal/Averages-Mean-angle | 1 + Lang/Pascal/Conways-Game-of-Life | 1 + Lang/Pascal/Entropy | 1 + Lang/Pascal/Hailstone-sequence | 1 + Lang/Pascal/Hamming-numbers | 1 + Lang/Pascal/Harshad-or-Niven-series | 1 + .../Pascal/Hofstadter-Conway-$10,000-sequence | 1 + .../Pascal/Largest-int-from-concatenated-ints | 1 + Lang/Pascal/Man-or-boy-test | 1 + Lang/Pascal/Mandelbrot-set | 1 + Lang/Pascal/Random-numbers | 1 + Lang/Pascal/SHA-1 | 1 + Lang/Pascal/Spiral-matrix | 1 + Lang/Pascal/Standard-deviation | 1 + Lang/Pascal/Sum-digits-of-an-integer | 1 + Lang/Pascal/Van-der-Corput-sequence | 1 + Lang/Pascal/Window-creation-X11 | 1 + Lang/Pascal/Xiaolin-Wus-line-algorithm | 1 + Lang/Perl-6/Cut-a-rectangle | 1 + Lang/Perl-6/Events | 1 + .../Perl-6/GUI-enabling-disabling-of-controls | 1 + Lang/Perl-6/Handle-a-signal | 1 + Lang/Perl-6/Image-noise | 1 + Lang/Perl-6/K-means++-clustering | 1 + Lang/Perl-6/Simple-windowed-application | 1 + Lang/Perl-6/Speech-synthesis | 1 + Lang/Perl-6/Stable-marriage-problem | 1 + Lang/Perl-6/User-input-Graphical | 1 + Lang/Perl-6/Window-creation | 1 + Lang/Perl-6/Window-creation-X11 | 1 + Lang/Perl/Averages-Mean-angle | 1 + Lang/Perl/Call-a-function | 1 + Lang/Perl/Carmichael-3-strong-pseudoprimes | 1 + ...-Arithmetic-Construct-from-rational-number | 1 + Lang/Perl/Cut-a-rectangle | 1 + Lang/Perl/Dinesmans-multiple-dwelling-problem | 1 + Lang/Perl/Discordian-date | 1 + Lang/Perl/Dragon-curve | 1 + ...est-left-truncatable-prime-in-a-given-base | 1 + ...st-class-functions-Use-numbers-analogously | 1 + Lang/Perl/Four-bit-adder | 1 + Lang/Perl/Multiplicative-order | 1 + Lang/Perl/RIPEMD-160 | 1 + Lang/Perl/Rock-paper-scissors | 1 + Lang/Perl/Terminal-control-Cursor-positioning | 1 + Lang/Perl/Write-language-name-in-3D-ASCII | 1 + Lang/PicoLisp/00DESCRIPTION | 4 +- Lang/PicoLisp/Average-loop-length | 1 + Lang/PicoLisp/Balanced-ternary | 1 + Lang/PicoLisp/Bitcoin-address-validation | 1 + Lang/PicoLisp/CRC-32 | 1 + .../PicoLisp/Carmichael-3-strong-pseudoprimes | 1 + Lang/PicoLisp/MD4 | 1 + Lang/PicoLisp/Main-step-of-GOST-28147-89 | 1 + Lang/PicoLisp/Modular-inverse | 1 + Lang/PicoLisp/Permutations-by-swapping | 1 + Lang/PicoLisp/RIPEMD-160 | 1 + Lang/PicoLisp/SHA-256 | 1 + Lang/PicoLisp/String-comparison | 1 + Lang/PicoLisp/Universal-Turing-machine | 1 + Lang/PicoLisp/Write-language-name-in-3D-ASCII | 1 + Lang/PicoLisp/Zeckendorf-arithmetic | 1 + .../PicoLisp/Zeckendorf-number-representation | 1 + Lang/PlainTeX/Towers-of-Hanoi | 1 + Lang/PowerShell/Caesar-cipher | 1 + Lang/PowerShell/Concurrent-computing | 1 + Lang/PowerShell/Create-an-HTML-table | 1 + Lang/PowerShell/JSON | 1 + Lang/Prolog/24-game | 1 + .../Arbitrary-precision-integers--included- | 1 + Lang/Prolog/Arithmetic-Integer | 1 + Lang/Prolog/Averages-Arithmetic-mean | 1 + Lang/Prolog/Binary-search | 1 + Lang/Prolog/Bitmap-Bresenhams-line-algorithm | 1 + Lang/Prolog/Check-that-file-exists | 1 + Lang/Prolog/Concurrent-computing | 1 + Lang/Prolog/Count-occurrences-of-a-substring | 1 + Lang/Prolog/Date-format | 1 + Lang/Prolog/Determine-if-a-string-is-numeric | 1 + Lang/Prolog/Empty-string | 1 + Lang/Prolog/Equilibrium-index | 1 + Lang/Prolog/Ethiopian-multiplication | 1 + Lang/Prolog/Exponentiation-operator | 1 + Lang/Prolog/Guess-the-number | 1 + Lang/Prolog/Guess-the-number-With-feedback | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/Prolog/JSON | 1 + Lang/Prolog/Loops-Foreach | 1 + Lang/Prolog/Menu | 1 + Lang/Prolog/Middle-three-digits | 1 + Lang/Prolog/Miller-Rabin-primality-test | 1 + Lang/Prolog/Pick-random-element | 1 + Lang/Prolog/Substring | 1 + Lang/Prolog/Top-rank-per-group | 1 + Lang/Prolog/Vector-products | 1 + Lang/PureBasic/Create-an-HTML-table | 1 + Lang/Python/GUI-component-interaction | 1 + Lang/Python/Metaprogramming | 1 + Lang/Python/Simulate-input-Keyboard | 1 + Lang/Python/Topic-variable | 1 + Lang/Qi/00DESCRIPTION | 1 + Lang/R/Call-a-function | 1 + Lang/R/Call-a-function-in-a-shared-library | 1 + Lang/R/DNS-query | 1 + Lang/R/Dragon-curve | 1 + Lang/R/Euler-method | 1 + Lang/R/Gray-code | 1 + Lang/R/Integer-sequence | 1 + Lang/R/One-of-n-lines-in-a-file | 1 + Lang/R/Roman-numerals-Decode | 1 + Lang/R/String-comparison | 1 + Lang/R/Sum-digits-of-an-integer | 1 + Lang/R/URL-decoding | 1 + Lang/R/URL-encoding | 1 + Lang/R/Unicode-variable-names | 1 + Lang/R/Word-wrap | 1 + Lang/R/Zebra-puzzle | 1 + Lang/REALbasic/Classes | 1 + Lang/REALbasic/Function-definition | 1 + Lang/REALbasic/Hello-world-Graphical | 1 + Lang/REALbasic/Variadic-function | 1 + Lang/REBOL/Dot-product | 1 + Lang/REBOL/Hello-world-Newline-omission | 1 + .../Horners-rule-for-polynomial-evaluation | 1 + Lang/REBOL/Last-Friday-of-each-month | 1 + Lang/REBOL/Mad-Libs | 1 + Lang/REBOL/Number-reversal-game | 1 + Lang/REBOL/Runtime-evaluation | 1 + Lang/REBOL/Simple-database | 1 + Lang/REXX/00DESCRIPTION | 16 +- Lang/REXX/Averages-Mean-time-of-day | 1 + Lang/REXX/Bulls-and-cows-Player | 1 + Lang/REXX/Colour-bars-Display | 1 + Lang/REXX/Extend-your-language | 1 + Lang/REXX/Include-a-file | 1 + Lang/REXX/LZW-compression | 1 + Lang/REXX/Man-or-boy-test | 1 + Lang/REXX/Mandelbrot-set | 1 + Lang/REXX/Ordered-Partitions | 1 + Lang/REXX/Set-puzzle | 1 + Lang/REXX/Simple-database | 1 + Lang/REXX/Sort-stability | 1 + Lang/REXX/Topic-variable | 1 + Lang/REXX/Truncate-a-file | 1 + Lang/REXX/Visualize-a-tree | 1 + Lang/REXX/Wireworld | 1 + Lang/REXX/XML-XPath | 1 + Lang/RPG/Substring | 1 + Lang/Racket/00DESCRIPTION | 2 + Lang/Racket/Bitmap-Histogram | 1 + Lang/Racket/Constrained-genericity | 1 + Lang/Racket/Delegates | 1 + Lang/Racket/Object-serialization | 1 + Lang/Racket/Resistor-mesh | 1 + Lang/RapidQ/100-doors | 1 + Lang/RapidQ/99-Bottles-of-Beer | 1 + Lang/RapidQ/Address-of-a-variable | 1 + Lang/RapidQ/Align-columns | 1 + Lang/RapidQ/Anagrams | 1 + Lang/RapidQ/Array-concatenation | 1 + Lang/RapidQ/Find-the-missing-permutation | 1 + Lang/RapidQ/Greatest-element-of-a-list | 1 + Lang/RapidQ/Greyscale-bars-Display | 1 + Lang/RapidQ/Guess-the-number | 1 + Lang/RapidQ/Read-a-configuration-file | 1 + Lang/RapidQ/Read-a-file-line-by-line | 1 + Lang/RapidQ/Repeat-a-string | 1 + Lang/RapidQ/Sleep | 1 + Lang/Ruby/Bitcoin-address-validation | 1 + Lang/Ruby/Color-of-a-screen-pixel | 1 + Lang/Ruby/Cut-a-rectangle | 1 + Lang/Ruby/Draw-a-cuboid | 1 + Lang/Ruby/Knapsack-problem-Continuous | 1 + Lang/Ruby/Nautical-bell | 1 + Lang/Ruby/Permutation-test | 1 + Lang/Ruby/Scope-modifiers | 1 + Lang/Ruby/Set-of-real-numbers | 1 + Lang/Ruby/Sokoban | 1 + Lang/Ruby/Start-from-a-main-routine | 1 + Lang/Ruby/Topic-variable | 1 + ...y-distribution-uniformity-Chi-squared-test | 1 + Lang/Ruby/Visualize-a-tree | 1 + Lang/Ruby/Zebra-puzzle | 1 + Lang/Rust/00DESCRIPTION | 37 +- Lang/Rust/Accumulator-factory | 1 + Lang/Rust/Align-columns | 1 + Lang/Rust/Arithmetic-Integer | 1 + Lang/Rust/Arithmetic-geometric-mean | 1 + Lang/Rust/Associative-array-Iteration | 1 + Lang/Rust/Averages-Arithmetic-mean | 1 + Lang/Rust/Binary-digits | 1 + Lang/Rust/Call-an-object-method | 1 + Lang/Rust/Catalan-numbers | 1 + Lang/Rust/Dot-product | 1 + Lang/Rust/Ethiopian-multiplication | 1 + Lang/Rust/Even-or-odd | 1 + Lang/Rust/Filter | 1 + Lang/Rust/Guess-the-number | 1 + Lang/Rust/Hailstone-sequence | 1 + Lang/Rust/Happy-numbers | 1 + Lang/Rust/Hello-world-Newline-omission | 1 + Lang/Rust/Hello-world-Standard-error | 1 + Lang/Rust/Hello-world-Web-server | 1 + Lang/Rust/Infinity | 1 + Lang/Rust/Integer-comparison | 1 + Lang/Rust/JSON | 1 + Lang/Rust/Knapsack-problem-0-1 | 1 + Lang/Rust/Langtons-ant | 1 + Lang/Rust/Letter-frequency | 1 + Lang/Rust/Loops-Infinite | 1 + Lang/Rust/Loops-While | 1 + Lang/Rust/Luhn-test-of-credit-card-numbers | 1 + Lang/Rust/Parametric-polymorphism | 1 + Lang/Rust/Playing-cards | 1 + Lang/Rust/Price-fraction | 1 + Lang/Rust/Primality-by-trial-division | 1 + Lang/Rust/Read-a-file-line-by-line | 1 + Lang/Rust/SHA-256 | 1 + Lang/Rust/Sort-an-integer-array | 1 + Lang/Rust/Sorting-algorithms-Quicksort | 1 + Lang/Rust/Sum-of-a-series | 1 + Lang/Rust/Sum-of-squares | 1 + Lang/SAS/Hailstone-sequence | 1 + Lang/SAS/Haversine-formula | 1 + Lang/SAS/Power-set | 1 + Lang/SAS/Stair-climbing-puzzle | 1 + Lang/SNOBOL4/00DESCRIPTION | 2 +- Lang/SPARC-Assembly/Hello-world-Text | 1 + Lang/SQL/100-doors | 1 + Lang/SQL/Associative-array-Creation | 1 + Lang/SQL/Comments | 1 + Lang/SQL/Fibonacci-sequence | 1 + Lang/SQL/Gray-code | 1 + Lang/SQL/Middle-three-digits | 1 + Lang/SQL/N-queens-problem | 1 + Lang/Scala/00DESCRIPTION | 2 +- Lang/Scala/Averages-Mean-angle | 1 + Lang/Scala/Averages-Mean-time-of-day | 1 + Lang/Scala/Bitmap-Flood-fill | 1 + Lang/Scala/Break-OO-privacy | 1 + Lang/Scala/Call-a-function | 1 + .../Scala/Call-a-function-in-a-shared-library | 1 + Lang/Scala/Color-of-a-screen-pixel | 1 + Lang/Scala/Conditional-structures | 1 + Lang/Scala/Create-a-file | 1 + Lang/Scala/Create-an-HTML-table | 1 + Lang/Scala/DNS-query | 1 + Lang/Scala/Define-a-primitive-data-type | 1 + Lang/Scala/Dutch-national-flag-problem | 1 + Lang/Scala/Exceptions | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Scala/Fibonacci-n-step-number-sequences | 1 + Lang/Scala/File-modification-time | 1 + Lang/Scala/File-size | 1 + Lang/Scala/Find-common-directory-path | 1 + Lang/Scala/Flow-control-structures | 1 + Lang/Scala/Fork | 1 + Lang/Scala/Handle-a-signal | 1 + Lang/Scala/Here-document | 1 + Lang/Scala/Host-introspection | 1 + Lang/Scala/I-before-E-except-after-C | 1 + Lang/Scala/Inverted-index | 1 + Lang/Scala/Last-letter-first-letter | 1 + Lang/Scala/Longest-string-challenge | 1 + Lang/Scala/Loops-N-plus-one-half | 1 + Lang/Scala/MD4 | 1 + Lang/Scala/Mad-Libs | 1 + Lang/Scala/Miller-Rabin-primality-test | 1 + Lang/Scala/Number-reversal-game | 1 + Lang/Scala/One-of-n-lines-in-a-file | 1 + Lang/Scala/OpenGL | 1 + Lang/Scala/Order-two-numerical-lists | 1 + Lang/Scala/Permutations-Derangements | 1 + Lang/Scala/Pick-random-element | 1 + Lang/Scala/Probabilistic-choice | 1 + Lang/Scala/Program-termination | 1 + Lang/Scala/RIPEMD-160 | 1 + Lang/Scala/Record-sound | 1 + Lang/Scala/Remove-lines-from-a-file | 1 + Lang/Scala/Rock-paper-scissors | 1 + Lang/Scala/Roots-of-a-function | 1 + Lang/Scala/SHA-256 | 1 + Lang/Scala/Send-an-unknown-method-call | 1 + Lang/Scala/Set-consolidation | 1 + Lang/Scala/Simple-database | 1 + Lang/Scala/Simulate-input-Mouse | 1 + Lang/Scala/Sockets | 1 + Lang/Scala/Sort-disjoint-sublist | 1 + Lang/Scala/Special-characters | 1 + Lang/Scala/Standard-deviation | 1 + Lang/Scala/Start-from-a-main-routine | 1 + Lang/Scala/String-comparison | 1 + Lang/Scala/Strip-block-comments | 1 + .../Scala/Sutherland-Hodgman-polygon-clipping | 1 + Lang/Scala/Temperature-conversion | 1 + Lang/Scala/Terminal-control-Clear-the-screen | 1 + ...inal-control-Display-an-extended-character | 1 + Lang/Scala/Terminal-control-Preserve-screen | 1 + Lang/Scala/Terminal-control-Unicode-output | 1 + Lang/Scala/Topswops | 1 + Lang/Scala/Trigonometric-functions | 1 + Lang/Scala/Truncate-a-file | 1 + Lang/Scala/URL-encoding | 1 + Lang/Scala/Variable-size-Get | 1 + Lang/Scala/Window-creation-X11 | 1 + Lang/Scala/Word-wrap | 1 + Lang/Scala/Write-float-arrays-to-a-text-file | 1 + Lang/Scala/Xiaolin-Wus-line-algorithm | 1 + Lang/Scala/Zebra-puzzle | 1 + Lang/Scheme/Associative-array-Iteration | 1 + Lang/Scheme/Count-occurrences-of-a-substring | 1 + Lang/Scheme/Formatted-numeric-output | 1 + Lang/Scheme/Huffman-coding | 1 + Lang/Scheme/Knights-tour | 1 + .../Scheme/Largest-int-from-concatenated-ints | 1 + Lang/Scheme/Multisplit | 1 + Lang/Scheme/Probabilistic-choice | 1 + Lang/Scheme/Pythagorean-triples | 1 + Lang/Scheme/Roman-numerals-Decode | 1 + Lang/Scheme/Same-Fringe | 1 + Lang/Scheme/Sort-disjoint-sublist | 1 + Lang/Scheme/Top-rank-per-group | 1 + Lang/Scilab/Ackermann-function | 1 + Lang/Scilab/Comments | 1 + Lang/Scilab/Empty-program | 1 + Lang/Scilab/Fibonacci-sequence | 1 + Lang/Scilab/Gamma-function | 1 + Lang/Scilab/Hailstone-sequence | 1 + Lang/Scilab/Lucas-Lehmer-test | 1 + Lang/Scilab/Monty-Hall-problem | 1 + Lang/Scilab/Sieve-of-Eratosthenes | 1 + Lang/Scilab/Sorting-algorithms-Bubble-sort | 1 + Lang/Scilab/Spiral-matrix | 1 + Lang/Scilab/Standard-deviation | 1 + Lang/Scilab/String-concatenation | 1 + .../Strip-a-set-of-characters-from-a-string | 1 + Lang/Sed/00DESCRIPTION | 12 +- .../Globally-replace-text-in-several-files | 1 + Lang/Seed7/00DESCRIPTION | 5 +- Lang/Seed7/Abstract-type | 1 + Lang/Seed7/Anonymous-recursion | 1 + Lang/Seed7/Average-loop-length | 1 + Lang/Seed7/Bulls-and-cows | 1 + Lang/Seed7/Deal-cards-for-FreeCell | 1 + Lang/Seed7/Delete-a-file | 1 + Lang/Seed7/Determine-if-a-string-is-numeric | 1 + ...Catch-an-exception-thrown-in-a-nested-call | 1 + Lang/Seed7/Find-the-missing-permutation | 1 + Lang/Seed7/Gray-code | 1 + Lang/Seed7/Hello-world-Line-printer | 1 + Lang/Seed7/Langtons-ant | 1 + Lang/Seed7/Nautical-bell | 1 + Lang/Seed7/Non-continuous-subsequences | 1 + Lang/Seed7/Parametrized-SQL-statement | 1 + Lang/Seed7/Solve-a-Hidato-puzzle | 1 + Lang/Seed7/Sorting-algorithms-Bead-sort | 1 + Lang/Seed7/Window-creation | 1 + Lang/Simula/Comments | 1 + Lang/Simula/Empty-program | 1 + Lang/Simula/Hello-world-Line-printer | 1 + Lang/Simula/Hello-world-Text | 1 + Lang/Simula/Loops-For | 1 + Lang/Smalltalk/Cholesky-decomposition | 1 + Lang/Smalltalk/Date-format | 1 + Lang/Smalltalk/Empty-string | 1 + Lang/Smalltalk/Environment-variables | 1 + Lang/Smalltalk/Hello-world-Newline-omission | 1 + Lang/Smalltalk/JSON | 1 + Lang/Smalltalk/Leap-year | 1 + Lang/Smalltalk/Least-common-multiple | 1 + Lang/Smalltalk/Mouse-position | 1 + .../Read-a-specific-line-from-a-file | 1 + Lang/Smalltalk/SHA-256 | 1 + Lang/Smalltalk/Singleton | 1 + Lang/Smalltalk/Stack | 1 + Lang/Standard-ML/Abstract-type | 1 + Lang/Standard-ML/Anonymous-recursion | 1 + Lang/Standard-ML/Bitmap-Flood-fill | 1 + Lang/Standard-ML/Empty-string | 1 + Lang/Standard-ML/Sorting-algorithms-Heapsort | 1 + Lang/Standard-ML/Soundex | 1 + Lang/Standard-ML/Topic-variable | 1 + Lang/TI-83-BASIC/Conditional-structures | 1 + Lang/TI-83-BASIC/Factorial | 1 + Lang/TI-83-BASIC/Gamma-function | 1 + Lang/TI-83-BASIC/Hailstone-sequence | 1 + Lang/TI-83-BASIC/Loops-While | 1 + Lang/TI-83-BASIC/Lucas-Lehmer-test | 1 + Lang/TI-83-BASIC/Sieve-of-Eratosthenes | 1 + Lang/TI-83-BASIC/Spiral-matrix | 1 + Lang/TXR/Anonymous-recursion | 1 + Lang/TXR/First-class-functions | 1 + Lang/TXR/Self-referential-sequence | 1 + Lang/Tcl/00DESCRIPTION | 30 +- Lang/TorqueScript/Comments | 1 + .../Loops-For-with-a-specified-step | 1 + Lang/TorqueScript/Window-creation | 1 + .../Transact-SQL/Hello-world-Newline-omission | 1 + Lang/Transact-SQL/Hello-world-Standard-error | 1 + Lang/Transact-SQL/SEDOLs | 1 + Lang/UBASIC/Haversine-formula | 1 + Lang/UNIX-Shell/24-game | 1 + Lang/UNIX-Shell/Anagrams | 1 + Lang/UNIX-Shell/Anagrams-Deranged-anagrams | 1 + Lang/UNIX-Shell/Arithmetic-Complex | 1 + Lang/UNIX-Shell/Arithmetic-geometric-mean | 1 + Lang/UNIX-Shell/Assertions | 1 + Lang/UNIX-Shell/Associative-array-Creation | 1 + Lang/UNIX-Shell/Balanced-brackets | 1 + Lang/UNIX-Shell/Bitmap | 1 + Lang/UNIX-Shell/Bitmap-Read-a-PPM-file | 1 + Lang/UNIX-Shell/Bitmap-Write-a-PPM-file | 1 + Lang/UNIX-Shell/CSV-to-HTML-translation | 1 + Lang/UNIX-Shell/Caesar-cipher | 1 + Lang/UNIX-Shell/Classes | 1 + Lang/UNIX-Shell/Collections | 1 + Lang/UNIX-Shell/Compound-data-type | 1 + Lang/UNIX-Shell/Create-an-HTML-table | 1 + Lang/UNIX-Shell/Define-a-primitive-data-type | 1 + Lang/UNIX-Shell/Five-weekends | 1 + Lang/UNIX-Shell/Generic-swap | 1 + .../Globally-replace-text-in-several-files | 1 + .../Guess-the-number-With-feedback--player- | 1 + Lang/UNIX-Shell/Hamming-numbers | 1 + Lang/UNIX-Shell/Hash-from-two-arrays | 1 + Lang/UNIX-Shell/Hello-world-Web-server | 1 + Lang/UNIX-Shell/Introspection | 1 + Lang/UNIX-Shell/Linear-congruential-generator | 1 + Lang/UNIX-Shell/Look-and-say-sequence | 1 + .../Luhn-test-of-credit-card-numbers | 1 + Lang/UNIX-Shell/Multisplit | 1 + Lang/UNIX-Shell/Queue-Definition | 1 + Lang/UNIX-Shell/Queue-Usage | 1 + .../Random-number-generator--device- | 1 + Lang/UNIX-Shell/Read-a-configuration-file | 1 + .../Read-a-specific-line-from-a-file | 1 + Lang/UNIX-Shell/Real-constants-and-functions | 1 + Lang/UNIX-Shell/Regular-expressions | 1 + Lang/UNIX-Shell/Roman-numerals-Encode | 1 + Lang/UNIX-Shell/Runtime-evaluation | 1 + Lang/UNIX-Shell/Search-a-list | 1 + Lang/UNIX-Shell/Self-describing-numbers | 1 + Lang/VBA/Comments | 1 + Lang/VBA/Parsing-RPN-calculator-algorithm | 1 + Lang/VBA/Parsing-Shunting-yard-algorithm | 1 + Lang/VBScript/Comments | 1 + Lang/VBScript/Greatest-common-divisor | 1 + Lang/VBScript/Hello-world-Graphical | 1 + Lang/VBScript/Lucas-Lehmer-test | 1 + .../VBScript/Luhn-test-of-credit-card-numbers | 1 + Lang/VBScript/Sierpinski-carpet | 1 + Lang/VBScript/Sieve-of-Eratosthenes | 1 + Lang/VBScript/Sudoku | 1 + Lang/VBScript/URL-decoding | 1 + Lang/VBScript/URL-encoding | 1 + Lang/VBScript/Van-der-Corput-sequence | 1 + Lang/Vim-Script/00DESCRIPTION | 3 +- Lang/Vim-Script/Apply-a-callback-to-an-array | 1 + Lang/Vim-Script/Arithmetic-Integer | 1 + Lang/Vim-Script/Arrays | 1 + Lang/Vim-Script/Associative-array-Creation | 1 + Lang/Vim-Script/Associative-array-Iteration | 1 + Lang/Vim-Script/Averages-Arithmetic-mean | 1 + Lang/Vim-Script/Binary-digits | 1 + Lang/Vim-Script/Boolean-values | 1 + Lang/Vim-Script/Character-codes | 1 + Lang/Vim-Script/Comments | 1 + Lang/Vim-Script/Compound-data-type | 1 + Lang/Vim-Script/Copy-a-string | 1 + Lang/Vim-Script/Count-in-octal | 1 + .../Create-a-two-dimensional-array-at-runtime | 1 + Lang/Vim-Script/FizzBuzz | 1 + Lang/Vim-Script/Greatest-element-of-a-list | 1 + Lang/Vim-Script/Hello-world-Newline-omission | 1 + Lang/Vim-Script/Hello-world-Text | 1 + Lang/Vim-Script/Hostname | 1 + .../Loops-For-with-a-specified-step | 1 + Lang/Vim-Script/Loops-Foreach | 1 + Lang/Vim-Script/Loops-N-plus-one-half | 1 + Lang/Vim-Script/Loops-While | 1 + Lang/Visual-Basic-.NET/Align-columns | 1 + Lang/Visual-Basic-.NET/Arrays | 1 + Lang/Visual-Basic-.NET/Dragon-curve | 1 + Lang/Visual-Basic-.NET/Lucas-Lehmer-test | 1 + Lang/Visual-Basic/Ackermann-function | 1 + Lang/Visual-Basic/Align-columns | 1 + Lang/Visual-Basic/Dragon-curve | 1 + Lang/Visual-Basic/Empty-program | 1 + Lang/Visual-Basic/Fibonacci-sequence | 1 + Lang/Visual-Basic/Hailstone-sequence | 1 + Lang/Visual-Basic/Knapsack-problem-Unbounded | 1 + Lang/Visual-Basic/Multiplication-tables | 1 + Lang/Visual-Basic/Sieve-of-Eratosthenes | 1 + Lang/Visual-Basic/Standard-deviation | 1 + .../Terminal-control-Cursor-positioning | 1 + Lang/XSLT/Averages-Arithmetic-mean | 1 + Lang/XSLT/Call-a-function | 1 + Lang/XSLT/Create-an-HTML-table | 1 + Lang/XSLT/FizzBuzz | 1 + Lang/XSLT/Greatest-element-of-a-list | 1 + Lang/XSLT/Hello-world-Graphical | 1 + Lang/XSLT/Here-document | 1 + Lang/Yacas/Apply-a-callback-to-an-array | 1 + Lang/Yacas/Array-concatenation | 1 + Lang/Yacas/Averages-Root-mean-square | 1 + Lang/Yacas/Greatest-element-of-a-list | 1 + Lang/Z80-Assembly/Mandelbrot-set | 1 + Lang/ZED/00DESCRIPTION | 19 +- Lang/ZED/Sorting-algorithms-Merge-sort | 1 + Meta/Task.yaml | 4 - Task/100-doors/00DESCRIPTION | 9 +- Task/100-doors/APL/100-doors-1.apl | 20 +- Task/100-doors/APL/100-doors-2.apl | 12 +- Task/100-doors/ATS/100-doors.ats | 41 + Task/100-doors/C-sharp/100-doors-1.cs | 48 +- Task/100-doors/C-sharp/100-doors-2.cs | 34 +- Task/100-doors/C-sharp/100-doors-3.cs | 23 +- Task/100-doors/C-sharp/100-doors-4.cs | 50 +- Task/100-doors/C-sharp/100-doors-5.cs | 18 +- Task/100-doors/ColdFusion/100-doors-4.cfm | 14 + Task/100-doors/Common-Lisp/100-doors-3.lisp | 30 +- Task/100-doors/Coq/100-doors-1.coq | 2 +- Task/100-doors/Coq/100-doors-2.coq | 2 +- Task/100-doors/Haskell/100-doors-1.hs | 2 +- Task/100-doors/Haskell/100-doors-2.hs | 16 +- Task/100-doors/Haskell/100-doors-3.hs | 7 +- Task/100-doors/Haskell/100-doors-4.hs | 1 + Task/100-doors/J/100-doors-3.j | 6 +- Task/100-doors/JavaScript/100-doors-1.js | 14 +- Task/100-doors/JavaScript/100-doors-2.js | 15 +- Task/100-doors/JavaScript/100-doors-3.js | 4 +- Task/100-doors/JavaScript/100-doors-4.js | 12 +- Task/100-doors/JavaScript/100-doors-5.js | 9 + Task/100-doors/JavaScript/100-doors-6.js | 9 + Task/100-doors/Julia/100-doors-1.julia | 6 +- Task/100-doors/Maple/100-doors-1.maple | 6 +- Task/100-doors/Mathematica/100-doors-3.math | 6 +- Task/100-doors/Mathematica/100-doors-4.math | 4 +- Task/100-doors/Mathematica/100-doors-5.math | 15 +- Task/100-doors/Mathematica/100-doors-6.math | 13 +- Task/100-doors/Mathematica/100-doors-7.math | 2 +- Task/100-doors/Mathematica/100-doors-8.math | 1 + Task/100-doors/Mercury/100-doors.mercury | 2 +- Task/100-doors/Objective-C/100-doors-1.m | 28 + Task/100-doors/Objective-C/100-doors-2.m | 68 ++ Task/100-doors/Perl/100-doors-2.pl | 11 +- Task/100-doors/Perl/100-doors-3.pl | 2 +- Task/100-doors/Perl/100-doors-4.pl | 13 +- Task/100-doors/Perl/100-doors-5.pl | 12 + Task/100-doors/PowerShell/100-doors-6.psh | 6 + Task/100-doors/PowerShell/100-doors-7.psh | 1 + Task/100-doors/Prolog/100-doors-2.pro | 35 +- Task/100-doors/Prolog/100-doors-3.pro | 4 + Task/100-doors/Python/100-doors-6.py | 1 + Task/100-doors/RapidQ/100-doors.rapidq | 20 + Task/100-doors/Rust/100-doors-1.rust | 25 +- Task/100-doors/SQL/100-doors.sql | 23 + Task/100-doors/Scheme/100-doors-3.ss | 17 + Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 | 4 +- Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 | 2 +- Task/100-doors/TI-89-BASIC/100-doors.ti-89 | 6 +- Task/100-doors/TXR/100-doors.txr | 6 +- Task/24-game-Solve/00DESCRIPTION | 5 +- Task/24-game-Solve/C++/24-game-solve.cpp | 90 ++ Task/24-game-Solve/Clojure/24-game-solve.clj | 49 +- .../CoffeeScript/24-game-solve.coffee | 87 ++ Task/24-game-Solve/D/24-game-solve.d | 63 +- Task/24-game-Solve/Go/24-game-solve.go | 10 +- Task/24-game-Solve/Haskell/24-game-solve-2.hs | 96 +-- Task/24-game-Solve/Haskell/24-game-solve-3.hs | 76 ++ Task/24-game-Solve/Java/24-game-solve.java | 264 ++++++ Task/24-game-Solve/ProDOS/24-game-solve.dos | 35 + ...{24-game-solve.pro => 24-game-solve-1.pro} | 0 Task/24-game-Solve/Prolog/24-game-solve-2.pro | 22 + Task/24-game-Solve/REXX/24-game-solve.rexx | 40 +- Task/24-game-Solve/Tcl/24-game-solve.tcl | 12 +- Task/24-game/00DESCRIPTION | 3 +- Task/24-game/Batch-File/24-game.bat | 83 ++ Task/24-game/Common-Lisp/24-game-1.lisp | 2 +- Task/24-game/Java/24-game.java | 62 ++ Task/24-game/JavaScript/24-game.js | 89 +- Task/24-game/Julia/24-game.julia | 87 +- Task/24-game/Perl-6/24-game.pl6 | 51 +- Task/24-game/Perl/24-game.pl | 132 +-- Task/24-game/Prolog/24-game.pro | 30 + Task/24-game/REXX/24-game-1.rexx | 226 +---- Task/24-game/REXX/24-game-2.rexx | 183 ++++- Task/24-game/REXX/24-game-3.rexx | 25 + Task/24-game/Ruby/24-game.rb | 2 +- Task/24-game/UNIX-Shell/24-game.sh | 30 + Task/99-Bottles-of-Beer/00DESCRIPTION | 18 +- .../ATS/99-bottles-of-beer.ats | 40 +- .../AWK/99-bottles-of-beer.awk | 28 +- ...s-of-beer.clj => 99-bottles-of-beer-1.clj} | 14 +- .../Clojure/99-bottles-of-beer-2.clj | 5 + .../Fexl/99-bottles-of-beer.fexl | 50 +- .../Frege/99-bottles-of-beer.frege | 5 +- ...les-of-beer.go => 99-bottles-of-beer-1.go} | 0 .../Go/99-bottles-of-beer-2.go | 80 ++ .../99-Bottles-of-Beer/J/99-bottles-of-beer.j | 4 + ...s-of-beer.lua => 99-bottles-of-beer-1.lua} | 0 .../Lua/99-bottles-of-beer-2.lua | 10 + .../OOC/99-bottles-of-beer.ooc | 24 + ...-beer.rebol => 99-bottles-of-beer-1.rebol} | 0 .../REBOL/99-bottles-of-beer-2.rebol | 9 + .../REBOL/99-bottles-of-beer-3.rebol | 1 + .../REXX/99-bottles-of-beer.rexx | 21 +- .../RapidQ/99-bottles-of-beer.rapidq | 13 + .../Rust/99-bottles-of-beer.rust | 48 +- .../SQL/99-bottles-of-beer-1.sql | 38 +- .../SQL/99-bottles-of-beer-2.sql | 61 +- .../SQL/99-bottles-of-beer-3.sql | 46 ++ Task/A+B/00META.yaml | 3 + Task/A+B/Aime/a+b.aime | 2 +- Task/A+B/BASIC/{a+b.basic => a+b-1.basic} | 0 Task/A+B/BASIC/a+b-2.basic | 11 + Task/A+B/C/a+b-3.c | 7 + Task/A+B/Fortran/a+b.f | 6 +- Task/A+B/Gema/a+b.gema | 1 + Task/A+B/Kite/a+b.kite | 13 + Task/A+B/M4/a+b.m4 | 4 + Task/A+B/Maple/a+b.maple | 2 +- Task/A+B/Perl/a+b.pl | 2 +- Task/A+B/Python/a+b-2.py | 6 +- Task/A+B/Scheme/a+b.ss | 4 +- Task/A+B/ZED/a+b.zed | 17 +- .../Mathematica/abstract-type.math | 26 + .../Oberon-2/abstract-type.oberon-2 | 7 + Task/Abstract-type/Seed7/abstract-type.seed7 | 5 + .../Standard-ML/abstract-type-1.ml | 6 + .../Standard-ML/abstract-type-2.ml | 6 + .../accumulator-factory.applescript | 16 + .../Elena/accumulator-factory.elena | 2 +- .../Java/accumulator-factory-3.java | 41 +- .../Java/accumulator-factory-4.java | 30 + .../Rust/accumulator-factory.rust | 19 + ...-factory.txr => accumulator-factory-1.txr} | 0 .../TXR/accumulator-factory-2.txr | 2 + Task/Ackermann-function/00DESCRIPTION | 9 +- .../Babel/ackermann-function.pb | 21 - .../C++/ackermann-function-1.cpp | 19 + .../C++/ackermann-function-2.cpp | 54 ++ .../C++/ackermann-function.cpp | 18 - .../D/ackermann-function-1.d | 2 +- .../D/ackermann-function-2.d | 17 +- .../Elena/ackermann-function.elena | 9 +- .../Elixir/ackermann-function.elixir | 5 + .../GML/ackermann-function.gml | 14 +- .../JavaScript/ackermann-function.js | 3 +- .../Julia/ackermann-function-3.julia | 5 + .../OOC/ackermann-function.ooc | 17 + .../Perl/ackermann-function-4.pl | 15 + .../Python/ackermann-function-2.py | 4 +- ...unction.rust => ackermann-function-1.rust} | 0 .../Rust/ackermann-function-2.rust | 7 + .../Scilab/ackermann-function.scilab | 23 + .../Visual-Basic/ackermann-function.vb | 29 + .../ZED/ackermann-function.zed | 39 +- .../ColdFusion/active-directory-connect.cfm | 10 + ...ariable-to-a-class-instance-at-runtime-1.m | 6 +- Task/Address-of-a-variable/00DESCRIPTION | 5 +- .../Go/address-of-a-variable-1.go | 32 +- .../REXX/address-of-a-variable.rexx | 2 +- .../RapidQ/address-of-a-variable.rapidq | 19 + Task/Align-columns/D/align-columns.d | 14 +- .../{align-columns.js => align-columns-1.js} | 0 .../JavaScript/align-columns-2.js | 48 ++ .../Oberon-2/align-columns.oberon-2 | 107 +++ Task/Align-columns/REXX/align-columns-2.rexx | 49 +- Task/Align-columns/REXX/align-columns-3.rexx | 57 +- .../Align-columns/RapidQ/align-columns.rapidq | 41 + Task/Align-columns/Ruby/align-columns.rb | 63 +- Task/Align-columns/Rust/align-columns.rust | 62 ++ .../Visual-Basic-.NET/align-columns.visual | 67 ++ .../Visual-Basic/align-columns-1.vb | 16 + .../Visual-Basic/align-columns-2.vb | 12 + .../AWK/anagrams-deranged-anagrams.awk | 59 ++ .../Clojure/anagrams-deranged-anagrams.clj | 14 +- .../D/anagrams-deranged-anagrams-3.d | 15 +- .../Groovy/anagrams-deranged-anagrams.groovy | 29 + .../Ruby/anagrams-deranged-anagrams.rb | 21 +- .../UNIX-Shell/anagrams-deranged-anagrams.sh | 47 ++ Task/Anagrams/00DESCRIPTION | 3 +- .../Component-Pascal/anagrams-3.component | 14 +- Task/Anagrams/JavaScript/anagrams-1.js | 23 + Task/Anagrams/JavaScript/anagrams-2.js | 22 + Task/Anagrams/JavaScript/anagrams.js | 20 - Task/Anagrams/Objeck/anagrams.objeck | 7 +- Task/Anagrams/Python/anagrams-2.py | 39 +- Task/Anagrams/Python/anagrams-3.py | 19 +- Task/Anagrams/RapidQ/anagrams.rapidq | 63 ++ Task/Anagrams/Rust/anagrams.rust | 40 +- Task/Anagrams/UNIX-Shell/anagrams.sh | 36 + Task/Animate-a-pendulum/00DESCRIPTION | 3 +- .../Common-Lisp/animate-a-pendulum.lisp | 45 + .../Fortran/animate-a-pendulum.f | 74 ++ ...te-a-pendulum.j => animate-a-pendulum-1.j} | 5 +- .../J/animate-a-pendulum-2.j | 52 ++ .../Scala/animate-a-pendulum.scala | 42 +- Task/Animation/00DESCRIPTION | 2 +- Task/Animation/MAXScript/animation.max | 47 ++ .../Common-Lisp/anonymous-recursion-3.lisp | 6 +- .../D/anonymous-recursion-1.d | 12 +- .../Elena/anonymous-recursion.elena | 4 +- .../PARI-GP/anonymous-recursion-1.pari | 4 + .../PARI-GP/anonymous-recursion-2.pari | 4 + .../PHP/anonymous-recursion-1.php | 15 +- .../Seed7/anonymous-recursion.seed7 | 32 + .../Standard-ML/anonymous-recursion-1.ml | 9 + .../Standard-ML/anonymous-recursion-2.ml | 11 + .../Standard-ML/anonymous-recursion-3.ml | 6 + .../TXR/anonymous-recursion.txr | 17 + .../00DESCRIPTION | 3 +- .../ACL2/apply-a-callback-to-an-array.acl2 | 7 +- .../Aime/apply-a-callback-to-an-array.aime | 2 +- .../apply-a-callback-to-an-array.applescript | 11 + .../Babel/apply-a-callback-to-an-array-1.pb | 6 + .../Babel/apply-a-callback-to-an-array-2.pb | 9 + .../Babel/apply-a-callback-to-an-array-3.pb | 9 + .../apply-a-callback-to-an-array.bracmat | 29 + .../TXR/apply-a-callback-to-an-array.txr | 2 +- .../apply-a-callback-to-an-array.vim | 4 + .../Yacas/apply-a-callback-to-an-array.yacas | 5 + ...itrary-precision-integers--included--1.pro | 8 + ...itrary-precision-integers--included--2.pro | 3 + ...rbitrary-precision-integers--included-.txr | 5 +- Task/Arena-storage-pool/00DESCRIPTION | 4 +- .../Go/arena-storage-pool.go | 56 ++ Task/Arithmetic-Complex/00DESCRIPTION | 3 +- .../Bracmat/arithmetic-complex.bracmat | 28 + .../Clojure/arithmetic-complex.clj | 37 + .../CoffeeScript/arithmetic-complex.coffee | 60 ++ .../Groovy/arithmetic-complex-1.groovy | 66 +- .../Groovy/arithmetic-complex-2.groovy | 47 +- .../Groovy/arithmetic-complex-3.groovy | 63 ++ .../Haskell/arithmetic-complex.hs | 14 + .../REXX/arithmetic-complex.rexx | 42 +- .../UNIX-Shell/arithmetic-complex.sh | 75 ++ Task/Arithmetic-Integer/00DESCRIPTION | 5 +- Task/Arithmetic-Integer/00META.yaml | 1 + .../Clipper/arithmetic-integer.clipper | 4 +- .../Elena/arithmetic-integer.elena | 15 +- .../Excel/arithmetic-integer-1.excel | 1 + .../Excel/arithmetic-integer-2.excel | 1 + .../Excel/arithmetic-integer-3.excel | 1 + .../Excel/arithmetic-integer-4.excel | 1 + .../Excel/arithmetic-integer-5.excel | 1 + .../Excel/arithmetic-integer-6.excel | 1 + .../Julia/arithmetic-integer.julia | 5 + .../Prolog/arithmetic-integer-1.pro | 9 + .../Prolog/arithmetic-integer-2.pro | 10 + .../Ruby/arithmetic-integer.rb | 9 +- .../Rust/arithmetic-integer.rust | 14 + .../Scala/arithmetic-integer.scala | 12 +- .../Vim-Script/arithmetic-integer.vim | 10 + .../D/arithmetic-rational.d | 30 +- .../Groovy/arithmetic-rational-1.groovy | 128 ++- .../Groovy/arithmetic-rational-2.groovy | 84 +- .../Groovy/arithmetic-rational-3.groovy | 103 ++- .../Groovy/arithmetic-rational-4.groovy | 25 + .../PL-I/arithmetic-rational.pli | 246 ++++++ .../Ruby/arithmetic-rational.rb | 2 +- .../Common-Lisp/arithmetic-evaluation.lisp | 24 +- .../D/arithmetic-evaluation.d | 33 +- .../Elena/arithmetic-evaluation-1.elena | 4 +- .../PicoLisp/arithmetic-evaluation-1.l | 2 +- .../REXX/arithmetic-evaluation.rexx | 16 +- .../Ruby/arithmetic-evaluation-1.rb | 22 +- .../C/arithmetic-geometric-mean.c | 54 +- .../D/arithmetic-geometric-mean.d | 12 +- .../Groovy/arithmetic-geometric-mean-1.groovy | 5 + .../Groovy/arithmetic-geometric-mean-2.groovy | 2 + .../Lua/arithmetic-geometric-mean.lua | 11 + .../OOC/arithmetic-geometric-mean.ooc | 19 + ...mean.rb => arithmetic-geometric-mean-1.rb} | 5 +- .../Ruby/arithmetic-geometric-mean-2.rb | 16 + .../Rust/arithmetic-geometric-mean.rust | 37 + .../UNIX-Shell/arithmetic-geometric-mean-1.sh | 12 + .../UNIX-Shell/arithmetic-geometric-mean-2.sh | 1 + .../UNIX-Shell/arithmetic-geometric-mean-3.sh | 1 + .../Babel/array-concatenation.pb | 2 +- ...oncatenation.f => array-concatenation-1.f} | 0 .../Fortran/array-concatenation-2.f | 12 + .../Oberon-2/array-concatenation.oberon-2 | 50 ++ .../RapidQ/array-concatenation.rapidq | 6 + .../Yacas/array-concatenation.yacas | 3 + Task/Arrays/00DESCRIPTION | 5 +- Task/Arrays/00META.yaml | 2 + Task/Arrays/Babel/arrays-1.pb | 1 + Task/Arrays/Babel/arrays-2.pb | 1 + Task/Arrays/Babel/arrays-3.pb | 1 + Task/Arrays/Babel/arrays-4.pb | 1 + Task/Arrays/Babel/arrays-5.pb | 1 + Task/Arrays/Babel/arrays-6.pb | 1 + Task/Arrays/Babel/arrays-7.pb | 4 + Task/Arrays/Babel/arrays-8.pb | 2 + Task/Arrays/Boo/arrays.boo | 8 + Task/Arrays/Bracmat/arrays.bracmat | 11 + Task/Arrays/C++/arrays.cpp | 44 + Task/Arrays/Oberon-2/arrays.oberon-2 | 36 + Task/Arrays/REXX/arrays-1.rexx | 2 +- Task/Arrays/REXX/arrays-3.rexx | 2 +- Task/Arrays/REXX/arrays-4.rexx | 2 +- Task/Arrays/Vim-Script/arrays.vim | 19 + Task/Arrays/Visual-Basic-.NET/arrays.visual | 31 + Task/Assertions/UNIX-Shell/assertions.sh | 11 + .../Babel/associative-array-creation.pb | 4 + .../Dao/associative-array-creation.dao | 6 +- .../Emacs-Lisp/associative-array-creation-1.l | 2 + .../Emacs-Lisp/associative-array-creation-2.l | 2 + .../Go/associative-array-creation.go | 17 +- .../Julia/associative-array-creation.julia | 27 + .../MATLAB/associative-array-creation-4.m | 1 + .../MATLAB/associative-array-creation-5.m | 4 + .../MATLAB/associative-array-creation-6.m | 1 + .../MATLAB/associative-array-creation-7.m | 4 + .../associative-array-creation.oberon-2 | 41 + .../PL-SQL/associative-array-creation.sql | 4 +- .../REXX/associative-array-creation-1.rexx | 8 +- .../SQL/associative-array-creation.sql | 6 + .../associative-array-creation-1.sh | 4 + .../associative-array-creation-2.sh | 1 + .../Vim-Script/associative-array-creation.vim | 20 + .../Associative-array-Iteration/00DESCRIPTION | 5 +- .../Aime/associative-array-iteration.aime | 2 +- .../Babel/associative-array-iteration.pb | 21 + .../C++/associative-array-iteration-1.cpp | 18 +- .../C++/associative-array-iteration-2.cpp | 8 +- .../Dao/associative-array-iteration.dao | 10 +- ....fth => associative-array-iteration-1.fth} | 0 .../Forth/associative-array-iteration-2.fth | 137 ++++ ...ava => associative-array-iteration-1.java} | 0 .../Java/associative-array-iteration-2.java | 15 + .../Lua/associative-array-iteration.lua | 9 +- .../Maple/associative-array-iteration-1.maple | 9 + .../Maple/associative-array-iteration-2.maple | 7 + .../Maple/associative-array-iteration-3.maple | 6 + .../Maple/associative-array-iteration-4.maple | 6 + .../Maple/associative-array-iteration.maple | 21 - .../associative-array-iteration.newlisp | 12 + .../associative-array-iteration.oberon-2 | 41 + .../REXX/associative-array-iteration.rexx | 26 +- ...on.rb => associative-array-iteration-1.rb} | 0 .../Ruby/associative-array-iteration-2.rb | 11 + .../Rust/associative-array-iteration.rust | 16 + .../Scala/associative-array-iteration.scala | 12 +- .../Scheme/associative-array-iteration-1.ss | 11 + .../Scheme/associative-array-iteration-2.ss | 11 + .../associative-array-iteration-1.sh | 2 +- .../associative-array-iteration.vim | 18 + .../D/average-loop-length.d | 6 +- .../Haskell/average-loop-length.hs | 54 ++ .../PicoLisp/average-loop-length.l | 42 + .../REXX/average-loop-length.rexx | 2 +- .../Seed7/average-loop-length.seed7 | 64 ++ .../Babel/averages-arithmetic-mean.pb | 12 + .../Befunge/averages-arithmetic-mean.bf | 5 +- .../D/averages-arithmetic-mean-1.d | 10 +- .../D/averages-arithmetic-mean-2.d | 2 +- .../D/averages-arithmetic-mean-3.d | 8 +- .../Elena/averages-arithmetic-mean.elena | 4 +- .../Elixir/averages-arithmetic-mean.elixir | 3 + .../JavaScript/averages-arithmetic-mean-1.js | 1 + .../JavaScript/averages-arithmetic-mean-2.js | 13 +- .../JavaScript/averages-arithmetic-mean-3.js | 9 + .../JavaScript/averages-arithmetic-mean-4.js | 9 + .../JavaScript/averages-arithmetic-mean-5.js | 4 + .../averages-arithmetic-mean-1.mercury | 20 + .../averages-arithmetic-mean-2.mercury | 3 + .../Prolog/averages-arithmetic-mean.pro | 4 + .../REXX/averages-arithmetic-mean.rexx | 34 +- .../Ruby/averages-arithmetic-mean.rb | 9 +- .../Rust/averages-arithmetic-mean.rust | 15 + .../Vim-Script/averages-arithmetic-mean.vim | 10 + .../XSLT/averages-arithmetic-mean-1.xslt | 1 + .../XSLT/averages-arithmetic-mean-2.xslt | 8 + .../XSLT/averages-arithmetic-mean-3.xslt | 8 + .../AutoHotkey/averages-mean-angle.ahk | 7 +- .../D/averages-mean-angle.d | 6 +- .../Euphoria/averages-mean-angle.euphoria | 26 + .../Go/averages-mean-angle-1.go | 24 +- .../Go/averages-mean-angle-2.go | 14 +- ...mean-angle.hs => averages-mean-angle-1.hs} | 0 .../Haskell/averages-mean-angle-2.hs | 17 + .../Logo/averages-mean-angle.logo | 13 + .../Pascal/averages-mean-angle.pascal | 71 ++ .../Perl/averages-mean-angle.pl | 17 + .../REXX/averages-mean-angle.rexx | 109 ++- .../Scala/averages-mean-angle.scala | 19 + Task/Averages-Mean-time-of-day/00DESCRIPTION | 8 +- .../AutoHotkey/averages-mean-time-of-day.ahk | 11 +- .../C-sharp/averages-mean-time-of-day.cs | 55 ++ .../D/averages-mean-time-of-day.d | 39 + .../averages-mean-time-of-day.euphoria | 63 ++ .../PL-I/averages-mean-time-of-day.pli | 46 ++ .../REXX/averages-mean-time-of-day.rexx | 100 +++ .../Scala/averages-mean-time-of-day.scala | 30 + Task/Averages-Median/D/averages-median.d | 6 +- .../Elixir/averages-median.elixir | 9 + .../Averages-Median/REXX/averages-median.rexx | 37 +- Task/Averages-Mode/D/averages-mode.d | 4 +- Task/Averages-Mode/Maple/averages-mode.maple | 2 + Task/Averages-Mode/REXX/averages-mode-1.rexx | 45 +- .../D/averages-pythagorean-means.d | 6 +- .../Elixir/averages-pythagorean-means.elixir | 16 + .../Erlang/averages-pythagorean-means.erl | 35 + .../Julia/averages-pythagorean-means.julia | 5 + .../Maple/averages-pythagorean-means.maple | 8 + .../OCaml/averages-pythagorean-means-2.ocaml | 11 +- .../Objeck/averages-pythagorean-means.objeck | 47 ++ .../Perl-6/averages-pythagorean-means.pl6 | 6 +- .../averages-pythagorean-means-2.ps | 12 +- .../REXX/averages-pythagorean-means.rexx | 2 +- .../Ruby/averages-pythagorean-means.rb | 4 +- .../Scala/averages-pythagorean-means.scala | 1 - .../C++/averages-root-mean-square.cpp | 4 +- .../Elixir/averages-root-mean-square.elixir | 7 + .../Emacs-Lisp/averages-root-mean-square-1.l | 5 + .../Emacs-Lisp/averages-root-mean-square-2.l | 6 + .../Excel/averages-root-mean-square.excel | 1 + .../MAXScript/averages-root-mean-square-1.max | 6 + .../MAXScript/averages-root-mean-square-2.max | 2 + .../Maple/averages-root-mean-square.maple | 5 + .../PL-I/averages-root-mean-square.pli | 10 +- ...re.pl6 => averages-root-mean-square-1.pl6} | 0 .../Perl-6/averages-root-mean-square-2.pl6 | 1 + .../REXX/averages-root-mean-square.rexx | 15 +- .../Ruby/averages-root-mean-square-1.rb | 4 +- .../Ruby/averages-root-mean-square-2.rb | 4 +- .../Yacas/averages-root-mean-square.yacas | 1 + .../00DESCRIPTION | 3 +- .../averages-simple-moving-average.bracmat | 38 + .../averages-simple-moving-average.coffee | 44 + .../D/averages-simple-moving-average-1.d | 7 +- .../D/averages-simple-moving-average-2.d | 5 +- .../averages-simple-moving-average.elena | 39 +- .../averages-simple-moving-average-1.hs | 26 + ...hs => averages-simple-moving-average-2.hs} | 0 .../averages-simple-moving-average-3.hs | 28 + ...js => averages-simple-moving-average-1.js} | 0 .../averages-simple-moving-average-2.js | 10 + .../averages-simple-moving-average-1.julia | 3 + .../averages-simple-moving-average-2.julia | 6 + ...i => averages-simple-moving-average-1.pli} | 0 .../PL-I/averages-simple-moving-average-2.pli | 45 + .../REXX/averages-simple-moving-average.rexx | 57 +- .../Aime/balanced-brackets.aime | 2 +- .../Balanced-brackets/D/balanced-brackets-3.d | 4 +- .../Elena/balanced-brackets.elena | 24 +- .../Balanced-brackets/Go/balanced-brackets.go | 9 +- .../Perl/balanced-brackets-3.pl | 9 +- .../Perl/balanced-brackets-4.pl | 8 + .../Scala/balanced-brackets-2.scala | 28 +- .../Scala/balanced-brackets-3.scala | 19 + .../TXR/balanced-brackets.txr | 16 +- .../UNIX-Shell/balanced-brackets.sh | 38 + .../Balanced-ternary/ATS/balanced-ternary.ats | 213 +++++ Task/Balanced-ternary/D/balanced-ternary.d | 14 +- .../Icon/balanced-ternary.icon | 90 ++ .../PicoLisp/balanced-ternary.l | 122 +++ Task/Best-shuffle/D/best-shuffle-1.d | 6 +- Task/Best-shuffle/D/best-shuffle-2.d | 24 +- Task/Best-shuffle/Elena/best-shuffle.elena | 20 +- Task/Best-shuffle/Go/best-shuffle.go | 4 +- Task/Best-shuffle/Java/best-shuffle.java | 14 +- Task/Best-shuffle/Python/best-shuffle-2.py | 2 +- Task/Best-shuffle/REXX/best-shuffle-2.rexx | 17 +- Task/Binary-digits/Aime/binary-digits.aime | 3 +- Task/Binary-digits/C++/binary-digits.cpp | 35 +- Task/Binary-digits/D/binary-digits.d | 6 +- .../Binary-digits/Delphi/binary-digits.delphi | 56 +- .../Oberon-2/binary-digits.oberon-2 | 85 ++ Task/Binary-digits/Rust/binary-digits.rust | 5 + Task/Binary-digits/Scala/binary-digits.scala | 17 +- Task/Binary-digits/Seed7/binary-digits.seed7 | 2 +- .../Vim-Script/binary-digits.vim | 21 + .../CoffeeScript/binary-search-1.coffee | 8 + .../CoffeeScript/binary-search-2.coffee | 9 + .../CoffeeScript/binary-search-3.coffee | 8 + .../CoffeeScript/binary-search.coffee | 16 - Task/Binary-search/D/binary-search.d | 12 +- Task/Binary-search/Eiffel/binary-search.e | 120 +++ .../Binary-search/Julia/binary-search-1.julia | 4 +- Task/Binary-search/Lua/binary-search-2.lua | 1 + Task/Binary-search/Prolog/binary-search.pro | 23 + ...ary-search.scala => binary-search-1.scala} | 0 .../Binary-search/Scala/binary-search-2.scala | 10 + .../Binary-search/Scala/binary-search-3.scala | 10 + Task/Binary-strings/D/binary-strings.d | 52 +- Task/Bitcoin-address-validation/00DESCRIPTION | 10 +- Task/Bitcoin-address-validation/00META.yaml | 3 + .../D/bitcoin-address-validation.d | 14 +- .../Perl-6/bitcoin-address-validation.pl6 | 2 +- .../Perl/bitcoin-address-validation.pl | 11 +- .../PicoLisp/bitcoin-address-validation.l | 43 + .../Ruby/bitcoin-address-validation.rb | 16 + .../D/bitmap-b-zier-curves-cubic.d | 2 +- .../XPL0/bitmap-b-zier-curves-cubic.xpl0 | 24 +- .../D/bitmap-b-zier-curves-quadratic.d | 2 +- .../00DESCRIPTION | 2 +- .../bitmap-bresenhams-line-algorithm.bat | 128 +++ .../C++/bitmap-bresenhams-line-algorithm.cpp | 24 +- .../bitmap-bresenhams-line-algorithm.clj | 8 +- .../bitmap-bresenhams-line-algorithm.lisp | 32 +- .../D/bitmap-bresenhams-line-algorithm.d | 2 +- .../bitmap-bresenhams-line-algorithm.delphi | 72 ++ .../bitmap-bresenhams-line-algorithm.java | 93 +++ .../bitmap-bresenhams-line-algorithm-3.pli | 51 ++ .../bitmap-bresenhams-line-algorithm.pro | 36 + .../bitmap-bresenhams-line-algorithm-1.rexx | 43 + .../bitmap-bresenhams-line-algorithm-2.rexx | 44 + .../bitmap-bresenhams-line-algorithm.rexx | 64 -- Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d | 5 +- .../Scala/bitmap-flood-fill.scala | 43 + .../Standard-ML/bitmap-flood-fill.ml | 49 ++ Task/Bitmap-Histogram/D/bitmap-histogram.d | 4 +- .../Racket/bitmap-histogram.rkt | 62 ++ .../00DESCRIPTION | 4 +- .../D/bitmap-midpoint-circle-algorithm.d | 7 +- .../bitmap-midpoint-circle-algorithm-4.mod3 | 63 +- .../bitmap-midpoint-circle-algorithm-5.mod3 | 27 + .../PL-I/bitmap-midpoint-circle-algorithm.pli | 52 ++ .../bitmap-midpoint-circle-algorithm.rexx | 84 +- .../UNIX-Shell/bitmap-read-a-ppm-file-1.sh | 11 + .../UNIX-Shell/bitmap-read-a-ppm-file-2.sh | 39 + .../UNIX-Shell/bitmap-read-a-ppm-file-3.sh | 13 + .../Modula-3/bitmap-write-a-ppm-file-3.mod3 | 21 +- .../Modula-3/bitmap-write-a-ppm-file-4.mod3 | 14 + .../Perl-6/bitmap-write-a-ppm-file.pl6 | 21 +- .../UNIX-Shell/bitmap-write-a-ppm-file-1.sh | 3 + .../UNIX-Shell/bitmap-write-a-ppm-file-2.sh | 3 + Task/Bitmap/00DESCRIPTION | 11 +- Task/Bitmap/D/bitmap.d | 34 +- Task/Bitmap/Go/bitmap-1.go | 57 ++ Task/Bitmap/Go/{bitmap.go => bitmap-2.go} | 0 Task/Bitmap/J/bitmap-2.j | 1 + Task/Bitmap/Perl-6/bitmap.pl6 | 42 +- Task/Bitmap/REXX/bitmap-1.rexx | 37 + Task/Bitmap/REXX/bitmap-2.rexx | 111 +++ Task/Bitmap/REXX/bitmap.rexx | 35 - Task/Bitmap/UNIX-Shell/bitmap.sh | 74 ++ Task/Bitwise-IO/D/bitwise-io.d | 10 +- .../Babel/bitwise-operations-1.pb | 10 + .../Babel/bitwise-operations-2.pb | 11 + .../Bitwise-operations/D/bitwise-operations.d | 2 +- .../Elena/bitwise-operations.elena | 4 +- .../PHP/bitwise-operations.php | 18 +- .../PL-I/bitwise-operations.pli | 10 +- .../Perl-6/bitwise-operations.pl6 | 28 + .../REXX/bitwise-operations.rexx | 3 +- .../Scheme/bitwise-operations-1.ss | 2 + Task/Boolean-values/00DESCRIPTION | 3 +- Task/Boolean-values/00META.yaml | 2 + .../Oberon-2/boolean-values.oberon-2 | 6 + Task/Boolean-values/PL-I/boolean-values-1.pli | 3 + Task/Boolean-values/PL-I/boolean-values-2.pli | 11 + Task/Boolean-values/PL-I/boolean-values.pli | 1 - .../Vim-Script/boolean-values.vim | 5 + ...{box-the-compass.d => box-the-compass-1.d} | 0 Task/Box-the-compass/D/box-the-compass-2.d | 24 + .../OCaml/box-the-compass.ocaml | 31 + .../OoRexx/box-the-compass.rexx | 259 ++++++ Task/Break-OO-privacy/00DESCRIPTION | 20 +- Task/Break-OO-privacy/00META.yaml | 3 + .../Clojure/break-oo-privacy-1.clj | 7 + .../Clojure/break-oo-privacy-2.clj | 2 + .../Break-OO-privacy/Go/break-oo-privacy-1.go | 82 ++ .../Break-OO-privacy/Go/break-oo-privacy-2.go | 17 + .../Objective-C/break-oo-privacy-1.m | 4 +- .../Objective-C/break-oo-privacy-2.m | 4 +- .../Objective-C/break-oo-privacy-3.m | 4 +- .../Scala/break-oo-privacy.scala | 22 + Task/Brownian-tree/D/brownian-tree.d | 18 +- ...rownian-tree.java => brownian-tree-1.java} | 0 Task/Brownian-tree/Java/brownian-tree-2.java | 90 ++ Task/Brownian-tree/REXX/brownian-tree.rexx | 132 +-- .../Common-Lisp/bulls-and-cows-player.lisp | 43 + .../D/bulls-and-cows-player.d | 30 +- .../MATLAB/bulls-and-cows-player.m | 58 ++ .../REXX/bulls-and-cows-player.rexx | 63 ++ Task/Bulls-and-cows/D/bulls-and-cows.d | 11 +- .../Bulls-and-cows/Elena/bulls-and-cows.elena | 12 +- Task/Bulls-and-cows/Go/bulls-and-cows.go | 68 ++ Task/Bulls-and-cows/MATLAB/bulls-and-cows.m | 62 ++ .../MAXScript/bulls-and-cows-1.max | 69 ++ .../MAXScript/bulls-and-cows-2.max | 20 + .../Bulls-and-cows/REXX/bulls-and-cows-1.rexx | 56 +- Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb | 30 +- Task/Bulls-and-cows/Rust/bulls-and-cows.rust | 110 ++- .../Bulls-and-cows/Seed7/bulls-and-cows.seed7 | 49 ++ Task/CRC-32/00DESCRIPTION | 9 +- Task/CRC-32/00META.yaml | 2 + Task/CRC-32/C++/crc-32-1.cpp | 80 +- Task/CRC-32/D/crc-32.d | 6 +- Task/CRC-32/Oberon-2/crc-32.oberon-2 | 11 + Task/CRC-32/PicoLisp/crc-32.l | 27 + Task/CRC-32/REXX/crc-32.rexx | 53 +- Task/CSV-to-HTML-translation/00DESCRIPTION | 19 +- .../D/csv-to-html-translation-1.d | 53 +- .../JavaScript/csv-to-html-translation-1.js | 32 +- .../JavaScript/csv-to-html-translation-2.js | 21 +- .../JavaScript/csv-to-html-translation-3.js | 31 +- .../Mathematica/csv-to-html-translation.math | 20 - .../Maxima/csv-to-html-translation-1.maxima | 11 +- .../Oberon-2/csv-to-html-translation.oberon-2 | 72 ++ .../REXX/csv-to-html-translation.rexx | 36 + .../Scala/csv-to-html-translation-1.scala | 73 +- .../Scala/csv-to-html-translation-2.scala | 61 +- .../UNIX-Shell/csv-to-html-translation-1.sh | 42 + .../UNIX-Shell/csv-to-html-translation-2.sh | 12 + Task/Caesar-cipher/00DESCRIPTION | 12 +- Task/Caesar-cipher/00META.yaml | 2 + Task/Caesar-cipher/Babel/caesar-cipher.pb | 52 ++ Task/Caesar-cipher/D/caesar-cipher-1.d | 6 +- Task/Caesar-cipher/D/caesar-cipher-3.d | 4 +- Task/Caesar-cipher/Eiffel/caesar-cipher.e | 53 ++ Task/Caesar-cipher/Elena/caesar-cipher.elena | 6 +- .../Groovy/caesar-cipher-1.groovy | 13 + .../Groovy/caesar-cipher-2.groovy | 7 + .../Groovy/caesar-cipher-3.groovy | 4 + .../Groovy/caesar-cipher-4.groovy | 4 + .../Groovy/caesar-cipher-5.groovy | 5 + .../Groovy/caesar-cipher-6.groovy | 10 + .../Caesar-cipher/Groovy/caesar-cipher.groovy | 24 - Task/Caesar-cipher/Java/caesar-cipher.java | 48 +- .../Mathematica/caesar-cipher.math | 2 +- Task/Caesar-cipher/OOC/caesar-cipher.ooc | 19 + .../Oberon-2/caesar-cipher.oberon-2 | 59 ++ Task/Caesar-cipher/Perl/caesar-cipher.pl | 12 +- .../PowerShell/caesar-cipher.psh | 75 ++ Task/Caesar-cipher/REXX/caesar-cipher-1.rexx | 14 +- Task/Caesar-cipher/REXX/caesar-cipher-2.rexx | 15 +- .../Caesar-cipher/UNIX-Shell/caesar-cipher.sh | 56 ++ Task/Calendar/00DESCRIPTION | 6 +- Task/Calendar/D/calendar.d | 2 +- Task/Calendar/Haskell/calendar.hs | 92 +++ Task/Calendar/Java/calendar.java | 57 ++ Task/Calendar/Ruby/calendar.rb | 2 +- .../Lua/call-a-foreign-language-function.lua | 14 + ...call-a-foreign-language-function-1.mercury | 2 +- .../R/call-a-function-in-a-shared-library-1.r | 2 + .../R/call-a-function-in-a-shared-library-2.r | 1 + .../call-a-function-in-a-shared-library.scala | 26 + Task/Call-a-function/00META.yaml | 1 + .../ALGOL-68/call-a-function.alg | 28 + Task/Call-a-function/D/call-a-function.d | 103 +++ .../Call-a-function/Forth/call-a-function.fth | 25 + .../Call-a-function/Fortran/call-a-function.f | 70 ++ Task/Call-a-function/Go/call-a-function-1.go | 11 + Task/Call-a-function/Go/call-a-function-2.go | 9 + Task/Call-a-function/Go/call-a-function-3.go | 8 + Task/Call-a-function/Go/call-a-function-4.go | 1 + Task/Call-a-function/Go/call-a-function-5.go | 1 + Task/Call-a-function/Go/call-a-function-6.go | 9 + Task/Call-a-function/Go/call-a-function-7.go | 4 + Task/Call-a-function/Go/call-a-function-8.go | 2 + .../Maple/call-a-function-1.maple | 1 + .../Maple/call-a-function-2.maple | 1 + .../Maple/call-a-function-3.maple | 1 + .../Maple/call-a-function-4.maple | 1 + .../Maple/call-a-function-5.maple | 1 + .../Maple/call-a-function-6.maple | 1 + .../Maple/call-a-function-7.maple | 1 + .../Maple/call-a-function-8.maple | 1 + .../Maple/call-a-function-9.maple | 2 + .../Call-a-function/Perl/call-a-function-1.pl | 4 + .../Call-a-function/Perl/call-a-function-2.pl | 1 + .../Call-a-function/Perl/call-a-function-3.pl | 1 + .../Call-a-function/Perl/call-a-function-4.pl | 1 + .../Call-a-function/Perl/call-a-function-5.pl | 3 + .../Call-a-function/Python/call-a-function.py | 19 + Task/Call-a-function/R/call-a-function.r | 58 ++ .../Scala/call-a-function.scala | 65 ++ .../Call-a-function/XSLT/call-a-function.xslt | 277 +++++++ .../Clojure/call-an-object-method.clj | 5 + .../Maple/call-an-object-method-1.maple | 2 + .../Maple/call-an-object-method-2.maple | 2 + .../Rust/call-an-object-method.rust | 26 + Task/Canny-edge-detector/00META.yaml | 2 + .../D/canny-edge-detector.d | 47 +- .../C/carmichael-3-strong-pseudoprimes.c | 48 ++ .../D/carmichael-3-strong-pseudoprimes.d | 4 +- .../carmichael-3-strong-pseudoprimes.icon | 24 + .../Perl/carmichael-3-strong-pseudoprimes.pl | 17 + .../carmichael-3-strong-pseudoprimes.l | 40 + .../carmichael-3-strong-pseudoprimes.py | 2 +- .../carmichael-3-strong-pseudoprimes.rexx | 44 + .../case-sensitivity-of-identifiers.elixir | 4 + .../case-sensitivity-of-identifiers.oberon-2 | 12 + Task/Catalan-numbers/00DESCRIPTION | 4 + .../Bracmat/catalan-numbers-1.bracmat | 4 +- .../Bracmat/catalan-numbers-2.bracmat | 17 + Task/Catalan-numbers/D/catalan-numbers.d | 31 +- .../Eiffel/catalan-numbers-1.e | 19 + .../Eiffel/catalan-numbers-2.e | 24 + Task/Catalan-numbers/GAP/catalan-numbers.gap | 8 +- .../Maple/catalan-numbers.maple | 4 + .../PARI-GP/catalan-numbers-1.pari | 2 +- .../PARI-GP/catalan-numbers-2.pari | 2 +- .../PARI-GP/catalan-numbers-3.pari | 2 +- .../PARI-GP/catalan-numbers-4.pari | 2 +- .../PARI-GP/catalan-numbers-5.pari | 2 +- .../Perl-6/catalan-numbers.pl6 | 4 +- .../Catalan-numbers/Perl/catalan-numbers-1.pl | 7 +- .../Catalan-numbers/Perl/catalan-numbers-3.pl | 6 + .../REXX/catalan-numbers-1.rexx | 31 + .../REXX/catalan-numbers-2.rexx | 51 ++ .../Catalan-numbers/REXX/catalan-numbers.rexx | 47 -- .../Run-BASIC/catalan-numbers.run | 7 +- .../Catalan-numbers/Rust/catalan-numbers.rust | 13 + Task/Character-codes/00DESCRIPTION | 6 +- Task/Character-codes/00META.yaml | 1 + .../Babel/character-codes-1.pb | 2 + .../Babel/character-codes-2.pb | 1 + Task/Character-codes/D/character-codes.d | 11 +- Task/Character-codes/Eiffel/character-codes.e | 28 + .../Elena/character-codes.elena | 2 +- .../Frink/character-codes.frink | 1 + Task/Character-codes/Go/character-codes-2.go | 23 +- .../JavaScript/character-codes.js | 4 +- .../Vim-Script/character-codes.vim | 6 + Task/Chat-server/Go/chat-server.go | 281 ++++--- .../{chat-server.hs => chat-server-1.hs} | 0 Task/Chat-server/Haskell/chat-server-2.hs | 27 + .../D/check-machin-like-formulas.d | 6 +- .../PARI-GP/check-machin-like-formulas.pari | 31 + .../REXX/check-machin-like-formulas.rexx | 48 +- Task/Check-that-file-exists/00DESCRIPTION | 3 +- Task/Check-that-file-exists/00META.yaml | 2 + .../Emacs-Lisp/check-that-file-exists.l | 4 + .../NewLISP/check-that-file-exists.newlisp | 7 + .../Prolog/check-that-file-exists.pro | 5 + .../Scala/check-that-file-exists.scala | 22 +- Task/Cholesky-decomposition/00DESCRIPTION | 2 +- .../D/cholesky-decomposition.d | 20 +- .../J/cholesky-decomposition-1.j | 3 +- .../Smalltalk/cholesky-decomposition.st | 22 + Task/Classes/00DESCRIPTION | 26 +- Task/Classes/Clojure/classes.clj | 9 + .../Java/{classes.java => classes-1.java} | 6 +- Task/Classes/Java/classes-2.java | 1 + Task/Classes/Objective-C/classes-2.m | 7 +- Task/Classes/REALbasic/classes-1.realbasic | 14 + Task/Classes/REALbasic/classes-2.realbasic | 2 + Task/Classes/Ruby/classes.rb | 19 +- Task/Classes/UNIX-Shell/classes.sh | 19 + Task/Closest-pair-problem/00DESCRIPTION | 8 +- .../C++/closest-pair-problem.cpp | 115 +++ .../D/closest-pair-problem-1.d | 7 +- .../D/closest-pair-problem-2.d | 2 +- .../REXX/closest-pair-problem.rexx | 61 +- .../Ruby/closest-pair-problem.rb | 45 +- .../Scala/closest-pair-problem.scala | 145 +++- Task/Collections/00DESCRIPTION | 4 +- Task/Collections/00META.yaml | 2 + Task/Collections/Java/collections-5.java | 5 +- Task/Collections/Maple/collections-1.maple | 5 + Task/Collections/Maple/collections-2.maple | 2 + Task/Collections/Maple/collections-3.maple | 2 + Task/Collections/Maple/collections-4.maple | 2 + Task/Collections/Ruby/collections-1.rb | 1 - Task/Collections/Ruby/collections-2.rb | 1 - Task/Collections/Ruby/collections-4.rb | 21 + Task/Collections/Ruby/collections-5.rb | 24 + Task/Collections/Ruby/collections-6.rb | 23 + ...{collections.scala => collections-1.scala} | 0 Task/Collections/Scala/collections-2.scala | 30 + Task/Collections/Scheme/collections-3.ss | 3 +- Task/Collections/Scheme/collections-4.ss | 3 +- Task/Collections/Scheme/collections-5.ss | 3 +- Task/Collections/Scheme/collections-6.ss | 3 +- Task/Collections/UNIX-Shell/collections-1.sh | 9 + Task/Collections/UNIX-Shell/collections-2.sh | 9 + Task/Collections/UNIX-Shell/collections-3.sh | 1 + Task/Collections/UNIX-Shell/collections-4.sh | 1 + .../Ruby/color-of-a-screen-pixel.rb | 12 + .../Scala/color-of-a-screen-pixel.scala | 1 + ...-quantization.d => color-quantization-1.d} | 48 +- .../D/color-quantization-2.d | 447 ++++++++++ .../Haskell/color-quantization.hs | 128 +++ .../Factor/colour-bars-display.factor | 23 + .../REXX/colour-bars-display.rexx | 26 + Task/Colour-pinstripe-Display/00DESCRIPTION | 2 + .../Java/colour-pinstripe-display.java | 38 + .../00DESCRIPTION | 4 +- .../AWK/combinations-with-repetitions.awk | 23 + .../combinations-with-repetitions.bracmat | 19 + .../Clojure/combinations-with-repetitions.clj | 6 + .../combinations-with-repetitions.coffee | 12 + .../D/combinations-with-repetitions-1.d | 15 +- .../Erlang/combinations-with-repetitions.erl | 9 + .../Go/combinations-with-repetitions-3.go | 8 +- .../combinations-with-repetitions.js | 24 + .../Julia/combinations-with-repetitions.julia | 4 + .../Lua/combinations-with-repetitions.lua | 46 ++ .../PHP/combinations-with-repetitions.php | 32 + ....pl => combinations-with-repetitions-1.pl} | 0 .../Perl/combinations-with-repetitions-2.pl | 8 + .../REXX/combinations-with-repetitions.rexx | 49 +- .../Ruby/combinations-with-repetitions.rb | 4 + Task/Combinations/00DESCRIPTION | 1 + .../AppleScript/combinations.applescript | 27 + .../CoffeeScript/combinations.coffee | 25 + Task/Combinations/D/combinations-2.d | 5 +- Task/Combinations/D/combinations-3.d | 176 ++-- Task/Combinations/Eiffel/combinations-1.e | 96 +++ Task/Combinations/Eiffel/combinations-2.e | 14 + Task/Combinations/Elena/combinations.elena | 8 +- .../{combinations.erl => combinations-1.erl} | 0 Task/Combinations/Erlang/combinations-2.erl | 13 + Task/Combinations/Lua/combinations.lua | 33 - Task/Combinations/Maple/combinations.maple | 4 + Task/Combinations/Perl-6/combinations-2.pl6 | 19 +- Task/Combinations/Perl-6/combinations-3.pl6 | 10 + Task/Combinations/Perl/combinations-1.pl | 2 + Task/Combinations/Perl/combinations-2.pl | 3 + Task/Combinations/Perl/combinations-3.pl | 5 + Task/Combinations/Perl/combinations.pl | 4 - Task/Combinations/Prolog/combinations-2.pro | 22 +- Task/Combinations/Prolog/combinations-3.pro | 13 +- Task/Combinations/REXX/combinations.rexx | 29 +- Task/Combinations/Scala/combinations-2.scala | 10 +- Task/Combinations/Scala/combinations-3.scala | 16 + Task/Combinations/Scala/combinations-4.scala | 2 + Task/Combinations/Smalltalk/combinations.st | 4 +- .../PHP/command-line-arguments.php | 2 +- .../Scala/command-line-arguments-1.scala | 6 +- .../Scala/command-line-arguments-2.scala | 2 +- ...ments.txr => command-line-arguments-1.txr} | 0 .../TXR/command-line-arguments-2.txr | 4 + Task/Comments/00DESCRIPTION | 3 +- Task/Comments/00META.yaml | 2 + Task/Comments/360-Assembly/comments.360 | 5 +- Task/Comments/ALGOL-60/comments.alg | 4 + Task/Comments/ALGOL-W/comments.alg | 8 + Task/Comments/BASIC/comments-1.basic | 2 +- Task/Comments/Elixir/comments.elixir | 1 + .../JCL/{comments.jcl => comments-1.jcl} | 0 Task/Comments/JCL/comments-2.jcl | 1 + Task/Comments/Oberon-2/comments.oberon-2 | 6 + .../PL-I/{comments.pli => comments-1.pli} | 0 Task/Comments/PL-I/comments-2.pli | 3 + Task/Comments/SQL/comments-1.sql | 1 + Task/Comments/SQL/comments-2.sql | 2 + Task/Comments/SQL/comments-3.sql | 2 + Task/Comments/Scilab/comments.scilab | 2 + Task/Comments/Simula/comments.simula | 1 + Task/Comments/TorqueScript/comments.torque | 1 + Task/Comments/VBA/comments.vba | 1 + Task/Comments/VBScript/comments.vb | 1 + Task/Comments/Vim-Script/comments.vim | 2 + .../D/compile-time-calculation-1.d | 8 +- .../compile-time-calculation.oberon-2 | 8 + Task/Compound-data-type/00DESCRIPTION | 3 +- .../AWK/compound-data-type.awk | 13 +- .../Euphoria/compound-data-type.euphoria | 11 + .../UNIX-Shell/compound-data-type-1.sh | 11 + .../UNIX-Shell/compound-data-type-2.sh | 5 + .../Vim-Script/compound-data-type.vim | 9 + .../PowerShell/concurrent-computing-1.psh | 10 + .../PowerShell/concurrent-computing-2.psh | 16 + .../Prolog/concurrent-computing.pro | 12 + .../Rust/concurrent-computing.rust | 8 +- Task/Conditional-structures/00DESCRIPTION | 4 +- .../360-Assembly/conditional-structures.360 | 48 ++ .../AWK/conditional-structures-2.awk | 6 +- .../AWK/conditional-structures-3.awk | 1 + .../Babel/conditional-structures-1.pb | 1 + .../Babel/conditional-structures-2.pb | 5 + .../Babel/conditional-structures-3.pb | 6 + .../Batch-File/conditional-structures-1.bat | 14 + .../Batch-File/conditional-structures-2.bat | 5 + .../Dao/conditional-structures-1.dao | 2 +- .../Dao/conditional-structures-2.dao | 2 +- .../PL-I/conditional-structures-1.pli | 24 +- .../PL-I/conditional-structures-2.pli | 33 +- .../PL-I/conditional-structures-3.pli | 19 +- .../PL-I/conditional-structures-4.pli | 21 + .../Pascal/conditional-structures-1.pascal | 8 +- .../REXX/conditional-structures-1.rexx | 32 +- .../REXX/conditional-structures-2.rexx | 29 +- .../REXX/conditional-structures-3.rexx | 2 +- .../Scala/conditional-structures.scala | 11 + .../Scheme/conditional-structures-4.ss | 3 +- .../Scheme/conditional-structures-5.ss | 10 +- .../Scheme/conditional-structures-6.ss | 10 +- .../Scheme/conditional-structures-7.ss | 13 +- .../conditional-structures-1.ti-83 | 2 + .../conditional-structures-2.ti-83 | 1 + .../conditional-structures-3.ti-83 | 4 + .../conditional-structures-4.ti-83 | 6 + .../VBScript/conditional-structures-1.vb | 14 + .../VBScript/conditional-structures-2.vb | 3 + .../VBScript/conditional-structures-3.vb | 19 + .../VBScript/conditional-structures.vb | 5 - Task/Constrained-genericity/00DESCRIPTION | 16 +- .../Racket/constrained-genericity.rkt | 86 ++ .../constrained-random-points-on-a-circle.clj | 16 +- ...nstrained-random-points-on-a-circle.elixir | 30 + ...nstrained-random-points-on-a-circle.falcon | 17 + ...onstrained-random-points-on-a-circle.maple | 12 + ...nstrained-random-points-on-a-circle-1.pli} | 0 ...onstrained-random-points-on-a-circle-2.pli | 43 + ...nstrained-random-points-on-a-circle-1.rexx | 37 +- ...nstrained-random-points-on-a-circle-2.rexx | 39 +- ...nstrained-random-points-on-a-circle-3.rexx | 40 + ...nstrained-random-points-on-a-circle-4.rexx | 78 ++ ...onstrained-random-points-on-a-circle-1.rb} | 16 +- ...constrained-random-points-on-a-circle-2.rb | 10 + ...onstrained-random-points-on-a-circle.scala | 98 +-- ...ithmetic-construct-from-rational-number.pl | 26 + .../ATS/continued-fraction.ats | 89 +- .../AutoHotkey/continued-fraction-1.ahk | 47 ++ .../AutoHotkey/continued-fraction-2.ahk | 3 + .../AutoHotkey/continued-fraction-3.ahk | 3 + Task/Conways-Game-of-Life/00DESCRIPTION | 6 +- .../AWK/conways-game-of-life.awk | 12 +- .../BASIC256/conways-game-of-life-1.basic256 | 8 + ...sic256 => conways-game-of-life-2.basic256} | 9 +- .../D/conways-game-of-life-1.d | 23 +- .../D/conways-game-of-life-2.d | 36 +- .../Julia/conways-game-of-life.julia | 11 + .../Pascal/conways-game-of-life.pascal | 179 ++++ .../Perl-6/conways-game-of-life.pl6 | 3 +- .../Python/conways-game-of-life-2.py | 12 +- .../REXX/conways-game-of-life-1.rexx | 53 ++ .../REXX/conways-game-of-life-2.rexx | 185 +++++ .../REXX/conways-game-of-life.rexx | 70 -- .../Ruby/conways-game-of-life-1.rb | 16 +- .../Ruby/conways-game-of-life-2.rb | 205 ++--- .../conways-game-of-life.vedit | 58 ++ Task/Copy-a-string/00DESCRIPTION | 5 +- Task/Copy-a-string/00META.yaml | 1 + Task/Copy-a-string/Babel/copy-a-string.pb | 4 + Task/Copy-a-string/REXX/copy-a-string.rexx | 1 - Task/Copy-a-string/Ruby/copy-a-string-1.rb | 9 + Task/Copy-a-string/Ruby/copy-a-string-2.rb | 7 + Task/Copy-a-string/Ruby/copy-a-string.rb | 4 - .../Vim-Script/copy-a-string.vim | 6 + .../Count-in-factors/Ada/count-in-factors.ada | 43 +- .../Count-in-factors/C++/count-in-factors.cpp | 37 + .../Eiffel/count-in-factors.e | 33 + .../Perl/count-in-factors-1.pl | 2 + .../Perl/count-in-factors-2.pl | 6 + .../Perl/count-in-factors-3.pl | 2 + .../Perl/count-in-factors-4.pl | 16 + .../Perl/count-in-factors-5.pl | 16 + .../Perl/count-in-factors-6.pl | 32 + .../Count-in-factors/Perl/count-in-factors.pl | 26 - .../REXX/count-in-factors.rexx | 6 +- Task/Count-in-octal/00META.yaml | 5 + Task/Count-in-octal/D/count-in-octal.d | 4 +- Task/Count-in-octal/REXX/count-in-octal.rexx | 13 +- Task/Count-in-octal/Ruby/count-in-octal.rb | 5 + .../Count-in-octal/Seed7/count-in-octal.seed7 | 2 +- .../Vim-Script/count-in-octal.vim | 5 + .../00DESCRIPTION | 7 +- ... count-occurrences-of-a-substring-1.basic} | 0 .../count-occurrences-of-a-substring-2.basic | 20 + .../count-occurrences-of-a-substring.pari | 14 + .../count-occurrences-of-a-substring-1.pro | 16 + .../count-occurrences-of-a-substring-2.pro | 5 + .../count-occurrences-of-a-substring.rexx | 17 +- ... count-occurrences-of-a-substring-1.scala} | 3 - .../count-occurrences-of-a-substring-2.scala | 1 + .../count-occurrences-of-a-substring-3.scala | 2 + .../count-occurrences-of-a-substring.ss | 6 + .../ALGOL-68/count-the-coins.alg | 31 + .../Clojure/count-the-coins.clj | 14 + .../Common-Lisp/count-the-coins-1.lisp | 18 + .../Common-Lisp/count-the-coins-2.lisp | 6 + .../Common-Lisp/count-the-coins.lisp | 23 - Task/Count-the-coins/D/count-the-coins-1.d | 8 +- Task/Count-the-coins/D/count-the-coins-2.d | 53 +- Task/Count-the-coins/D/count-the-coins-3.d | 64 +- Task/Count-the-coins/D/count-the-coins-4.d | 76 +- Task/Count-the-coins/D/count-the-coins-5.d | 32 + .../REXX/count-the-coins-1.rexx | 21 + .../REXX/count-the-coins-2.rexx | 24 + .../Count-the-coins/REXX/count-the-coins.rexx | 23 - .../00DESCRIPTION | 18 +- .../00META.yaml | 2 + .../create-a-file-on-magnetic-tape.cobol | 22 + .../create-a-file-on-magnetic-tape.clj | 1 + .../Go/create-a-file-on-magnetic-tape.go | 53 ++ .../Icon/create-a-file-on-magnetic-tape.icon | 3 + .../REXX/create-a-file-on-magnetic-tape.rexx | 9 - Task/Create-a-file/00META.yaml | 2 + Task/Create-a-file/Fortran/create-a-file.f | 8 + Task/Create-a-file/Maple/create-a-file.maple | 4 + Task/Create-a-file/Scala/create-a-file.scala | 12 + ...ate-a-two-dimensional-array-at-runtime-2.c | 130 ++- ...ate-a-two-dimensional-array-at-runtime-3.c | 24 +- ...ate-a-two-dimensional-array-at-runtime-4.c | 30 +- ...ate-a-two-dimensional-array-at-runtime-5.c | 18 + ...e-a-two-dimensional-array-at-runtime-1.pl6 | 4 +- ...te-a-two-dimensional-array-at-runtime.rexx | 66 +- ...ate-a-two-dimensional-array-at-runtime.vim | 29 + .../C-sharp/create-an-html-table-2.cs | 47 +- .../Clojure/create-an-html-table.clj | 11 + .../D/create-an-html-table.d | 6 +- .../Go/create-an-html-table-1.go | 8 +- .../PowerShell/create-an-html-table-1.psh | 7 + .../PowerShell/create-an-html-table-2.psh | 25 + .../PowerShell/create-an-html-table-3.psh | 1 + .../create-an-html-table-1.purebasic | 40 + .../create-an-html-table-2.purebasic | 9 + .../REXX/create-an-html-table.rexx | 52 +- .../Scala/create-an-html-table.scala | 17 + .../UNIX-Shell/create-an-html-table.sh | 38 + .../XSLT/create-an-html-table-1.xslt | 58 ++ .../XSLT/create-an-html-table-2.xslt | 18 + .../XSLT/create-an-html-table-3.xslt | 45 + Task/Cut-a-rectangle/D/cut-a-rectangle.d | 16 +- Task/Cut-a-rectangle/Go/cut-a-rectangle.go | 82 ++ .../Perl-6/cut-a-rectangle.pl6 | 75 ++ Task/Cut-a-rectangle/Perl/cut-a-rectangle.pl | 82 ++ .../Cut-a-rectangle/REXX/cut-a-rectangle.rexx | 51 +- .../Cut-a-rectangle/Ruby/cut-a-rectangle-1.rb | 40 + .../Cut-a-rectangle/Ruby/cut-a-rectangle-2.rb | 74 ++ Task/DNS-query/R/dns-query-1.r | 47 ++ Task/DNS-query/R/dns-query-2.r | 5 + Task/DNS-query/REXX/dns-query.rexx | 10 +- Task/DNS-query/Scala/dns-query.scala | 9 + Task/Date-format/JavaScript/date-format.js | 15 +- Task/Date-format/Prolog/date-format.pro | 5 + Task/Date-format/REXX/date-format-1.rexx | 12 + Task/Date-format/REXX/date-format-2.rexx | 28 + Task/Date-format/REXX/date-format-3.rexx | 6 + Task/Date-format/REXX/date-format.rexx | 11 - Task/Date-format/Ruby/date-format.rb | 1 + Task/Date-format/Smalltalk/date-format.st | 4 + Task/Date-manipulation/00DESCRIPTION | 6 +- Task/Date-manipulation/00META.yaml | 2 + .../Date-manipulation/J/date-manipulation-1.j | 27 + .../Date-manipulation/J/date-manipulation-2.j | 6 + .../JavaScript/date-manipulation.js | 60 +- .../Ruby/date-manipulation-3.rb | 6 + Task/Day-of-the-week/00DESCRIPTION | 6 +- Task/Day-of-the-week/00META.yaml | 2 + .../Bracmat/day-of-the-week.bracmat | 27 + .../REXX/day-of-the-week-3.rexx | 14 +- .../REXX/day-of-the-week-4.rexx | 15 +- .../Day-of-the-week/Ruby/day-of-the-week-2.rb | 12 +- .../Scala/day-of-the-week-1.scala | 14 +- .../Scala/day-of-the-week-3.scala | 11 +- .../Scala/day-of-the-week-4.scala | 11 +- .../Day-of-the-week/XPL0/day-of-the-week.xpl0 | 2 +- Task/Deal-cards-for-FreeCell/00DESCRIPTION | 13 +- Task/Deal-cards-for-FreeCell/00META.yaml | 2 + .../D/deal-cards-for-freecell.d | 14 +- .../Fortran/deal-cards-for-freecell.f | 55 ++ .../Seed7/deal-cards-for-freecell.seed7 | 65 ++ Task/Death-Star/D/death-star.d | 6 +- Task/Death-Star/JavaScript/death-star.js | 41 + Task/Death-Star/REXX/death-star.rexx | 14 +- Task/Deconvolution-1D/00DESCRIPTION | 3 +- Task/Deconvolution-1D/C/deconvolution-1d.c | 92 +++ .../Java/deconvolution-1d.java | 25 +- Task/Deconvolution-2D+/D/deconvolution-2d+.d | 104 +-- Task/Deepcopy/Babel/deepcopy.pb | 4 + .../00DESCRIPTION | 2 - Task/Define-a-primitive-data-type/00META.yaml | 2 + .../Clojure/define-a-primitive-data-type.clj | 6 + .../Scala/define-a-primitive-data-type.scala | 14 + .../define-a-primitive-data-type.sh | 16 + Task/Delegates/Aime/delegates.aime | 4 +- .../Java/{delegates.java => delegates-1.java} | 0 Task/Delegates/Java/delegates-2.java | 6 + Task/Delegates/Java/delegates-3.java | 19 + Task/Delegates/Java/delegates-4.java | 17 + Task/Delegates/Java/delegates-5.java | 8 + Task/Delegates/Java/delegates-6.java | 36 + Task/Delegates/Racket/delegates.rkt | 34 + .../Delete-a-file/Groovy/delete-a-file.groovy | 18 + Task/Delete-a-file/Maple/delete-a-file.maple | 4 + .../NewLISP/delete-a-file.newlisp | 4 + Task/Delete-a-file/Scala/delete-a-file.scala | 13 +- Task/Delete-a-file/Seed7/delete-a-file.seed7 | 10 + Task/Detect-division-by-zero/00DESCRIPTION | 3 +- Task/Detect-division-by-zero/00META.yaml | 3 + .../Emacs-Lisp/detect-division-by-zero.l | 4 + .../PARI-GP/detect-division-by-zero-1.pari | 4 + ...ro.pari => detect-division-by-zero-2.pari} | 0 .../PL-I/detect-division-by-zero.pli | 13 +- .../AWK/determine-if-a-string-is-numeric.awk | 3 +- .../determine-if-a-string-is-numeric.aime | 8 +- .../determine-if-a-string-is-numeric.bat | 10 + .../D/determine-if-a-string-is-numeric-1.d | 2 +- .../D/determine-if-a-string-is-numeric-2.d | 2 +- .../determine-if-a-string-is-numeric-1.pro | 3 + .../determine-if-a-string-is-numeric-2.pro | 8 + .../determine-if-a-string-is-numeric-3.pro | 7 + .../determine-if-a-string-is-numeric-1.py | 2 +- .../determine-if-a-string-is-numeric-2.py | 2 +- .../determine-if-a-string-is-numeric.rexx | 2 +- .../determine-if-a-string-is-numeric.rapidq | 48 ++ .../determine-if-a-string-is-numeric.run | 10 +- .../determine-if-a-string-is-numeric.seed7 | 12 + Task/Digital-root/00DESCRIPTION | 21 +- Task/Digital-root/Ada/digital-root-1.ada | 15 + Task/Digital-root/Ada/digital-root-2.ada | 26 + Task/Digital-root/Ada/digital-root-3.ada | 26 + Task/Digital-root/Ada/digital-root.ada | 48 -- Task/Digital-root/D/digital-root.d | 2 +- Task/Digital-root/Eiffel/digital-root.e | 69 ++ Task/Digital-root/Erlang/digital-root.erl | 1 - Task/Digital-root/Fortran/digital-root.f | 31 + Task/Digital-root/Go/digital-root.go | 98 ++- Task/Digital-root/Haskell/digital-root-1.hs | 12 +- Task/Digital-root/Haskell/digital-root-2.hs | 11 +- Task/Digital-root/JavaScript/digital-root.js | 16 + Task/Digital-root/Lua/digital-root.lua | 13 + .../{digital-root.pli => digital-root-1.pli} | 0 Task/Digital-root/PL-I/digital-root-2.pli | 15 + Task/Digital-root/REXX/digital-root-2.rexx | 12 +- Task/Digital-root/REXX/digital-root-3.rexx | 11 +- Task/Digital-root/Ruby/digital-root.rb | 19 +- .../00DESCRIPTION | 14 +- .../00META.yaml | 2 + .../C/dinesmans-multiple-dwelling-problem.c | 81 ++ .../D/dinesmans-multiple-dwelling-problem-2.d | 4 +- .../dinesmans-multiple-dwelling-problem-1.pl6 | 39 + ...dinesmans-multiple-dwelling-problem-2.pl6} | 17 +- .../dinesmans-multiple-dwelling-problem-1.pl | 55 ++ .../dinesmans-multiple-dwelling-problem-2.pl | 10 + ...inesmans-multiple-dwelling-problem-1.scala | 50 +- ...inesmans-multiple-dwelling-problem-2.scala | 42 +- ...inesmans-multiple-dwelling-problem-3.scala | 47 ++ Task/Discordian-date/00DESCRIPTION | 5 +- Task/Discordian-date/00META.yaml | 4 + .../Clojure/discordian-date.clj | 23 + .../Discordian-date/Java/discordian-date.java | 57 ++ Task/Discordian-date/Perl/discordian-date.pl | 33 + .../Emacs-Lisp/documentation-1.l | 3 + .../Emacs-Lisp/documentation-2.l | 2 + Task/Dot-product/Clojure/dot-product.clj | 8 + Task/Dot-product/Eiffel/dot-product.e | 34 + Task/Dot-product/Groovy/dot-product-1.groovy | 2 +- .../{dot-product.js => dot-product-1.js} | 0 Task/Dot-product/JavaScript/dot-product-2.js | 10 + Task/Dot-product/REBOL/dot-product.rebol | 16 + Task/Dot-product/Rust/dot-product.rust | 14 + Task/Dot-product/Scala/dot-product.scala | 5 +- ....go => doubly-linked-list-definition-1.go} | 0 .../Go/doubly-linked-list-definition-2.go | 18 + ...oubly-linked-list-element-definition-1.go} | 0 ...doubly-linked-list-element-definition-2.go | 4 + Task/Dragon-curve/00DESCRIPTION | 2 +- Task/Dragon-curve/PARI-GP/dragon-curve-1.pari | 17 + Task/Dragon-curve/PARI-GP/dragon-curve-2.pari | 17 + Task/Dragon-curve/Perl-6/dragon-curve.pl6 | 37 +- Task/Dragon-curve/Perl/dragon-curve.pl | 36 + Task/Dragon-curve/R/dragon-curve.r | 32 + Task/Dragon-curve/REXX/dragon-curve.rexx | 38 +- .../Visual-Basic-.NET/dragon-curve.visual | 54 ++ .../Dragon-curve/Visual-Basic/dragon-curve.vb | 30 + Task/Draw-a-cuboid/00DESCRIPTION | 9 +- Task/Draw-a-cuboid/00META.yaml | 2 + Task/Draw-a-cuboid/C/draw-a-cuboid.c | 136 +++ Task/Draw-a-cuboid/Clojure/draw-a-cuboid.clj | 22 + Task/Draw-a-cuboid/Java/draw-a-cuboid.java | 46 ++ .../{draw-a-cuboid.py => draw-a-cuboid-1.py} | 0 Task/Draw-a-cuboid/Python/draw-a-cuboid-2.py | 3 + Task/Draw-a-cuboid/Python/draw-a-cuboid-3.py | 261 ++++++ Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx | 4 +- Task/Draw-a-cuboid/Retro/draw-a-cuboid.retro | 19 + Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb | 26 + Task/Draw-a-sphere/00DESCRIPTION | 7 +- Task/Draw-a-sphere/00META.yaml | 2 + Task/Draw-a-sphere/C/draw-a-sphere-2.c | 221 +++-- Task/Draw-a-sphere/Clojure/draw-a-sphere.clj | 20 + Task/Draw-a-sphere/D/draw-a-sphere.d | 31 +- .../Draw-a-sphere/JavaScript/draw-a-sphere.js | 62 ++ Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 | 2 +- Task/Draw-a-sphere/Python/draw-a-sphere-2.py | 771 ------------------ Task/Draw-a-sphere/Python/draw-a-sphere-3.py | 771 ++++++++++++++++++ Task/Draw-a-sphere/Python/draw-a-sphere-4.py | 3 + Task/Draw-a-sphere/Python/draw-a-sphere-5.py | 22 + Task/Draw-a-sphere/REXX/draw-a-sphere.rexx | 53 +- .../D/dutch-national-flag-problem-1.d | 8 +- .../D/dutch-national-flag-problem-3.d | 93 +++ .../Java/dutch-national-flag-problem.java | 46 ++ .../Scala/dutch-national-flag-problem.scala | 11 + .../Emacs-Lisp/dynamic-variable-names.l | 1 + .../Ruby/dynamic-variable-names.rb | 6 +- .../{echo-server.hs => echo-server-1.hs} | 0 Task/Echo-server/Haskell/echo-server-2.hs | 18 + Task/Echo-server/Java/echo-server.java | 2 +- .../REALbasic/echo-server.realbasic | 2 +- .../Haskell/element-wise-operations-1.hs | 129 +++ .../Haskell/element-wise-operations-2.hs | 37 + .../MATLAB/element-wise-operations.m | 4 + Task/Empty-directory/00DESCRIPTION | 3 +- .../C-sharp/empty-directory.cs | 19 + Task/Empty-directory/Ruby/empty-directory.rb | 1 + Task/Empty-program/00META.yaml | 2 + .../360-Assembly/empty-program.360 | 2 + Task/Empty-program/ALGOL-60/empty-program.alg | 1 + ...{empty-program.awk => empty-program-1.awk} | 0 Task/Empty-program/AWK/empty-program-2.awk | 1 + .../Empty-program/BASIC/empty-program-1.basic | 1 - Task/Empty-program/OOC/empty-program.ooc | 0 Task/Empty-program/Oz/empty-program-1.oz | 1 + Task/Empty-program/Oz/empty-program-2.oz | 5 +- Task/Empty-program/REXX/empty-program-1.rexx | 1 - Task/Empty-program/REXX/empty-program-2.rexx | 2 +- Task/Empty-program/REXX/empty-program-3.rexx | 2 +- Task/Empty-program/REXX/empty-program-4.rexx | 2 +- Task/Empty-program/REXX/empty-program-5.rexx | 1 + .../Empty-program/Scilab/empty-program.scilab | 0 .../Empty-program/Simula/empty-program.simula | 2 + .../Visual-Basic/empty-program.vb | 2 + Task/Empty-string/00DESCRIPTION | 5 +- Task/Empty-string/Elixir/empty-string.elixir | 12 + Task/Empty-string/Go/empty-string.go | 14 +- .../Empty-string/JavaScript/empty-string-1.js | 2 + .../Empty-string/JavaScript/empty-string-2.js | 4 + .../Empty-string/JavaScript/empty-string-3.js | 4 + Task/Empty-string/Maple/empty-string.maple | 3 + Task/Empty-string/Prolog/empty-string.pro | 4 + Task/Empty-string/Smalltalk/empty-string.st | 8 + Task/Empty-string/Standard-ML/empty-string.ml | 6 + Task/Enforced-immutability/00DESCRIPTION | 1 - Task/Enforced-immutability/00META.yaml | 4 + .../Fortran/enforced-immutability-1.f | 1 + .../Fortran/enforced-immutability-2.f | 2 + .../PL-I/enforced-immutability.pli | 6 + .../Perl-6/enforced-immutability-3.pl6 | 3 +- ...tability.rb => enforced-immutability-1.rb} | 5 +- .../Ruby/enforced-immutability-2.rb | 8 + Task/Entropy/00DESCRIPTION | 10 +- Task/Entropy/ALGOL-68/entropy.alg | 43 + Task/Entropy/C-sharp/entropy-1.cs | 39 + Task/Entropy/C-sharp/entropy-2.cs | 43 + Task/Entropy/Clojure/entropy-1.clj | 12 +- Task/Entropy/Clojure/entropy-2.clj | 2 +- Task/Entropy/D/entropy.d | 5 +- Task/Entropy/Haskell/entropy.hs | 2 +- Task/Entropy/JavaScript/entropy.js | 31 + Task/Entropy/Julia/entropy.julia | 1 + Task/Entropy/OCaml/entropy.ocaml | 30 + Task/Entropy/PL-I/entropy.pli | 34 + Task/Entropy/Pascal/entropy.pascal | 50 ++ .../{enumerations.cpp => enumerations-1.cpp} | 0 Task/Enumerations/C++/enumerations-2.cpp | 3 + Task/Enumerations/C++/enumerations-3.cpp | 1 + Task/Enumerations/C++/enumerations-4.cpp | 1 + .../C/{enumerations.c => enumerations-1.c} | 0 Task/Enumerations/C/enumerations-2.c | 3 + Task/Enumerations/D/enumerations.d | 61 +- Task/Enumerations/Go/enumerations-1.go | 6 +- Task/Enumerations/Go/enumerations-2.go | 6 +- Task/Enumerations/Go/enumerations-3.go | 7 + Task/Enumerations/Go/enumerations-4.go | 7 + Task/Enumerations/Objective-C/enumerations.m | 3 + Task/Enumerations/Python/enumerations-1.py | 16 +- Task/Enumerations/Python/enumerations-2.py | 2 +- Task/Enumerations/Python/enumerations-3.py | 1 + Task/Enumerations/Ruby/enumerations-1.rb | 11 + Task/Enumerations/Ruby/enumerations-2.rb | 12 + Task/Enumerations/Ruby/enumerations.rb | 5 - Task/Environment-variables/00DESCRIPTION | 7 +- Task/Environment-variables/00META.yaml | 2 +- .../Make/environment-variables-1.make | 3 + .../Make/environment-variables-2.make | 2 + .../Make/environment-variables-3.make | 5 + ...ariables.pl => environment-variables-1.pl} | 0 .../Perl/environment-variables-2.pl | 2 + .../Scala/environment-variables.scala | 11 +- .../Smalltalk/environment-variables.st | 3 + .../Equilibrium-index/D/equilibrium-index-1.d | 4 +- .../Prolog/equilibrium-index-1.pro | 6 + .../Prolog/equilibrium-index-2.pro | 4 + .../REXX/equilibrium-index-1.rexx | 30 + .../REXX/equilibrium-index-2.rexx | 33 + .../REXX/equilibrium-index.rexx | 33 - .../ActionScript/ethiopian-multiplication.as | 31 + .../Aime/ethiopian-multiplication.aime | 18 +- .../D/ethiopian-multiplication.d | 8 +- .../Eiffel/ethiopian-multiplication-1.e | 41 + .../Eiffel/ethiopian-multiplication-2.e | 15 + .../Emacs-Lisp/ethiopian-multiplication.l | 14 +- .../J/ethiopian-multiplication-2.j | 3 +- .../J/ethiopian-multiplication-3.j | 3 +- .../J/ethiopian-multiplication-4.j | 9 +- .../Java/ethiopian-multiplication-3.java | 5 +- .../Julia/ethiopian-multiplication-1.julia | 8 + .../Julia/ethiopian-multiplication-2.julia | 9 + .../Julia/ethiopian-multiplication-3.julia | 9 + .../Julia/ethiopian-multiplication-4.julia | 4 + .../Julia/ethiopian-multiplication-5.julia | 1 + .../Julia/ethiopian-multiplication-6.julia | 15 + .../Julia/ethiopian-multiplication-7.julia | 1 + .../PHP/ethiopian-multiplication-2.php | 1 - .../Prolog/ethiopian-multiplication-1.pro | 23 + .../Prolog/ethiopian-multiplication-2.pro | 12 + .../Prolog/ethiopian-multiplication-3.pro | 25 + .../Prolog/ethiopian-multiplication-4.pro | 21 + .../Rust/ethiopian-multiplication.rust | 28 + .../Scala/ethiopian-multiplication.scala | 2 + Task/Euler-method/D/euler-method.d | 28 +- Task/Euler-method/JavaScript/euler-method.js | 29 + Task/Euler-method/R/euler-method.r | 17 + .../C/evaluate-binomial-coefficients.c | 43 + .../evaluate-binomial-coefficients.coffee | 9 + .../D/evaluate-binomial-coefficients.d | 6 +- .../Fortran/evaluate-binomial-coefficients.f | 31 + .../evaluate-binomial-coefficients-4.hs | 5 + .../evaluate-binomial-coefficients-1.java | 27 +- .../evaluate-binomial-coefficients-3.java | 17 + .../PL-I/evaluate-binomial-coefficients.pli | 22 + .../Perl-6/evaluate-binomial-coefficients.pl6 | 3 +- .../Perl/evaluate-binomial-coefficients-1.pl | 8 + .../Perl/evaluate-binomial-coefficients-2.pl | 5 + .../Perl/evaluate-binomial-coefficients-3.pl | 2 + .../Perl/evaluate-binomial-coefficients.pl | 8 - .../PicoLisp/evaluate-binomial-coefficients.l | 8 +- .../R/evaluate-binomial-coefficients.r | 1 + ... => evaluate-binomial-coefficients-1.rexx} | 13 +- .../evaluate-binomial-coefficients-2.rexx | 9 + .../evaluate-binomial-coefficients-2.scala | 9 +- .../evaluate-binomial-coefficients-3.scala | 14 +- .../Scheme/evaluate-binomial-coefficients.ss | 12 + .../evaluate-binomial-coefficients-1.seed7 | 14 + .../evaluate-binomial-coefficients-2.seed7 | 26 + .../evaluate-binomial-coefficients.seed7 | 26 - .../6502-Assembly/even-or-odd.6502 | 48 ++ Task/Even-or-odd/ALGOL-68/even-or-odd.alg | 8 + Task/Even-or-odd/C++/even-or-odd.cpp | 7 +- Task/Even-or-odd/ColdFusion/even-or-odd.cfm | 5 + Task/Even-or-odd/D/even-or-odd.d | 8 +- Task/Even-or-odd/JavaScript/even-or-odd-1.js | 3 + .../{even-or-odd.js => even-or-odd-2.js} | 0 Task/Even-or-odd/M4/even-or-odd.m4 | 8 + Task/Even-or-odd/Maple/even-or-odd.maple | 8 + Task/Even-or-odd/NewLISP/even-or-odd.newlisp | 2 + Task/Even-or-odd/OOC/even-or-odd.ooc | 9 + Task/Even-or-odd/REXX/even-or-odd.rexx | 22 +- Task/Even-or-odd/Rust/even-or-odd-1.rust | 2 + Task/Even-or-odd/Rust/even-or-odd-2.rust | 2 + Task/Events/Perl-6/events.pl6 | 14 + .../Aime/evolutionary-algorithm.aime | 16 +- .../ColdFusion/evolutionary-algorithm.cfm | 67 ++ .../D/evolutionary-algorithm.d | 2 +- .../Octave/evolutionary-algorithm.octave | 24 +- .../OoRexx/evolutionary-algorithm.rexx | 54 ++ .../Perl-6/evolutionary-algorithm.pl6 | 2 +- .../00DESCRIPTION | 10 +- .../00META.yaml | 2 + ...-an-exception-thrown-in-a-nested-call.aime | 19 +- ...tch-an-exception-thrown-in-a-nested-call.c | 119 +++ ...an-exception-thrown-in-a-nested-call-1.go} | 0 ...-an-exception-thrown-in-a-nested-call-2.go | 59 ++ ...-an-exception-thrown-in-a-nested-call.rexx | 10 +- ...ch-an-exception-thrown-in-a-nested-call.rb | 25 + ...an-exception-thrown-in-a-nested-call.scala | 19 + ...an-exception-thrown-in-a-nested-call.seed7 | 36 + Task/Exceptions/00DESCRIPTION | 8 +- Task/Exceptions/Go/exceptions.go | 25 +- Task/Exceptions/Logtalk/exceptions.logtalk | 23 + Task/Exceptions/Scala/exceptions.scala | 62 ++ Task/Executable-library/00DESCRIPTION | 9 +- Task/Execute-Brain----/00DESCRIPTION | 31 +- ...cute-brain----.l => execute-brain-----1.l} | 0 .../PicoLisp/execute-brain-----2.l | 58 ++ Task/Execute-HQ9+/Haxe/execute-hq9+.haxe | 21 + Task/Execute-HQ9+/Inform-7/execute-hq9+.inf | 8 +- Task/Execute-SNUSP/J/execute-snusp-1.j | 53 ++ Task/Execute-SNUSP/J/execute-snusp-2.j | 5 + Task/Execute-a-Markov-algorithm/00DESCRIPTION | 6 +- .../Java/execute-a-markov-algorithm.java | 63 ++ .../AWK/execute-a-system-command.awk | 3 +- .../execute-a-system-command.euphoria | 32 + .../Go/execute-a-system-command.go | 21 +- .../NewLISP/execute-a-system-command.newlisp | 1 + Task/Exponentiation-operator/00META.yaml | 2 + ...operator.c => exponentiation-operator-1.c} | 0 .../C/exponentiation-operator-2.c | 13 + .../D/exponentiation-operator.d | 6 +- ...erator.pl => exponentiation-operator-1.pl} | 0 .../Perl/exponentiation-operator-2.pl | 13 + .../Prolog/exponentiation-operator-1.pro | 2 + .../Prolog/exponentiation-operator-2.pro | 24 + .../Prolog/exponentiation-operator-3.pro | 11 + .../Prolog/exponentiation-operator-4.pro | 16 + .../Seed7/exponentiation-operator-2.seed7 | 44 +- Task/Extend-your-language/00DESCRIPTION | 2 +- .../Ada/extend-your-language.ada | 20 + .../Mathematica/extend-your-language-1.math | 9 + .../Mathematica/extend-your-language-2.math | 5 + .../Mathematica/extend-your-language.math | 5 - .../REXX/extend-your-language-1.rexx | 8 + .../REXX/extend-your-language-2.rexx | 20 + .../Ruby/extend-your-language-1.rb | 10 +- .../Ruby/extend-your-language-2.rb | 19 +- .../00DESCRIPTION | 6 +- .../Extreme-floating-point-values/00META.yaml | 3 + .../AWK/extreme-floating-point-values.awk | 2 +- .../Clojure/extreme-floating-point-values.clj | 11 + .../Eiffel/extreme-floating-point-values.e | 33 + Task/Factorial/00DESCRIPTION | 4 +- Task/Factorial/00META.yaml | 1 + Task/Factorial/360-Assembly/factorial.360 | 64 ++ Task/Factorial/Babel/factorial-1.pb | 10 + Task/Factorial/Babel/factorial-2.pb | 10 + Task/Factorial/Babel/factorial.pb | 16 - Task/Factorial/D/factorial-1.d | 2 +- Task/Factorial/D/factorial-2.d | 2 +- Task/Factorial/D/factorial-3.d | 2 +- Task/Factorial/D/factorial-4.d | 2 +- Task/Factorial/Elixir/factorial.elixir | 14 + .../Forth/{factorial.fth => factorial-1.fth} | 0 Task/Factorial/Forth/factorial-2.fth | 14 + Task/Factorial/Haskell/factorial-2.hs | 2 +- Task/Factorial/Haskell/factorial-3.hs | 2 +- Task/Factorial/Haskell/factorial-4.hs | 4 +- Task/Factorial/Haskell/factorial-5.hs | 8 +- Task/Factorial/Haskell/factorial-6.hs | 5 + Task/Factorial/Haskell/factorial-7.hs | 8 + Task/Factorial/Mercury/factorial-1.mercury | 16 + Task/Factorial/Mercury/factorial-2.mercury | 18 + Task/Factorial/Mercury/factorial-3.mercury | 1 + Task/Factorial/PARI-GP/factorial-3.pari | 2 +- Task/Factorial/Perl/factorial-4.pl | 3 + Task/Factorial/Perl/factorial-5.pl | 2 + Task/Factorial/Perl/factorial-6.pl | 2 + Task/Factorial/Perl/factorial-7.pl | 2 + Task/Factorial/PicoLisp/factorial-2.l | 2 +- Task/Factorial/Python/factorial-3.py | 3 +- Task/Factorial/Python/factorial-4.py | 35 +- Task/Factorial/Python/factorial-5.py | 30 +- Task/Factorial/REXX/factorial-3.rexx | 59 +- Task/Factorial/Rascal/factorial-3.rascal | 9 +- .../{factorial.scilab => factorial-1.scilab} | 0 Task/Factorial/Scilab/factorial-2.scilab | 6 + Task/Factorial/Scilab/factorial-3.scilab | 5 + Task/Factorial/TI-83-BASIC/factorial.ti-83 | 3 + .../00DESCRIPTION | 34 +- Task/Factors-of-a-Mersenne-number/00META.yaml | 1 + .../factors-of-a-mersenne-number.bracmat | 62 ++ .../factors-of-a-mersenne-number-2.lisp | 8 - .../D/factors-of-a-mersenne-number.d | 7 +- .../Perl/factors-of-a-mersenne-number-2.pl | 41 +- .../Befunge/factors-of-an-integer.bf | 4 + .../D/factors-of-an-integer-1.d | 2 +- .../Frink/factors-of-an-integer.frink | 1 + .../Haskell/factors-of-an-integer-6.hs | 3 + .../Haskell/factors-of-an-integer-7.hs | 4 + .../MAXScript/factors-of-an-integer-1.max | 4 + .../MAXScript/factors-of-an-integer-2.max | 10 + ....pascal => factors-of-an-integer-1.pascal} | 0 .../Pascal/factors-of-an-integer-2.pascal | 36 + .../Perl-6/factors-of-an-integer.pl6 | 7 +- ...-integer.pl => factors-of-an-integer-1.pl} | 2 +- .../Perl/factors-of-an-integer-2.pl | 11 + .../Perl/factors-of-an-integer-3.pl | 3 + .../Prolog/factors-of-an-integer-1.pro | 5 + .../Prolog/factors-of-an-integer-2.pro | 12 + .../Prolog/factors-of-an-integer-3.pro | 15 + .../Prolog/factors-of-an-integer.pro | 26 - .../Python/factors-of-an-integer-4.py | 31 +- .../REXX/factors-of-an-integer-1.rexx | 24 +- .../Ruby/factors-of-an-integer-2.rb | 7 +- Task/Fast-Fourier-transform/00DESCRIPTION | 11 +- .../C/fast-fourier-transform.c | 50 ++ .../D/fast-fourier-transform-1.d | 4 +- .../D/fast-fourier-transform-2.d | 4 +- .../D/fast-fourier-transform-3.d | 6 +- .../JavaScript/fast-fourier-transform-1.js | 66 ++ .../JavaScript/fast-fourier-transform-2.js | 50 ++ .../Perl-6/fast-fourier-transform.pl6 | 7 +- .../Perl/fast-fourier-transform.pl | 10 +- .../Python/fast-fourier-transform-1.py | 12 +- .../Python/fast-fourier-transform-2.py | 4 +- .../REXX/fast-fourier-transform.rexx | 68 +- .../Racket/fast-fourier-transform.rkt | 3 + .../Ruby/fast-fourier-transform.rb | 4 +- .../Scala/fast-fourier-transform-1.scala | 25 + .../Scala/fast-fourier-transform-2.scala | 25 + .../Scala/fast-fourier-transform-3.scala | 5 + .../Scala/fast-fourier-transform.scala | 32 - .../00DESCRIPTION | 1 + .../fibonacci-n-step-number-sequences.bracmat | 41 + ...> fibonacci-n-step-number-sequences-1.cpp} | 0 .../fibonacci-n-step-number-sequences-2.cpp | 65 ++ .../fibonacci-n-step-number-sequences.cs | 84 ++ .../fibonacci-n-step-number-sequences.lisp | 18 + .../D/fibonacci-n-step-number-sequences-1.d | 7 +- .../D/fibonacci-n-step-number-sequences-2.d | 7 +- .../D/fibonacci-n-step-number-sequences-3.d | 5 +- .../D/fibonacci-n-step-number-sequences-4.d | 19 + .../fibonacci-n-step-number-sequences.f | 64 ++ .../fibonacci-n-step-number-sequences-1.icon | 15 + .../fibonacci-n-step-number-sequences-2.icon | 10 + ...ibonacci-n-step-number-sequences-1.pascal} | 0 ...fibonacci-n-step-number-sequences-2.pascal | 113 +++ .../fibonacci-n-step-number-sequences-1.pl6 | 2 +- .../fibonacci-n-step-number-sequences-1.rust | 41 + .../fibonacci-n-step-number-sequences-2.rust | 4 + .../fibonacci-n-step-number-sequences.rust | 21 - .../fibonacci-n-step-number-sequences-1.scala | 7 + .../fibonacci-n-step-number-sequences-2.scala | 10 + .../fibonacci-n-step-number-sequences-3.scala | 11 + .../fibonacci-n-step-number-sequences-4.scala | 4 + Task/Fibonacci-sequence/00DESCRIPTION | 3 +- .../360-Assembly/fibonacci-sequence.360 | 49 ++ .../APL/fibonacci-sequence-1.apl | 1 + .../APL/fibonacci-sequence-2.apl | 1 + .../ATS/fibonacci-sequence-1.ats | 2 + .../ATS/fibonacci-sequence-2.ats | 9 + .../ATS/fibonacci-sequence-3.ats | 27 + .../ATS/fibonacci-sequence-4.ats | 79 ++ .../Babel/fibonacci-sequence.pb | 31 +- .../Clojure/fibonacci-sequence-7.clj | 6 + .../Clojure/fibonacci-sequence-8.clj | 8 + .../CoffeeScript/fibonacci-sequence-2.coffee | 10 +- .../CoffeeScript/fibonacci-sequence-3.coffee | 5 +- .../Common-Lisp/fibonacci-sequence-7.lisp | 21 + .../Dart/fibonacci-sequence.dart | 16 +- .../Fexl/fibonacci-sequence.fexl | 34 +- .../Fortran/fibonacci-sequence-1.f | 36 +- .../Fortran/fibonacci-sequence-2.f | 31 +- .../Fortran/fibonacci-sequence-3.f | 17 +- .../Fortran/fibonacci-sequence-4.f | 20 + .../Fortran/fibonacci-sequence-5.f | 7 + .../Go/fibonacci-sequence-3.go | 16 + .../Haskell/fibonacci-sequence-6.hs | 4 +- .../Java/fibonacci-sequence-2.java | 30 +- .../Java/fibonacci-sequence-3.java | 6 +- .../Java/fibonacci-sequence-4.java | 11 +- .../Java/fibonacci-sequence-5.java | 9 + .../JavaScript/fibonacci-sequence-2.js | 26 +- .../JavaScript/fibonacci-sequence-5.js | 10 + .../Lush/fibonacci-sequence.lush | 4 + .../MATLAB/fibonacci-sequence-1.m | 20 +- .../MATLAB/fibonacci-sequence-2.m | 21 +- .../MATLAB/fibonacci-sequence-3.m | 13 + .../Mathematica/fibonacci-sequence-3.math | 3 + .../Mathematica/fibonacci-sequence-4.math | 3 + .../Mathematica/fibonacci-sequence-5.math | 2 + .../Mathematica/fibonacci-sequence-6.math | 21 + .../OPL/fibonacci-sequence.opl | 1 - .../PARI-GP/fibonacci-sequence-10.pari | 15 +- .../PARI-GP/fibonacci-sequence-11.pari | 12 +- .../PARI-GP/fibonacci-sequence-12.pari | 1 + .../PL-I/fibonacci-sequence.pli | 8 +- .../Pascal/fibonacci-sequence-1.pascal | 25 +- .../Pascal/fibonacci-sequence-2.pascal | 16 +- .../Pascal/fibonacci-sequence-3.pascal | 22 + .../Perl-6/fibonacci-sequence-2.pl6 | 2 +- .../Perl/fibonacci-sequence-1.pl | 37 +- .../Perl/fibonacci-sequence-3.pl | 20 + .../Python/fibonacci-sequence-10.py | 10 + .../Python/fibonacci-sequence-5.py | 10 +- .../Python/fibonacci-sequence-6.py | 18 +- .../Python/fibonacci-sequence-7.py | 31 +- .../Python/fibonacci-sequence-8.py | 35 +- .../Python/fibonacci-sequence-9.py | 7 + .../REXX/fibonacci-sequence.rexx | 40 +- .../Racket/fibonacci-sequence-1.rkt | 5 + .../Racket/fibonacci-sequence-2.rkt | 11 + .../Racket/fibonacci-sequence.rkt | 6 - .../Ruby/fibonacci-sequence-1.rb | 8 +- .../Ruby/fibonacci-sequence-2.rb | 6 +- .../Ruby/fibonacci-sequence-3.rb | 4 +- .../Ruby/fibonacci-sequence-4.rb | 2 +- .../Ruby/fibonacci-sequence-5.rb | 4 +- .../Rust/fibonacci-sequence-1.rust | 51 +- .../Rust/fibonacci-sequence-2.rust | 28 +- .../SQL/fibonacci-sequence.sql | 27 + .../Scala/fibonacci-sequence-3.scala | 9 +- .../Scala/fibonacci-sequence-5.scala | 16 +- .../Scilab/fibonacci-sequence.scilab | 11 + .../Visual-Basic/fibonacci-sequence.vb | 14 + Task/File-modification-time/00DESCRIPTION | 10 + Task/File-modification-time/00META.yaml | 4 +- .../AWK/file-modification-time.awk | 34 + .../Emacs-Lisp/file-modification-time.l | 5 + .../NewLISP/file-modification-time.newlisp | 5 + .../Run-BASIC/file-modification-time.run | 4 +- .../Scala/file-modification-time.scala | 18 + Task/File-size/AWK/file-size.awk | 17 + Task/File-size/Lua/file-size-1.lua | 1 + Task/File-size/Lua/file-size-2.lua | 1 + Task/File-size/Lua/file-size.lua | 9 - Task/File-size/NewLISP/file-size.newlisp | 2 + Task/File-size/Scala/file-size.scala | 8 + Task/File-size/UNIX-Shell/file-size-2.sh | 12 +- Task/File-size/UNIX-Shell/file-size-3.sh | 4 +- Task/File-size/UNIX-Shell/file-size-4.sh | 7 +- Task/File-size/UNIX-Shell/file-size-5.sh | 5 + Task/Filter/00DESCRIPTION | 6 +- Task/Filter/AWK/{filter.awk => filter-1.awk} | 1 - Task/Filter/AWK/filter-2.awk | 5 + Task/Filter/CoffeeScript/filter.coffee | 1 + Task/Filter/D/filter-1.d | 8 +- Task/Filter/Julia/filter.julia | 3 +- Task/Filter/Lua/filter-1.lua | 11 + Task/Filter/Lua/filter-2.lua | 11 + Task/Filter/Lua/filter.lua | 9 - Task/Filter/Rust/filter.rust | 27 + Task/Filter/XQuery/filter-1.xquery | 2 +- Task/Find-common-directory-path/00META.yaml | 2 + .../Aime/find-common-directory-path.aime | 8 +- .../Go/find-common-directory-path.go | 90 +- .../Perl/find-common-directory-path-1.pl | 6 + .../Perl/find-common-directory-path-2.pl | 12 + .../Perl/find-common-directory-path-3.pl | 4 + .../Perl/find-common-directory-path.pl | 19 - .../Ruby/find-common-directory-path-1.rb | 2 +- .../Ruby/find-common-directory-path-2.rb | 5 +- .../Scala/find-common-directory-path-1.scala | 17 + .../Scala/find-common-directory-path-2.scala | 50 ++ ...-left-truncatable-prime-in-a-given-base.pl | 20 + Task/Find-limit-of-recursion/00DESCRIPTION | 3 +- .../Fortran/find-limit-of-recursion.f | 19 + .../Go/find-limit-of-recursion.go | 21 +- .../J/find-limit-of-recursion.j | 2 +- .../00DESCRIPTION | 12 +- .../find-the-missing-permutation.coffee | 35 + .../D/find-the-missing-permutation.d | 28 +- .../R/find-the-missing-permutation.r | 12 + .../REXX/find-the-missing-permutation.rexx | 52 +- .../find-the-missing-permutation.rapidq | 24 + .../Ruby/find-the-missing-permutation.rb | 4 +- .../Seed7/find-the-missing-permutation.seed7 | 33 + .../00DESCRIPTION | 2 +- ...ass-functions-use-numbers-analogously-1.pl | 20 + ...ass-functions-use-numbers-analogously-2.pl | 9 + .../first-class-functions.applescript | 56 ++ .../AutoHotkey/first-class-functions.ahk | 54 +- .../Bracmat/first-class-functions.bracmat | 17 + .../Groovy/first-class-functions-2.groovy | 4 +- .../Java/first-class-functions-2.java | 15 +- .../TXR/first-class-functions.txr | 11 + Task/Five-weekends/00DESCRIPTION | 5 + Task/Five-weekends/00META.yaml | 5 + Task/Five-weekends/AWK/five-weekends.awk | 56 ++ Task/Five-weekends/D/five-weekends-2.d | 24 +- Task/Five-weekends/Racket/five-weekends.rkt | 26 + Task/Five-weekends/Ruby/five-weekends.rb | 14 +- .../Five-weekends/UNIX-Shell/five-weekends.sh | 12 + Task/Five-weekends/XPL0/five-weekends.xpl0 | 2 +- Task/FizzBuzz/00DESCRIPTION | 9 +- Task/FizzBuzz/00META.yaml | 1 + .../APL/{fizzbuzz.apl => fizzbuzz-1.apl} | 0 Task/FizzBuzz/APL/fizzbuzz-2.apl | 1 + Task/FizzBuzz/C++/fizzbuzz-1.cpp | 16 +- Task/FizzBuzz/C++/fizzbuzz-2.cpp | 2 +- Task/FizzBuzz/C++/fizzbuzz-3.cpp | 27 +- Task/FizzBuzz/C++/fizzbuzz-4.cpp | 61 +- Task/FizzBuzz/C++/fizzbuzz-5.cpp | 172 +--- Task/FizzBuzz/C++/fizzbuzz-6.cpp | 164 ++++ Task/FizzBuzz/C/fizzbuzz-1.c | 21 +- Task/FizzBuzz/C/fizzbuzz-2.c | 32 +- Task/FizzBuzz/C/fizzbuzz-3.c | 17 +- Task/FizzBuzz/C/fizzbuzz-4.c | 14 +- Task/FizzBuzz/C/fizzbuzz-5.c | 11 + Task/FizzBuzz/C/fizzbuzz-6.c | 11 + Task/FizzBuzz/Clipper/fizzbuzz.clipper | 19 +- Task/FizzBuzz/Clojure/fizzbuzz-1.clj | 14 +- Task/FizzBuzz/Clojure/fizzbuzz-2.clj | 6 +- Task/FizzBuzz/Clojure/fizzbuzz-3.clj | 7 +- Task/FizzBuzz/Clojure/fizzbuzz-4.clj | 19 +- Task/FizzBuzz/Clojure/fizzbuzz-5.clj | 19 +- Task/FizzBuzz/Clojure/fizzbuzz-6.clj | 10 +- Task/FizzBuzz/Clojure/fizzbuzz-7.clj | 4 + Task/FizzBuzz/Clojure/fizzbuzz-8.clj | 1 + Task/FizzBuzz/ColdFusion/fizzbuzz.cfm | 7 + Task/FizzBuzz/D/fizzbuzz.d | 58 +- Task/FizzBuzz/Eiffel/fizzbuzz.e | 35 + .../{fizzbuzz.elixir => fizzbuzz-1.elixir} | 0 Task/FizzBuzz/Elixir/fizzbuzz-2.elixir | 13 + Task/FizzBuzz/JavaScript/fizzbuzz-1.js | 26 +- Task/FizzBuzz/JavaScript/fizzbuzz-2.js | 26 +- Task/FizzBuzz/Julia/fizzbuzz-3.julia | 2 +- Task/FizzBuzz/Julia/fizzbuzz-4.julia | 1 + Task/FizzBuzz/Julia/fizzbuzz-5.julia | 7 + Task/FizzBuzz/Julia/fizzbuzz-6.julia | 4 + Task/FizzBuzz/Lua/fizzbuzz-2.lua | 2 +- Task/FizzBuzz/Maple/fizzbuzz-1.maple | 1 + Task/FizzBuzz/Maple/fizzbuzz-2.maple | 2 + Task/FizzBuzz/Maple/fizzbuzz-3.maple | 2 + Task/FizzBuzz/Maple/fizzbuzz-4.maple | 8 + Task/FizzBuzz/Mercury/fizzbuzz.mercury | 26 +- Task/FizzBuzz/Mirah/fizzbuzz-1.mirah | 6 + .../{fizzbuzz.mirah => fizzbuzz-2.mirah} | 8 - Task/FizzBuzz/NewLISP/fizzbuzz.newlisp | 7 + Task/FizzBuzz/OCaml/fizzbuzz-1.ocaml | 9 + Task/FizzBuzz/OCaml/fizzbuzz-2.ocaml | 9 + Task/FizzBuzz/OCaml/fizzbuzz.ocaml | 9 - Task/FizzBuzz/PL-SQL/fizzbuzz.sql | 32 +- Task/FizzBuzz/Perl-6/fizzbuzz-4.pl6 | 5 +- Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 | 4 + Task/FizzBuzz/Python/fizzbuzz-2.py | 8 +- Task/FizzBuzz/Python/fizzbuzz-3.py | 16 +- Task/FizzBuzz/R/fizzbuzz-1.r | 9 +- Task/FizzBuzz/REXX/fizzbuzz-1.rexx | 11 +- Task/FizzBuzz/REXX/fizzbuzz-2.rexx | 17 +- Task/FizzBuzz/REXX/fizzbuzz-3.rexx | 12 +- Task/FizzBuzz/REXX/fizzbuzz-4.rexx | 6 + Task/FizzBuzz/Ruby/fizzbuzz-1.rb | 2 +- Task/FizzBuzz/Ruby/fizzbuzz-10.rb | 8 + Task/FizzBuzz/Ruby/fizzbuzz-11.rb | 8 + Task/FizzBuzz/Ruby/fizzbuzz-7.rb | 2 +- Task/FizzBuzz/Ruby/fizzbuzz-8.rb | 11 +- Task/FizzBuzz/Ruby/fizzbuzz-9.rb | 11 +- Task/FizzBuzz/Rust/fizzbuzz-1.rust | 26 +- Task/FizzBuzz/Rust/fizzbuzz-2.rust | 20 +- Task/FizzBuzz/Rust/fizzbuzz-3.rust | 22 +- Task/FizzBuzz/Rust/fizzbuzz-4.rust | 24 +- Task/FizzBuzz/Rust/fizzbuzz-5.rust | 25 +- Task/FizzBuzz/Rust/fizzbuzz-6.rust | 14 + Task/FizzBuzz/Rust/fizzbuzz-7.rust | 14 + Task/FizzBuzz/Rust/fizzbuzz-8.rust | 20 + Task/FizzBuzz/SQL/fizzbuzz-1.sql | 18 +- Task/FizzBuzz/SQL/fizzbuzz-2.sql | 5 +- Task/FizzBuzz/Scala/fizzbuzz-1.scala | 9 +- Task/FizzBuzz/Scala/fizzbuzz-2.scala | 11 +- Task/FizzBuzz/Scala/fizzbuzz-3.scala | 4 +- Task/FizzBuzz/Scala/fizzbuzz-4.scala | 3 +- .../Scheme/{fizzbuzz.ss => fizzbuzz-1.ss} | 0 Task/FizzBuzz/Scheme/fizzbuzz-2.ss | 10 + Task/FizzBuzz/Vim-Script/fizzbuzz.vim | 11 + Task/FizzBuzz/XSLT/fizzbuzz-1.xslt | 53 ++ Task/FizzBuzz/XSLT/fizzbuzz-2.xslt | 33 + Task/FizzBuzz/XSLT/fizzbuzz-3.xslt | 10 + .../Elixir/flatten-a-list.elixir | 12 + .../JavaScript/flatten-a-list-2.js | 6 +- .../Mercury/flatten-a-list.mercury | 34 + .../Flatten-a-list/Python/flatten-a-list-1.py | 14 +- .../Flatten-a-list/Python/flatten-a-list-3.py | 4 +- .../Racket/flatten-a-list-2.rkt | 7 +- .../Run-BASIC/flatten-a-list.run | 23 +- .../VBScript/flatten-a-list-3.vb | 16 +- Task/Flow-control-structures/00DESCRIPTION | 5 +- .../Scala/flow-control-structures.scala | 26 + .../ALGOL-68/floyds-triangle.alg | 33 + .../C-sharp/floyds-triangle.cs | 46 ++ .../Python/floyds-triangle-2.py | 4 +- .../REXX/floyds-triangle-2.rexx | 18 +- .../REXX/floyds-triangle-3.rexx | 18 +- .../REXX/floyds-triangle-4.rexx | 40 +- .../Run-BASIC/floyds-triangle.run | 7 +- Task/Forest-fire/D/forest-fire-1.d | 80 +- Task/Forest-fire/D/forest-fire-2.d | 9 +- Task/Forest-fire/Lua/forest-fire.lua | 97 +++ Task/Forest-fire/Perl-6/forest-fire.pl6 | 48 +- Task/Forest-fire/REXX/forest-fire.rexx | 88 +- Task/Forest-fire/Ruby/forest-fire.rb | 86 +- Task/Fork/J/fork.j | 2 + Task/Fork/NewLISP/fork.newlisp | 4 + Task/Fork/Scala/fork-1.scala | 16 + Task/Fork/Scala/fork-2.scala | 14 + Task/Formatted-numeric-output/00META.yaml | 1 + .../Mathematica/formatted-numeric-output.math | 4 +- .../REBOL/formatted-numeric-output.rebol | 4 +- .../Scheme/formatted-numeric-output.ss | 7 + Task/Forward-difference/00DESCRIPTION | 6 +- .../C++/forward-difference-1.cpp | 2 +- .../D/forward-difference-1.d | 31 +- .../D/forward-difference-2.d | 2 +- .../D/forward-difference-3.d | 10 +- .../D/forward-difference-4.d | 12 +- .../HicEst/forward-difference.hicest | 12 + .../Julia/forward-difference.julia | 1 + .../MATLAB/forward-difference.m | 1 + .../REXX/forward-difference-1.rexx | 77 +- Task/Four-bit-adder/00DESCRIPTION | 11 +- Task/Four-bit-adder/D/four-bit-adder-1.d | 8 +- Task/Four-bit-adder/Go/four-bit-adder-2.go | 176 ++-- Task/Four-bit-adder/Perl/four-bit-adder.pl | 43 + Task/Four-bit-adder/REXX/four-bit-adder.rexx | 41 +- Task/Four-bit-adder/Ruby/four-bit-adder.rb | 19 +- .../Fractal-tree/BBC-BASIC/fractal-tree-1.bbc | 5 + .../{fractal-tree.bbc => fractal-tree-2.bbc} | 6 - Task/Function-composition/00DESCRIPTION | 3 +- .../function-composition.applescript | 24 + .../C++/function-composition-3.cpp | 12 +- .../C++/function-composition-4.cpp | 9 + ...n.coffee => function-composition-1.coffee} | 2 + .../function-composition-2.coffee | 15 + .../Emacs-Lisp/function-composition-1.l | 7 + .../Emacs-Lisp/function-composition-2.l | 7 + .../Emacs-Lisp/function-composition-3.l | 11 + .../REXX/function-composition.rexx | 1 + .../UNIX-Shell/function-composition-2.sh | 142 +++- .../UNIX-Shell/function-composition-3.sh | 8 +- .../UNIX-Shell/function-composition-4.sh | 9 + Task/Function-definition/00DESCRIPTION | 3 +- Task/Function-definition/00META.yaml | 1 + .../Eiffel/function-definition.e | 4 + .../Emacs-Lisp/function-definition-1.l | 2 + .../Emacs-Lisp/function-definition-2.l | 3 + .../Gnuplot/function-definition.gnuplot | 4 + .../OOC/function-definition.ooc | 3 + .../Perl/function-definition-4.pl | 2 +- .../REALbasic/function-definition.realbasic | 3 + .../TXR/function-definition-2.txr | 2 +- .../X86-Assembly/function-definition-1.x86 | 31 +- .../X86-Assembly/function-definition-2.x86 | 25 +- .../X86-Assembly/function-definition-3.x86 | 12 +- .../X86-Assembly/function-definition-4.x86 | 5 + .../ALGOL-68/function-prototype.alg | 37 + .../C++/function-prototype.cpp | 7 + .../Function-prototype/C/function-prototype.c | 6 +- .../Clojure/function-prototype.clj | 1 + .../Perl/function-prototype.pl | 2 + .../Java/gui-maximum-window-dimensions.java | 23 + Task/GUI-component-interaction/00DESCRIPTION | 40 +- .../J/gui-component-interaction-1.j | 31 +- .../J/gui-component-interaction-2.j | 33 +- .../J/gui-component-interaction-3.j | 1 + .../Python/gui-component-interaction.py | 55 ++ .../Ruby/gui-component-interaction.rb | 12 +- .../00DESCRIPTION | 43 +- .../J/gui-enabling-disabling-of-controls-1.j | 22 +- .../J/gui-enabling-disabling-of-controls-2.j | 25 +- .../J/gui-enabling-disabling-of-controls-3.j | 1 + ...gui-enabling-disabling-of-controls-1.java} | 0 .../gui-enabling-disabling-of-controls-2.java | 78 ++ .../gui-enabling-disabling-of-controls.pl6 | 26 + .../gui-enabling-disabling-of-controls.scala | 35 +- Task/Galton-box-animation/00DESCRIPTION | 15 +- Task/Galton-box-animation/00META.yaml | 5 + .../D/galton-box-animation.d | 77 +- .../360-Assembly/gamma-function.360 | 159 ++++ Task/Gamma-function/C-sharp/gamma-function.cs | 27 + Task/Gamma-function/D/gamma-function.d | 4 +- Task/Gamma-function/F-Sharp/gamma-function.fs | 14 + ...{gamma-function.hs => gamma-function-1.hs} | 0 .../Haskell/gamma-function-2.hs | 7 + .../JavaScript/gamma-function.js | 19 + Task/Gamma-function/Perl-6/gamma-function.pl6 | 69 +- Task/Gamma-function/Perl/gamma-function.pl | 11 +- ...{gamma-function.rb => gamma-function-1.rb} | 0 Task/Gamma-function/Ruby/gamma-function-2.rb | 1 + .../Scilab/gamma-function.scilab | 22 + .../TI-83-BASIC/gamma-function-1.ti-83 | 6 + .../TI-83-BASIC/gamma-function-2.ti-83 | 14 + Task/Generator-Exponential/00DESCRIPTION | 7 +- .../D/generator-exponential-5.d | 28 + .../Julia/generator-exponential.julia | 16 + .../Ruby/generator-exponential-1.rb | 7 +- .../Ruby/generator-exponential-2.rb | 8 +- .../Ruby/generator-exponential-3.rb | 14 + .../Scheme/generator-exponential.ss | 27 + Task/Generic-swap/Aime/generic-swap.aime | 12 + Task/Generic-swap/Emacs-Lisp/generic-swap-1.l | 6 + Task/Generic-swap/Emacs-Lisp/generic-swap-2.l | 2 + Task/Generic-swap/Emacs-Lisp/generic-swap-3.l | 8 + .../Generic-swap/NewLISP/generic-swap.newlisp | 1 + .../Generic-swap/UNIX-Shell/generic-swap-1.sh | 10 + .../Generic-swap/UNIX-Shell/generic-swap-2.sh | 10 + ...globally-replace-text-in-several-files.clj | 3 + ...lobally-replace-text-in-several-files.java | 65 +- ...lobally-replace-text-in-several-files.math | 7 + ...globally-replace-text-in-several-files.sed | 1 + ...bally-replace-text-in-several-files-1.txr} | 6 +- ...obally-replace-text-in-several-files-2.txr | 8 + ...lobally-replace-text-in-several-files-1.sh | 13 + ...lobally-replace-text-in-several-files-2.sh | 13 + Task/Gray-code/00DESCRIPTION | 15 +- Task/Gray-code/D/gray-code-1.d | 4 +- Task/Gray-code/D/gray-code-2.d | 29 +- Task/Gray-code/Haskell/gray-code.hs | 17 +- Task/Gray-code/MATLAB/gray-code.m | 43 + Task/Gray-code/R/gray-code.r | 25 + Task/Gray-code/Ruby/gray-code.rb | 5 +- Task/Gray-code/SQL/gray-code.sql | 32 + Task/Gray-code/Seed7/gray-code.seed7 | 25 + Task/Grayscale-image/D/grayscale-image.d | 16 +- .../C++/greatest-common-divisor.cpp | 9 + .../D/greatest-common-divisor.d | 6 +- .../Frink/greatest-common-divisor.frink | 1 + .../Mercury/greatest-common-divisor-1.mercury | 11 + .../Mercury/greatest-common-divisor-2.mercury | 28 + .../Mercury/greatest-common-divisor-3.mercury | 1 + .../Oberon-2/greatest-common-divisor.oberon-2 | 22 + .../Perl/greatest-common-divisor-4.pl | 18 +- .../Perl/greatest-common-divisor-5.pl | 16 +- .../R/greatest-common-divisor-2.r | 1 + .../REXX/greatest-common-divisor-2.rexx | 4 +- .../REXX/greatest-common-divisor-3.rexx | 13 + .../Ruby/greatest-common-divisor-1.rb | 4 +- .../TXR/greatest-common-divisor.txr | 3 +- .../VBScript/greatest-common-divisor.vb | 17 + Task/Greatest-element-of-a-list/00DESCRIPTION | 3 +- Task/Greatest-element-of-a-list/00META.yaml | 2 + .../APL/greatest-element-of-a-list.apl | 2 + ...t.awk => greatest-element-of-a-list-1.awk} | 0 .../AWK/greatest-element-of-a-list-2.awk | 12 + .../Ada/greatest-element-of-a-list-1.ada | 2 +- .../Aime/greatest-element-of-a-list.aime | 9 +- .../greatest-element-of-a-list-1.cfm | 6 + .../greatest-element-of-a-list-2.cfm | 3 + .../greatest-element-of-a-list-2.math | 8 +- .../greatest-element-of-a-list-3.math | 5 +- .../greatest-element-of-a-list-1.oberon-2 | 38 + .../greatest-element-of-a-list-2.oberon-2 | 26 + .../RapidQ/greatest-element-of-a-list.rapidq | 9 + .../greatest-element-of-a-list-1.vim | 1 + .../greatest-element-of-a-list-2.vim | 19 + .../XSLT/greatest-element-of-a-list-1.xslt | 13 + .../XSLT/greatest-element-of-a-list-2.xslt | 6 + .../Yacas/greatest-element-of-a-list.yacas | 4 + Task/Greatest-subsequential-sum/00DESCRIPTION | 3 +- .../ATS/greatest-subsequential-sum.ats | 71 ++ .../greatest-subsequential-sum.component | 45 + .../D/greatest-subsequential-sum-1.d | 8 +- .../D/greatest-subsequential-sum-2.d | 24 +- .../greatest-subsequential-sum.oberon-2 | 85 ++ .../REXX/greatest-subsequential-sum-1.rexx | 32 +- .../REXX/greatest-subsequential-sum-2.rexx | 33 +- .../Ruby/greatest-subsequential-sum-1.rb | 12 +- .../Ruby/greatest-subsequential-sum-2.rb | 36 +- .../Ruby/greatest-subsequential-sum-3.rb | 22 + .../Frink/greyscale-bars-display.frink | 20 + .../MAXScript/greyscale-bars-display.max | 69 ++ .../RapidQ/greyscale-bars-display.rapidq | 28 + ...guess-the-number-with-feedback--player-.cs | 132 +++ .../guess-the-number-with-feedback--player-.m | 30 + ...ss-the-number-with-feedback--player--1.max | 26 + ...ss-the-number-with-feedback--player--2.max | 21 + ...ss-the-number-with-feedback--player--1.pro | 22 + ...ss-the-number-with-feedback--player--2.pro | 11 + ...s-the-number-with-feedback--player--1.rexx | 48 +- ...s-the-number-with-feedback--player--2.rexx | 39 +- ...ess-the-number-with-feedback--player-.rust | 78 +- ...guess-the-number-with-feedback--player-.sh | 18 + .../guess-the-number-with-feedback.alg | 47 ++ .../guess-the-number-with-feedback.bat | 17 + .../guess-the-number-with-feedback.elixir | 28 + .../MATLAB/guess-the-number-with-feedback.m | 40 +- .../guess-the-number-with-feedback-1.max | 15 + .../guess-the-number-with-feedback-2.max | 13 + .../guess-the-number-with-feedback-1.pro | 37 + .../guess-the-number-with-feedback-2.pro | 6 + .../Rust/guess-the-number-with-feedback.rust | 59 +- .../guess-the-number-with-feedback.seed7 | 4 +- .../Eiffel/guess-the-number.e | 33 + .../Elixir/guess-the-number.elixir | 24 + .../MAXScript/guess-the-number.max | 8 + .../Oberon-2/guess-the-number.oberon-2 | 24 + .../Objective-C/guess-the-number.m | 2 +- .../Prolog/guess-the-number-1.pro | 7 + .../Prolog/guess-the-number-2.pro | 6 + Task/Guess-the-number/R/guess-the-number.r | 2 +- .../REXX/guess-the-number-2.rexx | 17 +- .../RapidQ/guess-the-number.rapidq | 10 + .../Rust/guess-the-number.rust | 26 + Task/HTTP/Dart/http.dart | 4 +- Task/HTTP/JavaScript/http-1.js | 7 + Task/HTTP/JavaScript/http-2.js | 3 + Task/HTTP/JavaScript/http.js | 35 - Task/HTTP/Lua/http.lua | 22 +- Task/HTTP/Maple/http-1.maple | 1 + Task/HTTP/Maple/http-2.maple | 1 + Task/HTTP/Maple/http.maple | 1 - Task/HTTPS/Delphi/https.delphi | 5 +- Task/HTTPS/Maple/https.maple | 1 + .../Aime/hailstone-sequence.aime | 58 ++ .../Befunge/hailstone-sequence.bf | 22 +- .../D/hailstone-sequence-1.d | 2 +- .../D/hailstone-sequence-2.d | 17 +- .../D/hailstone-sequence-3.d | 30 +- .../D/hailstone-sequence-4.d | 33 + .../D/hailstone-sequence-5.d | 24 + .../Frege/hailstone-sequence.frege | 9 +- .../Pascal/hailstone-sequence.pascal | 94 +++ .../PowerShell/hailstone-sequence.psh | 41 +- .../Hailstone-sequence/R/hailstone-sequence.r | 34 + .../REXX/hailstone-sequence-1.rexx | 2 +- .../REXX/hailstone-sequence-2.rexx | 8 +- .../Ruby/hailstone-sequence-1.rb | 7 +- .../Ruby/hailstone-sequence-2.rb | 35 +- .../Rust/hailstone-sequence.rust | 27 + .../SAS/hailstone-sequence.sas | 54 ++ .../Scilab/hailstone-sequence.scilab | 33 + .../TI-83-BASIC/hailstone-sequence-1.ti-83 | 15 + .../TI-83-BASIC/hailstone-sequence-2.ti-83 | 21 + .../Visual-Basic/hailstone-sequence.vb | 57 ++ Task/Hamming-numbers/ATS/hamming-numbers.ats | 89 ++ .../Clojure/hamming-numbers.clj | 10 +- Task/Hamming-numbers/D/hamming-numbers-1.d | 8 +- Task/Hamming-numbers/D/hamming-numbers-3.d | 24 +- Task/Hamming-numbers/D/hamming-numbers-4.d | 154 ++++ Task/Hamming-numbers/Go/hamming-numbers-2.go | 146 ++-- .../Haskell/hamming-numbers-5.hs | 8 +- Task/Hamming-numbers/J/hamming-numbers-1.j | 2 +- Task/Hamming-numbers/J/hamming-numbers-6.j | 2 +- Task/Hamming-numbers/J/hamming-numbers-7.j | 2 +- Task/Hamming-numbers/J/hamming-numbers-8.j | 2 +- Task/Hamming-numbers/J/hamming-numbers-9.j | 2 +- .../Java/hamming-numbers-3.java | 110 +++ .../Julia/hamming-numbers.julia | 19 + Task/Hamming-numbers/MATLAB/hamming-numbers.m | 20 + ...amming-numbers.oz => hamming-numbers-1.oz} | 0 Task/Hamming-numbers/Oz/hamming-numbers-2.oz | 163 ++++ .../Pascal/hamming-numbers-1.pascal | 75 ++ .../Pascal/hamming-numbers-2.pascal | 329 ++++++++ Task/Hamming-numbers/Perl/hamming-numbers.pl | 10 +- Task/Hamming-numbers/R/hamming-numbers.r | 4 +- .../Hamming-numbers/Ruby/hamming-numbers-1.rb | 18 +- .../Hamming-numbers/Ruby/hamming-numbers-2.rb | 19 +- .../UNIX-Shell/hamming-numbers.sh | 36 + Task/Handle-a-signal/00DESCRIPTION | 20 +- .../JavaScript/handle-a-signal.js | 16 + .../MATLAB/handle-a-signal-1.m | 10 + .../MATLAB/handle-a-signal-2.m | 14 + .../NewLISP/handle-a-signal.newlisp | 11 + .../Perl-6/handle-a-signal.pl6 | 9 + .../Python/handle-a-signal-1.py | 27 +- .../Python/handle-a-signal-2.py | 35 +- .../Python/handle-a-signal-3.py | 38 +- .../Python/handle-a-signal-4.py | 23 + .../Scala/handle-a-signal.scala | 20 + Task/Happy-numbers/Clojure/happy-numbers.clj | 17 +- Task/Happy-numbers/D/happy-numbers-1.d | 6 +- Task/Happy-numbers/D/happy-numbers-2.d | 6 +- Task/Happy-numbers/Eiffel/happy-numbers.e | 70 ++ Task/Happy-numbers/Frege/happy-numbers.frege | 6 +- Task/Happy-numbers/Go/happy-numbers.go | 46 +- .../Happy-numbers/Groovy/happy-numbers.groovy | 15 + Task/Happy-numbers/MATLAB/happy-numbers.m | 22 + .../MAXScript/happy-numbers-1.max | 26 + .../MAXScript/happy-numbers-2.max | 8 + .../Mercury/happy-numbers.mercury | 40 + ...-numbers.pascal => happy-numbers-1.pascal} | 0 .../Pascal/happy-numbers-2.pascal | 171 ++++ Task/Happy-numbers/Perl/happy-numbers-1.pl | 17 +- Task/Happy-numbers/REXX/happy-numbers-2.rexx | 43 +- Task/Happy-numbers/REXX/happy-numbers-3.rexx | 60 +- Task/Happy-numbers/Ruby/happy-numbers-2.rb | 4 +- Task/Happy-numbers/Ruby/happy-numbers-4.rb | 18 + Task/Happy-numbers/Rust/happy-numbers.rust | 36 + Task/Harshad-or-Niven-series/00DESCRIPTION | 13 +- .../ColdFusion/harshad-or-niven-series.cfm | 39 + .../Common-Lisp/harshad-or-niven-series.lisp | 12 + .../Eiffel/harshad-or-niven-series.e | 76 ++ .../Frink/harshad-or-niven-series.frink | 2 +- .../Pascal/harshad-or-niven-series.pascal | 118 +++ .../Perl-6/harshad-or-niven-series.pl6 | 7 +- .../Ruby/harshad-or-niven-series.rb | 5 +- .../Scala/harshad-or-niven-series.scala | 6 +- Task/Hash-from-two-arrays/00DESCRIPTION | 9 +- Task/Hash-from-two-arrays/00META.yaml | 2 + .../AWK/hash-from-two-arrays.awk | 19 +- .../D/hash-from-two-arrays.d | 6 +- ...wo-arrays.js => hash-from-two-arrays-1.js} | 2 +- .../JavaScript/hash-from-two-arrays-2.js | 7 + .../MATLAB/hash-from-two-arrays.m | 15 + .../Maple/hash-from-two-arrays.maple | 3 + .../Oberon-2/hash-from-two-arrays.oberon-2 | 35 + .../REXX/hash-from-two-arrays.rexx | 18 +- .../Ruby/hash-from-two-arrays-1.rb | 11 +- .../Ruby/hash-from-two-arrays-3.rb | 4 + .../TXR/hash-from-two-arrays-1.txr | 2 + .../TXR/hash-from-two-arrays-2.txr | 2 + .../TXR/hash-from-two-arrays-3.txr | 7 + .../TXR/hash-from-two-arrays.txr | 10 - .../Tcl/hash-from-two-arrays-1.tcl | 4 +- .../Tcl/hash-from-two-arrays-2.tcl | 7 + .../UNIX-Shell/hash-from-two-arrays.sh | 11 + Task/Haversine-formula/00DESCRIPTION | 11 +- .../ATS/haversine-formula.ats | 36 + .../CoffeeScript/haversine-formula.coffee | 10 + .../Haversine-formula/D/haversine-formula-1.d | 6 +- .../Haversine-formula/D/haversine-formula-2.d | 25 +- .../Fortran/haversine-formula.f | 2 +- .../Haskell/haversine-formula.hs | 4 +- .../JavaScript/haversine-formula.js | 11 + .../MATLAB/haversine-formula.m | 10 +- .../Oberon-2/haversine-formula.oberon-2 | 27 + .../PL-I/haversine-formula.pli | 2 +- .../Python/haversine-formula.py | 10 +- ...-formula.rexx => haversine-formula-1.rexx} | 24 - .../REXX/haversine-formula-2.rexx | 24 + .../SAS/haversine-formula.sas | 51 ++ .../UBASIC/haversine-formula.ubasic | 13 + Task/Hello-world-Graphical/00META.yaml | 1 + .../ATS/hello-world-graphical.ats | 122 ++- .../AWK/hello-world-graphical.awk | 2 + .../C++/hello-world-graphical-3.cpp | 2 +- ...phical.fth => hello-world-graphical-1.fth} | 0 .../Forth/hello-world-graphical-2.fth | 1 + ...phical.lua => hello-world-graphical-1.lua} | 0 .../Lua/hello-world-graphical-2.lua | 3 + .../Perl/hello-world-graphical-4.pl | 7 +- .../Perl/hello-world-graphical-5.pl | 4 +- .../Perl/hello-world-graphical-6.pl | 7 + .../Python/hello-world-graphical-5.py | 57 +- .../Python/hello-world-graphical-6.py | 6 + .../REALbasic/hello-world-graphical.realbasic | 1 + .../VBScript/hello-world-graphical.vb | 1 + .../XSLT/hello-world-graphical-1.xslt | 21 + .../XSLT/hello-world-graphical-2.xslt | 1 + .../XSLT/hello-world-graphical-3.xslt | 8 + Task/Hello-world-Line-printer/00DESCRIPTION | 7 +- Task/Hello-world-Line-printer/00META.yaml | 4 + .../C-sharp/hello-world-line-printer.cs | 60 ++ .../Icon/hello-world-line-printer.icon | 3 + .../PL-I/hello-world-line-printer.pli | 4 +- .../Scala/hello-world-line-printer-1.scala | 13 +- .../Seed7/hello-world-line-printer.seed7 | 10 + .../Simula/hello-world-line-printer.simula | 4 + .../ATS/hello-world-newline-omission.ats | 2 +- .../C++/hello-world-newline-omission.cpp | 5 +- .../C/hello-world-newline-omission.c | 1 + .../hello-world-newline-omission-2.dylan.net | 6 +- .../hello-world-newline-omission.elixir | 1 + .../hello-world-newline-omission-1.falcon | 1 + .../hello-world-newline-omission-2.falcon | 1 + .../OOC/hello-world-newline-omission.ooc | 3 + .../hello-world-newline-omission.oberon-2 | 5 + .../REBOL/hello-world-newline-omission.rebol | 1 + .../Rust/hello-world-newline-omission.rust | 3 + .../Smalltalk/hello-world-newline-omission.st | 1 + .../hello-world-newline-omission-1.sql | 1 + .../hello-world-newline-omission-2.sql | 1 + .../hello-world-newline-omission.vim | 1 + Task/Hello-world-Standard-error/00DESCRIPTION | 20 +- .../ATS/hello-world-standard-error.ats | 2 +- .../C++/hello-world-standard-error.cpp | 7 +- .../hello-world-standard-error-2.dylan.net | 4 +- .../Frink/hello-world-standard-error.frink | 1 + .../REXX/hello-world-standard-error-2.rexx | 2 +- .../REXX/hello-world-standard-error-3.rexx | 3 +- .../REXX/hello-world-standard-error-4.rexx | 15 +- .../Rust/hello-world-standard-error.rust | 7 + .../hello-world-standard-error.sql | 1 + Task/Hello-world-Text/00DESCRIPTION | 4 +- .../360-Assembly/hello-world-text-1.360 | 8 + .../360-Assembly/hello-world-text-2.360 | 3 + .../360-Assembly/hello-world-text.360 | 16 - .../ALGOL-60/hello-world-text.alg | 4 + .../Hello-world-Text/ATS/hello-world-text.ats | 2 +- .../Aime/hello-world-text-1.aime | 2 +- .../Aime/hello-world-text-2.aime | 2 +- .../Babel/hello-world-text.pb | 2 +- .../Hello-world-Text/C++/hello-world-text.cpp | 3 +- Task/Hello-world-Text/C/hello-world-text-3.c | 7 + ...-text.coffee => hello-world-text-1.coffee} | 0 .../CoffeeScript/hello-world-text-2.coffee | 1 + .../Dylan.NET/hello-world-text-2.dylan.net | 4 +- .../Elena/hello-world-text-2.elena | 5 +- .../Elixir/hello-world-text.elixir | 1 + .../Falcon/hello-world-text-1.falcon | 1 + ...-text.falcon => hello-world-text-2.falcon} | 0 .../Fexl/hello-world-text.fexl | 2 +- .../Hello-world-Text/GML/hello-world-text.gml | 2 + .../Gentee/hello-world-text.gentee | 4 + ...orld-text.glee => hello-world-text-1.glee} | 0 .../Glee/hello-world-text-2.glee | 1 + .../Glee/hello-world-text-3.glee | 1 + .../Glee/hello-world-text-4.glee | 1 + Task/Hello-world-Text/Go/hello-world-text.go | 4 +- .../Haxe/hello-world-text.haxe | 1 + ...-world-text.ooc => hello-world-text-1.ooc} | 0 .../OOC/hello-world-text-2.ooc | 3 + .../PL-I/hello-world-text.pli | 4 +- .../Ruby/hello-world-text-3.rb | 1 + .../Rust/hello-world-text.rust | 4 +- .../SPARC-Assembly/hello-world-text.sparc | 16 + .../Scheme/hello-world-text-4.ss | 4 + .../Simula/hello-world-text.simula | 4 + .../Vim-Script/hello-world-text.vim | 1 + Task/Hello-world-Web-server/00DESCRIPTION | 19 +- Task/Hello-world-Web-server/00META.yaml | 2 + .../C/hello-world-web-server.c | 2 +- .../Clojure/hello-world-web-server.clj | 12 + .../Common-Lisp/hello-world-web-server-2.lisp | 27 +- .../Rust/hello-world-web-server.rust | 28 + ...-server.st => hello-world-web-server-1.st} | 0 .../Smalltalk/hello-world-web-server-2.st | 3 + .../Smalltalk/hello-world-web-server-3.st | 1 + ...erver.tcl => hello-world-web-server-1.tcl} | 0 .../Tcl/hello-world-web-server-2.tcl | 8 + .../UNIX-Shell/hello-world-web-server.sh | 1 + Task/Here-document/00DESCRIPTION | 11 +- Task/Here-document/00META.yaml | 3 + Task/Here-document/C++/here-document.cpp | 18 + .../Here-document/Factor/here-document.factor | 8 + Task/Here-document/Scala/here-document.scala | 27 + Task/Here-document/Tcl/here-document.tcl | 12 +- Task/Here-document/XSLT/here-document.xslt | 25 + .../ATS/higher-order-functions.ats | 13 + .../higher-order-functions.applescript | 25 + .../Inform-7/higher-order-functions.inf | 2 +- .../Oberon-2/higher-order-functions.oberon-2 | 34 + Task/History-variables/00DESCRIPTION | 10 +- .../Clojure/history-variables.clj | 3 + .../hofstadter-conway-$10,000-sequence.clj | 57 +- .../hofstadter-conway-$10,000-sequence.pascal | 120 +++ .../Bracmat/hofstadter-q-sequence.bracmat | 32 + .../Common-Lisp/hofstadter-q-sequence-2.lisp | 15 +- .../D/hofstadter-q-sequence-2.d | 22 +- .../Eiffel/hofstadter-q-sequence.e | 51 ++ .../Oberon-2/hofstadter-q-sequence.oberon-2 | 36 + .../REXX/hofstadter-q-sequence-1.rexx | 4 +- .../REXX/hofstadter-q-sequence-2.rexx | 2 +- .../Scheme/hofstadter-q-sequence.ss | 47 ++ .../Java/holidays-related-to-easter.java | 59 ++ .../Ruby/holidays-related-to-easter.rb | 43 +- Task/Honeycombs/Haskell/honeycombs.hs | 141 ++++ Task/Honeycombs/Java/honeycombs-1.java | 134 +++ Task/Honeycombs/Java/honeycombs-2.java | 184 +++++ Task/Honeycombs/MATLAB/honeycombs.m | 57 ++ Task/Honeycombs/Ruby/honeycombs.rb | 62 +- .../horizontal-sundial-calculations.euphoria | 35 + ...horners-rule-for-polynomial-evaluation.ats | 30 +- ...horners-rule-for-polynomial-evaluation.clj | 2 +- ...horners-rule-for-polynomial-evaluation-1.d | 6 +- ...horners-rule-for-polynomial-evaluation-2.d | 4 +- ...horners-rule-for-polynomial-evaluation-3.d | 4 +- ...ers-rule-for-polynomial-evaluation-1.julia | 7 + ...ers-rule-for-polynomial-evaluation-2.julia | 2 + ...ers-rule-for-polynomial-evaluation-3.julia | 1 + ...ers-rule-for-polynomial-evaluation-4.julia | 2 + ...orners-rule-for-polynomial-evaluation-1.r} | 0 ...horners-rule-for-polynomial-evaluation-2.r | 5 + ...rners-rule-for-polynomial-evaluation.rebol | 11 + ...ers-rule-for-polynomial-evaluation-1.rexx} | 15 +- ...ners-rule-for-polynomial-evaluation-2.rexx | 45 + ...ners-rule-for-polynomial-evaluation-2.rust | 8 +- Task/Host-introspection/00DESCRIPTION | 9 + .../Go/host-introspection-1.go | 95 ++- .../Host-introspection/R/host-introspection.r | 3 + .../Scala/host-introspection.scala | 7 + .../Hostname/AppleScript/hostname.applescript | 1 + Task/Hostname/Batch-File/hostname.bat | 1 + Task/Hostname/Factor/hostname.factor | 1 + .../Haskell/{hostname.hs => hostname-1.hs} | 0 Task/Hostname/Haskell/hostname-2.hs | 19 + Task/Hostname/Oberon-2/hostname.oberon-2 | 7 + Task/Hostname/Vim-Script/hostname.vim | 1 + .../Haskell/hough-transform-1.hs | 111 +++ .../Haskell/hough-transform-2.hs | 1 + .../CoffeeScript/huffman-coding.coffee | 85 ++ Task/Huffman-coding/D/huffman-coding.d | 16 +- Task/Huffman-coding/Eiffel/huffman-coding.e | 188 +++++ .../Groovy/huffman-coding-1.groovy | 50 ++ .../Groovy/huffman-coding-2.groovy | 10 + .../Mathematica/huffman-coding.math | 13 + .../Objective-C/huffman-coding.m | 12 +- Task/Huffman-coding/Perl/huffman-coding.pl | 57 ++ Task/Huffman-coding/Scheme/huffman-coding.ss | 54 ++ Task/I-before-E-except-after-C/00DESCRIPTION | 6 +- .../i-before-e-except-after-c-1.math | 42 +- .../i-before-e-except-after-c-2.math | 12 +- .../Scala/i-before-e-except-after-c.scala | 23 + Task/Identity-matrix/00DESCRIPTION | 5 +- Task/Identity-matrix/ATS/identity-matrix.ats | 33 + Task/Identity-matrix/Eiffel/identity-matrix.e | 61 ++ .../JavaScript/identity-matrix.js | 3 + .../Perl-6/identity-matrix-3.pl6 | 3 + .../REXX/identity-matrix-1.rexx | 49 +- ...dentity-matrix.rb => identity-matrix-1.rb} | 0 .../Identity-matrix/Ruby/identity-matrix-2.rb | 4 + Task/Image-convolution/D/image-convolution.d | 2 +- .../MATLAB/image-convolution.m | 168 ++++ Task/Image-noise/00DESCRIPTION | 12 +- Task/Image-noise/00META.yaml | 2 + Task/Image-noise/Common-Lisp/image-noise.lisp | 3 +- Task/Image-noise/Haskell/image-noise.hs | 68 ++ Task/Image-noise/MAXScript/image-noise.max | 33 + Task/Image-noise/Perl-6/image-noise.pl6 | 48 ++ Task/Include-a-file/C/include-a-file.c | 8 +- .../JavaScript/include-a-file-3.js | 1 + .../JavaScript/include-a-file-4.js | 1 + .../JavaScript/include-a-file-5.js | 1 + .../NewLISP/include-a-file.newlisp | 5 + Task/Include-a-file/REXX/include-a-file.rexx | 1 + Task/Increment-a-numerical-string/00META.yaml | 2 + .../AWK/increment-a-numerical-string.awk | 2 +- .../C/increment-a-numerical-string.c | 70 ++ .../Eiffel/increment-a-numerical-string.e | 17 + .../Frink/increment-a-numerical-string.frink | 3 +- .../Go/increment-a-numerical-string-2.go | 16 +- .../Neko/increment-a-numerical-string.neko | 4 + .../increment-a-numerical-string.newlisp | 1 + .../REXX/increment-a-numerical-string-1.rexx | 20 +- .../increment-a-numerical-string.rascal | 3 + Task/Infinity/Rust/infinity.rust | 4 + Task/Inheritance-Multiple/00DESCRIPTION | 8 +- .../Objective-C/inheritance-multiple.m | 8 +- .../Oberon-2/inheritance-single.oberon-2 | 18 + Task/Input-loop/00DESCRIPTION | 8 +- Task/Input-loop/Bracmat/input-loop.bracmat | 27 + Task/Input-loop/D/input-loop-1.d | 25 +- Task/Input-loop/D/input-loop-2.d | 6 +- Task/Input-loop/D/input-loop-3.d | 8 + Task/Input-loop/Go/input-loop-1.go | 26 + Task/Input-loop/Go/input-loop-2.go | 24 + Task/Input-loop/Go/input-loop.go | 17 - Task/Input-loop/NetRexx/input-loop-1.netrexx | 2 +- Task/Input-loop/Oberon-2/input-loop.oberon-2 | 18 + Task/Input-loop/PL-I/input-loop.pli | 2 +- Task/Input-loop/REXX/input-loop-2.rexx | 9 +- Task/Input-loop/REXX/input-loop-3.rexx | 11 +- Task/Input-loop/REXX/input-loop-4.rexx | 6 + Task/Input-loop/REXX/input-loop-5.rexx | 6 + Task/Integer-comparison/00DESCRIPTION | 6 +- .../360-Assembly/integer-comparison.360 | 33 + ...rison.basic => integer-comparison-1.basic} | 0 .../BASIC/integer-comparison-2.basic | 5 + .../Brat/integer-comparison.brat | 6 + .../Excel/integer-comparison-1.excel | 1 + .../Excel/integer-comparison-2.excel | 1 + .../Frink/integer-comparison.frink | 2 +- .../Go/integer-comparison.go | 46 +- .../Julia/integer-comparison.julia | 10 + .../Rust/integer-comparison.rust | 15 + .../XPL0/integer-comparison.xpl0 | 7 +- .../C++/integer-sequence-1.cpp | 11 + .../C++/integer-sequence-2.cpp | 19 + .../Integer-sequence/C++/integer-sequence.cpp | 11 - .../NewLISP/integer-sequence.newlisp | 1 + .../Oberon-2/integer-sequence.oberon-2 | 27 + ...eger-sequence.pl => integer-sequence-1.pl} | 0 .../Perl/integer-sequence-2.pl | 2 + Task/Integer-sequence/R/integer-sequence.r | 5 + .../REXX/integer-sequence.rexx | 8 +- .../Integer-sequence/Ruby/integer-sequence.rb | 3 +- .../interactive-programming.coffee | 5 + Task/Introspection/D/introspection.d | 3 +- ...{introspection.fth => introspection-1.fth} | 0 Task/Introspection/Forth/introspection-2.fth | 11 + Task/Introspection/Julia/introspection.julia | 5 + .../UNIX-Shell/introspection-1.sh | 22 + .../UNIX-Shell/introspection-2.sh | 26 + .../Inverted-index/Scala/inverted-index.scala | 31 + Task/Inverted-syntax/C++/inverted-syntax.cpp | 22 + Task/JSON/00DESCRIPTION | 7 +- Task/JSON/Bracmat/json-1.bracmat | 1 + Task/JSON/Bracmat/json-2.bracmat | 1 + Task/JSON/Bracmat/json-3.bracmat | 1 + Task/JSON/Bracmat/json-4.bracmat | 1 + Task/JSON/Bracmat/json-5.bracmat | 1 + Task/JSON/Bracmat/json-6.bracmat | 4 + Task/JSON/D/json.d | 2 +- Task/JSON/Haskell/{json.hs => json-1.hs} | 0 Task/JSON/Haskell/json-2.hs | 16 + Task/JSON/Lua/json.lua | 38 + Task/JSON/PowerShell/json-1.psh | 7 + Task/JSON/PowerShell/json-2.psh | 11 + Task/JSON/Prolog/json-1.pro | 22 + Task/JSON/Prolog/json-2.pro | 19 + Task/JSON/Rust/json.rust | 14 + Task/JSON/Smalltalk/json.st | 1 + Task/Jensens-Device/D/jensens-device.d | 8 +- Task/Jensens-Device/REXX/jensens-device.rexx | 3 +- Task/Josephus-problem/00DESCRIPTION | 16 +- Task/Josephus-problem/D/josephus-problem.d | 11 +- .../PL-I/josephus-problem.pli | 2 +- ...ephus-problem.py => josephus-problem-1.py} | 0 .../Python/josephus-problem-2.py | 11 + .../Python/josephus-problem-3.py | 19 + Task/Joystick-position/00DESCRIPTION | 22 +- Task/Joystick-position/00META.yaml | 2 + .../D/k-means++-clustering.d | 8 +- .../Mathematica/k-means++-clustering.math | 24 + .../Perl-6/k-means++-clustering.pl6 | 24 + Task/Kaprekar-numbers/00DESCRIPTION | 12 +- .../C-sharp/kaprekar-numbers.cs | 63 ++ Task/Kaprekar-numbers/D/kaprekar-numbers-1.d | 4 +- Task/Kaprekar-numbers/D/kaprekar-numbers-2.d | 7 +- .../Julia/kaprekar-numbers.julia | 6 + .../Perl/kaprekar-numbers-1.pl | 17 + .../Perl/kaprekar-numbers-2.pl | 17 + .../Kaprekar-numbers/Perl/kaprekar-numbers.pl | 11 - .../REXX/kaprekar-numbers.rexx | 24 +- .../00DESCRIPTION | 12 +- .../00META.yaml | 4 + ...rd-input-flush-the-keyboard-buffer-1.basic | 2 +- ...rd-input-flush-the-keyboard-buffer-2.basic | 2 +- ...rd-input-flush-the-keyboard-buffer-3.basic | 1 + ...eyboard-input-flush-the-keyboard-buffer.go | 16 + .../00DESCRIPTION | 3 +- .../Go/keyboard-input-keypress-check.go | 41 + .../Python/keyboard-input-keypress-check.py | 4 +- .../00DESCRIPTION | 4 +- .../00META.yaml | 3 + ...keyboard-input-obtain-a-y-or-n-response.go | 30 + ...oard-input-obtain-a-y-or-n-response-1.rexx | 11 +- ...oard-input-obtain-a-y-or-n-response-2.rexx | 6 +- ...oard-input-obtain-a-y-or-n-response-3.rexx | 8 + .../Keyboard-macros/Icon/keyboard-macros.icon | 21 + Task/Knapsack-problem-0-1/00DESCRIPTION | 15 +- Task/Knapsack-problem-0-1/00META.yaml | 1 + .../D/knapsack-problem-0-1-1.d | 6 +- .../D/knapsack-problem-0-1-2.d | 8 +- .../JavaScript/knapsack-problem-0-1.js | 202 +++++ .../MAXScript/knapsack-problem-0-1-1.max | 63 ++ .../MAXScript/knapsack-problem-0-1-2.max | 15 + .../REXX/knapsack-problem-0-1.rexx | 181 ++-- .../Ruby/knapsack-problem-0-1-1.rb | 50 +- .../Ruby/knapsack-problem-0-1-2.rb | 87 +- .../Rust/knapsack-problem-0-1.rust | 140 ++++ .../Scala/knapsack-problem-0-1.scala | 9 +- .../D/knapsack-problem-bounded.d | 11 +- .../Go/knapsack-problem-bounded.go | 77 +- .../REXX/knapsack-problem-bounded.rexx | 335 ++++---- .../knapsack-problem-continuous.bracmat | 50 ++ ....cpp => knapsack-problem-continuous-1.cpp} | 0 .../C++/knapsack-problem-continuous-2.cpp | 53 ++ .../Clojure/knapsack-problem-continuous.clj | 48 ++ .../D/knapsack-problem-continuous-1.d | 8 +- .../Fortran/knapsack-problem-continuous.f | 2 +- .../PL-I/knapsack-problem-continuous.pli | 75 ++ .../REXX/knapsack-problem-continuous-1.rexx | 47 ++ .../REXX/knapsack-problem-continuous-2.rexx | 77 ++ .../REXX/knapsack-problem-continuous.rexx | 63 -- .../Ruby/knapsack-problem-continuous.rb | 20 + .../D/knapsack-problem-unbounded-1.d | 32 +- .../D/knapsack-problem-unbounded-2.d | 50 +- .../Go/knapsack-problem-unbounded.go | 94 +-- .../REXX/knapsack-problem-unbounded.rexx | 59 +- .../Ruby/knapsack-problem-unbounded.rb | 4 +- .../knapsack-problem-unbounded.vb | 25 + Task/Knights-tour/00DESCRIPTION | 4 + Task/Knights-tour/ALGOL-68/knights-tour.alg | 288 +++++++ Task/Knights-tour/AWK/knights-tour.awk | 68 ++ Task/Knights-tour/Ada/knights-tour-1.ada | 12 +- Task/Knights-tour/Ada/knights-tour-2.ada | 50 +- Task/Knights-tour/Ada/knights-tour-4.ada | 3 +- Task/Knights-tour/Ada/knights-tour-5.ada | 11 +- .../D/{knights-tour.d => knights-tour-1.d} | 0 Task/Knights-tour/D/knights-tour-2.d | 27 + .../{knights-tour.pro => knights-tour-1.pro} | 0 Task/Knights-tour/Prolog/knights-tour-2.pro | 57 ++ Task/Knights-tour/REXX/knights-tour.rexx | 53 +- Task/Knights-tour/Ruby/knights-tour.rb | 110 +-- Task/Knights-tour/Scheme/knights-tour.ss | 46 ++ Task/Knuth-shuffle/00DESCRIPTION | 3 +- Task/Knuth-shuffle/Eiffel/knuth-shuffle.e | 46 ++ Task/Knuth-shuffle/Frink/knuth-shuffle.frink | 2 + Task/Knuth-shuffle/GAP/knuth-shuffle.gap | 20 +- .../Knuth-shuffle/Objective-C/knuth-shuffle.m | 22 + .../Knuth-shuffle/UNIX-Shell/knuth-shuffle.sh | 1 - .../D/knuths-algorithm-s-1.d | 2 +- .../D/knuths-algorithm-s-2.d | 8 +- Task/LU-decomposition/00DESCRIPTION | 18 +- Task/LU-decomposition/D/lu-decomposition.d | 6 +- .../Fortran/lu-decomposition.f | 125 ++- ...decomposition.rb => lu-decomposition-1.rb} | 30 +- .../Ruby/lu-decomposition-2.rb | 4 + Task/LZW-compression/00DESCRIPTION | 2 +- Task/LZW-compression/C/lzw-compression.c | 2 +- .../CoffeeScript/lzw-compression.coffee | 36 + Task/LZW-compression/D/lzw-compression-2.d | 9 +- Task/LZW-compression/D/lzw-compression-3.d | 222 +++++ .../JavaScript/lzw-compression.js | 81 ++ .../Liberty-BASIC/lzw-compression.liberty | 280 +++++++ Task/LZW-compression/PHP/lzw-compression.php | 4 +- .../LZW-compression/Python/lzw-compression.py | 11 +- .../LZW-compression/REXX/lzw-compression.rexx | 76 ++ .../Scala/lzw-compression.scala | 31 +- Task/Langtons-ant/00DESCRIPTION | 15 +- Task/Langtons-ant/AWK/langtons-ant.awk | 93 +++ Task/Langtons-ant/AutoHotkey/langtons-ant.ahk | 74 +- Task/Langtons-ant/D/langtons-ant-1.d | 43 +- Task/Langtons-ant/Fortran/langtons-ant.f | 35 + Task/Langtons-ant/Logo/langtons-ant.logo | 51 ++ Task/Langtons-ant/Lua/langtons-ant.lua | 107 +++ Task/Langtons-ant/Python/langtons-ant.py | 4 +- Task/Langtons-ant/REXX/langtons-ant.rexx | 68 +- .../{langtons-ant.rb => langtons-ant-1.rb} | 0 Task/Langtons-ant/Ruby/langtons-ant-2.rb | 27 + Task/Langtons-ant/Rust/langtons-ant.rust | 76 ++ Task/Langtons-ant/Seed7/langtons-ant.seed7 | 30 + .../D/largest-int-from-concatenated-ints.d | 10 +- .../largest-int-from-concatenated-ints.lua | 10 + .../largest-int-from-concatenated-ints.math | 7 + ...argest-int-from-concatenated-ints-1.pascal | 139 ++++ ...argest-int-from-concatenated-ints-2.pascal | 126 +++ .../largest-int-from-concatenated-ints.rexx | 43 +- .../largest-int-from-concatenated-ints.scala | 7 +- .../largest-int-from-concatenated-ints.ss | 6 + Task/Last-Friday-of-each-month/00DESCRIPTION | 4 +- Task/Last-Friday-of-each-month/00META.yaml | 3 + .../Clojure/last-friday-of-each-month.clj | 11 + .../last-friday-of-each-month.lisp | 14 + .../Go/last-friday-of-each-month.go | 30 +- .../Haskell/last-friday-of-each-month.hs | 26 + .../REBOL/last-friday-of-each-month-1.rebol | 22 + .../REBOL/last-friday-of-each-month-2.rebol | 12 + .../Racket/last-friday-of-each-month.rkt | 41 + .../D/last-letter-first-letter-1.d | 26 +- .../D/last-letter-first-letter-4.d | 21 +- .../D/last-letter-first-letter-5.d | 29 +- .../REXX/last-letter-first-letter-1.rexx | 34 +- .../REXX/last-letter-first-letter-2.rexx | 59 +- .../Scala/last-letter-first-letter-1.scala | 21 + .../Scala/last-letter-first-letter-2.scala | 26 + .../Scala/last-letter-first-letter-3.scala | 27 + Task/Leap-year/Ada/leap-year.ada | 18 +- Task/Leap-year/C++/leap-year.cpp | 11 + Task/Leap-year/C/leap-year.c | 11 +- .../D/{leap-year.d => leap-year-1.d} | 0 Task/Leap-year/D/leap-year-2.d | 8 + Task/Leap-year/Excel/leap-year.excel | 1 + Task/Leap-year/Haskell/leap-year-4.hs | 2 +- Task/Leap-year/Java/leap-year.java | 11 +- Task/Leap-year/PHP/leap-year-1.php | 8 +- Task/Leap-year/PHP/leap-year-2.php | 4 +- Task/Leap-year/PL-I/leap-year.pli | 2 +- Task/Leap-year/REXX/leap-year-2.rexx | 4 +- Task/Leap-year/REXX/leap-year-3.rexx | 6 +- Task/Leap-year/REXX/leap-year-4.rexx | 5 + Task/Leap-year/Smalltalk/leap-year.st | 1 + .../Clojure/least-common-multiple.clj | 2 + .../D/least-common-multiple.d | 4 +- .../Groovy/least-common-multiple.groovy | 11 + .../REXX/least-common-multiple-1.rexx | 24 + .../REXX/least-common-multiple-2.rexx | 21 + .../REXX/least-common-multiple-3.rexx | 72 ++ .../REXX/least-common-multiple.rexx | 27 - .../Smalltalk/least-common-multiple.st | 1 + Task/Letter-frequency/00DESCRIPTION | 3 +- Task/Letter-frequency/00META.yaml | 4 + .../Letter-frequency/AWK/letter-frequency.awk | 7 +- Task/Letter-frequency/D/letter-frequency.d | 4 +- .../Eiffel/letter-frequency.e | 41 + .../Euphoria/letter-frequency.euphoria | 24 + Task/Letter-frequency/J/letter-frequency-1.j | 5 +- .../Julia/letter-frequency.julia | 5 + Task/Letter-frequency/K/letter-frequency-3.k | 11 +- .../Python/letter-frequency-2.py | 8 +- .../Rust/letter-frequency.rust | 21 + .../Scheme/letter-frequency-1.ss | 21 + .../Scheme/letter-frequency-2.ss | 8 + .../Scheme/letter-frequency.ss | 36 - .../Aime/levenshtein-distance.aime | 2 +- .../C/levenshtein-distance-1.c | 2 +- .../C/levenshtein-distance-2.c | 2 +- ...istance.clj => levenshtein-distance-1.clj} | 0 .../Clojure/levenshtein-distance-2.clj | 21 + .../D/levenshtein-distance-1.d | 6 +- .../D/levenshtein-distance-2.d | 6 +- .../D/levenshtein-distance-3.d | 53 +- .../Julia/levenshtein-distance.julia | 20 + .../Lua/levenshtein-distance.lua | 29 +- .../Objeck/levenshtein-distance.objeck | 34 + .../PL-I/levenshtein-distance-1.pli | 56 ++ .../PL-I/levenshtein-distance-2.pli | 45 + .../Pascal/levenshtein-distance.pascal | 6 +- ...tance.rexx => levenshtein-distance-1.rexx} | 0 .../REXX/levenshtein-distance-2.rexx | 30 + .../REXX/levenshtein-distance-3.rexx | 22 + .../REXX/levenshtein-distance-4.rexx | 38 + ...-distance.rb => levenshtein-distance-1.rb} | 2 + .../Ruby/levenshtein-distance-2.rb | 34 + .../Scheme/levenshtein-distance.ss | 45 +- .../D/linear-congruential-generator.d | 18 +- .../Perl-6/linear-congruential-generator.pl6 | 20 +- .../REXX/linear-congruential-generator.rexx | 21 +- .../linear-congruential-generator.sh | 25 + .../Prolog/list-comprehensions.pro | 13 + .../REXX/list-comprehensions-1.rexx | 21 + .../REXX/list-comprehensions-2.rexx | 17 + .../REXX/list-comprehensions.rexx | 36 - .../Eiffel/literals-floating-point.e | 5 + .../Euphoria/literals-floating-point.euphoria | 3 + Task/Literals-Integer/00META.yaml | 2 + .../Eiffel/literals-integer-1.e | 5 + .../Eiffel/literals-integer-2.e | 2 + .../Euphoria/literals-integer.euphoria | 6 + .../Julia/literals-integer.julia | 2 + .../Mercury/literals-integer.mercury | 4 + Task/Literals-String/00DESCRIPTION | 4 +- Task/Literals-String/00META.yaml | 3 + .../Emacs-Lisp/literals-string-1.l | 1 + .../Emacs-Lisp/literals-string-2.l | 2 + Task/Literals-String/Go/literals-string-1.go | 5 + Task/Literals-String/Go/literals-string-2.go | 16 +- Task/Literals-String/Go/literals-string-3.go | 2 + Task/Literals-String/Go/literals-string-6.go | 2 +- .../REXX/literals-string-3.rexx | 15 +- .../REXX/literals-string-4.rexx | 5 + Task/Logical-operations/00DESCRIPTION | 4 +- .../Excel/logical-operations-1.excel | 1 + .../Excel/logical-operations-2.excel | 1 + .../Excel/logical-operations-3.excel | 1 + .../OOC/logical-operations.ooc | 14 + .../Perl-6/logical-operations.pl6 | 29 + .../Rascal/logical-operations.rascal | 9 + .../Ruby/logical-operations.rb | 7 +- .../Slate/logical-operations.slate | 9 + .../D/long-multiplication-2.d | 10 +- .../PicoLisp/long-multiplication.l | 7 +- .../Scheme/long-multiplication.ss | 9 +- .../APL/longest-common-subsequence.apl | 21 + .../C++/longest-common-subsequence-1.cpp | 154 ++++ .../C++/longest-common-subsequence-2.cpp | 3 + .../longest-common-subsequence-4.lisp | 14 + .../longest-common-subsequence-5.lisp | 3 + .../D/longest-common-subsequence-1.d | 2 +- .../D/longest-common-subsequence-3.d | 31 +- .../Erlang/longest-common-subsequence-3.erl | 23 + .../Go/longest-common-subsequence-2.go | 75 +- .../OCaml/longest-common-subsequence-2.ocaml | 35 +- .../OCaml/longest-common-subsequence-3.ocaml | 25 +- .../OCaml/longest-common-subsequence-4.ocaml | 10 + .../Ruby/longest-common-subsequence-1.rb | 14 +- .../Ruby/longest-common-subsequence-2.rb | 47 +- .../Scala/longest-common-subsequence.scala | 1 - .../Ada/longest-string-challenge-1.ada | 17 +- .../Ada/longest-string-challenge-2.ada | 36 +- .../Java/longest-string-challenge.java | 28 + .../Lua/longest-string-challenge-1.lua | 26 + .../Lua/longest-string-challenge-2.lua | 7 + ...lenge.rb => longest-string-challenge-1.rb} | 0 .../Ruby/longest-string-challenge-2.rb | 1 + .../Scala/longest-string-challenge.scala | 2 + Task/Look-and-say-sequence/00DESCRIPTION | 5 +- .../Bracmat/look-and-say-sequence.bracmat | 23 + .../D/look-and-say-sequence-5.d | 137 ++++ .../Elixir/look-and-say-sequence.elixir | 5 +- ...sequence.js => look-and-say-sequence-1.js} | 0 .../JavaScript/look-and-say-sequence-2.js | 26 + .../PHP/look-and-say-sequence.php | 18 +- ....pascal => look-and-say-sequence-1.pascal} | 0 .../Pascal/look-and-say-sequence-2.pascal | 78 ++ ...ce.scala => look-and-say-sequence-1.scala} | 0 .../Scala/look-and-say-sequence-2.scala | 17 + .../UNIX-Shell/look-and-say-sequence.sh | 17 + .../00DESCRIPTION | 3 +- ...loop-over-multiple-arrays-simultaneously.c | 11 + ...oop-over-multiple-arrays-simultaneously.go | 12 +- ...op-over-multiple-arrays-simultaneously-1.j | 5 +- ...op-over-multiple-arrays-simultaneously-2.j | 5 +- ...op-over-multiple-arrays-simultaneously-3.j | 5 +- ...op-over-multiple-arrays-simultaneously-4.j | 5 +- ...op-over-multiple-arrays-simultaneously-5.j | 9 +- ...p-over-multiple-arrays-simultaneously.java | 4 +- ...op-over-multiple-arrays-simultaneously-2.k | 4 +- ...op-over-multiple-arrays-simultaneously-3.k | 2 +- ...op-over-multiple-arrays-simultaneously-4.k | 2 +- ...ver-multiple-arrays-simultaneously.newlisp | 1 + ...er-multiple-arrays-simultaneously.oberon-2 | 24 + ...over-multiple-arrays-simultaneously-1.rexx | 6 +- ...over-multiple-arrays-simultaneously-2.rexx | 6 +- ...over-multiple-arrays-simultaneously-3.rexx | 8 + ...over-multiple-arrays-simultaneously-4.rexx | 7 + ...p-over-multiple-arrays-simultaneously-2.rb | 2 +- Task/Loops-Break/00DESCRIPTION | 5 +- Task/Loops-Break/00META.yaml | 1 + Task/Loops-Break/Batch-File/loops-break.bat | 2 + Task/Loops-Break/ColdFusion/loops-break.cfm | 8 + Task/Loops-Break/MAXScript/loops-break.max | 8 + Task/Loops-Break/NewLISP/loops-break.newlisp | 2 + .../Loops-Break/Oberon-2/loops-break.oberon-2 | 21 + Task/Loops-Break/PL-I/loops-break.pli | 4 +- Task/Loops-Break/Ruby/loops-break-1.rb | 10 + Task/Loops-Break/Ruby/loops-break-2.rb | 5 + Task/Loops-Break/Ruby/loops-break.rb | 9 - .../TorqueScript/loops-break.torque | 2 +- Task/Loops-Continue/00DESCRIPTION | 5 +- Task/Loops-Continue/00META.yaml | 2 + Task/Loops-Continue/Ada/loops-continue.ada | 22 +- .../Applesoft-BASIC/loops-continue.applesoft | 5 + .../Clojure/loops-continue-1.clj | 5 + .../Clojure/loops-continue-2.clj | 7 + .../Loops-Continue/Clojure/loops-continue.clj | 5 - .../NewLISP/loops-continue.newlisp | 5 + Task/Loops-Continue/Ruby/loops-continue-3.rb | 2 +- Task/Loops-Do-while/00DESCRIPTION | 4 +- Task/Loops-Do-while/00META.yaml | 1 + .../360-Assembly/loops-do-while.360 | 26 + .../Emacs-Lisp/loops-do-while.l | 5 + .../Euphoria/loops-do-while.euphoria | 12 + .../NewLISP/loops-do-while.newlisp | 3 + .../Oberon-2/loops-do-while.oberon-2 | 18 + .../OpenEdge-Progress/loops-do-while.openedge | 6 + ...ps-do-while.pari => loops-do-while-1.pari} | 2 +- .../PARI-GP/loops-do-while-2.pari | 2 + .../Suneido/loops-do-while.suneido | 5 + Task/Loops-Downward-for/00META.yaml | 2 + .../NewLISP/loops-downward-for.newlisp | 2 + .../00DESCRIPTION | 2 +- .../00META.yaml | 2 + .../AWK/loops-for-with-a-specified-step.awk | 6 +- .../loops-for-with-a-specified-step.cfm | 3 + .../J/loops-for-with-a-specified-step-4.j | 1 + .../J/loops-for-with-a-specified-step-5.j | 6 + .../J/loops-for-with-a-specified-step-6.j | 2 + .../loops-for-with-a-specified-step-1.max | 1 + .../loops-for-with-a-specified-step-2.max | 7 + .../loops-for-with-a-specified-step.newlisp | 2 + .../loops-for-with-a-specified-step.oberon-2 | 14 + .../loops-for-with-a-specified-step.torque | 4 + .../loops-for-with-a-specified-step.vim | 3 + Task/Loops-For/00DESCRIPTION | 1 + Task/Loops-For/00META.yaml | 2 + Task/Loops-For/ALGOL-60/loops-for.alg | 4 + .../AppleScript/loops-for.applescript | 8 + Task/Loops-For/BASIC/loops-for-11.basic | 14 +- Task/Loops-For/BASIC/loops-for-12.basic | 21 +- Task/Loops-For/BASIC/loops-for-13.basic | 12 +- Task/Loops-For/Babel/loops-for.pb | 22 +- Task/Loops-For/Oberon-2/loops-for.oberon-2 | 14 + Task/Loops-For/PL-I/loops-for-1.pli | 6 + .../PL-I/{loops-for.pli => loops-for-2.pli} | 0 Task/Loops-For/PL-I/loops-for-3.pli | 1 + Task/Loops-For/Ruby/loops-for-1.rb | 8 +- Task/Loops-For/Ruby/loops-for-2.rb | 10 +- Task/Loops-For/Ruby/loops-for-3.rb | 11 +- Task/Loops-For/Ruby/loops-for-4.rb | 15 +- Task/Loops-For/Ruby/loops-for-5.rb | 11 +- Task/Loops-For/Ruby/loops-for-6.rb | 1 + Task/Loops-For/Simula/loops-for.simula | 4 + Task/Loops-For/TI-83-BASIC/loops-for.ti-83 | 13 +- Task/Loops-Foreach/AWK/loops-foreach-2.awk | 7 +- Task/Loops-Foreach/C++/loops-foreach-2.cpp | 2 +- Task/Loops-Foreach/C++/loops-foreach-4.cpp | 2 - Task/Loops-Foreach/C++/loops-foreach-5.cpp | 2 - Task/Loops-Foreach/C++/loops-foreach-6.cpp | 4 + .../ColdFusion/loops-foreach.cfm | 3 + .../Emacs-Lisp/loops-foreach-1.l | 2 + .../Emacs-Lisp/loops-foreach-2.l | 3 + .../Euphoria/loops-foreach.euphoria | 24 + .../Loops-Foreach/MAXScript/loops-foreach.max | 9 +- .../NewLISP/loops-foreach.newlisp | 1 + Task/Loops-Foreach/Prolog/loops-foreach.pro | 7 + Task/Loops-Foreach/Python/loops-foreach-2.py | 2 +- Task/Loops-Foreach/Python/loops-foreach-3.py | 7 + Task/Loops-Foreach/Python/loops-foreach-4.py | 3 + Task/Loops-Foreach/REXX/loops-foreach.rexx | 3 +- .../Vim-Script/loops-foreach.vim | 3 + Task/Loops-Infinite/00META.yaml | 2 + .../360-Assembly/loops-infinite.360 | 16 + .../BASIC/loops-infinite-4.basic | 1 + .../Loops-Infinite/Fortran/loops-infinite-1.f | 18 +- .../Loops-Infinite/Fortran/loops-infinite-2.f | 9 +- .../Intercal/loops-infinite.ical | 11 + .../Loops-Infinite/LOLCODE/loops-infinite.lol | 6 + Task/Loops-Infinite/MATLAB/loops-infinite.m | 4 +- .../NewLISP/loops-infinite.newlisp | 1 + .../Oberon-2/loops-infinite.oberon-2 | 8 + .../Loops-Infinite/REXX/loops-infinite-3.rexx | 1 - .../Loops-Infinite/REXX/loops-infinite-4.rexx | 7 + Task/Loops-Infinite/Rust/loops-infinite.rust | 5 + Task/Loops-N-plus-one-half/00DESCRIPTION | 7 +- Task/Loops-N-plus-one-half/00META.yaml | 2 + ...e-half.awk => loops-n-plus-one-half-1.awk} | 1 - .../AWK/loops-n-plus-one-half-2.awk | 8 + .../Go/loops-n-plus-one-half.go | 2 +- .../Julia/loops-n-plus-one-half-1.julia | 5 + .../Julia/loops-n-plus-one-half-2.julia | 1 + .../Maple/loops-n-plus-one-half.maple | 2 + .../NewLISP/loops-n-plus-one-half.newlisp | 4 + .../Pascal/loops-n-plus-one-half.pascal | 10 +- .../REXX/loops-n-plus-one-half-3.rexx | 7 + .../Ruby/loops-n-plus-one-half-1.rb | 6 + .../Ruby/loops-n-plus-one-half-2.rb | 1 + .../Ruby/loops-n-plus-one-half.rb | 6 - .../Scala/loops-n-plus-one-half.scala | 3 + .../Vim-Script/loops-n-plus-one-half.vim | 6 + Task/Loops-Nested/00DESCRIPTION | 4 +- Task/Loops-Nested/ColdFusion/loops-nested.cfm | 9 + .../Loops-Nested/MAXScript/loops-nested-1.max | 11 + .../Loops-Nested/MAXScript/loops-nested-2.max | 11 + .../Loops-Nested/NewLISP/loops-nested.newlisp | 11 + Task/Loops-Nested/OoRexx/loops-nested.rexx | 14 + Task/Loops-Nested/REXX/loops-nested.rexx | 32 +- .../{loops-nested.rb => loops-nested-1.rb} | 1 - Task/Loops-Nested/Ruby/loops-nested-2.rb | 8 + Task/Loops-While/00DESCRIPTION | 4 +- Task/Loops-While/00META.yaml | 3 + Task/Loops-While/360-Assembly/loops-while.360 | 27 + Task/Loops-While/ALGOL-60/loops-while.alg | 7 + Task/Loops-While/Bracmat/loops-while.bracmat | 1 + Task/Loops-While/Emacs-Lisp/loops-while.l | 4 + Task/Loops-While/Fortran/loops-while-2.f | 16 - Task/Loops-While/Fortran/loops-while-3.f | 12 + Task/Loops-While/NewLISP/loops-while.newlisp | 4 + Task/Loops-While/OOC/loops-while.ooc | 7 + Task/Loops-While/Prolog/loops-while-1.pro | 5 + Task/Loops-While/Prolog/loops-while-2.pro | 1 + Task/Loops-While/Prolog/loops-while.pro | 2 - Task/Loops-While/Ruby/loops-while-2.rb | 4 +- Task/Loops-While/Rust/loops-while.rust | 7 + .../Loops-While/TI-83-BASIC/loops-while.ti-83 | 5 + Task/Loops-While/Vim-Script/loops-while.vim | 5 + .../360-Assembly/lucas-lehmer-test.360 | 73 ++ .../C++/lucas-lehmer-test.cpp | 52 +- .../Lucas-Lehmer-test/C/lucas-lehmer-test-1.c | 76 ++ ...as-lehmer-test.c => lucas-lehmer-test-2.c} | 0 Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d | 4 +- .../Perl-6/lucas-lehmer-test.pl6 | 11 +- .../Perl/lucas-lehmer-test-1.pl | 16 + .../Perl/lucas-lehmer-test-2.pl | 8 + .../Perl/lucas-lehmer-test-3.pl | 7 + ...-lehmer-test.pl => lucas-lehmer-test-4.pl} | 0 .../REXX/lucas-lehmer-test.rexx | 93 +-- .../Scala/lucas-lehmer-test.scala | 2 +- .../Scilab/lucas-lehmer-test.scilab | 10 + .../TI-83-BASIC/lucas-lehmer-test.ti-83 | 15 + .../VBScript/lucas-lehmer-test.vb | 18 + .../lucas-lehmer-test.visual | 23 + .../00DESCRIPTION | 1 + .../00META.yaml | 2 + .../luhn-test-of-credit-card-numbers.clj | 16 +- .../D/luhn-test-of-credit-card-numbers-1.d | 23 +- .../D/luhn-test-of-credit-card-numbers-2.d | 65 +- .../D/luhn-test-of-credit-card-numbers-3.d | 60 ++ .../K/luhn-test-of-credit-card-numbers-4.k | 6 + .../K/luhn-test-of-credit-card-numbers-5.k | 3 + ...> luhn-test-of-credit-card-numbers-1.math} | 0 .../luhn-test-of-credit-card-numbers-2.math | 6 + .../luhn-test-of-credit-card-numbers.openedge | 49 ++ .../R/luhn-test-of-credit-card-numbers.r | 19 + .../Ruby/luhn-test-of-credit-card-numbers.rb | 15 + .../luhn-test-of-credit-card-numbers.rust | 48 ++ .../luhn-test-of-credit-card-numbers-1.scala | 15 +- .../luhn-test-of-credit-card-numbers.sh | 36 + .../luhn-test-of-credit-card-numbers.vb | 33 + Task/MD4/00DESCRIPTION | 4 +- Task/MD4/Clojure/md4.clj | 2 + Task/MD4/D/md4.d | 47 ++ Task/MD4/Go/md4.go | 2 +- Task/MD4/PicoLisp/md4.l | 176 ++++ Task/MD4/Racket/md4.rkt | 3 + Task/MD4/Ruby/md4-2.rb | 45 +- Task/MD4/Scala/md4.scala | 12 + .../MD5-Implementation/D/md5-implementation.d | 40 +- .../Perl-6/md5-implementation.pl6 | 6 +- .../Python/md5-implementation.py | 2 +- Task/MD5/AutoHotkey/md5-1.ahk | 1 - Task/MD5/C/md5-2.c | 4 + Task/MD5/Maple/md5.maple | 21 + Task/MD5/NewLISP/md5.newlisp | 4 + Task/MD5/REXX/md5.rexx | 215 +++-- Task/MD5/Scala/md5.scala | 26 +- Task/Mad-Libs/00DESCRIPTION | 4 +- Task/Mad-Libs/ALGOL-68/mad-libs.alg | 128 +++ Task/Mad-Libs/C-sharp/mad-libs.cs | 25 + Task/Mad-Libs/Haskell/mad-libs.hs | 49 ++ Task/Mad-Libs/Mathematica/mad-libs.math | 14 + Task/Mad-Libs/REBOL/mad-libs.rebol | 7 + Task/Mad-Libs/REXX/mad-libs.rexx | 16 +- Task/Mad-Libs/Ruby/mad-libs.rb | 6 +- Task/Mad-Libs/Scala/mad-libs.scala | 14 + .../D/main-step-of-gost-28147-89.d | 25 +- .../Go/main-step-of-gost-28147-89.go | 1 + .../PicoLisp/main-step-of-gost-28147-89.l | 62 ++ Task/Man-or-boy-test/00DESCRIPTION | 23 +- Task/Man-or-boy-test/00META.yaml | 2 + .../Man-or-boy-test/Aime/man-or-boy-test.aime | 13 +- Task/Man-or-boy-test/D/man-or-boy-test-2.d | 12 +- Task/Man-or-boy-test/D/man-or-boy-test-3.d | 14 +- .../Dylan/man-or-boy-test.dylan | 27 + Task/Man-or-boy-test/Io/man-or-boy-test.io | 14 + .../Java/man-or-boy-test-1.java | 21 + ...r-boy-test.java => man-or-boy-test-2.java} | 0 .../Pascal/man-or-boy-test.pascal | 25 + .../Man-or-boy-test/REXX/man-or-boy-test.rexx | 16 + Task/Mandelbrot-set/00DESCRIPTION | 4 +- Task/Mandelbrot-set/00META.yaml | 1 + .../JavaScript/mandelbrot-set.js | 69 ++ .../Pascal/mandelbrot-set.pascal | 88 ++ .../Mandelbrot-set/Python/mandelbrot-set-1.py | 11 +- .../Mandelbrot-set/Python/mandelbrot-set-2.py | 17 +- Task/Mandelbrot-set/REXX/mandelbrot-set.rexx | 17 + .../Scala/mandelbrot-set-1.scala | 2 +- .../Scala/mandelbrot-set-2.scala | 2 + .../Z80-Assembly/mandelbrot-set.z80 | 240 ++++++ Task/Map-range/ACL2/map-range.acl2 | 10 + Task/Map-range/D/map-range.d | 14 +- .../{map-range.pascal => map-range-1.pascal} | 0 Task/Map-range/Pascal/map-range-2.pascal | 56 ++ Task/Map-range/REXX/map-range-4.rexx | 3 +- Task/Map-range/Ruby/map-range-1.rb | 6 + Task/Map-range/Ruby/map-range-2.rb | 3 + Task/Map-range/Ruby/map-range.rb | 9 - Task/Matrix-arithmetic/D/matrix-arithmetic.d | 18 +- .../D/matrix-exponentiation-operator.d | 42 +- .../D/matrix-multiplication-2.d | 2 +- .../D/matrix-multiplication-4.d | 8 +- ...iplication.f => matrix-multiplication-1.f} | 0 .../Fortran/matrix-multiplication-2.f | 7 + .../Mathematica/matrix-multiplication-1.math | 8 +- .../Mathematica/matrix-multiplication-2.math | 2 +- .../Mathematica/matrix-multiplication-3.math | 2 +- .../Mathematica/matrix-multiplication-4.math | 8 +- .../Mathematica/matrix-multiplication-5.math | 1 + .../Mathematica/matrix-multiplication-6.math | 1 + .../Mathematica/matrix-multiplication-7.math | 1 + .../Mathematica/matrix-multiplication-8.math | 1 + .../Mathematica/matrix-multiplication-9.math | 1 + .../REXX/matrix-multiplication.rexx | 58 +- ...on.ti-83 => matrix-multiplication-1.ti-83} | 0 .../TI-83-BASIC/matrix-multiplication-2.ti-83 | 1 + .../Clojure/matrix-transposition.clj | 11 + .../HicEst/matrix-transposition.hicest | 7 + .../Lua/matrix-transposition-2.lua | 4 +- Task/Maze-generation/D/maze-generation.d | 9 +- .../Maze-generation/Lua/maze-generation-1.lua | 17 + .../Maze-generation/Lua/maze-generation-2.lua | 114 +++ .../Maze-generation/Lua/maze-generation-3.lua | 41 + .../Maze-generation/Lua/maze-generation-4.lua | 9 + Task/Maze-solving/00DESCRIPTION | 9 +- Task/Maze-solving/00META.yaml | 1 + Task/Maze-solving/D/maze-solving.d | 18 +- Task/Maze-solving/J/maze-solving.j | 42 +- Task/Median-filter/D/median-filter.d | 20 +- Task/Memory-allocation/D/memory-allocation.d | 8 +- .../Maple/memory-allocation-1.maple | 1 + .../Maple/memory-allocation-2.maple | 1 + .../Maple/memory-allocation-3.maple | 1 + .../Go/memory-layout-of-a-data-structure.go | 24 +- Task/Menu/Prolog/menu-1.pro | 17 + Task/Menu/Prolog/menu-2.pro | 20 + .../Mathematica/metaprogramming.math | 2 + .../Python/metaprogramming-1.py | 9 + .../Python/metaprogramming-2.py | 2 + Task/Metronome/Go/metronome.go | 25 + .../ALGOL-68/middle-three-digits.alg | 92 +++ .../C++/middle-three-digits.cpp | 87 +- .../D/middle-three-digits-1.d | 12 +- .../Prolog/middle-three-digits-1.pro | 14 + .../Prolog/middle-three-digits-2.pro | 6 + .../Ruby/middle-three-digits-1.rb | 14 + .../Ruby/middle-three-digits-2.rb | 14 + .../Ruby/middle-three-digits.rb | 30 - .../SQL/middle-three-digits.sql | 12 + .../Miller-Rabin-primality-test/00DESCRIPTION | 5 +- .../D/miller-rabin-primality-test.d | 30 +- ...ava => miller-rabin-primality-test-1.java} | 0 .../Java/miller-rabin-primality-test-2.java | 79 ++ .../JavaScript/miller-rabin-primality-test.js | 62 +- .../miller-rabin-primality-test.mercury | 218 +++++ .../Oz/miller-rabin-primality-test.oz | 104 +++ ...st.pl => miller-rabin-primality-test-1.pl} | 0 .../Perl/miller-rabin-primality-test-2.pl | 10 + .../Perl/miller-rabin-primality-test-3.pl | 10 + .../Prolog/miller-rabin-primality-test.pro | 83 ++ .../REXX/miller-rabin-primality-test.rexx | 88 +- .../Scala/miller-rabin-primality-test-1.scala | 6 + .../Scala/miller-rabin-primality-test-2.scala | 38 + Task/Minesweeper-game/00DESCRIPTION | 2 +- .../Minesweeper-game/C++/minesweeper-game.cpp | 223 +++++ .../Julia/minesweeper-game-1.julia | 117 +++ .../Julia/minesweeper-game-2.julia | 83 ++ .../MATLAB/minesweeper-game.m | 243 ++++++ .../D/modular-exponentiation.d | 31 +- .../REXX/modular-exponentiation-1.rexx | 25 + .../REXX/modular-exponentiation-2.rexx | 22 + .../REXX/modular-exponentiation.rexx | 28 - .../Racket/modular-exponentiation.rkt | 6 + Task/Modular-inverse/00DESCRIPTION | 4 +- Task/Modular-inverse/AWK/modular-inverse.awk | 27 + .../Modular-inverse/Ada/modular-inverse-1.ada | 11 + ...ular-inverse.ada => modular-inverse-2.ada} | 8 +- .../Modular-inverse/Ada/modular-inverse-3.ada | 9 + Task/Modular-inverse/C/modular-inverse-1.c | 20 + Task/Modular-inverse/C/modular-inverse-2.c | 25 + Task/Modular-inverse/C/modular-inverse.c | 18 - .../Common-Lisp/modular-inverse.lisp | 23 + ...ar-inverse.math => modular-inverse-1.math} | 0 .../Mathematica/modular-inverse-2.math | 1 + Task/Modular-inverse/PL-I/modular-inverse.pli | 33 + .../Modular-inverse/Perl/modular-inverse-1.pl | 9 + .../Modular-inverse/Perl/modular-inverse-2.pl | 15 + Task/Modular-inverse/Perl/modular-inverse.pl | 2 - .../PicoLisp/modular-inverse.l | 17 + Task/Monte-Carlo-methods/00DESCRIPTION | 24 +- .../C/monte-carlo-methods.c | 2 +- .../D/monte-carlo-methods-1.d | 10 +- .../D/monte-carlo-methods-2.d | 10 +- .../Haskell/monte-carlo-methods.hs | 2 +- ...ethods.java => monte-carlo-methods-1.java} | 0 .../Java/monte-carlo-methods-2.java | 44 + .../Maxima/monte-carlo-methods.maxima | 4 +- .../Perl-6/monte-carlo-methods-1.pl6 | 15 +- .../Perl-6/monte-carlo-methods-2.pl6 | 8 +- .../Perl-6/monte-carlo-methods.pl6 | 9 - .../Python/monte-carlo-methods-3.py | 2 +- .../REXX/monte-carlo-methods.rexx | 39 +- Task/Monty-Hall-problem/00DESCRIPTION | 3 + ...all-problem.py => monty-hall-problem-1.py} | 0 .../Python/monty-hall-problem-2.py | 33 + .../Scilab/monty-hall-problem.scilab | 38 + Task/Morse-code/00DESCRIPTION | 13 +- Task/Morse-code/00META.yaml | 4 +- Task/Morse-code/AWK/morse-code.awk | 6 +- Task/Mouse-position/00DESCRIPTION | 22 +- Task/Mouse-position/00META.yaml | 2 + .../MAXScript/mouse-position.max | 20 + .../Mouse-position/Scala/mouse-position.scala | 3 +- .../Smalltalk/mouse-position.st | 1 + .../Multifactorial/Clojure/multifactorial.clj | 2 +- Task/Multifactorial/Java/multifactorial.java | 19 + Task/Multifactorial/Perl-6/multifactorial.pl6 | 5 +- ...bjects.j => multiple-distinct-objects-1.j} | 0 .../J/multiple-distinct-objects-2.j | 2 + .../Perl-6/multiple-distinct-objects.pl6 | 1 + Task/Multiple-regression/00DESCRIPTION | 3 +- .../J/multiple-regression-3.j | 3 + .../Racket/multiple-regression-2.rkt | 2 +- .../Ruby/multiple-regression-3.rb | 1 + Task/Multiplication-tables/00META.yaml | 2 + .../AWK/multiplication-tables.awk | 23 +- .../C/multiplication-tables.c | 13 + .../CoffeeScript/multiplication-tables.coffee | 31 + .../R/multiplication-tables.r | 10 + .../REXX/multiplication-tables.rexx | 86 +- .../Visual-Basic/multiplication-tables.vb | 24 + .../Maple/multiplicative-order-1.maple | 1 + .../Maple/multiplicative-order-2.maple | 2 + .../Perl/multiplicative-order-1.pl | 3 + .../Perl/multiplicative-order-2.pl | 3 + Task/Multisplit/00DESCRIPTION | 21 +- Task/Multisplit/00META.yaml | 3 + Task/Multisplit/D/multisplit.d | 7 +- Task/Multisplit/Haskell/multisplit.hs | 27 + Task/Multisplit/Java/multisplit.java | 33 + Task/Multisplit/REXX/multisplit.rexx | 22 +- Task/Multisplit/Ruby/multisplit-1.rb | 10 +- Task/Multisplit/Ruby/multisplit-2.rb | 2 +- Task/Multisplit/Scheme/multisplit.ss | 15 + Task/Multisplit/UNIX-Shell/multisplit.sh | 29 + Task/Mutual-recursion/00DESCRIPTION | 6 +- .../Elixir/mutual-recursion.elixir | 6 + .../REXX/mutual-recursion-1.rexx | 10 +- .../REXX/mutual-recursion-2.rexx | 21 +- .../REXX/mutual-recursion-3.rexx | 16 +- Task/N-queens-problem/00DESCRIPTION | 5 +- .../ABAP/n-queens-problem.abap | 285 +++++++ .../Bracmat/n-queens-problem.bracmat | 61 ++ .../C++/n-queens-problem-1.cpp | 191 ++--- .../C++/n-queens-problem-2.cpp | 313 +++++-- .../C++/n-queens-problem-3.cpp | 100 +++ .../C++/n-queens-problem-4.cpp | 88 ++ .../Common-Lisp/n-queens-problem-1.lisp | 35 +- .../Curry/n-queens-problem-4.curry | 19 + Task/N-queens-problem/D/n-queens-problem-2.d | 6 +- Task/N-queens-problem/D/n-queens-problem-3.d | 4 +- .../Eiffel/n-queens-problem.e | 68 ++ .../Fortran/n-queens-problem-3.f | 163 ++-- .../Fortran/n-queens-problem-4.f | 122 +++ .../N-queens-problem/GAP/n-queens-problem.gap | 89 +- .../Haskell/n-queens-problem-1.hs | 7 +- .../Haskell/n-queens-problem-2.hs | 2 +- .../MUMPS/n-queens-problem-1.mumps | 59 ++ ...problem.mumps => n-queens-problem-2.mumps} | 60 -- .../Mathematica/n-queens-problem-1.math | 8 +- .../Mathematica/n-queens-problem-4.math | 44 + ...oblem.pascal => n-queens-problem-1.pascal} | 0 .../Pascal/n-queens-problem-2.pascal | 112 +++ .../Prolog/n-queens-problem-4.pro | 35 +- .../Prolog/n-queens-problem-5.pro | 23 + .../Python/n-queens-problem-5.py | 20 + .../REXX/n-queens-problem.rexx | 73 +- .../Racket/n-queens-problem-5.rkt | 86 +- .../N-queens-problem/SQL/n-queens-problem.sql | 29 + .../Forth/named-parameters.fth | 21 + .../Perl/named-parameters-1.pl | 20 +- .../Perl/named-parameters-2.pl | 10 +- .../Perl/named-parameters-3.pl | 37 + ...arameters.rexx => named-parameters-1.rexx} | 0 .../REXX/named-parameters-2.rexx | 21 + Task/Narcissist/AutoHotkey/narcissist-1.ahk | 4 + Task/Narcissist/AutoHotkey/narcissist-2.ahk | 2 + Task/Narcissist/C-sharp/narcissist.cs | 28 + Task/Narcissist/Haskell/narcissist.hs | 1 + .../{narcissist.js => narcissist-1.js} | 0 Task/Narcissist/JavaScript/narcissist-2.js | 20 + Task/Nautical-bell/Haskell/nautical-bell.hs | 77 ++ Task/Nautical-bell/J/nautical-bell.j | 61 ++ Task/Nautical-bell/Java/nautical-bell.java | 50 ++ Task/Nautical-bell/Ruby/nautical-bell.rb | 23 + Task/Nautical-bell/Seed7/nautical-bell.seed7 | 37 + .../Non-continuous-subsequences/00DESCRIPTION | 3 +- .../C++/non-continuous-subsequences.cpp | 57 ++ .../non-continuous-subsequences.coffee | 57 ++ .../D/non-continuous-subsequences-1.d | 24 +- .../D/non-continuous-subsequences-2.d | 32 +- .../D/non-continuous-subsequences-3.d | 34 + .../Java/non-continuous-subsequences.java | 16 + .../Pop11/non-continuous-subsequences.pop11 | 24 + .../Seed7/non-continuous-subsequences.seed7 | 30 + .../D/non-decimal-radices-convert-3.d | 16 +- .../Perl/non-decimal-radices-convert-3.pl | 3 + .../REXX/non-decimal-radices-convert-1.rexx | 12 + .../REXX/non-decimal-radices-convert-2.rexx | 37 + .../REXX/non-decimal-radices-convert.rexx | 46 -- .../Ruby/non-decimal-radices-convert.rb | 13 + .../Go/non-decimal-radices-input.go | 30 +- .../REXX/non-decimal-radices-input.rexx | 27 +- .../Bc/non-decimal-radices-output.bc | 7 + .../C-sharp/non-decimal-radices-output.cs | 20 + .../Go/non-decimal-radices-output.go | 25 +- Task/Nth-root/NewLISP/nth-root.newlisp | 11 + Task/Nth-root/Objeck/nth-root.objeck | 18 + Task/Nth-root/PicoLisp/nth-root.l | 6 +- Task/Nth-root/REXX/nth-root.rexx | 2 +- Task/Null-object/C++/null-object-3.cpp | 6 +- Task/Null-object/Eiffel/null-object.e | 22 + Task/Null-object/Ruby/null-object.rb | 8 +- Task/Number-names/00DESCRIPTION | 4 +- .../CoffeeScript/number-names.coffee | 57 ++ Task/Number-names/D/number-names.d | 32 +- .../Number-names/MAXScript/number-names-1.max | 88 +- .../Number-names/MAXScript/number-names-2.max | 15 +- Task/Number-names/Objective-C/number-names.m | 16 + Task/Number-names/Ruby/number-names.rb | 35 +- Task/Number-names/Scala/number-names.scala | 44 +- .../Eiffel/number-reversal-game-1.e | 99 +++ .../Eiffel/number-reversal-game-2.e | 14 + .../MATLAB/number-reversal-game.m | 27 + .../REBOL/number-reversal-game.rebol | 22 + .../Scala/number-reversal-game.scala | 29 + ...egration-gauss-legendre-quadrature-1.axiom | 20 + ...egration-gauss-legendre-quadrature-2.axiom | 8 + ...al-integration-gauss-legendre-quadrature.d | 44 +- ...tegration-gauss-legendre-quadrature-2.rexx | 88 +- .../Chapel/numerical-integration-1.chapel | 129 +++ .../Chapel/numerical-integration-2.chapel | 27 + .../REXX/numerical-integration.rexx | 31 +- .../Racket/object-serialization-1.rkt | 1 + .../Racket/object-serialization-2.rkt | 72 ++ .../00DESCRIPTION | 4 +- .../one-dimensional-cellular-automata.coffee | 32 + .../D/one-dimensional-cellular-automata-3.d | 6 +- ...> one-dimensional-cellular-automata-1.rkt} | 0 .../one-dimensional-cellular-automata-2.rkt | 49 ++ .../Mathematica/one-of-n-lines-in-a-file.math | 8 + ...scal => one-of-n-lines-in-a-file-1.pascal} | 0 .../Pascal/one-of-n-lines-in-a-file-2.pascal | 86 ++ .../R/one-of-n-lines-in-a-file.r | 14 + .../Scala/one-of-n-lines-in-a-file.scala | 10 + Task/OpenGL/Common-Lisp/opengl.lisp | 67 ++ Task/OpenGL/Euphoria/opengl.euphoria | 292 +++++++ Task/OpenGL/Scala/opengl.scala | 39 + .../AWK/operator-precedence.awk | 61 ++ .../Bracmat/optional-parameters.bracmat | 22 + .../Groovy/optional-parameters-1.groovy | 3 + .../Groovy/optional-parameters-2.groovy | 7 + .../Groovy/optional-parameters-3.groovy | 7 + .../Groovy/optional-parameters-4.groovy | 7 + .../Haskell/optional-parameters-1.hs | 15 + .../Haskell/optional-parameters-2.hs | 12 + .../Maple/optional-parameters-1.maple | 13 + .../Maple/optional-parameters-2.maple | 7 + .../REXX/optional-parameters-1.rexx | 25 +- .../REXX/optional-parameters-2.rexx | 4 +- Task/Order-two-numerical-lists/00DESCRIPTION | 7 +- .../AWK/order-two-numerical-lists.awk | 24 + .../Lua/order-two-numerical-lists-1.lua | 11 + .../Lua/order-two-numerical-lists-2.lua | 20 + .../PL-I/order-two-numerical-lists.pli | 22 + .../REXX/order-two-numerical-lists.rexx | 32 +- .../Scala/order-two-numerical-lists-1.scala | 5 + .../Scala/order-two-numerical-lists-2.scala | 6 + .../Scala/order-two-numerical-lists-3.scala | 5 + .../Scala/order-two-numerical-lists-4.scala | 14 + Task/Ordered-Partitions/00DESCRIPTION | 2 +- .../D/ordered-partitions-1.d | 25 + .../D/ordered-partitions-2.d | 44 + .../Ordered-Partitions/D/ordered-partitions.d | 29 - .../Groovy/ordered-partitions-1.groovy | 6 +- .../Perl/ordered-partitions-2.pl | 61 +- .../REXX/ordered-partitions.rexx | 48 ++ .../Ruby/ordered-partitions-1.rb | 6 + .../Ruby/ordered-partitions-2.rb | 10 + .../Ruby/ordered-partitions-3.rb | 5 + .../Ruby/ordered-partitions.rb | 15 - Task/Ordered-words/D/ordered-words-1.d | 14 +- Task/Ordered-words/D/ordered-words-2.d | 1 + Task/Ordered-words/D/ordered-words-3.d | 4 +- Task/Ordered-words/D/ordered-words-4.d | 13 +- Task/Ordered-words/REXX/ordered-words.rexx | 29 +- Task/Ordered-words/Ruby/ordered-words.rb | 4 +- Task/Palindrome-detection/00DESCRIPTION | 34 +- Task/Palindrome-detection/00META.yaml | 1 + .../ALGOL-68/palindrome-detection.alg | 2 +- .../Batch-File/palindrome-detection-1.bat | 15 + .../Batch-File/palindrome-detection-2.bat | 19 + .../Bracmat/palindrome-detection.bracmat | 34 + .../D/palindrome-detection-1.d | 6 +- .../Eiffel/palindrome-detection.e | 18 + .../Elixir/palindrome-detection.elixir | 3 + .../FBSL/palindrome-detection.fbsl | 27 + ...ion.frink => palindrome-detection-1.frink} | 0 .../Frink/palindrome-detection-2.frink | 1 + .../JavaScript/palindrome-detection-1.js | 10 +- .../JavaScript/palindrome-detection-2.js | 24 +- .../palindrome-detection.liberty | 22 + .../PL-I/palindrome-detection-1.pli | 1 + ...tection.pli => palindrome-detection-2.pli} | 0 .../REXX/palindrome-detection-1.rexx | 1 - .../REXX/palindrome-detection-2.rexx | 1 - .../Ruby/palindrome-detection-1.rb | 2 +- .../Ruby/palindrome-detection-2.rb | 4 +- .../Ruby/palindrome-detection-3.rb | 8 +- .../Scala/palindrome-detection-1.scala | 5 +- .../Scala/palindrome-detection-2.scala | 10 +- .../Scala/palindrome-detection-3.scala | 12 +- .../Scala/palindrome-detection-4.scala | 2 +- Task/Pangram-checker/00DESCRIPTION | 7 +- Task/Pangram-checker/00META.yaml | 3 + ...gram-checker.awk => pangram-checker-1.awk} | 6 +- .../Pangram-checker/AWK/pangram-checker-2.awk | 29 + Task/Pangram-checker/D/pangram-checker-1.d | 12 +- Task/Parallel-calculations/00DESCRIPTION | 30 +- .../Factor/parallel-calculations-1.factor | 18 + .../Factor/parallel-calculations-2.factor | 7 + .../Haskell/parallel-calculations-1.hs | 2 +- .../Java/parallel-calculations.java | 40 + ...ulations.py => parallel-calculations-1.py} | 8 +- .../Python/parallel-calculations-2.py | 46 ++ .../C++/parametric-polymorphism-2.cpp | 6 +- .../Groovy/parametric-polymorphism.groovy | 17 + .../Rust/parametric-polymorphism.rust | 42 + Task/Parametrized-SQL-statement/00DESCRIPTION | 7 +- .../Go/parametrized-sql-statement.go | 33 + .../Seed7/parametrized-sql-statement.seed7 | 32 + .../parsing-rpn-calculator-algorithm.alg | 143 ++++ .../parsing-rpn-calculator-algorithm.julia | 16 + .../VBA/parsing-rpn-calculator-algorithm.vba | 86 ++ .../D/parsing-rpn-to-infix-conversion-2.d | 4 +- .../Java/parsing-rpn-to-infix-conversion.java | 62 ++ .../REXX/parsing-rpn-to-infix-conversion.rexx | 39 +- .../parsing-shunting-yard-algorithm-1.hs | 8 +- .../parsing-shunting-yard-algorithm-2.hs | 11 +- .../Java/parsing-shunting-yard-algorithm.java | 46 ++ .../parsing-shunting-yard-algorithm.js | 71 ++ .../Perl/parsing-shunting-yard-algorithm.pl | 76 +- .../VBA/parsing-shunting-yard-algorithm.vba | 110 +++ .../partial-function-application.bracmat | 27 + .../partial-function-application.lisp | 24 +- .../Go/partial-function-application.go | 55 ++ .../Lua/partial-function-application.lua | 30 + .../Scala/partial-function-application.scala | 19 +- Task/Pascals-triangle-Puzzle/00DESCRIPTION | 3 +- .../Curry/pascals-triangle-puzzle.curry | 25 + .../D/pascals-triangle-puzzle.d | 33 +- .../Ruby/pascals-triangle-puzzle.rb | 23 +- Task/Pascals-triangle/00DESCRIPTION | 3 +- .../Pascals-triangle/AWK/pascals-triangle.awk | 6 - .../Ada/pascals-triangle-1.ada | 11 + .../Ada/pascals-triangle-2.ada | 26 + .../Ada/pascals-triangle-3.ada | 18 + .../Pascals-triangle/Ada/pascals-triangle.ada | 34 - .../Pascals-triangle/C++/pascals-triangle.cpp | 94 ++- .../Clojure/pascals-triangle-4.clj | 5 + .../Clojure/pascals-triangle-5.clj | 1 + .../Clojure/pascals-triangle-6.clj | 1 + Task/Pascals-triangle/K/pascals-triangle.k | 2 +- .../Perl-6/pascals-triangle-1.pl6 | 8 +- .../Perl-6/pascals-triangle-2.pl6 | 11 +- .../Perl-6/pascals-triangle-3.pl6 | 8 +- .../Perl-6/pascals-triangle-4.pl6 | 10 +- .../Perl/pascals-triangle-1.pl | 18 +- .../Perl/pascals-triangle-2.pl | 10 +- .../Perl/pascals-triangle-3.pl | 3 + .../Ruby/pascals-triangle-1.rb | 33 +- .../Ruby/pascals-triangle-2.rb | 6 +- .../Erlang/pattern-matching.erl | 39 + .../percentage-difference-between-images.hs | 26 + .../percentage-difference-between-images.java | 8 +- Task/Perfect-numbers/00DESCRIPTION | 12 +- .../Clojure/perfect-numbers-1.clj | 11 +- .../Clojure/perfect-numbers-2.clj | 4 +- .../Eiffel/perfect-numbers-1.e | 24 + .../Eiffel/perfect-numbers-2.e | 20 + .../Elixir/perfect-numbers.elixir | 3 + Task/Perfect-numbers/J/perfect-numbers-1.j | 2 +- Task/Perfect-numbers/J/perfect-numbers-2.j | 7 +- .../MATLAB/perfect-numbers-1.m | 9 + .../MATLAB/perfect-numbers-2.m | 20 + .../Perfect-numbers/Perl/perfect-numbers-3.pl | 2 + .../Perfect-numbers/Perl/perfect-numbers-4.pl | 4 + .../Perfect-numbers/Perl/perfect-numbers-5.pl | 6 + .../REXX/perfect-numbers-1.rexx | 9 +- .../REXX/perfect-numbers-2.rexx | 16 +- .../REXX/perfect-numbers-3.rexx | 6 +- .../REXX/perfect-numbers-4.rexx | 15 +- .../REXX/perfect-numbers-5.rexx | 16 +- .../REXX/perfect-numbers-6.rexx | 8 +- .../REXX/perfect-numbers-7.rexx | 46 ++ .../Perfect-numbers/Ruby/perfect-numbers-5.rb | 24 + ...-numbers.scala => perfect-numbers-1.scala} | 0 .../Scala/perfect-numbers-2.scala | 2 + Task/Permutation-test/00DESCRIPTION | 10 +- Task/Permutation-test/D/permutation-test-1.d | 5 +- Task/Permutation-test/D/permutation-test-2.d | 6 +- .../REXX/permutation-test.rexx | 38 +- .../Permutation-test/Ruby/permutation-test.rb | 20 + Task/Permutations-Derangements/00DESCRIPTION | 3 +- .../BBC-BASIC/permutations-derangements.bbc | 75 ++ .../Bracmat/permutations-derangements.bracmat | 52 ++ .../D/permutations-derangements-1.d | 15 +- .../D/permutations-derangements-2.d | 6 +- .../Groovy/permutations-derangements-1.groovy | 2 +- .../permutations-derangements-2.purebasic | 84 +- .../REXX/permutations-derangements.rexx | 2 +- .../Scala/permutations-derangements.scala | 15 + .../C++/permutations-by-swapping.cpp | 196 ++--- .../D/permutations-by-swapping-1.d | 10 +- .../D/permutations-by-swapping-2.d | 27 +- .../Haskell/permutations-by-swapping.hs | 16 +- .../Icon/permutations-by-swapping.icon | 30 + .../PicoLisp/permutations-by-swapping.l | 42 + .../REXX/permutations-by-swapping.rexx | 46 +- Task/Permutations/D/permutations-2.d | 35 +- Task/Permutations/D/permutations-3.d | 8 +- Task/Permutations/Eiffel/permutations.e | 34 + .../{permutations.lua => permutations-1.lua} | 0 Task/Permutations/Lua/permutations-2.lua | 31 + Task/Permutations/Perl/permutations-1.pl | 5 + Task/Permutations/Perl/permutations-2.pl | 7 + Task/Permutations/Perl/permutations.pl | 8 - Task/Permutations/REXX/permutations-1.rexx | 9 +- Task/Permutations/SAS/permutations.sas | 68 +- Task/Pi/Pascal/pi.pascal | 59 +- Task/Pi/Perl/pi-1.pl | 81 +- Task/Pi/Perl/pi-2.pl | 93 +-- Task/Pi/Perl/pi-3.pl | 54 ++ Task/Pi/Perl/pi-4.pl | 18 + Task/Pi/Racket/pi-1.rkt | 19 + Task/Pi/Racket/pi-2.rkt | 1 + Task/Pi/Racket/pi.rkt | 4 - Task/Pick-random-element/00META.yaml | 2 + .../ALGOL-68/pick-random-element.alg | 23 + .../C-sharp/pick-random-element.cs | 11 + .../Elixir/pick-random-element.elixir | 11 + .../Erlang/pick-random-element.erl | 4 +- .../Falcon/pick-random-element.falcon | 2 + .../Haskell/pick-random-element-3.hs | 3 + .../Maxima/pick-random-element.maxima | 4 + .../Prolog/pick-random-element.pro | 2 + .../Scala/pick-random-element.scala | 3 + .../AutoHotkey/pig-the-dice-game-player.ahk | 1 - .../REXX/pig-the-dice-game-player.rexx | 72 +- .../Eiffel/pig-the-dice-game-1.e | 51 ++ .../Eiffel/pig-the-dice-game-2.e | 45 + .../Eiffel/pig-the-dice-game-3.e | 16 + .../OCaml/pig-the-dice-game.ocaml | 52 ++ .../REXX/pig-the-dice-game.rexx | 2 +- .../Ruby/pig-the-dice-game.rb | 41 +- .../C-sharp/pinstripe-display.cs | 29 + .../Java/pinstripe-display.java | 38 + Task/Playing-cards/00DESCRIPTION | 8 +- Task/Playing-cards/00META.yaml | 2 + Task/Playing-cards/D/playing-cards-1.d | 13 +- Task/Playing-cards/Go/playing-cards-1.go | 174 ++++ Task/Playing-cards/Go/playing-cards-2.go | 45 + Task/Playing-cards/Go/playing-cards.go | 125 --- Task/Playing-cards/Rust/playing-cards.rust | 125 +++ .../Clojure/plot-coordinate-pairs.clj | 4 + ...te-pairs.py => plot-coordinate-pairs-1.py} | 0 .../Python/plot-coordinate-pairs-2.py | 28 + .../Scala/plot-coordinate-pairs.scala | 3 +- .../Perl/pointers-and-references-1.pl | 6 +- .../Perl/pointers-and-references-2.pl | 15 +- .../Polymorphic-copy/Ada/polymorphic-copy.ada | 11 + Task/Polymorphic-copy/D/polymorphic-copy-2.d | 6 +- .../Groovy/polymorphic-copy-1.groovy | 14 + .../Groovy/polymorphic-copy-2.groovy | 14 + Task/Polymorphism/AutoHotkey/polymorphism.ahk | 73 ++ Task/Polymorphism/Ruby/polymorphism-1.rb | 23 + Task/Polymorphism/Ruby/polymorphism-2.rb | 15 + Task/Polymorphism/Ruby/polymorphism.rb | 22 - Task/Polymorphism/Tcl/polymorphism.tcl | 2 +- Task/Polynomial-long-division/00DESCRIPTION | 2 +- .../D/polynomial-long-division.d | 14 +- .../Ruby/polynomial-long-division-1.rb | 12 +- .../Ruby/polynomial-long-division-2.rb | 8 +- .../Ruby/polynomial-long-division-3.rb | 21 +- .../HicEst/polynomial-regression.hicest | 15 + .../Julia/polynomial-regression.julia | 4 + .../R/polynomial-regression.r | 3 + Task/Power-set/00DESCRIPTION | 18 +- Task/Power-set/Ada/power-set.ada | 108 +-- Task/Power-set/Clojure/power-set-2.clj | 8 +- Task/Power-set/D/power-set-1.d | 3 +- Task/Power-set/D/power-set-2.d | 33 +- Task/Power-set/Go/power-set.go | 157 ++-- Task/Power-set/Java/power-set-3.java | 6 +- Task/Power-set/Perl/power-set-7.pl | 21 + Task/Power-set/Ruby/power-set.rb | 3 +- Task/Power-set/SAS/power-set-1.sas | 53 ++ Task/Power-set/SAS/power-set-2.sas | 1 + Task/Power-set/Scala/power-set-1.scala | 9 + Task/Power-set/Scala/power-set-2.scala | 1 + Task/Power-set/Scala/power-set.scala | 1 - Task/Power-set/Scheme/power-set-3.ss | 12 +- .../Price-fraction/Clojure/price-fraction.clj | 4 + .../Factor/price-fraction.factor | 25 + Task/Price-fraction/K/price-fraction.k | 4 + Task/Price-fraction/Rust/price-fraction.rust | 36 + .../Primality-by-trial-division/00DESCRIPTION | 5 +- ....ada => primality-by-trial-division-1.ada} | 0 .../Ada/primality-by-trial-division-2.ada | 13 + .../primality-by-trial-division.lisp | 6 + .../primality-by-trial-division-1.l | 5 + .../primality-by-trial-division-2.l | 4 + .../primality-by-trial-division-3.l | 5 + .../primality-by-trial-division-4.l | 3 + .../primality-by-trial-division-5.l | 4 + .../Forth/primality-by-trial-division.fth | 2 +- .../Go/primality-by-trial-division.go | 15 +- .../Haskell/primality-by-trial-division-1.hs | 2 +- .../Haskell/primality-by-trial-division-2.hs | 2 +- .../primality-by-trial-division.math | 14 +- .../Oz/primality-by-trial-division.oz | 12 + ...l => primality-by-trial-division-1.pascal} | 0 .../primality-by-trial-division-2.pascal | 14 + .../Perl/primality-by-trial-division-2.pl | 15 +- .../Perl/primality-by-trial-division-3.pl | 4 + .../REXX/primality-by-trial-division-1.rexx | 22 +- .../REXX/primality-by-trial-division-2.rexx | 33 +- .../REXX/primality-by-trial-division-3.rexx | 39 +- .../Rust/primality-by-trial-division.rust | 16 + Task/Prime-decomposition/00DESCRIPTION | 11 +- .../AWK/prime-decomposition.awk | 1 + .../Ada/prime-decomposition-1.ada | 4 +- .../Ada/prime-decomposition-2.ada | 49 +- .../D/prime-decomposition.d | 2 +- .../Eiffel/prime-decomposition.e | 37 + .../Haskell/prime-decomposition-1.hs | 2 +- .../Haskell/prime-decomposition-2.hs | 12 +- .../J/prime-decomposition-2.j | 9 +- .../J/prime-decomposition-3.j | 6 + .../PL-I/prime-decomposition.pli | 4 - ...omposition.pl => prime-decomposition-1.pl} | 0 .../Perl/prime-decomposition-2.pl | 14 + .../Perl/prime-decomposition-3.pl | 7 + .../Perl/prime-decomposition-4.pl | 13 + .../Python/prime-decomposition-2.py | 9 +- .../Scala/prime-decomposition-1.scala | 4 +- Task/Priority-queue/C-sharp/priority-queue.cs | 60 ++ .../Priority-queue/Clojure/priority-queue.clj | 19 + Task/Priority-queue/Lua/priority-queue-1.lua | 50 ++ Task/Priority-queue/Lua/priority-queue-2.lua | 40 + .../Objective-C/priority-queue.m | 4 +- Task/Priority-queue/Ruby/priority-queue.rb | 39 +- .../D/probabilistic-choice-2.d | 7 +- .../Erlang/probabilistic-choice.erl | 31 + .../MATLAB/probabilistic-choice-1.m | 11 + .../MATLAB/probabilistic-choice-2.m | 17 + .../Perl-6/probabilistic-choice.pl6 | 24 +- .../Scala/probabilistic-choice.scala | 64 ++ .../Scheme/probabilistic-choice.ss | 45 + .../D/problem-of-apollonius.d | 68 +- .../REXX/problem-of-apollonius.rexx | 20 +- .../Program-name/Mercury/program-name.mercury | 16 + .../Oberon-2/program-name.oberon-2 | 7 + .../{program-name.pl => program-name-1.pl} | 0 Task/Program-name/Perl/program-name-2.pl | 2 + Task/Program-name/Ruby/program-name.rb | 2 +- Task/Program-name/Scala/program-name.scala | 5 + Task/Program-name/TXR/program-name.txr | 2 +- Task/Program-termination/00DESCRIPTION | 3 +- Task/Program-termination/00META.yaml | 2 + ...mination.awk => program-termination-1.awk} | 0 .../AWK/program-termination-2.awk | 9 + .../D/program-termination-1.d | 53 ++ .../D/program-termination-2.d | 21 + .../Emacs-Lisp/program-termination.l | 2 + .../Gnuplot/program-termination.gnuplot | 4 + .../Oberon-2/program-termination.oberon-2 | 3 + .../REXX/program-termination.rexx | 4 +- .../Ruby/program-termination-1.rb | 7 +- .../Ruby/program-termination-2.rb | 2 +- .../Scala/program-termination.scala | 6 + .../D/pythagorean-triples-1.d | 26 +- .../D/pythagorean-triples-2.d | 51 +- .../D/pythagorean-triples-3.d | 18 + .../D/pythagorean-triples-4.d | 40 + .../Eiffel/pythagorean-triples.e | 37 + .../Groovy/pythagorean-triples-1.groovy | 36 + .../Groovy/pythagorean-triples-2.groovy | 5 + .../REXX/pythagorean-triples-1.rexx | 34 +- .../REXX/pythagorean-triples-2.rexx | 49 +- .../Scheme/pythagorean-triples.ss | 12 + Task/QR-decomposition/D/qr-decomposition.d | 106 +-- .../Axiom/quaternion-type.axiom | 48 ++ Task/Quaternion-type/D/quaternion-type.d | 90 +- .../Julia/quaternion-type-1.julia | 10 +- .../Quaternion-type/Lua/quaternion-type-2.lua | 2 +- Task/Queue-Definition/00DESCRIPTION | 3 +- .../Bracmat/queue-definition.bracmat | 10 + .../Clojure/queue-definition.clj | 6 +- .../CoffeeScript/queue-definition.coffee | 38 + .../UNIX-Shell/queue-definition-1.sh | 25 + .../UNIX-Shell/queue-definition-2.sh | 14 + Task/Queue-Usage/Bracmat/queue-usage.bracmat | 38 + Task/Queue-Usage/D/queue-usage-2.d | 71 +- .../{queue-usage.lua => queue-usage-1.lua} | 0 Task/Queue-Usage/Lua/queue-usage-2.lua | 16 + Task/Queue-Usage/REXX/queue-usage.rexx | 12 +- Task/Queue-Usage/UNIX-Shell/queue-usage.sh | 14 + Task/Quine/00DESCRIPTION | 9 +- .../Frink/{quine.frink => quine-1.frink} | 0 Task/Quine/Frink/quine-2.frink | 1 + Task/Quine/J/quine-1.j | 0 Task/Quine/J/{quine.j => quine-2.j} | 0 Task/Quine/JavaScript/quine-4.js | 1 + Task/Quine/Mathematica/quine-4.math | 1 + Task/Quine/Mathematica/quine-5.math | 1 + .../Pascal/{quine.pascal => quine-1.pascal} | 0 Task/Quine/Pascal/quine-2.pascal | 1 + Task/Quine/Perl-6/{quine.pl6 => quine-1.pl6} | 0 Task/Quine/Perl-6/quine-2.pl6 | 1 + Task/Quine/Prolog/{quine.pro => quine-1.pro} | 0 Task/Quine/Prolog/quine-2.pro | 1 + Task/Quine/Python/quine-4.py | 2 +- Task/Quine/Python/quine-5.py | 1 - Task/Quine/Python/quine-6.py | 6 +- Task/Quine/Python/quine-7.py | 15 +- Task/Quine/Python/quine-8.py | 11 + Task/Quine/Ruby/quine-4.rb | 4 + Task/Quine/Rust/{quine.rust => quine-1.rust} | 1 - Task/Quine/Rust/quine-2.rust | 8 + .../Standard-ML/{quine.ml => quine-1.ml} | 0 Task/Quine/Standard-ML/quine-2.ml | 1 + Task/Quine/UNIX-Shell/quine-1.sh | 2 +- Task/RIPEMD-160/00DESCRIPTION | 12 +- Task/RIPEMD-160/Clojure/ripemd-160.clj | 2 + Task/RIPEMD-160/Go/ripemd-160.go | 2 +- Task/RIPEMD-160/Perl/ripemd-160-1.pl | 2 + Task/RIPEMD-160/Perl/ripemd-160-2.pl | 2 + Task/RIPEMD-160/PicoLisp/ripemd-160.l | 160 ++++ Task/RIPEMD-160/Scala/ripemd-160.scala | 10 + .../C/random-number-generator--device--1.c | 40 +- .../C/random-number-generator--device--5.c | 12 +- .../C/random-number-generator--device--6.c | 10 + .../random-number-generator--device-.f | 24 + .../random-number-generator--device--1.math | 1 + .../random-number-generator--device--2.math | 1 + .../random-number-generator--device--1.pl | 3 + .../random-number-generator--device--2.pl | 2 + ... => random-number-generator--device--3.pl} | 0 .../random-number-generator--device-.sh | 1 + .../random-number-generator--included-.elixir | 8 + .../random-number-generator--included--1.sql | 3 +- .../random-number-generator--included--3.rexx | 3 + Task/Random-numbers/00DESCRIPTION | 14 +- Task/Random-numbers/00META.yaml | 1 + ...andom-numbers.awk => random-numbers-1.awk} | 0 Task/Random-numbers/AWK/random-numbers-2.awk | 12 + Task/Random-numbers/D/random-numbers-1.d | 3 +- .../Elixir/random-numbers.elixir | 12 + Task/Random-numbers/PL-SQL/random-numbers.sql | 35 +- .../Pascal/random-numbers.pascal | 9 + .../Random-numbers/Python/random-numbers-1.py | 6 +- .../Random-numbers/Python/random-numbers-2.py | 13 +- .../Random-numbers/Python/random-numbers-3.py | 4 + Task/Random-numbers/REXX/random-numbers.rexx | 63 +- Task/Range-expansion/00DESCRIPTION | 3 +- .../COBOL/range-expansion.cobol | 93 +++ .../Haskell/range-expansion-3.hs | 22 +- Task/Range-expansion/Lua/range-expansion.lua | 28 + Task/Range-expansion/R/range-expansion.r | 7 + .../REXX/range-expansion-1.rexx | 24 +- .../Aime/range-extraction.aime | 55 +- ...ge-extraction.cs => range-extraction-1.cs} | 0 .../C-sharp/range-extraction-2.cs | 42 + Task/Range-extraction/C/range-extraction.c | 36 + Task/Range-extraction/D/range-extraction.d | 4 +- .../Eiffel/range-extraction.e | 72 ++ .../Emacs-Lisp/range-extraction.l | 12 + Task/Range-extraction/K/range-extraction.k | 3 + .../MATLAB/range-extraction.m | 39 +- .../Objective-C/range-extraction.m | 34 + Task/Range-extraction/Oz/range-extraction.oz | 47 ++ ...ge-extraction.pl => range-extraction-1.pl} | 0 .../Perl/range-extraction-2.pl | 2 + .../Perl/range-extraction-3.pl | 2 + .../REXX/range-extraction-1.rexx | 22 +- .../REXX/range-extraction-2.rexx | 24 +- .../Range-extraction/Ruby/range-extraction.rb | 28 +- Task/Rate-counter/Haskell/rate-counter.hs | 22 + .../Mathematica/rate-counter.math | 5 + .../C/ray-casting-algorithm.c | 10 +- .../D/ray-casting-algorithm.d | 8 +- Task/Read-a-configuration-file/00DESCRIPTION | 5 +- .../Clojure/read-a-configuration-file.clj | 2 + .../read-a-configuration-file.math | 21 + .../PicoLisp/read-a-configuration-file.l | 8 + .../RapidQ/read-a-configuration-file.rapidq | 59 ++ .../UNIX-Shell/read-a-configuration-file.sh | 44 + Task/Read-a-file-line-by-line/00DESCRIPTION | 10 +- Task/Read-a-file-line-by-line/00META.yaml | 2 + ...ine.awk => read-a-file-line-by-line-1.awk} | 0 .../AWK/read-a-file-line-by-line-2.awk | 1 + .../AWK/read-a-file-line-by-line-3.awk | 9 + .../C/read-a-file-line-by-line-1.c | 45 +- .../C/read-a-file-line-by-line-2.c | 102 +-- .../C/read-a-file-line-by-line-3.c | 180 ++-- .../C/read-a-file-line-by-line-4.c | 75 ++ .../D/read-a-file-line-by-line.d | 8 +- .../Perl/read-a-file-line-by-line-1.pl | 11 +- .../Perl/read-a-file-line-by-line-2.pl | 8 +- .../Perl/read-a-file-line-by-line-3.pl | 10 +- .../Perl/read-a-file-line-by-line-4.pl | 4 + .../Perl/read-a-file-line-by-line-5.pl | 1 + .../Perl/read-a-file-line-by-line-6.pl | 7 + ...e.rexx => read-a-file-line-by-line-1.rexx} | 10 +- .../REXX/read-a-file-line-by-line-2.rexx | 2 + .../REXX/read-a-file-line-by-line-3.rexx | 15 + .../RapidQ/read-a-file-line-by-line.rapidq | 12 + .../Rust/read-a-file-line-by-line.rust | 10 + .../Smalltalk/read-a-file-line-by-line-1.st | 2 +- .../Smalltalk/read-a-file-line-by-line-2.st | 7 +- .../Smalltalk/read-a-file-line-by-line-3.st | 7 +- .../Smalltalk/read-a-file-line-by-line-4.st | 1 + .../read-a-specific-line-from-a-file.alg | 91 +++ ...c => read-a-specific-line-from-a-file-1.c} | 0 .../C/read-a-specific-line-from-a-file-2.c | 101 +++ .../read-a-specific-line-from-a-file.clj | 5 + .../Go/read-a-specific-line-from-a-file.go | 102 +-- .../read-a-specific-line-from-a-file.icon | 2 +- .../Lua/read-a-specific-line-from-a-file.lua | 8 + .../read-a-specific-line-from-a-file-1.py | 7 + .../read-a-specific-line-from-a-file-2.py | 7 + .../read-a-specific-line-from-a-file-3.py | 1 + .../read-a-specific-line-from-a-file.py | 6 - .../read-a-specific-line-from-a-file.rexx | 28 +- .../read-a-specific-line-from-a-file.rkt | 2 +- .../Ruby/read-a-specific-line-from-a-file.rb | 16 +- .../read-a-specific-line-from-a-file.st | 1 + .../read-a-specific-line-from-a-file.sh | 12 + Task/Read-entire-file/00DESCRIPTION | 11 +- ...entire-file.awk => read-entire-file-1.awk} | 0 .../AWK/read-entire-file-2.awk | 10 + .../Emacs-Lisp/read-entire-file.l | 3 + .../Read-entire-file/Go/read-entire-file-2.go | 2 + Task/Read-entire-file/M4/read-entire-file.m4 | 3 + .../Make/read-entire-file.make | 1 + .../PARI-GP/read-entire-file.pari | 2 +- .../Perl/read-entire-file-4.pl | 8 +- .../Perl/read-entire-file-5.pl | 7 +- .../Perl/read-entire-file-6.pl | 1 + .../Perl/read-entire-file-7.pl | 3 + .../Perl/read-entire-file-8.pl | 4 + .../REXX/read-entire-file.rexx | 11 +- .../Rust/read-entire-file.rust | 14 +- .../Scala/read-entire-file.scala | 2 +- .../PL-I/real-constants-and-functions.pli | 2 +- .../REXX/real-constants-and-functions-1.rexx | 2 - .../REXX/real-constants-and-functions-2.rexx | 4 +- .../REXX/real-constants-and-functions-3.rexx | 2 +- .../REXX/real-constants-and-functions-4.rexx | 64 +- .../REXX/real-constants-and-functions-5.rexx | 48 +- .../REXX/real-constants-and-functions-6.rexx | 40 +- .../REXX/real-constants-and-functions-7.rexx | 14 + .../REXX/real-constants-and-functions-8.rexx | 27 + .../Ruby/real-constants-and-functions.rb | 16 +- .../real-constants-and-functions.sh | 15 + Task/Record-sound/00DESCRIPTION | 17 +- Task/Record-sound/00META.yaml | 4 + Task/Record-sound/C++/record-sound.cpp | 93 +++ Task/Record-sound/Scala/record-sound.scala | 51 ++ Task/Reduced-row-echelon-form/00DESCRIPTION | 9 +- .../D/reduced-row-echelon-form.d | 4 +- .../Icon/reduced-row-echelon-form.icon | 33 + .../Python/reduced-row-echelon-form.py | 2 +- .../REXX/reduced-row-echelon-form.rexx | 77 +- Task/Regular-expressions/00DESCRIPTION | 5 + Task/Regular-expressions/00META.yaml | 2 + .../D/regular-expressions.d | 2 +- .../Lua/regular-expressions.lua | 12 +- .../MAXScript/regular-expressions.max | 39 + .../Python/regular-expressions.py | 6 +- .../REXX/regular-expressions-1.rexx | 19 +- .../REXX/regular-expressions-2.rexx | 8 +- .../REXX/regular-expressions-3.rexx | 4 +- .../REXX/regular-expressions-4.rexx | 6 +- .../UNIX-Shell/regular-expressions-1.sh | 4 + .../UNIX-Shell/regular-expressions-2.sh | 3 + .../UNIX-Shell/regular-expressions-3.sh | 2 + .../UNIX-Shell/regular-expressions-4.sh | 5 + .../Go/remove-duplicate-elements-1.go | 23 +- .../Go/remove-duplicate-elements-2.go | 28 +- .../Go/remove-duplicate-elements-3.go | 50 +- .../Go/remove-duplicate-elements-4.go | 90 ++ .../remove-duplicate-elements-3.math | 3 +- .../PL-I/remove-duplicate-elements.pli | 11 +- .../Prolog/remove-duplicate-elements-3.pro | 2 +- .../Python/remove-duplicate-elements-2.py | 8 +- .../Python/remove-duplicate-elements-3.py | 6 +- .../Python/remove-duplicate-elements-4.py | 5 + .../Ruby/remove-duplicate-elements-1.rb | 2 + .../Ruby/remove-duplicate-elements-2.rb | 26 + .../Ruby/remove-duplicate-elements-3.rb | 15 + .../Ruby/remove-duplicate-elements.rb | 3 - .../Frink/remove-lines-from-a-file.frink | 12 + .../J/remove-lines-from-a-file-1.j | 6 +- .../Mathematica/remove-lines-from-a-file.math | 10 + .../Scala/remove-lines-from-a-file.scala | 18 + Task/Rename-a-file/00DESCRIPTION | 10 +- .../OpenEdge-Progress/rename-a-file.openedge | 5 + Task/Rename-a-file/REXX/rename-a-file-1.rexx | 14 +- Task/Rename-a-file/REXX/rename-a-file-2.rexx | 15 +- .../Rename-a-file/Scala/rename-a-file-2.scala | 8 +- Task/Repeat-a-string/ATS/repeat-a-string.ats | 32 + .../ColdFusion/repeat-a-string.cfm | 5 + .../Common-Lisp/repeat-a-string-1.lisp | 2 - .../Common-Lisp/repeat-a-string-2.lisp | 10 +- .../Common-Lisp/repeat-a-string-3.lisp | 1 + .../Common-Lisp/repeat-a-string-4.lisp | 1 + .../Delphi/repeat-a-string-3.delphi | 8 +- .../Delphi/repeat-a-string-4.delphi | 1 + Task/Repeat-a-string/Eiffel/repeat-a-string.e | 6 + .../Elixir/repeat-a-string.elixir | 1 + Task/Repeat-a-string/GAP/repeat-a-string.gap | 4 +- .../Haskell/repeat-a-string-3.hs | 2 +- .../Haskell/repeat-a-string-4.hs | 2 +- .../Haskell/repeat-a-string-5.hs | 1 + .../JavaScript/repeat-a-string-1.js | 5 + .../JavaScript/repeat-a-string-2.js | 1 + .../JavaScript/repeat-a-string.js | 5 - ...t-a-string.pari => repeat-a-string-1.pari} | 0 .../PARI-GP/repeat-a-string-2.pari | 1 + .../RapidQ/repeat-a-string.rapidq | 12 + .../repeat-a-string-1.visual | 1 + .../repeat-a-string-2.visual | 1 + .../Visual-Basic-.NET/repeat-a-string.visual | 6 - Task/Resistor-mesh/00DESCRIPTION | 3 +- Task/Resistor-mesh/00META.yaml | 3 + Task/Resistor-mesh/D/resistor-mesh.d | 42 +- .../Resistor-mesh/Octave/resistor-mesh.octave | 40 + .../{resistor-mesh.py => resistor-mesh-1.py} | 0 Task/Resistor-mesh/Python/resistor-mesh-2.py | 71 ++ Task/Resistor-mesh/REXX/resistor-mesh.rexx | 38 +- Task/Resistor-mesh/Racket/resistor-mesh.rkt | 70 ++ Task/Resistor-mesh/Tcl/resistor-mesh-1.tcl | 4 +- .../Go/respond-to-an-unknown-method-call.go | 29 + ...respond-to-an-unknown-method-call-1.groovy | 8 + ...respond-to-an-unknown-method-call-2.groovy | 4 + ...respond-to-an-unknown-method-call-3.groovy | 16 + ...respond-to-an-unknown-method-call-4.groovy | 31 + Task/Return-multiple-values/00DESCRIPTION | 2 + .../ALGOL-68/return-multiple-values.alg | 19 + .../ATS/return-multiple-values.ats | 23 +- .../Eiffel/return-multiple-values-1.e | 4 + .../Eiffel/return-multiple-values-2.e | 7 + .../Frink/return-multiple-values.frink | 3 + .../Haskell/return-multiple-values-1.hs | 3 +- .../Haskell/return-multiple-values-2.hs | 6 +- .../Reverse-a-string/ATS/reverse-a-string.ats | 38 + .../AWK/reverse-a-string-3.awk | 11 + .../Aime/reverse-a-string.aime | 2 +- .../Dart/reverse-a-string-1.dart | 1 + .../Dart/reverse-a-string-2.dart | 17 + .../Dart/reverse-a-string.dart | 11 - .../Elixir/reverse-a-string.elixir | 2 + .../JavaScript/reverse-a-string.js | 21 +- ...-string.julia => reverse-a-string-1.julia} | 0 .../Julia/reverse-a-string-2.julia | 2 + .../Reverse-a-string/OOC/reverse-a-string.ooc | 3 + .../Pascal/reverse-a-string-4.pascal | 16 + .../Prolog/reverse-a-string-2.pro | 7 +- .../Scala/reverse-a-string-2.scala | 2 +- .../Scala/reverse-a-string-3.scala | 37 +- .../Scala/reverse-a-string-4.scala | 30 + .../ALGOL-68/rock-paper-scissors.alg | 153 ++++ .../BASIC/rock-paper-scissors.basic | 62 ++ .../C/rock-paper-scissors-2.c | 105 ++- .../Clojure/rock-paper-scissors.clj | 39 + .../D/rock-paper-scissors.d | 57 ++ ...r-scissors.go => rock-paper-scissors-1.go} | 0 .../Go/rock-paper-scissors-2.go | 257 ++++++ .../Perl/rock-paper-scissors-1.pl | 121 +++ .../Perl/rock-paper-scissors-2.pl | 1 + .../Python/rock-paper-scissors.py | 75 +- .../REXX/rock-paper-scissors-1.rexx | 35 + .../REXX/rock-paper-scissors-2.rexx | 47 ++ .../REXX/rock-paper-scissors.rexx | 36 - .../Ruby/rock-paper-scissors.rb | 57 +- .../Scala/rock-paper-scissors-1.scala | 43 + .../Scala/rock-paper-scissors-2.scala | 60 ++ Task/Roman-numerals-Decode/00DESCRIPTION | 4 +- .../Clojure/roman-numerals-decode.clj | 8 + .../D/roman-numerals-decode-2.d | 4 +- .../Eiffel/roman-numerals-decode.e | 111 +++ .../Go/roman-numerals-decode-1.go | 10 +- .../Go/roman-numerals-decode-2.go | 19 +- .../Python/roman-numerals-decode-2.py | 6 - .../R/roman-numerals-decode-1.r | 13 + .../R/roman-numerals-decode-2.r | 1 + .../R/roman-numerals-decode-3.r | 1 + .../Scala/roman-numerals-decode.scala | 8 + .../Scheme/roman-numerals-decode-1.ss | 12 + .../Scheme/roman-numerals-decode-2.ss | 3 + Task/Roman-numerals-Encode/00DESCRIPTION | 13 +- Task/Roman-numerals-Encode/00META.yaml | 3 + .../Clojure/roman-numerals-encode-2.clj | 44 +- .../Clojure/roman-numerals-encode-3.clj | 7 +- .../Eiffel/roman-numerals-encode.e | 59 ++ .../Haskell/roman-numerals-encode.hs | 13 + .../Maple/roman-numerals-encode.maple | 4 + .../Perl/roman-numerals-encode-1.pl | 17 +- .../Perl/roman-numerals-encode-2.pl | 27 +- .../Perl/roman-numerals-encode-3.pl | 4 +- .../Perl/roman-numerals-encode-4.pl | 27 + ...s-encode.rb => roman-numerals-encode-1.rb} | 0 .../Ruby/roman-numerals-encode-2.rb | 6 + .../Ruby/roman-numerals-encode-3.rb | 8 + .../Rust/roman-numerals-encode.rust | 6 +- .../UNIX-Shell/roman-numerals-encode.sh | 22 + .../ATS/roots-of-a-function.ats | 46 ++ .../Go/roots-of-a-function.go | 63 +- .../Icon/roots-of-a-function.icon | 28 + .../JavaScript/roots-of-a-function.js | 30 + .../Scala/roots-of-a-function.scala | 12 + .../00DESCRIPTION | 3 +- .../D/roots-of-a-quadratic-function.d | 4 +- Task/Roots-of-unity/D/roots-of-unity.d | 3 +- ...ts-of-unity.pari => roots-of-unity-1.pari} | 0 .../PARI-GP/roots-of-unity-2.pari | 1 + .../PARI-GP/roots-of-unity-3.pari | 2 + Task/Roots-of-unity/Perl-6/roots-of-unity.pl6 | 6 +- .../rosetta-code-count-examples.bracmat | 41 + .../Objeck/rosetta-code-count-examples.objeck | 38 + .../Scala/rosetta-code-count-examples.scala | 31 +- ...setta-code-find-unimplemented-tasks-1.math | 21 + ...setta-code-find-unimplemented-tasks-2.math | 13 + .../D/rosetta-code-fix-code-tags-1.d | 3 +- .../Java/rosetta-code-fix-code-tags-1.java | 22 +- .../00DESCRIPTION | 2 +- ...etta-code-rank-languages-by-popularity.ahk | 127 +-- ...-code-rank-languages-by-popularity.bracmat | 91 +++ ...setta-code-rank-languages-by-popularity.go | 181 ++-- ...a-code-rank-languages-by-popularity.objeck | 80 ++ ...etta-code-rank-languages-by-popularity.pl6 | 8 +- ...tta-code-rank-languages-by-popularity.rexx | 40 +- Task/Rot-13/00DESCRIPTION | 37 +- Task/Rot-13/00META.yaml | 2 + Task/Rot-13/AWK/rot-13.awk | 1 + Task/Rot-13/Clojure/rot-13.clj | 19 + Task/Rot-13/Lua/rot-13.lua | 10 +- Task/Rot-13/NewLISP/rot-13.newlisp | 9 + Task/Rot-13/Perl/rot-13-1.pl | 4 +- Task/Rot-13/Python/rot-13-1.py | 25 +- Task/Rot-13/Python/rot-13-2.py | 26 +- Task/Rot-13/Python/rot-13-3.py | 21 + Task/Rot-13/Python/rot-13-4.py | 21 + Task/Rot-13/Python/rot-13-5.py | 15 + Task/Rot-13/REXX/rot-13.rexx | 41 +- Task/Rot-13/SQL/rot-13-1.sql | 6 + Task/Rot-13/SQL/{rot-13.sql => rot-13-2.sql} | 0 Task/Rot-13/TXR/{rot-13.txr => rot-13-1.txr} | 2 +- Task/Rot-13/TXR/rot-13-2.txr | 9 + Task/Rot-13/Tcl/rot-13-1.tcl | 2 + .../D/run-length-encoding-2.d | 4 +- ...ntime-evaluation-in-an-environment.bracmat | 9 + ...untime-evaluation-in-an-environment-1.lua} | 0 ...runtime-evaluation-in-an-environment-2.lua | 7 + .../runtime-evaluation-in-an-environment.m | 7 + Task/Runtime-evaluation/00DESCRIPTION | 3 +- ...valuation.alg => runtime-evaluation-1.alg} | 0 .../ALGOL-68/runtime-evaluation-2.alg | 35 + .../Frink/runtime-evaluation.frink | 1 + .../Groovy/runtime-evaluation-3.groovy | 2 +- .../Groovy/runtime-evaluation-4.groovy | 2 +- .../Groovy/runtime-evaluation-5.groovy | 2 +- ...valuation.lua => runtime-evaluation-1.lua} | 0 .../Lua/runtime-evaluation-2.lua | 2 + .../MATLAB/runtime-evaluation.m | 37 + .../REBOL/runtime-evaluation.rebol | 3 + .../REXX/runtime-evaluation.rexx | 12 +- .../UNIX-Shell/runtime-evaluation.sh | 4 + Task/S-Expressions/Perl-6/s-expressions.pl6 | 2 +- Task/S-Expressions/Ruby/s-expressions.rb | 12 +- Task/S-Expressions/Scheme/s-expressions.ss | 53 +- Task/SEDOLs/Clojure/sedols.clj | 6 + Task/SEDOLs/D/sedols-1.d | 20 +- Task/SEDOLs/D/sedols-2.d | 6 +- Task/SEDOLs/D/sedols-3.d | 17 +- Task/SEDOLs/Delphi/sedols.delphi | 79 ++ Task/SEDOLs/Ruby/sedols.rb | 4 +- Task/SEDOLs/Transact-SQL/sedols.sql | 63 ++ Task/SHA-1/D/sha-1.d | 6 +- Task/SHA-1/Haskell/sha-1.hs | 14 + Task/SHA-1/J/sha-1-1.j | 13 +- Task/SHA-1/NewLISP/sha-1.newlisp | 4 + Task/SHA-1/Pascal/sha-1.pascal | 9 + Task/SHA-1/Perl-6/sha-1.pl6 | 2 +- Task/SHA-1/PicoLisp/sha-1.l | 118 ++- Task/SHA-1/Ruby/sha-1-3.rb | 47 +- Task/SHA-256/Clojure/sha-256.clj | 2 + Task/SHA-256/D/sha-256-1.d | 5 + Task/SHA-256/D/{sha-256.d => sha-256-2.d} | 44 +- Task/SHA-256/Emacs-Lisp/sha-256.l | 1 + Task/SHA-256/NewLISP/sha-256.newlisp | 4 + Task/SHA-256/Objective-C/sha-256.m | 34 +- Task/SHA-256/Perl-6/sha-256.pl6 | 13 +- Task/SHA-256/PicoLisp/sha-256.l | 160 ++++ Task/SHA-256/Rust/sha-256.rust | 9 + Task/SHA-256/Scala/sha-256.scala | 11 + Task/SHA-256/Smalltalk/sha-256.st | 1 + .../Go/sql-based-authentication.go | 79 ++ .../Objeck/sql-based-authentication.objeck | 104 +++ Task/Safe-addition/00DESCRIPTION | 2 +- Task/Same-Fringe/D/same-fringe-2.d | 8 +- Task/Same-Fringe/D/same-fringe-3.d | 44 + Task/Same-Fringe/REXX/same-fringe-3.rexx | 136 ++- Task/Same-Fringe/Scheme/same-fringe.ss | 35 + .../Eiffel/scope-function-names-and-labels.e | 21 + .../Go/scope-function-names-and-labels-1.go | 24 + .../Go/scope-function-names-and-labels-2.go | 17 + .../Go/scope-function-names-and-labels-3.go | 29 + .../REXX/scope-function-names-and-labels.rexx | 24 +- Task/Scope-modifiers/00DESCRIPTION | 8 +- Task/Scope-modifiers/Eiffel/scope-modifiers.e | 21 + Task/Scope-modifiers/Ruby/scope-modifiers.rb | 9 + .../Search-a-list/Maxima/search-a-list.maxima | 9 + Task/Search-a-list/Python/search-a-list-3.py | 1 - .../Search-a-list/UNIX-Shell/search-a-list.sh | 15 + .../Clojure/secure-temporary-file.clj | 5 +- .../Emacs-Lisp/secure-temporary-file.l | 3 + .../Go/secure-temporary-file.go | 33 +- .../Icon/secure-temporary-file.icon | 5 + .../Scala/secure-temporary-file.scala | 26 +- ...bers.cpp => self-describing-numbers-1.cpp} | 1 - .../C++/self-describing-numbers-2.cpp | 26 + .../D/self-describing-numbers-1.d | 6 +- .../D/self-describing-numbers-2.d | 25 +- .../PHP/self-describing-numbers.php | 18 + .../Perl-6/self-describing-numbers.pl6 | 23 +- .../UNIX-Shell/self-describing-numbers.sh | 20 + .../D/self-referential-sequence-1.d | 18 +- .../D/self-referential-sequence-2.d | 47 +- .../D/self-referential-sequence-3.d | 10 +- .../Groovy/self-referential-sequence-1.groovy | 31 +- .../Groovy/self-referential-sequence-2.groovy | 8 +- .../Java/self-referential-sequence.java | 77 ++ .../REXX/self-referential-sequence.rexx | 19 +- .../TXR/self-referential-sequence-1.txr | 59 ++ .../TXR/self-referential-sequence-2.txr | 32 + .../TXR/self-referential-sequence-3.txr | 47 ++ Task/Semordnilap/Aime/semordnilap.aime | 6 +- Task/Semordnilap/Clojure/semordnilap.clj | 23 +- Task/Semordnilap/D/semordnilap-1.d | 10 +- Task/Semordnilap/Eiffel/semordnilap-1.e | 80 ++ Task/Semordnilap/Eiffel/semordnilap-2.e | 16 + Task/Semordnilap/Java/semordnilap.java | 20 +- Task/Semordnilap/Mathematica/semordnilap.math | 3 +- Task/Semordnilap/REXX/semordnilap-2.rexx | 28 +- Task/Semordnilap/Ruby/semordnilap.rb | 12 +- .../J/send-an-unknown-method-call.j | 21 + .../send-an-unknown-method-call.math | 1 + .../Scala/send-an-unknown-method-call.scala | 12 + Task/Send-email/Clojure/send-email.clj | 11 + Task/Send-email/D/send-email.d | 16 +- .../Go/{send-email.go => send-email-1.go} | 0 Task/Send-email/Go/send-email-2.go | 7 + .../sequence-of-non-squares.coffee | 19 + .../D/sequence-of-non-squares.d | 2 +- .../Eiffel/sequence-of-non-squares.e | 42 + ...ascal => sequence-of-non-squares-1.pascal} | 0 .../Pascal/sequence-of-non-squares-2.pascal | 50 ++ .../REXX/sequence-of-non-squares.rexx | 56 +- .../Set-consolidation/D/set-consolidation-1.d | 6 +- .../Set-consolidation/D/set-consolidation-2.d | 6 +- .../REXX/set-consolidation.rexx | 50 +- .../Ruby/set-consolidation.rb | 18 +- .../Scala/set-consolidation.scala | 27 + Task/Set-of-real-numbers/00DESCRIPTION | 2 +- .../Clojure/set-of-real-numbers.clj | 34 + .../D/set-of-real-numbers.d | 61 ++ .../Go/set-of-real-numbers-1.go | 28 + .../Go/set-of-real-numbers-2.go | 11 + .../Go/set-of-real-numbers-3.go | 100 +++ .../Mathematica/set-of-real-numbers.math | 27 + .../Python/set-of-real-numbers.py | 29 +- .../Ruby/set-of-real-numbers-1.rb | 171 ++++ .../Ruby/set-of-real-numbers-2.rb | 45 + .../Ruby/set-of-real-numbers-3.rb | 31 + Task/Set-puzzle/00DESCRIPTION | 19 +- Task/Set-puzzle/00META.yaml | 4 + Task/Set-puzzle/Ada/set-puzzle-1.ada | 18 + Task/Set-puzzle/Ada/set-puzzle-2.ada | 78 ++ Task/Set-puzzle/Ada/set-puzzle-3.ada | 50 ++ .../D/{set-puzzle.d => set-puzzle-1.d} | 54 +- Task/Set-puzzle/D/set-puzzle-2.d | 19 + Task/Set-puzzle/Go/set-puzzle.go | 25 +- Task/Set-puzzle/Java/set-puzzle.java | 11 +- Task/Set-puzzle/Mathematica/set-puzzle.math | 18 + .../Python/{set-puzzle.py => set-puzzle-1.py} | 0 Task/Set-puzzle/Python/set-puzzle-2.py | 21 + Task/Set-puzzle/REXX/set-puzzle.rexx | 99 +++ Task/Set/00DESCRIPTION | 7 +- Task/Set/Prolog/{set.pro => set-1.pro} | 0 Task/Set/Prolog/set-2.pro | 55 ++ Task/Set/Python/set.py | 42 +- Task/Set/REXX/set.rexx | 6 +- .../D/seven-sided-dice-from-five-sided-dice.d | 8 +- ...even-sided-dice-from-five-sided-dice.julia | 6 + .../Maple/shell-one-liner.maple | 1 + .../Sierpinski-carpet/D/sierpinski-carpet-1.d | 8 +- .../Sierpinski-carpet/D/sierpinski-carpet-3.d | 2 +- .../Euphoria/sierpinski-carpet.euphoria | 26 + .../Sierpinski-carpet/J/sierpinski-carpet-2.j | 28 +- .../Sierpinski-carpet/J/sierpinski-carpet-3.j | 14 +- .../Sierpinski-carpet/J/sierpinski-carpet-4.j | 27 + .../Sierpinski-carpet/J/sierpinski-carpet-5.j | 40 + .../Julia/sierpinski-carpet.julia | 12 + .../Objeck/sierpinski-carpet.objeck | 29 + .../VBScript/sierpinski-carpet.vb | 32 + .../D/sierpinski-triangle-graphical.d | 8 +- .../Java/sierpinski-triangle-graphical.java | 58 ++ .../Python/sierpinski-triangle-graphical-1.py | 20 + ....py => sierpinski-triangle-graphical-2.py} | 24 +- Task/Sierpinski-triangle/00DESCRIPTION | 6 +- .../ATS/sierpinski-triangle.ats | 42 + .../D/sierpinski-triangle-1.d | 6 +- .../D/sierpinski-triangle-2.d | 23 +- .../D/sierpinski-triangle-3.d | 17 + .../D/sierpinski-triangle-4.d | 42 + .../Python/sierpinski-triangle-3.py | 4 + .../Ruby/sierpinski-triangle-2.rb | 4 +- .../Ruby/sierpinski-triangle-3.rb | 9 +- Task/Sieve-of-Eratosthenes/00DESCRIPTION | 4 +- .../360-Assembly/sieve-of-eratosthenes.360 | 71 ++ .../ALGOL-60/sieve-of-eratosthenes.alg | 40 + .../AWK/sieve-of-eratosthenes.awk | 18 + .../Batch-File/sieve-of-eratosthenes.bat | 20 + .../C/sieve-of-eratosthenes-1.c | 28 + .../C/sieve-of-eratosthenes-2.c | 39 + .../C/sieve-of-eratosthenes-3.c | 25 + .../C/sieve-of-eratosthenes.c | 29 - .../CMake/sieve-of-eratosthenes.cmake | 35 + .../Clojure/sieve-of-eratosthenes-1.clj | 30 +- .../Clojure/sieve-of-eratosthenes-2.clj | 29 +- .../Clojure/sieve-of-eratosthenes-3.clj | 25 +- .../D/sieve-of-eratosthenes-1.d | 8 +- .../D/sieve-of-eratosthenes-2.d | 6 +- .../D/sieve-of-eratosthenes-3.d | 4 +- .../Dart/sieve-of-eratosthenes-1.dart | 33 + .../Dart/sieve-of-eratosthenes-2.dart | 35 + .../Dart/sieve-of-eratosthenes-3.dart | 77 ++ .../Dart/sieve-of-eratosthenes.dart | 34 - .../Delphi/sieve-of-eratosthenes.delphi | 85 ++ .../Emacs-Lisp/sieve-of-eratosthenes-1.l | 7 + .../Emacs-Lisp/sieve-of-eratosthenes-2.l | 7 + .../F-Sharp/sieve-of-eratosthenes-1.fs | 21 + .../F-Sharp/sieve-of-eratosthenes-2.fs | 21 + .../F-Sharp/sieve-of-eratosthenes-3.fs | 11 + .../F-Sharp/sieve-of-eratosthenes-4.fs | 9 + .../F-Sharp/sieve-of-eratosthenes-5.fs | 8 + .../F-Sharp/sieve-of-eratosthenes-6.fs | 3 + .../F-Sharp/sieve-of-eratosthenes-7.fs | 17 + .../GAP/sieve-of-eratosthenes.gap | 37 +- .../Groovy/sieve-of-eratosthenes-1.groovy | 6 +- .../Haskell/sieve-of-eratosthenes-10.hs | 3 + .../Haskell/sieve-of-eratosthenes-11.hs | 23 + .../Haskell/sieve-of-eratosthenes-4.hs | 4 +- .../Haskell/sieve-of-eratosthenes-5.hs | 13 +- .../Haskell/sieve-of-eratosthenes-6.hs | 13 +- .../Haskell/sieve-of-eratosthenes-7.hs | 10 + .../Haskell/sieve-of-eratosthenes-8.hs | 9 + .../Haskell/sieve-of-eratosthenes-9.hs | 2 + .../J/sieve-of-eratosthenes-1.j | 2 + .../J/sieve-of-eratosthenes-10.j | 10 + .../J/sieve-of-eratosthenes-11.j | 10 + .../J/sieve-of-eratosthenes-12.j | 9 + .../J/sieve-of-eratosthenes-2.j | 4 + .../J/sieve-of-eratosthenes-3.j | 6 + .../J/sieve-of-eratosthenes-4.j | 2 + .../J/sieve-of-eratosthenes-5.j | 6 + .../J/sieve-of-eratosthenes-6.j | 2 + .../J/sieve-of-eratosthenes-7.j | 2 + .../J/sieve-of-eratosthenes-8.j | 4 + .../J/sieve-of-eratosthenes-9.j | 1 + .../Java/sieve-of-eratosthenes-4.java | 54 ++ .../Java/sieve-of-eratosthenes-5.java | 59 ++ .../Java/sieve-of-eratosthenes-6.java | 78 ++ .../JavaScript/sieve-of-eratosthenes-1.js | 27 + .../JavaScript/sieve-of-eratosthenes-2.js | 22 + .../JavaScript/sieve-of-eratosthenes-3.js | 42 + .../JavaScript/sieve-of-eratosthenes-4.js | 7 + .../JavaScript/sieve-of-eratosthenes-5.js | 57 ++ .../JavaScript/sieve-of-eratosthenes.js | 27 - .../Lua/sieve-of-eratosthenes-1.lua | 10 + .../Lua/sieve-of-eratosthenes-2.lua | 14 + .../Lua/sieve-of-eratosthenes-3.lua | 33 + .../Lua/sieve-of-eratosthenes.lua | 6 - .../MATLAB/sieve-of-eratosthenes-2.m | 15 +- .../MATLAB/sieve-of-eratosthenes-3.m | 23 +- .../Mathematica/sieve-of-eratosthenes-1.math | 6 + .../Mathematica/sieve-of-eratosthenes-2.math | 5 + .../Mathematica/sieve-of-eratosthenes-3.math | 6 + .../Mathematica/sieve-of-eratosthenes.math | 10 - ....pascal => sieve-of-eratosthenes-1.pascal} | 0 .../Pascal/sieve-of-eratosthenes-2.pascal | 130 +++ .../Perl/sieve-of-eratosthenes-1.pl | 26 +- .../Perl/sieve-of-eratosthenes-10.pl | 54 ++ .../Perl/sieve-of-eratosthenes-2.pl | 19 +- .../Perl/sieve-of-eratosthenes-3.pl | 2 +- .../Perl/sieve-of-eratosthenes-4.pl | 15 +- .../Python/sieve-of-eratosthenes-1.py | 12 +- .../Python/sieve-of-eratosthenes-10.py | 40 +- .../Python/sieve-of-eratosthenes-11.py | 28 + .../Python/sieve-of-eratosthenes-12.py | 24 + .../Python/sieve-of-eratosthenes-13.py | 30 + .../Python/sieve-of-eratosthenes-14.py | 40 + .../Python/sieve-of-eratosthenes-2.py | 15 +- .../Python/sieve-of-eratosthenes-3.py | 7 +- .../Python/sieve-of-eratosthenes-4.py | 9 +- .../Python/sieve-of-eratosthenes-5.py | 13 +- .../Python/sieve-of-eratosthenes-6.py | 19 +- .../Python/sieve-of-eratosthenes-7.py | 40 +- .../Python/sieve-of-eratosthenes-8.py | 19 +- .../Python/sieve-of-eratosthenes-9.py | 48 +- .../REXX/sieve-of-eratosthenes-1.rexx | 19 +- .../REXX/sieve-of-eratosthenes-2.rexx | 35 +- .../REXX/sieve-of-eratosthenes-3.rexx | 32 +- .../Racket/sieve-of-eratosthenes-1.rkt | 1 - .../Racket/sieve-of-eratosthenes-10.rkt | 5 + .../Racket/sieve-of-eratosthenes-11.rkt | 26 + .../Racket/sieve-of-eratosthenes-12.rkt | 21 + .../Racket/sieve-of-eratosthenes-2.rkt | 1 - .../Racket/sieve-of-eratosthenes-3.rkt | 28 +- .../Racket/sieve-of-eratosthenes-4.rkt | 42 +- .../Racket/sieve-of-eratosthenes-5.rkt | 32 +- .../Racket/sieve-of-eratosthenes-6.rkt | 5 + .../Racket/sieve-of-eratosthenes-7.rkt | 6 + .../Racket/sieve-of-eratosthenes-8.rkt | 5 + .../Racket/sieve-of-eratosthenes-9.rkt | 6 + .../Rust/sieve-of-eratosthenes.rust | 16 +- .../Scala/sieve-of-eratosthenes-1.scala | 30 +- .../Scala/sieve-of-eratosthenes-2.scala | 39 +- .../Scala/sieve-of-eratosthenes-3.scala | 32 +- .../Scala/sieve-of-eratosthenes-4.scala | 10 + .../Scala/sieve-of-eratosthenes-5.scala | 92 +++ .../Scala/sieve-of-eratosthenes-6.scala | 10 + .../Scala/sieve-of-eratosthenes-7.scala | 22 + .../Scala/sieve-of-eratosthenes-8.scala | 33 + .../Scala/sieve-of-eratosthenes-9.scala | 25 + .../Scheme/sieve-of-eratosthenes-10.ss | 9 + .../Scheme/sieve-of-eratosthenes-11.ss | 23 + .../Scheme/sieve-of-eratosthenes-12.ss | 4 + .../Scheme/sieve-of-eratosthenes-7.ss | 32 + .../Scheme/sieve-of-eratosthenes-8.ss | 20 + .../Scheme/sieve-of-eratosthenes-9.ss | 27 + .../Scilab/sieve-of-eratosthenes.scilab | 13 + .../TI-83-BASIC/sieve-of-eratosthenes.ti-83 | 20 + .../VBScript/sieve-of-eratosthenes.vb | 20 + .../Visual-Basic/sieve-of-eratosthenes.vb | 19 + .../Bracmat/simple-database.bracmat | 79 ++ Task/Simple-database/D/simple-database.d | 2 +- .../Simple-database/Java/simple-database.java | 125 +++ .../REBOL/simple-database.rebol | 15 + .../Simple-database/REXX/simple-database.rexx | 77 ++ .../Scala/simple-database.scala | 38 + .../Simple-windowed-application/00DESCRIPTION | 3 +- Task/Simple-windowed-application/00META.yaml | 1 + ...t => simple-windowed-application-1.hicest} | 0 .../simple-windowed-application-2.hicest | 31 + .../J/simple-windowed-application-1.j | 20 + ...tion.j => simple-windowed-application-2.j} | 0 .../Perl-6/simple-windowed-application.pl6 | 21 + .../Scala/simple-windowed-application.scala | 33 +- Task/Simulate-input-Keyboard/00DESCRIPTION | 17 +- .../Python/simulate-input-keyboard.py | 10 + .../Scala/simulate-input-keyboard.scala | 26 +- .../Scala/simulate-input-mouse.scala | 4 + Task/Singleton/00DESCRIPTION | 3 +- Task/Singleton/Smalltalk/singleton.st | 4 + .../singly-linked-list-element-definition.clj | 1 + .../Clojure/singly-linked-list-traversal.clj | 2 +- .../singly-linked-list-traversal-2.lisp | 4 +- .../singly-linked-list-traversal-3.lisp | 1 + .../singly-linked-list-traversal-4.lisp | 1 + .../singly-linked-list-traversal-5.lisp | 3 + .../singly-linked-list-traversal.newlisp | 2 + .../Perl-6/singly-linked-list-traversal-1.pl6 | 2 +- .../Perl-6/singly-linked-list-traversal-2.pl6 | 2 +- Task/Sleep/360-Assembly/sleep.360 | 106 +++ Task/Sleep/ALGOL-68/sleep.alg | 8 + Task/Sleep/Perl/sleep-3.pl | 3 + Task/Sleep/REXX/{sleep.rexx => sleep-1.rexx} | 5 +- Task/Sleep/REXX/sleep-2.rexx | 54 ++ Task/Sleep/RapidQ/sleep.rapidq | 4 + Task/Sleep/Scala/sleep.scala | 15 +- Task/Sockets/Scala/sockets.scala | 13 + Task/Sokoban/C++/sokoban-1.cpp | 38 +- Task/Sokoban/D/sokoban-1.d | 52 +- Task/Sokoban/D/sokoban-2.d | 54 +- Task/Sokoban/Haskell/sokoban.hs | 132 +++ Task/Sokoban/Ruby/sokoban-1.rb | 63 ++ Task/Sokoban/Ruby/sokoban-2.rb | 11 + Task/Sokoban/Ruby/sokoban-3.rb | 95 +++ Task/Solve-a-Hidato-puzzle/00DESCRIPTION | 8 +- .../Curry/solve-a-hidato-puzzle.curry | 54 ++ .../D/solve-a-hidato-puzzle-2.d | 14 +- .../Java/solve-a-hidato-puzzle.java | 105 +++ .../Perl-6/solve-a-hidato-puzzle.pl6 | 150 ++-- .../REXX/solve-a-hidato-puzzle.rexx | 15 +- ...puzzle.rkt => solve-a-hidato-puzzle-1.rkt} | 0 .../Racket/solve-a-hidato-puzzle-2.rkt | 19 + .../Ruby/solve-a-hidato-puzzle-1.rb | 94 +-- .../Ruby/solve-a-hidato-puzzle-2.rb | 34 +- .../Ruby/solve-a-hidato-puzzle-3.rb | 89 +- .../Ruby/solve-a-hidato-puzzle-4.rb | 60 +- .../Seed7/solve-a-hidato-puzzle.seed7 | 100 +++ .../sort-an-array-of-composite-structures.cpp | 64 +- ...sort-an-array-of-composite-structures-3.py | 2 +- .../sort-an-array-of-composite-structures.rb | 9 +- ...ort-an-array-of-composite-structures.scala | 11 +- .../C++/sort-an-integer-array-1.cpp | 2 +- .../Frink/sort-an-integer-array.frink | 2 + .../REXX/sort-an-integer-array-1.rexx | 64 +- .../REXX/sort-an-integer-array-2.rexx | 37 +- .../Rust/sort-an-integer-array.rust | 6 + .../Scala/sort-an-integer-array-1.scala | 15 + .../Scala/sort-an-integer-array-2.scala | 2 + .../Scala/sort-an-integer-array.scala | 2 - Task/Sort-disjoint-sublist/00DESCRIPTION | 3 + .../Clojure/sort-disjoint-sublist.clj | 4 + .../D/sort-disjoint-sublist-1.d | 3 +- .../Scala/sort-disjoint-sublist.scala | 17 + .../Scheme/sort-disjoint-sublist.ss | 16 + Task/Sort-stability/REXX/sort-stability.rexx | 39 + .../Ada/sort-using-a-custom-comparator.ada | 108 +++ .../D/sort-using-a-custom-comparator-2.d | 4 +- .../Lua/sort-using-a-custom-comparator.lua | 17 +- .../sort-using-a-custom-comparator-3.ss | 11 + .../D/sorting-algorithms-bead-sort.d | 4 +- .../Eiffel/sorting-algorithms-bead-sort-1.e | 61 ++ .../Eiffel/sorting-algorithms-bead-sort-2.e | 20 + ...pli => sorting-algorithms-bead-sort-1.pli} | 0 .../PL-I/sorting-algorithms-bead-sort-2.pli | 46 ++ .../REXX/sorting-algorithms-bead-sort.rexx | 80 +- .../Ruby/sorting-algorithms-bead-sort.rb | 4 +- .../Seed7/sorting-algorithms-bead-sort.seed7 | 46 ++ .../Sorting-algorithms-Bogosort/00DESCRIPTION | 6 +- .../C++/sorting-algorithms-bogosort.cpp | 29 + .../Clojure/sorting-algorithms-bogosort.clj | 20 +- .../Eiffel/sorting-algorithms-bogosort-1.e | 58 ++ .../Eiffel/sorting-algorithms-bogosort-2.e | 24 + .../PL-I/sorting-algorithms-bogosort.pli | 54 ++ .../Python/sorting-algorithms-bogosort-4.py | 12 + .../REXX/sorting-algorithms-bogosort-1.rexx | 31 + .../REXX/sorting-algorithms-bogosort-2.rexx | 42 + .../REXX/sorting-algorithms-bogosort.rexx | 46 -- .../00DESCRIPTION | 8 +- .../sorting-algorithms-bubble-sort.360 | 83 ++ .../C++/sorting-algorithms-bubble-sort.cpp | 54 +- .../C/sorting-algorithms-bubble-sort.c | 38 +- .../sorting-algorithms-bubble-sort.cobol | 199 ++--- .../Fortran/sorting-algorithms-bubble-sort.f | 2 +- .../sorting-algorithms-bubble-sort-3.hs | 16 + .../MATLAB/sorting-algorithms-bubble-sort.m | 20 + .../sorting-algorithms-bubble-sort.m | 15 + ...o => sorting-algorithms-bubble-sort-1.pro} | 0 .../sorting-algorithms-bubble-sort-2.pro | 22 + .../sorting-algorithms-bubble-sort.realbasic | 5 +- .../REXX/sorting-algorithms-bubble-sort.rexx | 72 +- .../sorting-algorithms-bubble-sort.scilab | 16 + .../00DESCRIPTION | 3 +- ...=> sorting-algorithms-cocktail-sort-1.cpp} | 11 +- .../sorting-algorithms-cocktail-sort-2.cpp | 35 + .../D/sorting-algorithms-cocktail-sort-1.d | 37 + .../D/sorting-algorithms-cocktail-sort-2.d | 7 + .../D/sorting-algorithms-cocktail-sort.d | 26 - .../sorting-algorithms-cocktail-sort-1.e | 50 ++ .../sorting-algorithms-cocktail-sort-2.e | 18 + .../D/sorting-algorithms-comb-sort.d | 12 +- .../Eiffel/sorting-algorithms-comb-sort-1.e | 44 + .../Eiffel/sorting-algorithms-comb-sort-2.e | 24 + .../sorting-algorithms-comb-sort-1.max | 28 + .../sorting-algorithms-comb-sort-2.max | 4 + .../REXX/sorting-algorithms-comb-sort.rexx | 66 +- ...=> sorting-algorithms-counting-sort-1.cpp} | 2 +- .../sorting-algorithms-counting-sort-2.cpp | 30 + .../sorting-algorithms-counting-sort-1.e | 34 + .../sorting-algorithms-counting-sort-2.e | 24 + .../sorting-algorithms-counting-sort-1.max | 23 + .../sorting-algorithms-counting-sort-2.max | 4 + .../sorting-algorithms-counting-sort-1.rexx | 32 + .../sorting-algorithms-counting-sort-2.rexx | 43 + .../sorting-algorithms-counting-sort.rexx | 41 - .../sorting-algorithms-gnome-sort.bat | 60 ++ .../C++/sorting-algorithms-gnome-sort.cpp | 20 +- .../Eiffel/sorting-algorithms-gnome-sort-1.e | 38 + .../Eiffel/sorting-algorithms-gnome-sort-2.e | 21 + .../sorting-algorithms-gnome-sort-1.max | 24 + .../sorting-algorithms-gnome-sort-2.max | 4 + .../REXX/sorting-algorithms-gnome-sort-1.rexx | 31 + .../REXX/sorting-algorithms-gnome-sort-2.rexx | 46 ++ .../REXX/sorting-algorithms-gnome-sort.rexx | 41 - .../Sorting-algorithms-Heapsort/00DESCRIPTION | 7 +- .../C++/sorting-algorithms-heapsort.cpp | 16 + .../D/sorting-algorithms-heapsort-1.d | 2 +- .../D/sorting-algorithms-heapsort-2.d | 14 +- ....fth => sorting-algorithms-heapsort-1.fth} | 0 .../Forth/sorting-algorithms-heapsort-2.fth | 83 ++ .../sorting-algorithms-heapsort-1.max | 43 + .../sorting-algorithms-heapsort-2.max | 4 + .../REXX/sorting-algorithms-heapsort-1.rexx | 48 +- .../sorting-algorithms-heapsort.ml | 54 ++ .../00DESCRIPTION | 9 +- .../C++/sorting-algorithms-insertion-sort.cpp | 28 +- .../C/sorting-algorithms-insertion-sort.c | 23 +- ... sorting-algorithms-insertion-sort-1.lisp} | 0 .../sorting-algorithms-insertion-sort-2.lisp | 18 + ... => sorting-algorithms-insertion-sort-1.d} | 8 +- .../D/sorting-algorithms-insertion-sort-2.d | 31 + .../sorting-algorithms-insertion-sort-1.max | 14 + .../sorting-algorithms-insertion-sort-2.max | 4 + ... => sorting-algorithms-insertion-sort-1.r} | 0 .../R/sorting-algorithms-insertion-sort-2.r | 17 + .../sorting-algorithms-insertion-sort.rexx | 52 +- .../sorting-algorithms-insertion-sort.rkt | 18 +- .../sorting-algorithms-insertion-sort.scala | 8 +- .../00DESCRIPTION | 12 +- .../C/sorting-algorithms-merge-sort.c | 124 +-- .../D/sorting-algorithms-merge-sort-1.d | 2 +- .../Eiffel/sorting-algorithms-merge-sort-1.e | 117 +++ .../Eiffel/sorting-algorithms-merge-sort-2.e | 19 + .../Java/sorting-algorithms-merge-sort.java | 28 +- .../sorting-algorithms-merge-sort.js | 36 +- .../sorting-algorithms-merge-sort-1.max | 55 ++ .../sorting-algorithms-merge-sort-2.max | 4 + ...=> sorting-algorithms-merge-sort-1.pascal} | 0 .../sorting-algorithms-merge-sort-2.pascal | 168 ++++ .../Python/sorting-algorithms-merge-sort-1.py | 2 +- .../REXX/sorting-algorithms-merge-sort.rexx | 102 ++- .../Ruby/sorting-algorithms-merge-sort-1.rb | 2 +- .../Ruby/sorting-algorithms-merge-sort-2.rb | 2 +- .../ZED/sorting-algorithms-merge-sort.zed | 86 ++ .../D/sorting-algorithms-pancake-sort.d | 10 +- .../sorting-algorithms-pancake-sort-1.e | 87 ++ .../sorting-algorithms-pancake-sort-2.e | 21 + .../sorting-algorithms-pancake-sort-1.max | 29 + .../sorting-algorithms-pancake-sort-2.max | 4 + .../REXX/sorting-algorithms-pancake-sort.rexx | 77 +- .../00DESCRIPTION | 5 +- .../D/sorting-algorithms-permutation-sort-1.d | 6 +- .../D/sorting-algorithms-permutation-sort-2.d | 2 +- .../sorting-algorithms-permutation-sort-1.max | 29 + .../sorting-algorithms-permutation-sort-2.max | 4 + .../sorting-algorithms-permutation-sort.rexx | 50 +- .../00DESCRIPTION | 3 +- .../sorting-algorithms-quicksort-2.alg | 6 +- .../C/sorting-algorithms-quicksort.c | 38 +- .../D/sorting-algorithms-quicksort-1.d | 4 +- .../D/sorting-algorithms-quicksort-3.d | 2 +- .../Forth/sorting-algorithms-quicksort.fth | 6 +- .../sorting-algorithms-quicksort-1.julia | 1 + .../sorting-algorithms-quicksort-2.julia | 22 + .../sorting-algorithms-quicksort-3.julia | 1 + .../Julia/sorting-algorithms-quicksort.julia | 29 - .../K/sorting-algorithms-quicksort-3.k | 2 +- .../K/sorting-algorithms-quicksort-4.k | 2 +- .../K/sorting-algorithms-quicksort-5.k | 2 +- .../K/sorting-algorithms-quicksort-6.k | 10 +- .../K/sorting-algorithms-quicksort-7.k | 10 +- .../Lua/sorting-algorithms-quicksort.lua | 2 +- .../Perl/sorting-algorithms-quicksort.pl | 2 +- .../Python/sorting-algorithms-quicksort-6.py | 7 + .../Python/sorting-algorithms-quicksort-7.py | 17 + .../REXX/sorting-algorithms-quicksort-1.rexx | 197 +++-- .../Racket/sorting-algorithms-quicksort-1.rkt | 16 +- .../Racket/sorting-algorithms-quicksort-2.rkt | 4 +- .../Ruby/sorting-algorithms-quicksort-4.rb | 6 + .../Rust/sorting-algorithms-quicksort.rust | 53 ++ .../sorting-algorithms-quicksort-5.scala | 3 +- .../Java/sorting-algorithms-radix-sort-1.java | 66 +- .../sorting-algorithms-radix-sort-1.math | 17 + .../sorting-algorithms-radix-sort-2.math | 2 + .../00DESCRIPTION | 3 +- .../C++/sorting-algorithms-selection-sort.cpp | 17 +- .../C/sorting-algorithms-selection-sort.c | 10 +- .../sorting-algorithms-selection-sort-1.e | 62 ++ .../sorting-algorithms-selection-sort-2.e | 23 + .../sorting-algorithms-selection-sort.hs | 14 +- .../sorting-algorithms-selection-sort.rexx | 48 +- .../00DESCRIPTION | 7 +- .../C/sorting-algorithms-shell-sort.c | 15 +- .../REXX/sorting-algorithms-shell-sort.rexx | 74 +- .../Racket/sorting-algorithms-shell-sort.rkt | 10 +- .../C++/sorting-algorithms-sleep-sort.cpp | 38 + .../sorting-algorithms-sleep-sort-1.clj | 9 + .../sorting-algorithms-sleep-sort-2.clj | 2 + .../sorting-algorithms-sleep-sort.lisp | 8 + .../D/sorting-algorithms-sleep-sort.d | 8 +- .../Dart/sorting-algorithms-sleep-sort.dart | 18 + .../Go/sorting-algorithms-sleep-sort.go | 39 +- .../sorting-algorithms-sleep-sort.groovy | 9 + .../Lua/sorting-algorithms-sleep-sort-1.lua | 27 + .../Lua/sorting-algorithms-sleep-sort-2.lua | 29 + .../Perl-6/sorting-algorithms-sleep-sort.pl6 | 9 +- .../REXX/sorting-algorithms-sleep-sort.rexx | 50 +- .../00DESCRIPTION | 6 +- .../Eiffel/sorting-algorithms-stooge-sort-1.e | 28 + .../Eiffel/sorting-algorithms-stooge-sort-2.e | 20 + .../sorting-algorithms-stooge-sort-1.max | 18 + .../sorting-algorithms-stooge-sort-2.max | 4 + .../sorting-algorithms-strand-sort-1.max | 25 + .../sorting-algorithms-strand-sort-2.max | 4 + .../REXX/sorting-algorithms-strand-sort.rexx | 30 +- Task/Soundex/00DESCRIPTION | 3 +- Task/Soundex/Ada/soundex.ada | 4 +- Task/Soundex/REXX/soundex.rexx | 164 ++-- Task/Soundex/Standard-ML/soundex.ml | 66 ++ Task/Soundex/TXR/soundex-2.txr | 22 +- .../Scala/special-characters.scala | 1 + .../Clojure/special-variables.clj | 1 + .../Common-Lisp/special-variables.lisp | 12 + .../Julia/special-variables.julia | 1 + .../Lua/special-variables.lua | 1 + .../REXX/special-variables-1.rexx | 29 + .../REXX/special-variables-2.rexx | 23 + .../REXX/special-variables.rexx | 28 - .../Tcl/special-variables-1.tcl | 1 + ...-variables.tcl => special-variables-2.tcl} | 0 .../Clojure/speech-synthesis.clj | 2 + .../Perl-6/speech-synthesis.pl6 | 1 + .../Scala/speech-synthesis.scala | 59 +- Task/Spiral-matrix/00DESCRIPTION | 8 +- .../360-Assembly/spiral-matrix.360 | 120 +++ ...{spiral-matrix.cpp => spiral-matrix-1.cpp} | 0 Task/Spiral-matrix/C++/spiral-matrix-2.cpp | 17 + .../C/{spiral-matrix.c => spiral-matrix-1.c} | 0 Task/Spiral-matrix/C/spiral-matrix-2.c | 18 + Task/Spiral-matrix/Clojure/spiral-matrix.clj | 20 +- .../{spiral-matrix.hs => spiral-matrix-1.hs} | 7 +- Task/Spiral-matrix/Haskell/spiral-matrix-2.hs | 9 + Task/Spiral-matrix/Haskell/spiral-matrix-3.hs | 10 + Task/Spiral-matrix/J/spiral-matrix.j | 2 +- .../Spiral-matrix/Pascal/spiral-matrix.pascal | 70 ++ Task/Spiral-matrix/Python/spiral-matrix-3.py | 32 +- Task/Spiral-matrix/Python/spiral-matrix-4.py | 33 +- Task/Spiral-matrix/Python/spiral-matrix-5.py | 19 + Task/Spiral-matrix/Python/spiral-matrix-6.py | 11 + Task/Spiral-matrix/REXX/spiral-matrix-1.rexx | 22 + Task/Spiral-matrix/REXX/spiral-matrix-2.rexx | 25 + Task/Spiral-matrix/REXX/spiral-matrix.rexx | 27 - .../{spiral-matrix.rb => spiral-matrix-1.rb} | 4 +- Task/Spiral-matrix/Ruby/spiral-matrix-2.rb | 13 + .../Spiral-matrix/Scilab/spiral-matrix.scilab | 22 + .../TI-83-BASIC/spiral-matrix.ti-83 | 40 + .../Visual-Basic/spiral-matrix-4.vb | 55 ++ Task/Stable-marriage-problem/00DESCRIPTION | 2 + .../ColdFusion/stable-marriage-problem-1.cfm | 121 +++ .../ColdFusion/stable-marriage-problem-2.cfm | 113 +++ .../D/stable-marriage-problem-1.d | 10 +- .../D/stable-marriage-problem-2.d | 12 +- .../Objective-C/stable-marriage-problem.m | 8 +- .../Perl-6/stable-marriage-problem.pl6 | 91 +++ Task/Stack-traces/Clojure/stack-traces.clj | 2 + Task/Stack-traces/Go/stack-traces.go | 10 +- Task/Stack-traces/Ruby/stack-traces-3.rb | 1 + Task/Stack/00DESCRIPTION | 11 +- Task/Stack/Babel/stack.pb | 4 - Task/Stack/JavaScript/stack-2.js | 2 +- Task/Stack/JavaScript/stack-3.js | 24 + Task/Stack/Smalltalk/stack.st | 6 + .../REXX/stair-climbing-puzzle.rexx | 2 +- .../SAS/stair-climbing-puzzle.sas | 16 + Task/Standard-deviation/00DESCRIPTION | 7 +- .../360-Assembly/standard-deviation.360 | 102 +++ .../Common-Lisp/standard-deviation-1.lisp | 2 +- .../Java/standard-deviation.java | 41 +- .../Lua/standard-deviation.lua | 12 + .../PL-I/standard-deviation.pli | 42 +- .../Pascal/standard-deviation.pascal | 28 + .../REXX/standard-deviation.rexx | 20 +- .../Scala/standard-deviation.scala | 24 + .../Scilab/standard-deviation.scilab | 2 + .../Visual-Basic/standard-deviation.vb | 50 ++ .../Ruby/start-from-a-main-routine.rb | 7 + .../Scala/start-from-a-main-routine.scala | 7 + .../AWK/stem-and-leaf-plot.awk | 47 ++ .../Maple/stem-and-leaf-plot.maple | 49 ++ .../OCaml/stem-and-leaf-plot-2.ocaml | 6 +- Task/String-case/Elixir/string-case-1.elixir | 6 + Task/String-case/Elixir/string-case-2.elixir | 6 + .../{string-case.rust => string-case-1.rust} | 0 Task/String-case/Rust/string-case-2.rust | 5 + Task/String-comparison/00DESCRIPTION | 7 +- .../AWK/string-comparison.awk | 4 +- .../Ada/string-comparison.ada | 8 +- .../Aime/string-comparison.aime | 16 + .../Common-Lisp/string-comparison-1.lisp | 18 + .../Common-Lisp/string-comparison-2.lisp | 12 + .../Common-Lisp/string-comparison-3.lisp | 4 + .../String-comparison/Go/string-comparison.go | 2 +- .../Haskell/string-comparison.hs | 15 + .../Java/string-comparison.java | 38 + .../Mathematica/string-comparison.math | 19 + .../PicoLisp/string-comparison.l | 18 + .../String-comparison/R/string-comparison-1.r | 19 + .../String-comparison/R/string-comparison-2.r | 20 + .../Scala/string-comparison.scala | 24 + Task/String-concatenation/00DESCRIPTION | 5 +- .../Ada/string-concatenation.ada | 2 +- .../Dylan.NET/string-concatenation.dylan.net | 4 +- .../Elixir/string-concatenation.elixir | 5 + .../Lua/string-concatenation.lua | 4 + .../NewLISP/string-concatenation.newlisp | 4 + .../Rust/string-concatenation.rust | 19 +- .../Scilab/string-concatenation.scilab | 4 + .../00META.yaml | 1 + .../string-interpolation--included-.delphi | 36 + .../string-interpolation--included-.elixir | 2 + .../string-interpolation--included-.frink | 2 + .../OOC/string-interpolation--included-.ooc | 4 + Task/String-length/00DESCRIPTION | 14 +- Task/String-length/00META.yaml | 2 + .../ColdFusion/string-length-1.cfm | 7 +- .../Elixir/string-length-1.elixir | 3 + .../Elixir/string-length-2.elixir | 3 + .../Elixir/string-length-3.elixir | 3 + Task/String-length/Java/string-length-1.java | 6 +- .../String-length/Maple/string-length-1.maple | 1 + .../String-length/Maple/string-length-2.maple | 1 + .../Mercury/string-length-1.mercury | 20 + .../Mercury/string-length-2.mercury | 20 + ...rip-a-set-of-characters-from-a-string.aime | 18 +- ...trip-a-set-of-characters-from-a-string-2.c | 2 +- ...trip-a-set-of-characters-from-a-string.cfm | 6 + ...a-set-of-characters-from-a-string-1.elixir | 3 + ...a-set-of-characters-from-a-string-2.elixir | 10 + ...trip-a-set-of-characters-from-a-string.lua | 9 +- ...-a-set-of-characters-from-a-string.newlisp | 2 + ...et-of-characters-from-a-string.scriptbasic | 6 + .../Scala/strip-block-comments-1.scala | 3 + .../Scala/strip-block-comments-2.scala | 6 + .../Scala/strip-block-comments-3.scala | 7 + .../Go/strip-comments-from-a-string.go | 29 +- .../Maple/strip-comments-from-a-string.maple | 2 + .../REXX/strip-comments-from-a-string.rexx | 20 +- ...-and-extended-characters-from-a-string.clj | 8 + ...s-and-extended-characters-from-a-string.go | 113 +-- ...and-extended-characters-from-a-string.java | 15 + ...-whitespace-from-a-string-top-and-tail.alg | 54 ++ ...-whitespace-from-a-string-top-and-tail.clj | 7 + ...itespace-from-a-string-top-and-tail.elixir | 3 + ...tespace-from-a-string-top-and-tail.newlisp | 10 + .../Clojure/substring-top-and-tail.clj | 15 + .../NewLISP/substring-top-and-tail.newlisp | 7 + .../REXX/substring-top-and-tail.rexx | 1 - .../Ruby/substring-top-and-tail.rb | 1 + Task/Substring/00DESCRIPTION | 8 +- Task/Substring/00META.yaml | 2 - Task/Substring/Go/substring-1.go | 26 + Task/Substring/Go/substring-2.go | 29 + Task/Substring/Go/substring.go | 14 - Task/Substring/Maple/substring-1.maple | 4 + Task/Substring/Maple/substring-2.maple | 5 + Task/Substring/Maple/substring-3.maple | 5 + Task/Substring/Maple/substring-4.maple | 7 + Task/Substring/Prolog/substring-1.pro | 17 + Task/Substring/Prolog/substring-2.pro | 7 + Task/Substring/RPG/substring.rpg | 25 + Task/Substring/Scala/substring.scala | 7 +- Task/Subtractive-generator/00DESCRIPTION | 3 +- .../Fortran/subtractive-generator.f | 56 ++ .../REXX/subtractive-generator.rexx | 44 +- Task/Sudoku/00DESCRIPTION | 3 +- Task/Sudoku/Clojure/sudoku-1.clj | 61 +- Task/Sudoku/Clojure/sudoku-2.clj | 20 +- .../Curry/{sudoku.curry => sudoku-1.curry} | 0 Task/Sudoku/Curry/sudoku-2.curry | 34 + Task/Sudoku/D/{sudoku.d => sudoku-1.d} | 28 +- Task/Sudoku/D/sudoku-2.d | 34 + Task/Sudoku/D/sudoku-3.d | 42 + Task/Sudoku/Delphi/sudoku-1.delphi | 25 +- Task/Sudoku/PL-I/sudoku-1.pli | 83 ++ Task/Sudoku/PL-I/sudoku-2.pli | 138 ++++ .../Perl-6/{sudoku.pl6 => sudoku-1.pl6} | 0 Task/Sudoku/Perl-6/sudoku-2.pl6 | 224 +++++ .../Prolog/{sudoku.pro => sudoku-1.pro} | 0 Task/Sudoku/Prolog/sudoku-2.pro | 54 ++ Task/Sudoku/Ruby/sudoku.rb | 111 ++- Task/Sudoku/VBScript/sudoku.vb | 102 +++ .../sum-and-product-of-an-array.bracmat | 16 + .../sum-and-product-of-an-array.coffee | 5 + .../Eiffel/sum-and-product-of-an-array.e | 64 ++ ...ava => sum-and-product-of-an-array-1.java} | 0 .../Java/sum-and-product-of-an-array-2.java | 12 + .../Julia/sum-and-product-of-an-array.julia | 8 +- .../sum-and-product-of-an-array.newlisp | 3 + .../Perl/sum-and-product-of-an-array-2.pl | 9 +- .../Ruby/sum-and-product-of-an-array-1.rb | 4 +- .../Ruby/sum-and-product-of-an-array-2.rb | 11 +- .../Ruby/sum-and-product-of-an-array-3.rb | 5 + .../Rust/sum-and-product-of-an-array.rust | 2 +- Task/Sum-digits-of-an-integer/00DESCRIPTION | 2 +- .../ALGOL-68/sum-digits-of-an-integer.alg | 45 + .../ATS/sum-digits-of-an-integer.ats | 54 ++ .../Clojure/sum-digits-of-an-integer.clj | 3 + .../D/sum-digits-of-an-integer.d | 2 +- .../Factor/sum-digits-of-an-integer.factor | 3 + .../Go/sum-digits-of-an-integer-1.go | 55 +- .../Go/sum-digits-of-an-integer-2.go | 63 +- .../Logo/sum-digits-of-an-integer.logo | 11 + .../Lua/sum-digits-of-an-integer.lua | 15 + .../Pascal/sum-digits-of-an-integer.pascal | 27 + ...teger.py => sum-digits-of-an-integer-1.py} | 0 .../Python/sum-digits-of-an-integer-2.py | 8 + .../R/sum-digits-of-an-integer.r | 27 + Task/Sum-of-a-series/00DESCRIPTION | 2 +- Task/Sum-of-a-series/D/sum-of-a-series-1.d | 7 +- Task/Sum-of-a-series/D/sum-of-a-series-2.d | 4 +- .../Delphi/sum-of-a-series.delphi | 2 +- .../NewLISP/sum-of-a-series.newlisp | 4 + .../Perl-6/sum-of-a-series-7.pl6 | 2 +- Task/Sum-of-a-series/Ruby/sum-of-a-series.rb | 3 +- .../Sum-of-a-series/Rust/sum-of-a-series.rust | 8 + .../Sum-of-a-series/TXR/sum-of-a-series-1.txr | 4 +- .../Sum-of-a-series/TXR/sum-of-a-series-2.txr | 4 +- .../Sum-of-a-series/TXR/sum-of-a-series-3.txr | 4 +- .../Sum-of-a-series/TXR/sum-of-a-series-4.txr | 4 +- .../Sum-of-a-series/TXR/sum-of-a-series-5.txr | 4 +- Task/Sum-of-squares/00DESCRIPTION | 3 +- Task/Sum-of-squares/Aime/sum-of-squares.aime | 28 + .../Bracmat/sum-of-squares.bracmat | 13 + Task/Sum-of-squares/D/sum-of-squares-1.d | 9 +- Task/Sum-of-squares/D/sum-of-squares-2.d | 10 +- Task/Sum-of-squares/Java/sum-of-squares.java | 2 +- Task/Sum-of-squares/MOO/sum-of-squares.moo | 2 +- .../NetRexx/sum-of-squares.netrexx | 2 +- ...{sum-of-squares.py => sum-of-squares-1.py} | 0 .../Sum-of-squares/Python/sum-of-squares-2.py | 1 + Task/Sum-of-squares/REXX/sum-of-squares.rexx | 5 +- Task/Sum-of-squares/Ruby/sum-of-squares-2.rb | 2 +- Task/Sum-of-squares/Rust/sum-of-squares.rust | 17 + .../sutherland-hodgman-polygon-clipping-1.cs | 237 ++++++ .../sutherland-hodgman-polygon-clipping-2.cs | 20 + .../sutherland-hodgman-polygon-clipping-3.cs | 136 +++ .../C/sutherland-hodgman-polygon-clipping.c | 15 +- .../D/sutherland-hodgman-polygon-clipping.d | 17 +- .../sutherland-hodgman-polygon-clipping.java | 118 +++ .../sutherland-hodgman-polygon-clipping.scala | 90 ++ .../Haskell/symmetric-difference-1.hs | 2 +- ...ference.lua => symmetric-difference-1.lua} | 0 .../Lua/symmetric-difference-2.lua | 56 ++ .../Maple/symmetric-difference-1.maple | 2 + .../Maple/symmetric-difference-2.maple | 1 + .../Python/symmetric-difference-1.py | 5 +- .../Python/symmetric-difference-2.py | 3 +- .../Python/symmetric-difference-3.py | 10 + .../Ruby/symmetric-difference-1.rb | 10 +- .../Ruby/symmetric-difference-2.rb | 7 +- .../C-sharp/synchronous-concurrency.cs | 42 + .../Go/synchronous-concurrency.go | 84 +- .../J/synchronous-concurrency-1.j | 10 + .../J/synchronous-concurrency-2.j | 1 + .../Mercury/synchronous-concurrency.mercury | 59 ++ Task/System-time/00DESCRIPTION | 5 +- Task/System-time/00META.yaml | 3 + .../{system-time.awk => system-time-1.awk} | 1 - Task/System-time/AWK/system-time-2.awk | 20 + Task/System-time/Excel/system-time.excel | 1 + Task/System-time/Io/system-time.io | 1 + Task/System-time/JavaScript/system-time.js | 1 - Task/System-time/NewLISP/system-time.newlisp | 2 + Task/System-time/OCaml/system-time.ocaml | 2 +- Task/System-time/Perl/system-time-2.pl | 2 +- Task/System-time/Scala/system-time-2.scala | 2 +- .../SAS/table-creation-postal-addresses.sas | 14 +- .../00DESCRIPTION | 11 +- .../take-notes-on-the-command-line.delphi | 42 + .../Go/take-notes-on-the-command-line.go | 79 +- .../PL-I/take-notes-on-the-command-line.pli | 37 + .../take-notes-on-the-command-line.scala | 6 +- Task/Temperature-conversion/00DESCRIPTION | 13 +- ...rsion.awk => temperature-conversion-1.awk} | 0 .../AWK/temperature-conversion-2.awk | 19 + .../Clojure/temperature-conversion.clj | 12 + .../Common-Lisp/temperature-conversion.lisp | 13 + .../Delphi/temperature-conversion.delphi | 41 + .../Euphoria/temperature-conversion.euphoria | 7 + .../Excel/temperature-conversion.excel | 9 + .../Fortran/temperature-conversion.f | 26 + .../Haskell/temperature-conversion.hs | 18 + .../J/temperature-conversion-2.j | 44 +- .../Julia/temperature-conversion.julia | 5 +- .../Lua/temperature-conversion.lua | 13 + .../OCaml/temperature-conversion.ocaml | 20 + .../REXX/temperature-conversion.rexx | 172 ++-- .../Scala/temperature-conversion.scala | 27 + ...=> terminal-control-clear-the-screen-1.go} | 0 .../Go/terminal-control-clear-the-screen-2.go | 7 + .../Go/terminal-control-clear-the-screen-3.go | 25 + .../terminal-control-clear-the-screen.hs | 3 + .../terminal-control-clear-the-screen-1.java | 7 + .../terminal-control-clear-the-screen-2.java | 7 + .../terminal-control-clear-the-screen.rexx | 17 +- ...=> terminal-control-clear-the-screen-1.rb} | 0 .../terminal-control-clear-the-screen-2.rb | 1 + .../terminal-control-clear-the-screen.scala | 1 + .../Go/terminal-control-coloured-text-1.go | 28 + .../Go/terminal-control-coloured-text-2.go | 35 + .../Go/terminal-control-coloured-text-3.go | 9 + .../Go/terminal-control-coloured-text-4.go | 11 + .../Go/terminal-control-coloured-text-5.go | 31 + .../Go/terminal-control-coloured-text-6.go | 30 + .../PicoLisp/terminal-control-coloured-text.l | 2 +- ... terminal-control-cursor-movement-1.basic} | 0 .../terminal-control-cursor-movement-2.basic | 57 ++ .../Go/terminal-control-cursor-movement-1.go | 47 ++ .../Go/terminal-control-cursor-movement-2.go | 21 + .../Go/terminal-control-cursor-movement-3.go | 60 ++ .../terminal-control-cursor-positioning-1.go | 16 + .../terminal-control-cursor-positioning-2.go | 7 + .../terminal-control-cursor-positioning-3.go | 18 + .../terminal-control-cursor-positioning.pl | 5 + .../terminal-control-cursor-positioning-1.ws | 0 .../terminal-control-cursor-positioning-2.ws | 16 + .../terminal-control-dimensions.applesoft | 2 + .../Go/terminal-control-dimensions-1.go | 17 + .../Go/terminal-control-dimensions-2.go | 16 + .../Go/terminal-control-dimensions-3.go | 18 + ...-control-display-an-extended-character.clj | 1 + ...ontrol-display-an-extended-character.scala | 4 + .../terminal-control-hiding-the-cursor.cpp | 11 + .../terminal-control-hiding-the-cursor-1.go | 20 + .../terminal-control-hiding-the-cursor-2.go | 13 + .../terminal-control-hiding-the-cursor-3.go | 20 + .../Go/terminal-control-inverse-video-1.go | 20 + .../Go/terminal-control-inverse-video-2.go | 7 + .../Go/terminal-control-inverse-video-3.go | 20 + .../terminal-control-preserve-screen.scala | 9 + ...inal-control-ringing-the-terminal-bell.clj | 1 + ...inal-control-ringing-the-terminal-bell.php | 2 + .../terminal-control-unicode-output.clj | 4 + .../terminal-control-unicode-output.elixir | 8 + .../terminal-control-unicode-output.scala | 2 + Task/Ternary-logic/00DESCRIPTION | 4 +- Task/Ternary-logic/C/ternary-logic-2.c | 71 +- Task/Ternary-logic/C/ternary-logic-3.c | 69 +- .../Common-Lisp/ternary-logic.lisp | 31 + Task/Ternary-logic/Go/ternary-logic.go | 2 +- .../Ternary-logic/Maple/ternary-logic-1.maple | 6 + .../Ternary-logic/Maple/ternary-logic-2.maple | 33 + .../Test-a-function/Icon/test-a-function.icon | 20 + .../Text-processing-1/Go/text-processing-1.go | 176 ++-- .../Java/text-processing-1.java | 89 ++ .../Aime/text-processing-2.aime | 4 +- .../Text-processing-2/Go/text-processing-2.go | 140 ++-- .../Go/text-processing-max-licenses-in-use.go | 104 +-- .../D/thieles-interpolation-formula.d | 18 +- Task/Tic-tac-toe/00DESCRIPTION | 3 +- Task/Tic-tac-toe/Common-Lisp/tic-tac-toe.lisp | 92 +++ Task/Tic-tac-toe/D/tic-tac-toe.d | 16 +- .../Tic-tac-toe/Euphoria/tic-tac-toe.euphoria | 100 +++ Task/Tic-tac-toe/Haskell/tic-tac-toe.hs | 2 +- Task/Tic-tac-toe/MATLAB/tic-tac-toe.m | 224 +++++ Task/Tic-tac-toe/REXX/tic-tac-toe.rexx | 2 +- Task/Tic-tac-toe/Racket/tic-tac-toe-2.rkt | 4 +- Task/Tic-tac-toe/Ruby/tic-tac-toe.rb | 172 ++-- Task/Tic-tac-toe/Run-BASIC/tic-tac-toe.run | 2 +- Task/Time-a-function/00DESCRIPTION | 12 +- Task/Time-a-function/00META.yaml | 2 + .../Bracmat/time-a-function.bracmat | 14 + .../Time-a-function/Fortran/time-a-function.f | 9 +- Task/Tokenize-a-string/00DESCRIPTION | 8 +- Task/Tokenize-a-string/D/tokenize-a-string.d | 6 +- .../Elixir/tokenize-a-string.elixir | 2 + .../Java/tokenize-a-string-1.java | 7 +- .../Java/tokenize-a-string-2.java | 7 +- .../Java/tokenize-a-string-3.java | 6 + .../Logtalk/tokenize-a-string.logtalk | 22 + .../MATLAB/tokenize-a-string.m | 14 + .../NewLISP/tokenize-a-string.newlisp | 1 + .../PL-I/tokenize-a-string.pli | 2 + ...ize-a-string.pl => tokenize-a-string-1.pl} | 0 .../Perl/tokenize-a-string-2.pl | 1 + .../Perl/tokenize-a-string-3.pl | 10 + ...e-a-string.pro => tokenize-a-string-1.pro} | 0 .../Prolog/tokenize-a-string-2.pro | 4 + .../Scheme/tokenize-a-string-3.ss | 4 + .../TXR/tokenize-a-string-3.txr | 3 +- .../Forth/top-rank-per-group.fth | 129 +++ .../Go/top-rank-per-group.go | 219 +++-- .../Java/top-rank-per-group.java | 49 ++ ...k-per-group.js => top-rank-per-group-1.js} | 2 +- .../JavaScript/top-rank-per-group-2.js | 31 + .../Prolog/top-rank-per-group.pro | 53 ++ .../Ruby/top-rank-per-group.rb | 41 +- .../Scheme/top-rank-per-group.ss | 57 ++ .../Topic-variable/Clojure/topic-variable.clj | 6 + .../{topic-variable.j => topic-variable-1.j} | 0 Task/Topic-variable/J/topic-variable-2.j | 2 + Task/Topic-variable/Python/topic-variable.py | 5 + Task/Topic-variable/REXX/topic-variable.rexx | 6 + Task/Topic-variable/Ruby/topic-variable-1.rb | 7 + Task/Topic-variable/Ruby/topic-variable-2.rb | 4 + .../Standard-ML/topic-variable.ml | 7 + Task/Topological-sort/00DESCRIPTION | 4 +- .../Topological-sort/C++/topological-sort.cpp | 93 +++ Task/Topological-sort/D/topological-sort.d | 38 +- .../Topological-sort/Go/topological-sort-1.go | 140 ++++ .../Topological-sort/Go/topological-sort-2.go | 48 ++ Task/Topological-sort/Go/topological-sort.go | 107 --- .../Perl-6/topological-sort.pl6 | 37 + Task/Topswops/D/topswops-1.d | 6 +- Task/Topswops/D/topswops-2.d | 25 +- Task/Topswops/Eiffel/topswops-1.e | 109 +++ Task/Topswops/Eiffel/topswops-2.e | 14 + Task/Topswops/Ruby/topswops-1.rb | 4 +- Task/Topswops/Scala/topswops.scala | 32 + Task/Towers-of-Hanoi/Eiffel/towers-of-hanoi.e | 28 + Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi.m | 7 + .../PlainTeX/towers-of-hanoi.tex | 19 + .../REXX/towers-of-hanoi-1.rexx | 34 +- .../REXX/towers-of-hanoi-2.rexx | 96 +-- .../Towers-of-Hanoi/Rust/towers-of-hanoi.rust | 2 +- .../SNOBOL4/towers-of-hanoi.sno | 2 +- .../trabb-pardo-knuth-algorithm.lisp | 13 + .../Fortran/trabb-pardo-knuth-algorithm.f | 30 + .../Julia/trabb-pardo-knuth-algorithm.julia | 17 +- .../trabb-pardo-knuth-algorithm.math | 15 + .../Ruby/trabb-pardo-knuth-algorithm.rb | 15 +- Task/Tree-traversal/ATS/tree-traversal.ats | 136 +-- Task/Tree-traversal/D/tree-traversal-1.d | 3 +- .../Tree-traversal/Julia/tree-traversal.julia | 36 +- Task/Tree-traversal/PHP/tree-traversal.php | 102 +++ Task/Tree-traversal/REXX/tree-traversal.rexx | 7 +- Task/Tree-traversal/Ruby/tree-traversal.rb | 17 +- .../Tree-traversal/Scala/tree-traversal.scala | 24 +- Task/Trigonometric-functions/00DESCRIPTION | 8 +- Task/Trigonometric-functions/00META.yaml | 2 + .../Maple/trigonometric-functions-1.maple | 3 + .../Maple/trigonometric-functions-2.maple | 4 + .../Maple/trigonometric-functions-3.maple | 3 + .../Maple/trigonometric-functions-4.maple | 3 + .../REXX/trigonometric-functions-2.rexx | 100 +-- .../Scala/trigonometric-functions.scala | 23 + .../Common-Lisp/truncatable-primes.lisp | 41 + .../Java/truncatable-primes.java | 2 +- .../Perl-6/truncatable-primes.pl6 | 47 +- .../REXX/truncatable-primes.rexx | 32 +- .../Delphi/truncate-a-file-1.delphi | 13 + .../Delphi/truncate-a-file-2.delphi | 11 + .../Julia/truncate-a-file.julia | 5 + .../Truncate-a-file/REXX/truncate-a-file.rexx | 23 + .../Scala/truncate-a-file.scala | 10 + Task/Twelve-statements/00DESCRIPTION | 11 +- Task/Twelve-statements/00META.yaml | 4 + .../Common-Lisp/twelve-statements.lisp | 44 + Task/Twelve-statements/D/twelve-statements.d | 2 +- .../Ruby/twelve-statements.rb | 15 +- Task/URL-decoding/00DESCRIPTION | 3 +- .../{url-decoding.ada => url-decoding-1.ada} | 0 Task/URL-decoding/Ada/url-decoding-2.ada | 3 + Task/URL-decoding/Ada/url-decoding-3.ada | 28 + Task/URL-decoding/Ada/url-decoding-4.ada | 16 + Task/URL-decoding/Haskell/url-decoding.hs | 15 + Task/URL-decoding/Maple/url-decoding.maple | 1 + .../URL-decoding/NewLISP/url-decoding.newlisp | 7 + Task/URL-decoding/R/url-decoding.r | 1 + Task/URL-decoding/Scala/url-decoding.scala | 20 +- Task/URL-decoding/VBScript/url-decoding.vb | 14 + Task/URL-encoding/00DESCRIPTION | 16 +- Task/URL-encoding/00META.yaml | 3 + Task/URL-encoding/AutoHotkey/url-encoding.ahk | 26 +- Task/URL-encoding/Clojure/url-encoding.clj | 2 + Task/URL-encoding/Haskell/url-encoding.hs | 14 + Task/URL-encoding/Maple/url-encoding.maple | 1 + .../URL-encoding/NewLISP/url-encoding.newlisp | 6 + Task/URL-encoding/R/url-encoding-1.r | 1 + Task/URL-encoding/R/url-encoding-2.r | 2 + Task/URL-encoding/REXX/url-encoding-2.rexx | 22 +- Task/URL-encoding/Scala/url-encoding.scala | 16 + Task/URL-encoding/VBScript/url-encoding.vb | 13 + Task/Unbias-a-random-generator/00DESCRIPTION | 2 + .../D/unbias-a-random-generator.d | 4 +- .../Elixir/unbias-a-random-generator.elixir | 22 + Task/Unicode-strings/00DESCRIPTION | 9 +- .../Unicode-strings/Ruby/unicode-strings-1.rb | 2 + ...nicode-strings.rb => unicode-strings-2.rb} | 0 .../Unicode-strings/Ruby/unicode-strings-3.rb | 4 + .../Clojure/unicode-variable-names.clj | 2 + .../Emacs-Lisp/unicode-variable-names.l | 3 + .../JavaScript/unicode-variable-names.js | 7 + .../Julia/unicode-variable-names-1.julia | 2 + .../Julia/unicode-variable-names-2.julia | 2 + .../Julia/unicode-variable-names.julia | 4 - ...e-names.pl => unicode-variable-names-1.pl} | 3 +- .../Perl/unicode-variable-names-2.pl | 12 + .../Perl/unicode-variable-names-3.pl | 10 + .../R/unicode-variable-names.r | 3 + Task/Universal-Turing-machine/00DESCRIPTION | 18 +- .../universal-turing-machine-1.lisp | 35 + .../universal-turing-machine-2.lisp | 37 + .../universal-turing-machine-3.lisp | 55 ++ .../D/universal-turing-machine-1.d | 57 +- .../Go/universal-turing-machine-1.go | 177 ++++ .../Go/universal-turing-machine-2.go | 71 ++ .../J/universal-turing-machine-1.j | 3 +- .../J/universal-turing-machine-2.j | 4 +- .../J/universal-turing-machine-3.j | 2 +- .../J/universal-turing-machine-4.j | 2 +- .../universal-turing-machine-1.math | 18 + .../universal-turing-machine-2.math | 18 + .../universal-turing-machine-3.math | 17 + .../PicoLisp/universal-turing-machine.l | 76 ++ .../Java/update-a-configuration-file.java | 134 +++ .../J/user-input-graphical-1.j | 26 + ...t-graphical.j => user-input-graphical-2.j} | 0 .../Perl-6/user-input-graphical.pl6 | 26 + .../Scala/user-input-graphical.scala | 4 +- Task/User-input-Text/00DESCRIPTION | 3 +- .../BASIC/user-input-text-2.basic | 2 +- .../User-input-Text/REXX/user-input-text.rexx | 1 + Task/Vampire-number/D/vampire-number-1.d | 4 +- Task/Vampire-number/D/vampire-number-2.d | 14 +- ...pire-number.java => vampire-number-1.java} | 0 .../Vampire-number/Java/vampire-number-2.java | 70 ++ .../Mathematica/vampire-number-1.math | 27 + .../Mathematica/vampire-number-2.math | 2 + Task/Vampire-number/REXX/vampire-number.rexx | 77 +- Task/Vampire-number/Ruby/vampire-number.rb | 4 +- Task/Van-der-Corput-sequence/00DESCRIPTION | 3 +- .../C-sharp/van-der-corput-sequence.cs | 127 +++ .../C/van-der-corput-sequence.c | 35 + .../Clojure/van-der-corput-sequence.clj | 25 + .../Common-Lisp/van-der-corput-sequence.lisp | 11 + .../D/van-der-corput-sequence.d | 10 +- .../Lua/van-der-corput-sequence.lua | 13 + .../Pascal/van-der-corput-sequence.pascal | 88 ++ .../REXX/van-der-corput-sequence-1.rexx | 20 +- .../REXX/van-der-corput-sequence-2.rexx | 66 +- .../Ruby/van-der-corput-sequence.rb | 8 + .../VBScript/van-der-corput-sequence.vb | 48 ++ .../PARI-GP/variable-length-quantity.pari | 6 + .../REXX/variable-length-quantity.rexx | 50 +- .../Ruby/variable-length-quantity.rb | 2 +- Task/Variable-size-Get/00DESCRIPTION | 17 + .../Babel/variable-size-get-1.pb | 9 - .../Babel/variable-size-get-2.pb | 2 - .../Scala/variable-size-get.scala | 9 + .../360-Assembly/variable-size-set.360 | 24 + .../PL-I/variable-size-set.pli | 24 +- Task/Variables/00META.yaml | 2 + Task/Variables/AWK/variables-1.awk | 22 +- Task/Variables/AWK/variables-2.awk | 8 +- Task/Variables/AWK/variables-3.awk | 20 +- Task/Variables/AWK/variables-4.awk | 2 + Task/Variables/Bracmat/variables.bracmat | 1 + Task/Variables/Common-Lisp/variables-1.lisp | 1 + Task/Variables/Common-Lisp/variables-2.lisp | 1 + Task/Variables/Common-Lisp/variables-3.lisp | 1 + Task/Variables/Common-Lisp/variables-4.lisp | 3 + Task/Variables/Common-Lisp/variables-5.lisp | 4 + Task/Variables/Common-Lisp/variables-6.lisp | 1 + Task/Variables/Common-Lisp/variables-7.lisp | 4 + Task/Variables/Eiffel/variables-1.e | 23 + Task/Variables/Eiffel/variables-2.e | 3 + Task/Variables/REXX/variables-1.rexx | 2 +- Task/Variables/REXX/variables-2.rexx | 9 +- Task/Variables/REXX/variables-3.rexx | 28 +- Task/Variables/REXX/variables-4.rexx | 27 +- Task/Variables/REXX/variables-5.rexx | 18 + Task/Variables/REXX/variables-6.rexx | 7 + Task/Variables/REXX/variables-7.rexx | 4 + Task/Variables/REXX/variables-8.rexx | 7 + .../Perl/variadic-function-4.pl | 2 + .../Perl/variadic-function-5.pl | 3 + .../Perl/variadic-function-6.pl | 6 + .../REALbasic/variadic-function-1.realbasic | 5 + .../REALbasic/variadic-function-2.realbasic | 1 + Task/Vector-products/D/vector-products.d | 14 +- .../Vector-products/Forth/vector-products.fth | 39 + .../Prolog/vector-products.pro | 16 + .../Vector-products/Python/vector-products.py | 8 +- ...distribution-uniformity-chi-squared-test.d | 6 +- ...istribution-uniformity-chi-squared-test.rb | 61 ++ .../D/verify-distribution-uniformity-naive.d | 6 +- .../verify-distribution-uniformity-naive.rkt | 37 + .../video-display-modes.applesoft | 20 + .../Icon/video-display-modes.icon | 5 + .../D/vigen-re-cipher-cryptanalysis.d | 14 +- Task/Vigen-re-cipher/00DESCRIPTION | 12 +- Task/Vigen-re-cipher/00META.yaml | 2 + Task/Vigen-re-cipher/C/vigen-re-cipher.c | 56 ++ .../Common-Lisp/vigen-re-cipher.lisp | 26 + Task/Vigen-re-cipher/D/vigen-re-cipher-1.d | 8 +- Task/Vigen-re-cipher/D/vigen-re-cipher-2.d | 11 +- .../Visualize-a-tree/Ada/visualize-a-tree.ada | 36 + Task/Visualize-a-tree/D/visualize-a-tree.d | 2 +- ...ualize-a-tree.go => visualize-a-tree-1.go} | 0 .../Visualize-a-tree/Go/visualize-a-tree-2.go | 31 + .../Java/visualize-a-tree.java | 79 ++ .../REXX/visualize-a-tree.rexx | 71 ++ .../Ruby/visualize-a-tree-1.rb | 1 + .../Ruby/visualize-a-tree-2.rb | 2 + Task/Voronoi-diagram/D/voronoi-diagram.d | 6 +- ...{voronoi-diagram.j => voronoi-diagram-1.j} | 2 + Task/Voronoi-diagram/J/voronoi-diagram-2.j | 2 + .../C++/walk-a-directory-recursively.cpp | 2 +- .../IDL/walk-a-directory-recursively-2.idl | 57 ++ .../Java/walk-a-directory-recursively-3.java | 12 + Task/Web-scraping/00DESCRIPTION | 14 +- Task/Web-scraping/00META.yaml | 4 +- .../CoffeeScript/web-scraping.coffee | 39 + Task/Web-scraping/JavaScript/web-scraping.js | 7 + .../Pascal/window-creation-x11.pascal | 57 ++ .../Perl-6/window-creation-x11.pl6 | 58 ++ .../Scala/window-creation-x11.scala | 10 + .../Frink/window-creation.frink | 1 + .../Objective-C/window-creation.m | 2 +- .../Perl-6/window-creation.pl6 | 17 + .../Window-creation/Perl/window-creation-5.pl | 9 +- .../Window-creation/Perl/window-creation-6.pl | 6 +- .../Window-creation/Perl/window-creation-7.pl | 5 + .../Seed7/window-creation.seed7 | 10 + .../TorqueScript/window-creation.torque | 38 + Task/Window-management/00DESCRIPTION | 15 + .../Java/window-management.java | 144 ++++ .../Mathematica/window-management.math | 7 + .../Tcl/window-management.tcl | 12 +- Task/Wireworld/00DESCRIPTION | 13 +- Task/Wireworld/C/wireworld.c | 5 +- Task/Wireworld/D/wireworld.d | 12 +- Task/Wireworld/Perl-6/wireworld.pl6 | 2 +- Task/Wireworld/REXX/wireworld.rexx | 65 ++ Task/Word-wrap/00DESCRIPTION | 14 +- Task/Word-wrap/AutoHotkey/word-wrap.ahk | 6 +- Task/Word-wrap/Bracmat/word-wrap.bracmat | 6 +- .../Haskell/{word-wrap.hs => word-wrap-1.hs} | 0 Task/Word-wrap/Haskell/word-wrap-2.hs | 21 + Task/Word-wrap/Lua/word-wrap.lua | 45 + Task/Word-wrap/Mathematica/word-wrap-1.math | 27 + Task/Word-wrap/Mathematica/word-wrap-2.math | 2 + Task/Word-wrap/R/word-wrap.r | 14 + Task/Word-wrap/Scala/word-wrap.scala | 44 + .../00DESCRIPTION | 11 +- .../00META.yaml | 3 + .../write-float-arrays-to-a-text-file.rexx | 50 +- .../write-float-arrays-to-a-text-file.scala | 18 + .../00DESCRIPTION | 7 +- .../write-language-name-in-3d-ascii.clj | 5 + ....j => write-language-name-in-3d-ascii-1.j} | 0 .../J/write-language-name-in-3d-ascii-2.j | 36 + .../write-language-name-in-3d-ascii.pl6 | 26 +- .../Perl/write-language-name-in-3d-ascii.pl | 11 + .../write-language-name-in-3d-ascii.l | 35 + .../write-language-name-in-3d-ascii-2.scala | 18 +- .../Clojure/write-to-windows-event-log.clj | 2 + .../Clojure/xml-dom-serialization.clj | 7 + Task/XML-Input/Go/xml-input.go | 8 +- Task/XML-Input/JavaScript/xml-input-1.js | 26 +- Task/XML-Input/JavaScript/xml-input-2.js | 18 +- Task/XML-Input/JavaScript/xml-input-3.js | 20 + Task/XML-Output/00DESCRIPTION | 6 +- Task/XML-Output/Bracmat/xml-output.bracmat | 112 +++ Task/XML-Output/Euphoria/xml-output.euphoria | 34 + Task/XML-Output/PicoLisp/xml-output.l | 2 +- Task/XML-Output/REXX/xml-output.rexx | 88 +- Task/XML-Output/Scala/xml-output-1.scala | 1 - Task/XML-XPath/Factor/xml-xpath.factor | 83 ++ Task/XML-XPath/Go/xml-xpath-1.go | 80 ++ .../Go/{xml-xpath.go => xml-xpath-2.go} | 0 .../Python/{xml-xpath.py => xml-xpath-1.py} | 0 Task/XML-XPath/Python/xml-xpath-2.py | 18 + Task/XML-XPath/Python/xml-xpath-3.py | 15 + Task/XML-XPath/REXX/xml-xpath-1.rexx | 36 + Task/XML-XPath/REXX/xml-xpath-2.rexx | 34 + .../AutoHotkey/xiaolin-wus-line-algorithm.ahk | 105 +++ .../D/xiaolin-wus-line-algorithm.d | 44 +- .../J/xiaolin-wus-line-algorithm-2.j | 3 +- .../Pascal/xiaolin-wus-line-algorithm.pascal | 122 +++ .../Scala/xiaolin-wus-line-algorithm-1.scala | 69 ++ .../Scala/xiaolin-wus-line-algorithm-2.scala | 10 + Task/Y-combinator/00DESCRIPTION | 3 +- .../{y-combinator.cpp => y-combinator-1.cpp} | 6 +- Task/Y-combinator/C++/y-combinator-2.cpp | 6 + .../Common-Lisp/y-combinator.lisp | 4 +- .../Go/{y-combinator.go => y-combinator-1.go} | 6 +- Task/Y-combinator/Go/y-combinator-2.go | 5 + Task/Y-combinator/Haskell/y-combinator-2.hs | 18 +- Task/Y-combinator/Java/y-combinator-1.java | 76 +- Task/Y-combinator/Java/y-combinator-2.java | 24 +- Task/Y-combinator/Java/y-combinator-3.java | 59 +- Task/Y-combinator/Java/y-combinator-4.java | 7 +- Task/Y-combinator/Java/y-combinator-5.java | 42 +- Task/Y-combinator/Java/y-combinator-6.java | 91 +-- Task/Y-combinator/Java/y-combinator-7.java | 77 +- Task/Y-combinator/Java/y-combinator-8.java | 3 + .../Y-combinator/JavaScript/y-combinator-1.js | 26 +- .../Y-combinator/JavaScript/y-combinator-2.js | 17 +- .../Y-combinator/JavaScript/y-combinator-3.js | 14 +- .../Y-combinator/JavaScript/y-combinator-4.js | 20 +- Task/Y-combinator/Julia/y-combinator-1.julia | 1 + Task/Y-combinator/Julia/y-combinator-2.julia | 2 + .../{y-combinator.m => y-combinator-1.m} | 31 +- .../Y-combinator/Objective-C/y-combinator-2.m | 5 + Task/Y-combinator/PARI-GP/y-combinator.pari | 5 + Task/Y-combinator/PHP/y-combinator-2.php | 27 +- Task/Y-combinator/PHP/y-combinator-3.php | 36 +- Task/Y-combinator/PHP/y-combinator-4.php | 20 + Task/Y-combinator/Perl-6/y-combinator-1.pl6 | 6 +- .../{y-combinator.pl => y-combinator-1.pl} | 0 Task/Y-combinator/Perl/y-combinator-2.pl | 3 + .../{y-combinator.py => y-combinator-1.py} | 0 Task/Y-combinator/Python/y-combinator-2.py | 1 + Task/Y-combinator/Ruby/y-combinator-2.rb | 18 +- Task/Y-combinator/Ruby/y-combinator-3.rb | 13 + Task/Y-combinator/Ruby/y-combinator-4.rb | 3 + .../{y-combinator.ss => y-combinator-1.ss} | 4 +- Task/Y-combinator/Scheme/y-combinator-2.ss | 3 + .../{y-combinator.st => y-combinator-1.st} | 0 Task/Y-combinator/Smalltalk/y-combinator-2.st | 1 + .../{y-combinator.ml => y-combinator-1.ml} | 0 .../Standard-ML/y-combinator-2.ml | 1 + Task/Yin-and-yang/00DESCRIPTION | 2 + Task/Yin-and-yang/00META.yaml | 2 + Task/Yin-and-yang/D/yin-and-yang-1.d | 18 +- Task/Yin-and-yang/D/yin-and-yang-2.d | 8 +- ...{yin-and-yang.java => yin-and-yang-1.java} | 0 Task/Yin-and-yang/Java/yin-and-yang-2.java | 82 ++ .../Yin-and-yang/JavaScript/yin-and-yang-1.js | 123 ++- .../Yin-and-yang/JavaScript/yin-and-yang-2.js | 162 ++-- .../Yin-and-yang/JavaScript/yin-and-yang-3.js | 104 +++ Task/Zebra-puzzle/00DESCRIPTION | 9 +- Task/Zebra-puzzle/00META.yaml | 4 +- .../Zebra-puzzle/Bracmat/zebra-puzzle.bracmat | 83 ++ Task/Zebra-puzzle/C++/zebra-puzzle.cpp | 147 ++++ Task/Zebra-puzzle/Curry/zebra-puzzle.curry | 43 + Task/Zebra-puzzle/D/zebra-puzzle-1.d | 13 +- Task/Zebra-puzzle/D/zebra-puzzle-2.d | 118 +-- Task/Zebra-puzzle/D/zebra-puzzle-3.d | 33 + Task/Zebra-puzzle/Go/zebra-puzzle.go | 294 +++++++ .../{zebra-puzzle.hs => zebra-puzzle-1.hs} | 5 +- Task/Zebra-puzzle/Haskell/zebra-puzzle-2.hs | 60 ++ Task/Zebra-puzzle/Java/zebra-puzzle-1.java | 220 +++++ Task/Zebra-puzzle/Java/zebra-puzzle-2.java | 98 +++ Task/Zebra-puzzle/Java/zebra-puzzle-3.java | 317 +++++++ .../Mathematica/zebra-puzzle.math | 114 +++ Task/Zebra-puzzle/Prolog/zebra-puzzle-1.pro | 22 +- Task/Zebra-puzzle/Prolog/zebra-puzzle-2.pro | 52 +- Task/Zebra-puzzle/Prolog/zebra-puzzle-3.pro | 14 +- Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro | 45 + Task/Zebra-puzzle/R/zebra-puzzle.r | 80 ++ Task/Zebra-puzzle/Ruby/zebra-puzzle.rb | 53 ++ Task/Zebra-puzzle/Scala/zebra-puzzle.scala | 76 ++ .../PicoLisp/zeckendorf-arithmetic.l | 133 +++ .../00DESCRIPTION | 2 + .../zeckendorf-number-representation.cs | 65 ++ ...> zeckendorf-number-representation-1.java} | 0 .../zeckendorf-number-representation-2.java | 41 + .../PHP/zeckendorf-number-representation.php | 22 + .../zeckendorf-number-representation.l | 31 + .../zeckendorf-number-representation-2.rexx | 32 +- .../zeckendorf-number-representation-3.rexx | 16 +- Task/Zig-zag-matrix/00DESCRIPTION | 7 +- Task/Zig-zag-matrix/C/zig-zag-matrix.c | 23 + .../CoffeeScript/zig-zag-matrix.coffee | 41 + Task/Zig-zag-matrix/D/zig-zag-matrix-1.d | 8 +- Task/Zig-zag-matrix/D/zig-zag-matrix-2.d | 17 +- Task/Zig-zag-matrix/MATLAB/zig-zag-matrix.m | 66 ++ Task/Zig-zag-matrix/Prolog/zig-zag-matrix.pro | 2 - .../Zig-zag-matrix/Python/zig-zag-matrix-4.py | 4 - 6591 files changed, 94363 insertions(+), 23227 deletions(-) create mode 120000 Lang/360-Assembly/Conditional-structures create mode 120000 Lang/360-Assembly/Empty-program create mode 120000 Lang/360-Assembly/Factorial create mode 120000 Lang/360-Assembly/Fibonacci-sequence create mode 120000 Lang/360-Assembly/Gamma-function create mode 120000 Lang/360-Assembly/Integer-comparison create mode 120000 Lang/360-Assembly/Loops-Do-while create mode 120000 Lang/360-Assembly/Loops-Infinite create mode 120000 Lang/360-Assembly/Loops-While create mode 120000 Lang/360-Assembly/Lucas-Lehmer-test create mode 120000 Lang/360-Assembly/Sieve-of-Eratosthenes create mode 120000 Lang/360-Assembly/Sleep create mode 120000 Lang/360-Assembly/Sorting-algorithms-Bubble-sort create mode 120000 Lang/360-Assembly/Spiral-matrix create mode 120000 Lang/360-Assembly/Standard-deviation create mode 120000 Lang/360-Assembly/Variable-size-Set create mode 120000 Lang/6502-Assembly/Even-or-odd create mode 120000 Lang/ABAP/N-queens-problem create mode 120000 Lang/ALGOL-60/Comments create mode 120000 Lang/ALGOL-60/Empty-program create mode 120000 Lang/ALGOL-60/Hello-world-Text create mode 120000 Lang/ALGOL-60/Loops-For create mode 120000 Lang/ALGOL-60/Loops-While create mode 120000 Lang/ALGOL-60/Sieve-of-Eratosthenes create mode 120000 Lang/ALGOL-68/Call-a-function create mode 120000 Lang/ALGOL-68/Count-the-coins create mode 120000 Lang/ALGOL-68/Entropy create mode 120000 Lang/ALGOL-68/Even-or-odd create mode 120000 Lang/ALGOL-68/Floyds-triangle create mode 120000 Lang/ALGOL-68/Function-prototype create mode 120000 Lang/ALGOL-68/Guess-the-number-With-feedback create mode 120000 Lang/ALGOL-68/Knights-tour create mode 120000 Lang/ALGOL-68/Mad-Libs create mode 120000 Lang/ALGOL-68/Middle-three-digits create mode 120000 Lang/ALGOL-68/Parsing-RPN-calculator-algorithm create mode 120000 Lang/ALGOL-68/Pick-random-element create mode 120000 Lang/ALGOL-68/Read-a-specific-line-from-a-file create mode 120000 Lang/ALGOL-68/Return-multiple-values create mode 120000 Lang/ALGOL-68/Rock-paper-scissors create mode 120000 Lang/ALGOL-68/Sleep create mode 120000 Lang/ALGOL-68/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/ALGOL-68/Sum-digits-of-an-integer create mode 120000 Lang/ALGOL-W/Comments create mode 120000 Lang/APL/Fibonacci-sequence create mode 120000 Lang/APL/Longest-common-subsequence create mode 120000 Lang/ATS/100-doors create mode 120000 Lang/ATS/Balanced-ternary create mode 120000 Lang/ATS/Fibonacci-sequence create mode 120000 Lang/ATS/Greatest-subsequential-sum create mode 120000 Lang/ATS/Hamming-numbers create mode 120000 Lang/ATS/Haversine-formula create mode 120000 Lang/ATS/Higher-order-functions create mode 120000 Lang/ATS/Identity-matrix create mode 120000 Lang/ATS/Repeat-a-string create mode 120000 Lang/ATS/Reverse-a-string create mode 120000 Lang/ATS/Roots-of-a-function create mode 120000 Lang/ATS/Sierpinski-triangle create mode 120000 Lang/ATS/Sum-digits-of-an-integer create mode 120000 Lang/AWK/Anagrams-Deranged-anagrams create mode 120000 Lang/AWK/Combinations-with-repetitions create mode 120000 Lang/AWK/File-modification-time create mode 120000 Lang/AWK/File-size create mode 120000 Lang/AWK/Five-weekends create mode 120000 Lang/AWK/Hello-world-Graphical create mode 120000 Lang/AWK/Knights-tour create mode 120000 Lang/AWK/Langtons-ant create mode 120000 Lang/AWK/Modular-inverse create mode 120000 Lang/AWK/Operator-precedence create mode 120000 Lang/AWK/Order-two-numerical-lists create mode 120000 Lang/AWK/Sieve-of-Eratosthenes create mode 120000 Lang/AWK/Stem-and-leaf-plot create mode 120000 Lang/Ada/Extend-your-language create mode 120000 Lang/Ada/Set-puzzle create mode 120000 Lang/Ada/Visualize-a-tree create mode 120000 Lang/Aime/Generic-swap create mode 120000 Lang/Aime/Hailstone-sequence create mode 120000 Lang/Aime/String-comparison create mode 120000 Lang/Aime/Sum-of-squares create mode 120000 Lang/AppleScript/Accumulator-factory create mode 120000 Lang/AppleScript/Apply-a-callback-to-an-array create mode 120000 Lang/AppleScript/First-class-functions create mode 120000 Lang/AppleScript/Function-composition create mode 120000 Lang/AppleScript/Higher-order-functions create mode 120000 Lang/AppleScript/Hostname create mode 120000 Lang/Applesoft-BASIC/Loops-Continue create mode 120000 Lang/Applesoft-BASIC/Terminal-control-Dimensions create mode 120000 Lang/Applesoft-BASIC/Video-display-modes create mode 120000 Lang/AutoHotkey/Continued-fraction create mode 120000 Lang/AutoHotkey/Narcissist create mode 120000 Lang/AutoHotkey/Polymorphism create mode 120000 Lang/AutoHotkey/Xiaolin-Wus-line-algorithm create mode 120000 Lang/Axiom/Numerical-integration-Gauss-Legendre-Quadrature create mode 120000 Lang/Axiom/Quaternion-type create mode 120000 Lang/Babel/Apply-a-callback-to-an-array create mode 120000 Lang/Babel/Arrays create mode 120000 Lang/Babel/Associative-array-Creation create mode 120000 Lang/Babel/Associative-array-Iteration create mode 120000 Lang/Babel/Averages-Arithmetic-mean create mode 120000 Lang/Babel/Bitwise-operations create mode 120000 Lang/Babel/Caesar-cipher create mode 120000 Lang/Babel/Character-codes create mode 120000 Lang/Babel/Conditional-structures create mode 120000 Lang/Babel/Copy-a-string create mode 120000 Lang/Babel/Deepcopy create mode 120000 Lang/Batch-File/24-game create mode 120000 Lang/Batch-File/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/Batch-File/Conditional-structures create mode 120000 Lang/Batch-File/Determine-if-a-string-is-numeric create mode 120000 Lang/Batch-File/Guess-the-number-With-feedback create mode 120000 Lang/Batch-File/Hostname create mode 120000 Lang/Batch-File/Palindrome-detection create mode 120000 Lang/Batch-File/Sieve-of-Eratosthenes create mode 120000 Lang/Batch-File/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Bc/Non-decimal-radices-Output create mode 120000 Lang/Befunge/Factors-of-an-integer create mode 120000 Lang/Boo/Arrays create mode 120000 Lang/Bracmat/Apply-a-callback-to-an-array create mode 120000 Lang/Bracmat/Arithmetic-Complex create mode 120000 Lang/Bracmat/Arrays create mode 120000 Lang/Bracmat/Averages-Simple-moving-average create mode 120000 Lang/Bracmat/Combinations-with-repetitions create mode 120000 Lang/Bracmat/Day-of-the-week create mode 120000 Lang/Bracmat/Factors-of-a-Mersenne-number create mode 120000 Lang/Bracmat/Fibonacci-n-step-number-sequences create mode 120000 Lang/Bracmat/First-class-functions create mode 120000 Lang/Bracmat/Hofstadter-Q-sequence create mode 120000 Lang/Bracmat/Input-loop create mode 120000 Lang/Bracmat/JSON create mode 120000 Lang/Bracmat/Knapsack-problem-Continuous create mode 120000 Lang/Bracmat/Look-and-say-sequence create mode 120000 Lang/Bracmat/Loops-While create mode 120000 Lang/Bracmat/N-queens-problem create mode 120000 Lang/Bracmat/Optional-parameters create mode 120000 Lang/Bracmat/Palindrome-detection create mode 120000 Lang/Bracmat/Partial-function-application create mode 120000 Lang/Bracmat/Permutations-Derangements create mode 120000 Lang/Bracmat/Queue-Definition create mode 120000 Lang/Bracmat/Queue-Usage create mode 120000 Lang/Bracmat/Rosetta-Code-Count-examples create mode 120000 Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity create mode 120000 Lang/Bracmat/Runtime-evaluation-In-an-environment create mode 120000 Lang/Bracmat/Simple-database create mode 120000 Lang/Bracmat/Sum-and-product-of-an-array create mode 120000 Lang/Bracmat/Sum-of-squares create mode 120000 Lang/Bracmat/Time-a-function create mode 120000 Lang/Bracmat/Variables create mode 120000 Lang/Bracmat/Zebra-puzzle create mode 120000 Lang/Brat/Integer-comparison create mode 120000 Lang/C++/24-game-Solve create mode 120000 Lang/C++/Closest-pair-problem create mode 120000 Lang/C++/Count-in-factors create mode 120000 Lang/C++/Function-prototype create mode 120000 Lang/C++/Greatest-common-divisor create mode 120000 Lang/C++/Here-document create mode 120000 Lang/C++/Inverted-syntax create mode 120000 Lang/C++/Leap-year create mode 120000 Lang/C++/Longest-common-subsequence create mode 120000 Lang/C++/Minesweeper-game create mode 120000 Lang/C++/Non-continuous-subsequences create mode 120000 Lang/C++/Record-sound create mode 120000 Lang/C++/Sorting-algorithms-Sleep-sort create mode 120000 Lang/C++/Terminal-control-Hiding-the-cursor create mode 120000 Lang/C++/Topological-sort create mode 120000 Lang/C++/Zebra-puzzle create mode 120000 Lang/C-sharp/Averages-Mean-time-of-day create mode 120000 Lang/C-sharp/Empty-directory create mode 120000 Lang/C-sharp/Entropy create mode 120000 Lang/C-sharp/Fibonacci-n-step-number-sequences create mode 120000 Lang/C-sharp/Floyds-triangle create mode 120000 Lang/C-sharp/Gamma-function create mode 120000 Lang/C-sharp/Guess-the-number-With-feedback--player- create mode 120000 Lang/C-sharp/Hello-world-Line-printer create mode 120000 Lang/C-sharp/Kaprekar-numbers create mode 120000 Lang/C-sharp/Mad-Libs create mode 120000 Lang/C-sharp/Narcissist create mode 120000 Lang/C-sharp/Non-decimal-radices-Output create mode 120000 Lang/C-sharp/Pick-random-element create mode 120000 Lang/C-sharp/Pinstripe-Display create mode 120000 Lang/C-sharp/Priority-queue create mode 120000 Lang/C-sharp/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/C-sharp/Synchronous-concurrency create mode 120000 Lang/C-sharp/Van-der-Corput-sequence create mode 120000 Lang/C-sharp/Zeckendorf-number-representation create mode 120000 Lang/C/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/COBOL/Create-a-file-on-magnetic-tape create mode 120000 Lang/COBOL/Range-expansion create mode 120000 Lang/Chapel/Numerical-integration create mode 120000 Lang/Clojure/Break-OO-privacy create mode 120000 Lang/Clojure/Call-an-object-method create mode 120000 Lang/Clojure/Classes create mode 120000 Lang/Clojure/Count-the-coins create mode 120000 Lang/Clojure/Create-a-file-on-magnetic-tape create mode 120000 Lang/Clojure/Create-an-HTML-table create mode 120000 Lang/Clojure/Define-a-primitive-data-type create mode 120000 Lang/Clojure/Discordian-date create mode 120000 Lang/Clojure/Draw-a-cuboid create mode 120000 Lang/Clojure/Draw-a-sphere create mode 120000 Lang/Clojure/Extreme-floating-point-values create mode 120000 Lang/Clojure/Function-prototype create mode 120000 Lang/Clojure/Globally-replace-text-in-several-files create mode 120000 Lang/Clojure/Hello-world-Web-server create mode 120000 Lang/Clojure/History-variables create mode 120000 Lang/Clojure/Knapsack-problem-Continuous create mode 120000 Lang/Clojure/Last-Friday-of-each-month create mode 120000 Lang/Clojure/MD4 create mode 120000 Lang/Clojure/Plot-coordinate-pairs create mode 120000 Lang/Clojure/Price-fraction create mode 120000 Lang/Clojure/Priority-queue create mode 120000 Lang/Clojure/RIPEMD-160 create mode 120000 Lang/Clojure/Read-a-configuration-file create mode 120000 Lang/Clojure/Read-a-specific-line-from-a-file create mode 120000 Lang/Clojure/Rock-paper-scissors create mode 120000 Lang/Clojure/SEDOLs create mode 120000 Lang/Clojure/SHA-256 create mode 120000 Lang/Clojure/Send-email create mode 120000 Lang/Clojure/Set-of-real-numbers create mode 120000 Lang/Clojure/Singly-linked-list-Element-definition create mode 120000 Lang/Clojure/Sort-disjoint-sublist create mode 120000 Lang/Clojure/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Clojure/Special-variables create mode 120000 Lang/Clojure/Speech-synthesis create mode 120000 Lang/Clojure/Stack-traces create mode 120000 Lang/Clojure/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/Clojure/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Clojure/Substring-Top-and-tail create mode 120000 Lang/Clojure/Sum-digits-of-an-integer create mode 120000 Lang/Clojure/Temperature-conversion create mode 120000 Lang/Clojure/Terminal-control-Display-an-extended-character create mode 120000 Lang/Clojure/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/Clojure/Terminal-control-Unicode-output create mode 120000 Lang/Clojure/Topic-variable create mode 120000 Lang/Clojure/URL-encoding create mode 120000 Lang/Clojure/Unicode-variable-names create mode 120000 Lang/Clojure/Write-language-name-in-3D-ASCII create mode 120000 Lang/Clojure/Write-to-Windows-event-log create mode 120000 Lang/Clojure/XML-DOM-serialization create mode 120000 Lang/CoffeeScript/Filter create mode 120000 Lang/CoffeeScript/Haversine-formula create mode 120000 Lang/CoffeeScript/Interactive-programming create mode 120000 Lang/CoffeeScript/Sum-and-product-of-an-array create mode 120000 Lang/ColdFusion/Active-Directory-Connect create mode 120000 Lang/ColdFusion/Even-or-odd create mode 120000 Lang/ColdFusion/Evolutionary-algorithm create mode 120000 Lang/ColdFusion/FizzBuzz create mode 120000 Lang/ColdFusion/Greatest-element-of-a-list create mode 120000 Lang/ColdFusion/Harshad-or-Niven-series create mode 120000 Lang/ColdFusion/Loops-Break create mode 120000 Lang/ColdFusion/Loops-For-with-a-specified-step create mode 120000 Lang/ColdFusion/Loops-Foreach create mode 120000 Lang/ColdFusion/Loops-Nested create mode 120000 Lang/ColdFusion/Repeat-a-string create mode 120000 Lang/ColdFusion/Stable-marriage-problem create mode 120000 Lang/ColdFusion/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Common-Lisp/Animate-a-pendulum create mode 120000 Lang/Common-Lisp/Bulls-and-cows-Player create mode 120000 Lang/Common-Lisp/Fibonacci-n-step-number-sequences create mode 120000 Lang/Common-Lisp/Harshad-or-Niven-series create mode 120000 Lang/Common-Lisp/Last-Friday-of-each-month create mode 120000 Lang/Common-Lisp/Modular-inverse create mode 120000 Lang/Common-Lisp/OpenGL create mode 120000 Lang/Common-Lisp/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Common-Lisp/Special-variables create mode 120000 Lang/Common-Lisp/String-comparison create mode 120000 Lang/Common-Lisp/Temperature-conversion create mode 120000 Lang/Common-Lisp/Tic-tac-toe create mode 120000 Lang/Common-Lisp/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Common-Lisp/Truncatable-primes create mode 120000 Lang/Common-Lisp/Twelve-statements create mode 120000 Lang/Common-Lisp/Universal-Turing-machine create mode 120000 Lang/Common-Lisp/Variables create mode 120000 Lang/Component-Pascal/Greatest-subsequential-sum create mode 120000 Lang/Curry/Pascals-triangle-Puzzle create mode 120000 Lang/Curry/Solve-a-Hidato-puzzle create mode 120000 Lang/Curry/Zebra-puzzle create mode 120000 Lang/D/Averages-Mean-time-of-day create mode 120000 Lang/D/Call-a-function create mode 120000 Lang/D/MD4 create mode 120000 Lang/D/Program-termination create mode 120000 Lang/Dart/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Delphi/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/Delphi/SEDOLs create mode 120000 Lang/Delphi/Sieve-of-Eratosthenes create mode 120000 Lang/Delphi/String-interpolation--included- create mode 120000 Lang/Delphi/Take-notes-on-the-command-line create mode 120000 Lang/Delphi/Temperature-conversion create mode 120000 Lang/Delphi/Truncate-a-file create mode 120000 Lang/Dylan/Man-or-boy-test create mode 120000 Lang/Eiffel/Binary-search create mode 120000 Lang/Eiffel/Caesar-cipher create mode 120000 Lang/Eiffel/Catalan-numbers create mode 120000 Lang/Eiffel/Character-codes create mode 120000 Lang/Eiffel/Combinations create mode 120000 Lang/Eiffel/Count-in-factors create mode 120000 Lang/Eiffel/Digital-root create mode 120000 Lang/Eiffel/Dot-product create mode 120000 Lang/Eiffel/Ethiopian-multiplication create mode 120000 Lang/Eiffel/Extreme-floating-point-values create mode 120000 Lang/Eiffel/FizzBuzz create mode 120000 Lang/Eiffel/Function-definition create mode 120000 Lang/Eiffel/Guess-the-number create mode 120000 Lang/Eiffel/Happy-numbers create mode 120000 Lang/Eiffel/Harshad-or-Niven-series create mode 120000 Lang/Eiffel/Hofstadter-Q-sequence create mode 120000 Lang/Eiffel/Huffman-coding create mode 120000 Lang/Eiffel/Identity-matrix create mode 120000 Lang/Eiffel/Increment-a-numerical-string create mode 120000 Lang/Eiffel/Knuth-shuffle create mode 120000 Lang/Eiffel/Letter-frequency create mode 120000 Lang/Eiffel/Literals-Floating-point create mode 120000 Lang/Eiffel/Literals-Integer create mode 120000 Lang/Eiffel/N-queens-problem create mode 120000 Lang/Eiffel/Null-object create mode 120000 Lang/Eiffel/Number-reversal-game create mode 120000 Lang/Eiffel/Palindrome-detection create mode 120000 Lang/Eiffel/Perfect-numbers create mode 120000 Lang/Eiffel/Permutations create mode 120000 Lang/Eiffel/Pig-the-dice-game create mode 120000 Lang/Eiffel/Prime-decomposition create mode 120000 Lang/Eiffel/Pythagorean-triples create mode 120000 Lang/Eiffel/Range-extraction create mode 120000 Lang/Eiffel/Repeat-a-string create mode 120000 Lang/Eiffel/Return-multiple-values create mode 120000 Lang/Eiffel/Roman-numerals-Decode create mode 120000 Lang/Eiffel/Roman-numerals-Encode create mode 120000 Lang/Eiffel/Scope-Function-names-and-labels create mode 120000 Lang/Eiffel/Scope-modifiers create mode 120000 Lang/Eiffel/Semordnilap create mode 120000 Lang/Eiffel/Sequence-of-non-squares create mode 120000 Lang/Eiffel/Sorting-algorithms-Bead-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Bogosort create mode 120000 Lang/Eiffel/Sorting-algorithms-Cocktail-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Comb-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Counting-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Gnome-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Merge-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Pancake-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Selection-sort create mode 120000 Lang/Eiffel/Sorting-algorithms-Stooge-sort create mode 120000 Lang/Eiffel/Sum-and-product-of-an-array create mode 120000 Lang/Eiffel/Topswops create mode 120000 Lang/Eiffel/Towers-of-Hanoi create mode 120000 Lang/Eiffel/Variables create mode 120000 Lang/Elixir/Ackermann-function create mode 120000 Lang/Elixir/Averages-Arithmetic-mean create mode 120000 Lang/Elixir/Averages-Median create mode 120000 Lang/Elixir/Averages-Pythagorean-means create mode 120000 Lang/Elixir/Averages-Root-mean-square create mode 120000 Lang/Elixir/Case-sensitivity-of-identifiers create mode 120000 Lang/Elixir/Comments create mode 120000 Lang/Elixir/Constrained-random-points-on-a-circle create mode 120000 Lang/Elixir/Empty-string create mode 120000 Lang/Elixir/Factorial create mode 120000 Lang/Elixir/Flatten-a-list create mode 120000 Lang/Elixir/Guess-the-number create mode 120000 Lang/Elixir/Guess-the-number-With-feedback create mode 120000 Lang/Elixir/Hello-world-Newline-omission create mode 120000 Lang/Elixir/Hello-world-Text create mode 120000 Lang/Elixir/Mutual-recursion create mode 120000 Lang/Elixir/Palindrome-detection create mode 120000 Lang/Elixir/Perfect-numbers create mode 120000 Lang/Elixir/Pick-random-element create mode 120000 Lang/Elixir/Random-number-generator--included- create mode 120000 Lang/Elixir/Random-numbers create mode 120000 Lang/Elixir/Repeat-a-string create mode 120000 Lang/Elixir/Reverse-a-string create mode 120000 Lang/Elixir/String-case create mode 120000 Lang/Elixir/String-concatenation create mode 120000 Lang/Elixir/String-interpolation--included- create mode 120000 Lang/Elixir/String-length create mode 120000 Lang/Elixir/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Elixir/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/Elixir/Terminal-control-Unicode-output create mode 120000 Lang/Elixir/Tokenize-a-string create mode 120000 Lang/Elixir/Unbias-a-random-generator create mode 120000 Lang/Emacs-Lisp/Associative-array-Creation create mode 120000 Lang/Emacs-Lisp/Averages-Root-mean-square create mode 120000 Lang/Emacs-Lisp/Check-that-file-exists create mode 120000 Lang/Emacs-Lisp/Detect-division-by-zero create mode 120000 Lang/Emacs-Lisp/Documentation create mode 120000 Lang/Emacs-Lisp/Dynamic-variable-names create mode 120000 Lang/Emacs-Lisp/File-modification-time create mode 120000 Lang/Emacs-Lisp/Function-composition create mode 120000 Lang/Emacs-Lisp/Function-definition create mode 120000 Lang/Emacs-Lisp/Generic-swap create mode 120000 Lang/Emacs-Lisp/Literals-String create mode 120000 Lang/Emacs-Lisp/Loops-Do-while create mode 120000 Lang/Emacs-Lisp/Loops-Foreach create mode 120000 Lang/Emacs-Lisp/Loops-While create mode 120000 Lang/Emacs-Lisp/Primality-by-trial-division create mode 120000 Lang/Emacs-Lisp/Program-termination create mode 120000 Lang/Emacs-Lisp/Range-extraction create mode 120000 Lang/Emacs-Lisp/Read-entire-file create mode 120000 Lang/Emacs-Lisp/SHA-256 create mode 120000 Lang/Emacs-Lisp/Secure-temporary-file create mode 120000 Lang/Emacs-Lisp/Sieve-of-Eratosthenes create mode 120000 Lang/Emacs-Lisp/Unicode-variable-names create mode 120000 Lang/Erlang/Pattern-matching create mode 120000 Lang/Erlang/Probabilistic-choice create mode 120000 Lang/Euphoria/Averages-Mean-angle create mode 120000 Lang/Euphoria/Averages-Mean-time-of-day create mode 120000 Lang/Euphoria/Compound-data-type create mode 120000 Lang/Euphoria/Execute-a-system-command create mode 120000 Lang/Euphoria/Horizontal-sundial-calculations create mode 120000 Lang/Euphoria/Letter-frequency create mode 120000 Lang/Euphoria/Literals-Floating-point create mode 120000 Lang/Euphoria/Literals-Integer create mode 120000 Lang/Euphoria/Loops-Do-while create mode 120000 Lang/Euphoria/Loops-Foreach create mode 120000 Lang/Euphoria/OpenGL create mode 120000 Lang/Euphoria/Sierpinski-carpet create mode 120000 Lang/Euphoria/Temperature-conversion create mode 120000 Lang/Euphoria/Tic-tac-toe create mode 120000 Lang/Excel/Arithmetic-Integer create mode 120000 Lang/Excel/Averages-Root-mean-square create mode 120000 Lang/Excel/Integer-comparison create mode 120000 Lang/Excel/Logical-operations create mode 120000 Lang/Excel/Temperature-conversion create mode 120000 Lang/F-Sharp/Gamma-function create mode 120000 Lang/F-Sharp/Sieve-of-Eratosthenes create mode 120000 Lang/Factor/Colour-bars-Display create mode 120000 Lang/Factor/Here-document create mode 120000 Lang/Factor/Parallel-calculations create mode 120000 Lang/Factor/Price-fraction create mode 120000 Lang/Factor/Sum-digits-of-an-integer create mode 120000 Lang/Factor/XML-XPath create mode 120000 Lang/Falcon/Constrained-random-points-on-a-circle create mode 120000 Lang/Falcon/Hello-world-Newline-omission create mode 120000 Lang/Falcon/Pick-random-element create mode 120000 Lang/Forth/Call-a-function create mode 120000 Lang/Forth/Named-parameters create mode 120000 Lang/Forth/Top-rank-per-group create mode 120000 Lang/Forth/Vector-products create mode 120000 Lang/Fortran/Animate-a-pendulum create mode 120000 Lang/Fortran/Call-a-function create mode 120000 Lang/Fortran/Deal-cards-for-FreeCell create mode 120000 Lang/Fortran/Digital-root create mode 120000 Lang/Fortran/Enforced-immutability create mode 120000 Lang/Fortran/Fibonacci-n-step-number-sequences create mode 120000 Lang/Fortran/Langtons-ant create mode 120000 Lang/Fortran/Random-number-generator--device- create mode 120000 Lang/Fortran/Subtractive-generator create mode 120000 Lang/Fortran/Temperature-conversion create mode 120000 Lang/Fortran/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Frink/Factors-of-an-integer create mode 120000 Lang/Frink/Greyscale-bars-Display create mode 120000 Lang/Frink/Hello-world-Standard-error create mode 120000 Lang/Frink/Knuth-shuffle create mode 120000 Lang/Frink/Remove-lines-from-a-file create mode 120000 Lang/Frink/Return-multiple-values create mode 120000 Lang/Frink/Runtime-evaluation create mode 120000 Lang/Frink/Sort-an-integer-array create mode 120000 Lang/Frink/String-interpolation--included- create mode 120000 Lang/Frink/Window-creation create mode 120000 Lang/GML/Hello-world-Text create mode 120000 Lang/Gema/A+B create mode 120000 Lang/Gentee/Hello-world-Text create mode 120000 Lang/Gnuplot/Function-definition create mode 120000 Lang/Gnuplot/Program-termination create mode 120000 Lang/Go/Arena-storage-pool create mode 120000 Lang/Go/Break-OO-privacy create mode 120000 Lang/Go/Call-a-function create mode 120000 Lang/Go/Create-a-file-on-magnetic-tape create mode 120000 Lang/Go/Cut-a-rectangle create mode 120000 Lang/Go/Keyboard-input-Flush-the-keyboard-buffer create mode 120000 Lang/Go/Keyboard-input-Keypress-check create mode 120000 Lang/Go/Keyboard-input-Obtain-a-Y-or-N-response create mode 120000 Lang/Go/Metronome create mode 120000 Lang/Go/Parametrized-SQL-statement create mode 120000 Lang/Go/Partial-function-application create mode 120000 Lang/Go/SQL-based-authentication create mode 120000 Lang/Go/Scope-Function-names-and-labels create mode 120000 Lang/Go/Set-of-real-numbers create mode 120000 Lang/Go/Terminal-control-Coloured-text create mode 120000 Lang/Go/Terminal-control-Cursor-movement create mode 120000 Lang/Go/Terminal-control-Cursor-positioning create mode 120000 Lang/Go/Terminal-control-Dimensions create mode 120000 Lang/Go/Terminal-control-Hiding-the-cursor create mode 120000 Lang/Go/Terminal-control-Inverse-video create mode 120000 Lang/Go/Universal-Turing-machine create mode 120000 Lang/Go/Zebra-puzzle create mode 120000 Lang/Groovy/Anagrams-Deranged-anagrams create mode 120000 Lang/Groovy/Arithmetic-geometric-mean create mode 120000 Lang/Groovy/Delete-a-file create mode 120000 Lang/Groovy/Happy-numbers create mode 120000 Lang/Groovy/Huffman-coding create mode 120000 Lang/Groovy/Least-common-multiple create mode 120000 Lang/Groovy/Optional-parameters create mode 120000 Lang/Groovy/Parametric-polymorphism create mode 120000 Lang/Groovy/Polymorphic-copy create mode 120000 Lang/Groovy/Pythagorean-triples create mode 120000 Lang/Groovy/Respond-to-an-unknown-method-call create mode 120000 Lang/Groovy/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Haskell/Average-loop-length create mode 120000 Lang/Haskell/Calendar create mode 120000 Lang/Haskell/Color-quantization create mode 120000 Lang/Haskell/Element-wise-operations create mode 120000 Lang/Haskell/Honeycombs create mode 120000 Lang/Haskell/Hough-transform create mode 120000 Lang/Haskell/Image-noise create mode 120000 Lang/Haskell/Last-Friday-of-each-month create mode 120000 Lang/Haskell/Mad-Libs create mode 120000 Lang/Haskell/Multisplit create mode 120000 Lang/Haskell/Narcissist create mode 120000 Lang/Haskell/Nautical-bell create mode 120000 Lang/Haskell/Optional-parameters create mode 120000 Lang/Haskell/Percentage-difference-between-images create mode 120000 Lang/Haskell/Rate-counter create mode 120000 Lang/Haskell/SHA-1 create mode 120000 Lang/Haskell/Sokoban create mode 120000 Lang/Haskell/String-comparison create mode 120000 Lang/Haskell/Temperature-conversion create mode 120000 Lang/Haskell/Terminal-control-Clear-the-screen create mode 120000 Lang/Haskell/URL-decoding create mode 120000 Lang/Haskell/URL-encoding create mode 120000 Lang/Haxe/Execute-HQ9+ create mode 120000 Lang/Haxe/Hello-world-Text create mode 120000 Lang/Icon/Balanced-ternary create mode 120000 Lang/Icon/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Icon/Create-a-file-on-magnetic-tape create mode 120000 Lang/Icon/Fibonacci-n-step-number-sequences create mode 120000 Lang/Icon/Hello-world-Line-printer create mode 120000 Lang/Icon/Keyboard-macros create mode 120000 Lang/Icon/Permutations-by-swapping create mode 120000 Lang/Icon/Reduced-row-echelon-form create mode 120000 Lang/Icon/Roots-of-a-function create mode 120000 Lang/Icon/Secure-temporary-file create mode 120000 Lang/Icon/Test-a-function create mode 120000 Lang/Icon/Video-display-modes create mode 120000 Lang/Intercal/Loops-Infinite create mode 120000 Lang/Io/Man-or-boy-test create mode 120000 Lang/J/Date-manipulation create mode 120000 Lang/J/Execute-SNUSP create mode 120000 Lang/J/Fork create mode 120000 Lang/J/Nautical-bell create mode 120000 Lang/J/Send-an-unknown-method-call create mode 120000 Lang/J/Sieve-of-Eratosthenes create mode 120000 Lang/J/Synchronous-concurrency create mode 120000 Lang/Java/24-game create mode 120000 Lang/Java/24-game-Solve create mode 120000 Lang/Java/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/Java/Calendar create mode 120000 Lang/Java/Colour-pinstripe-Display create mode 120000 Lang/Java/Discordian-date create mode 120000 Lang/Java/Draw-a-cuboid create mode 120000 Lang/Java/Dutch-national-flag-problem create mode 120000 Lang/Java/Execute-a-Markov-algorithm create mode 120000 Lang/Java/GUI-Maximum-window-dimensions create mode 120000 Lang/Java/Holidays-related-to-Easter create mode 120000 Lang/Java/Honeycombs create mode 120000 Lang/Java/Longest-string-challenge create mode 120000 Lang/Java/Multifactorial create mode 120000 Lang/Java/Multisplit create mode 120000 Lang/Java/Nautical-bell create mode 120000 Lang/Java/Non-continuous-subsequences create mode 120000 Lang/Java/Parallel-calculations create mode 120000 Lang/Java/Parsing-RPN-to-infix-conversion create mode 120000 Lang/Java/Parsing-Shunting-yard-algorithm create mode 120000 Lang/Java/Pinstripe-Display create mode 120000 Lang/Java/Self-referential-sequence create mode 120000 Lang/Java/Sierpinski-triangle-Graphical create mode 120000 Lang/Java/Simple-database create mode 120000 Lang/Java/Solve-a-Hidato-puzzle create mode 120000 Lang/Java/String-comparison create mode 120000 Lang/Java/Strip-control-codes-and-extended-characters-from-a-string create mode 120000 Lang/Java/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Java/Terminal-control-Clear-the-screen create mode 120000 Lang/Java/Text-processing-1 create mode 120000 Lang/Java/Top-rank-per-group create mode 120000 Lang/Java/Update-a-configuration-file create mode 120000 Lang/Java/Visualize-a-tree create mode 120000 Lang/Java/Window-management create mode 120000 Lang/Java/Zebra-puzzle create mode 120000 Lang/JavaScript/Death-Star create mode 120000 Lang/JavaScript/Digital-root create mode 120000 Lang/JavaScript/Draw-a-sphere create mode 120000 Lang/JavaScript/Empty-string create mode 120000 Lang/JavaScript/Entropy create mode 120000 Lang/JavaScript/Euler-method create mode 120000 Lang/JavaScript/Fast-Fourier-transform create mode 120000 Lang/JavaScript/Gamma-function create mode 120000 Lang/JavaScript/Handle-a-signal create mode 120000 Lang/JavaScript/Haversine-formula create mode 120000 Lang/JavaScript/Identity-matrix create mode 120000 Lang/JavaScript/Knapsack-problem-0-1 create mode 120000 Lang/JavaScript/Parsing-Shunting-yard-algorithm create mode 120000 Lang/JavaScript/Roots-of-a-function create mode 120000 Lang/JavaScript/Unicode-variable-names create mode 120000 Lang/JavaScript/Web-scraping create mode 120000 Lang/Julia/Arithmetic-Integer create mode 120000 Lang/Julia/Associative-array-Creation create mode 120000 Lang/Julia/Averages-Pythagorean-means create mode 120000 Lang/Julia/Averages-Simple-moving-average create mode 120000 Lang/Julia/Combinations-with-repetitions create mode 120000 Lang/Julia/Conways-Game-of-Life create mode 120000 Lang/Julia/Entropy create mode 120000 Lang/Julia/Ethiopian-multiplication create mode 120000 Lang/Julia/Generator-Exponential create mode 120000 Lang/Julia/Hamming-numbers create mode 120000 Lang/Julia/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/Julia/Integer-comparison create mode 120000 Lang/Julia/Introspection create mode 120000 Lang/Julia/Kaprekar-numbers create mode 120000 Lang/Julia/Letter-frequency create mode 120000 Lang/Julia/Levenshtein-distance create mode 120000 Lang/Julia/Literals-Integer create mode 120000 Lang/Julia/Loops-N-plus-one-half create mode 120000 Lang/Julia/Minesweeper-game create mode 120000 Lang/Julia/Parsing-RPN-calculator-algorithm create mode 120000 Lang/Julia/Seven-sided-dice-from-five-sided-dice create mode 120000 Lang/Julia/Sierpinski-carpet create mode 120000 Lang/Julia/Special-variables create mode 120000 Lang/Julia/Truncate-a-file create mode 120000 Lang/Julia/Y-combinator create mode 120000 Lang/LOLCODE/Loops-Infinite create mode 120000 Lang/Liberty-BASIC/LZW-compression create mode 120000 Lang/Logo/Averages-Mean-angle create mode 120000 Lang/Logo/Langtons-ant create mode 120000 Lang/Logo/Sum-digits-of-an-integer create mode 120000 Lang/Lua/Arithmetic-geometric-mean create mode 120000 Lang/Lua/Call-a-foreign-language-function create mode 120000 Lang/Lua/Combinations-with-repetitions create mode 120000 Lang/Lua/Digital-root create mode 120000 Lang/Lua/Forest-fire create mode 120000 Lang/Lua/JSON create mode 120000 Lang/Lua/Langtons-ant create mode 120000 Lang/Lua/Largest-int-from-concatenated-ints create mode 120000 Lang/Lua/Longest-string-challenge create mode 120000 Lang/Lua/Maze-generation create mode 120000 Lang/Lua/Order-two-numerical-lists create mode 120000 Lang/Lua/Partial-function-application create mode 120000 Lang/Lua/Priority-queue create mode 120000 Lang/Lua/Range-expansion create mode 120000 Lang/Lua/Read-a-specific-line-from-a-file create mode 120000 Lang/Lua/Sorting-algorithms-Sleep-sort create mode 120000 Lang/Lua/Special-variables create mode 120000 Lang/Lua/Standard-deviation create mode 120000 Lang/Lua/String-concatenation create mode 120000 Lang/Lua/Sum-digits-of-an-integer create mode 120000 Lang/Lua/Temperature-conversion create mode 120000 Lang/Lua/Van-der-Corput-sequence create mode 120000 Lang/Lua/Word-wrap create mode 120000 Lang/Lush/Fibonacci-sequence create mode 120000 Lang/M4/A+B create mode 120000 Lang/M4/Even-or-odd create mode 120000 Lang/M4/Read-entire-file create mode 120000 Lang/MATLAB/Bulls-and-cows create mode 120000 Lang/MATLAB/Bulls-and-cows-Player create mode 120000 Lang/MATLAB/Element-wise-operations create mode 120000 Lang/MATLAB/Gray-code create mode 120000 Lang/MATLAB/Guess-the-number-With-feedback--player- create mode 120000 Lang/MATLAB/Hamming-numbers create mode 120000 Lang/MATLAB/Handle-a-signal create mode 120000 Lang/MATLAB/Happy-numbers create mode 120000 Lang/MATLAB/Hash-from-two-arrays create mode 120000 Lang/MATLAB/Honeycombs create mode 120000 Lang/MATLAB/Image-convolution create mode 120000 Lang/MATLAB/Minesweeper-game create mode 120000 Lang/MATLAB/Number-reversal-game create mode 120000 Lang/MATLAB/Perfect-numbers create mode 120000 Lang/MATLAB/Probabilistic-choice create mode 120000 Lang/MATLAB/Runtime-evaluation create mode 120000 Lang/MATLAB/Runtime-evaluation-In-an-environment create mode 120000 Lang/MATLAB/Tic-tac-toe create mode 120000 Lang/MAXScript/Animation create mode 120000 Lang/MAXScript/Averages-Root-mean-square create mode 120000 Lang/MAXScript/Bulls-and-cows create mode 120000 Lang/MAXScript/Factors-of-an-integer create mode 120000 Lang/MAXScript/Greyscale-bars-Display create mode 120000 Lang/MAXScript/Guess-the-number create mode 120000 Lang/MAXScript/Guess-the-number-With-feedback create mode 120000 Lang/MAXScript/Guess-the-number-With-feedback--player- create mode 120000 Lang/MAXScript/Happy-numbers create mode 120000 Lang/MAXScript/Image-noise create mode 120000 Lang/MAXScript/Knapsack-problem-0-1 create mode 120000 Lang/MAXScript/Loops-Break create mode 120000 Lang/MAXScript/Loops-For-with-a-specified-step create mode 120000 Lang/MAXScript/Loops-Nested create mode 120000 Lang/MAXScript/Mouse-position create mode 120000 Lang/MAXScript/Regular-expressions create mode 120000 Lang/MAXScript/Sorting-algorithms-Comb-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Counting-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Gnome-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Heapsort create mode 120000 Lang/MAXScript/Sorting-algorithms-Insertion-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Merge-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Pancake-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Permutation-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Stooge-sort create mode 120000 Lang/MAXScript/Sorting-algorithms-Strand-sort create mode 120000 Lang/Make/Environment-variables create mode 120000 Lang/Make/Read-entire-file create mode 120000 Lang/Maple/Averages-Mode create mode 120000 Lang/Maple/Averages-Pythagorean-means create mode 120000 Lang/Maple/Averages-Root-mean-square create mode 120000 Lang/Maple/Call-a-function create mode 120000 Lang/Maple/Call-an-object-method create mode 120000 Lang/Maple/Catalan-numbers create mode 120000 Lang/Maple/Collections create mode 120000 Lang/Maple/Combinations create mode 120000 Lang/Maple/Constrained-random-points-on-a-circle create mode 120000 Lang/Maple/Create-a-file create mode 120000 Lang/Maple/Delete-a-file create mode 120000 Lang/Maple/Empty-string create mode 120000 Lang/Maple/Even-or-odd create mode 120000 Lang/Maple/FizzBuzz create mode 120000 Lang/Maple/HTTPS create mode 120000 Lang/Maple/Hash-from-two-arrays create mode 120000 Lang/Maple/Loops-N-plus-one-half create mode 120000 Lang/Maple/MD5 create mode 120000 Lang/Maple/Memory-allocation create mode 120000 Lang/Maple/Multiplicative-order create mode 120000 Lang/Maple/Optional-parameters create mode 120000 Lang/Maple/Roman-numerals-Encode create mode 120000 Lang/Maple/Shell-one-liner create mode 120000 Lang/Maple/Stem-and-leaf-plot create mode 120000 Lang/Maple/String-length create mode 120000 Lang/Maple/Strip-comments-from-a-string create mode 120000 Lang/Maple/Substring create mode 120000 Lang/Maple/Symmetric-difference create mode 120000 Lang/Maple/Ternary-logic create mode 120000 Lang/Maple/Trigonometric-functions create mode 120000 Lang/Maple/URL-decoding create mode 120000 Lang/Maple/URL-encoding create mode 120000 Lang/Mathematica/Abstract-type create mode 120000 Lang/Mathematica/Globally-replace-text-in-several-files create mode 120000 Lang/Mathematica/Huffman-coding create mode 120000 Lang/Mathematica/K-means++-clustering create mode 120000 Lang/Mathematica/Largest-int-from-concatenated-ints create mode 120000 Lang/Mathematica/Mad-Libs create mode 120000 Lang/Mathematica/Metaprogramming create mode 120000 Lang/Mathematica/One-of-n-lines-in-a-file create mode 120000 Lang/Mathematica/Random-number-generator--device- create mode 120000 Lang/Mathematica/Rate-counter create mode 120000 Lang/Mathematica/Read-a-configuration-file create mode 120000 Lang/Mathematica/Remove-lines-from-a-file create mode 120000 Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks create mode 120000 Lang/Mathematica/Send-an-unknown-method-call create mode 120000 Lang/Mathematica/Set-of-real-numbers create mode 120000 Lang/Mathematica/Set-puzzle create mode 120000 Lang/Mathematica/Sorting-algorithms-Radix-sort create mode 120000 Lang/Mathematica/String-comparison create mode 120000 Lang/Mathematica/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Mathematica/Universal-Turing-machine create mode 120000 Lang/Mathematica/Vampire-number create mode 120000 Lang/Mathematica/Window-management create mode 120000 Lang/Mathematica/Word-wrap create mode 120000 Lang/Mathematica/Zebra-puzzle create mode 120000 Lang/Maxima/Pick-random-element create mode 120000 Lang/Mercury/Averages-Arithmetic-mean create mode 120000 Lang/Mercury/Factorial create mode 120000 Lang/Mercury/Flatten-a-list create mode 120000 Lang/Mercury/Greatest-common-divisor create mode 120000 Lang/Mercury/Happy-numbers create mode 120000 Lang/Mercury/Literals-Integer create mode 120000 Lang/Mercury/Miller-Rabin-primality-test create mode 120000 Lang/Mercury/Program-name create mode 120000 Lang/Mercury/String-length create mode 120000 Lang/Mercury/Synchronous-concurrency create mode 120000 Lang/Neko/Increment-a-numerical-string create mode 120000 Lang/NewLISP/Associative-array-Iteration create mode 120000 Lang/NewLISP/Check-that-file-exists create mode 120000 Lang/NewLISP/Delete-a-file create mode 120000 Lang/NewLISP/Even-or-odd create mode 120000 Lang/NewLISP/Execute-a-system-command create mode 120000 Lang/NewLISP/File-modification-time create mode 120000 Lang/NewLISP/File-size create mode 120000 Lang/NewLISP/FizzBuzz create mode 120000 Lang/NewLISP/Fork create mode 120000 Lang/NewLISP/Generic-swap create mode 120000 Lang/NewLISP/Handle-a-signal create mode 120000 Lang/NewLISP/Include-a-file create mode 120000 Lang/NewLISP/Increment-a-numerical-string create mode 120000 Lang/NewLISP/Integer-sequence create mode 120000 Lang/NewLISP/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/NewLISP/Loops-Break create mode 120000 Lang/NewLISP/Loops-Continue create mode 120000 Lang/NewLISP/Loops-Do-while create mode 120000 Lang/NewLISP/Loops-Downward-for create mode 120000 Lang/NewLISP/Loops-For-with-a-specified-step create mode 120000 Lang/NewLISP/Loops-Foreach create mode 120000 Lang/NewLISP/Loops-Infinite create mode 120000 Lang/NewLISP/Loops-N-plus-one-half create mode 120000 Lang/NewLISP/Loops-Nested create mode 120000 Lang/NewLISP/Loops-While create mode 120000 Lang/NewLISP/MD5 create mode 120000 Lang/NewLISP/Nth-root create mode 120000 Lang/NewLISP/Rot-13 create mode 120000 Lang/NewLISP/SHA-1 create mode 120000 Lang/NewLISP/SHA-256 create mode 120000 Lang/NewLISP/Singly-linked-list-Traversal create mode 120000 Lang/NewLISP/String-concatenation create mode 120000 Lang/NewLISP/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/NewLISP/Strip-whitespace-from-a-string-Top-and-tail create mode 120000 Lang/NewLISP/Substring-Top-and-tail create mode 120000 Lang/NewLISP/Sum-and-product-of-an-array create mode 120000 Lang/NewLISP/Sum-of-a-series create mode 120000 Lang/NewLISP/System-time create mode 120000 Lang/NewLISP/Tokenize-a-string create mode 120000 Lang/NewLISP/URL-decoding create mode 120000 Lang/NewLISP/URL-encoding create mode 120000 Lang/OCaml/Box-the-compass create mode 120000 Lang/OCaml/Entropy create mode 120000 Lang/OCaml/Pig-the-dice-game create mode 120000 Lang/OCaml/Temperature-conversion create mode 120000 Lang/OOC/99-Bottles-of-Beer create mode 120000 Lang/OOC/Ackermann-function create mode 120000 Lang/OOC/Arithmetic-geometric-mean create mode 120000 Lang/OOC/Caesar-cipher create mode 120000 Lang/OOC/Empty-program create mode 120000 Lang/OOC/Even-or-odd create mode 120000 Lang/OOC/Function-definition create mode 120000 Lang/OOC/Hello-world-Newline-omission create mode 120000 Lang/OOC/Logical-operations create mode 120000 Lang/OOC/Loops-While create mode 120000 Lang/OOC/Reverse-a-string create mode 120000 Lang/OOC/String-interpolation--included- create mode 120000 Lang/Oberon-2/Abstract-type create mode 120000 Lang/Oberon-2/Align-columns create mode 120000 Lang/Oberon-2/Array-concatenation create mode 120000 Lang/Oberon-2/Arrays create mode 120000 Lang/Oberon-2/Associative-array-Creation create mode 120000 Lang/Oberon-2/Associative-array-Iteration create mode 120000 Lang/Oberon-2/Binary-digits create mode 120000 Lang/Oberon-2/Boolean-values create mode 120000 Lang/Oberon-2/CRC-32 create mode 120000 Lang/Oberon-2/CSV-to-HTML-translation create mode 120000 Lang/Oberon-2/Caesar-cipher create mode 120000 Lang/Oberon-2/Case-sensitivity-of-identifiers create mode 120000 Lang/Oberon-2/Comments create mode 120000 Lang/Oberon-2/Compile-time-calculation create mode 120000 Lang/Oberon-2/Greatest-common-divisor create mode 120000 Lang/Oberon-2/Greatest-element-of-a-list create mode 120000 Lang/Oberon-2/Greatest-subsequential-sum create mode 120000 Lang/Oberon-2/Guess-the-number create mode 120000 Lang/Oberon-2/Hash-from-two-arrays create mode 120000 Lang/Oberon-2/Haversine-formula create mode 120000 Lang/Oberon-2/Hello-world-Newline-omission create mode 120000 Lang/Oberon-2/Higher-order-functions create mode 120000 Lang/Oberon-2/Hofstadter-Q-sequence create mode 120000 Lang/Oberon-2/Hostname create mode 120000 Lang/Oberon-2/Inheritance-Single create mode 120000 Lang/Oberon-2/Input-loop create mode 120000 Lang/Oberon-2/Integer-sequence create mode 120000 Lang/Oberon-2/Loop-over-multiple-arrays-simultaneously create mode 120000 Lang/Oberon-2/Loops-Break create mode 120000 Lang/Oberon-2/Loops-Do-while create mode 120000 Lang/Oberon-2/Loops-For create mode 120000 Lang/Oberon-2/Loops-For-with-a-specified-step create mode 120000 Lang/Oberon-2/Loops-Infinite create mode 120000 Lang/Oberon-2/Program-name create mode 120000 Lang/Oberon-2/Program-termination create mode 120000 Lang/Objeck/Averages-Pythagorean-means create mode 120000 Lang/Objeck/Levenshtein-distance create mode 120000 Lang/Objeck/Nth-root create mode 120000 Lang/Objeck/Rosetta-Code-Count-examples create mode 120000 Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity create mode 120000 Lang/Objeck/SQL-based-authentication create mode 120000 Lang/Objeck/Sierpinski-carpet create mode 120000 Lang/Objective-C/100-doors create mode 120000 Lang/Objective-C/Enumerations create mode 120000 Lang/Objective-C/Knuth-shuffle create mode 120000 Lang/Objective-C/Number-names create mode 120000 Lang/Objective-C/Range-extraction create mode 120000 Lang/Objective-C/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Octave/Resistor-mesh create mode 120000 Lang/OoRexx/Box-the-compass create mode 120000 Lang/OoRexx/Evolutionary-algorithm create mode 120000 Lang/OoRexx/Loops-Nested create mode 120000 Lang/OpenEdge-Progress/Loops-Do-while create mode 120000 Lang/OpenEdge-Progress/Luhn-test-of-credit-card-numbers create mode 120000 Lang/OpenEdge-Progress/Rename-a-file create mode 120000 Lang/Oz/Miller-Rabin-primality-test create mode 120000 Lang/Oz/Primality-by-trial-division create mode 120000 Lang/PARI-GP/Anonymous-recursion create mode 120000 Lang/PARI-GP/Check-Machin-like-formulas create mode 120000 Lang/PARI-GP/Count-occurrences-of-a-substring create mode 120000 Lang/PARI-GP/Dragon-curve create mode 120000 Lang/PARI-GP/Variable-length-quantity create mode 120000 Lang/PARI-GP/Y-combinator create mode 120000 Lang/PHP/Self-describing-numbers create mode 120000 Lang/PHP/Terminal-control-Ringing-the-terminal-bell create mode 120000 Lang/PHP/Tree-traversal create mode 120000 Lang/PHP/Zeckendorf-number-representation create mode 120000 Lang/PL-I/Arithmetic-Rational create mode 120000 Lang/PL-I/Averages-Mean-time-of-day create mode 120000 Lang/PL-I/Enforced-immutability create mode 120000 Lang/PL-I/Entropy create mode 120000 Lang/PL-I/Knapsack-problem-Continuous create mode 120000 Lang/PL-I/Levenshtein-distance create mode 120000 Lang/PL-I/Modular-inverse create mode 120000 Lang/PL-I/Order-two-numerical-lists create mode 120000 Lang/PL-I/Sorting-algorithms-Bogosort create mode 120000 Lang/PL-I/Sudoku create mode 120000 Lang/PL-I/Take-notes-on-the-command-line create mode 120000 Lang/Pascal/Averages-Mean-angle create mode 120000 Lang/Pascal/Conways-Game-of-Life create mode 120000 Lang/Pascal/Entropy create mode 120000 Lang/Pascal/Hailstone-sequence create mode 120000 Lang/Pascal/Hamming-numbers create mode 120000 Lang/Pascal/Harshad-or-Niven-series create mode 120000 Lang/Pascal/Hofstadter-Conway-$10,000-sequence create mode 120000 Lang/Pascal/Largest-int-from-concatenated-ints create mode 120000 Lang/Pascal/Man-or-boy-test create mode 120000 Lang/Pascal/Mandelbrot-set create mode 120000 Lang/Pascal/Random-numbers create mode 120000 Lang/Pascal/SHA-1 create mode 120000 Lang/Pascal/Spiral-matrix create mode 120000 Lang/Pascal/Standard-deviation create mode 120000 Lang/Pascal/Sum-digits-of-an-integer create mode 120000 Lang/Pascal/Van-der-Corput-sequence create mode 120000 Lang/Pascal/Window-creation-X11 create mode 120000 Lang/Pascal/Xiaolin-Wus-line-algorithm create mode 120000 Lang/Perl-6/Cut-a-rectangle create mode 120000 Lang/Perl-6/Events create mode 120000 Lang/Perl-6/GUI-enabling-disabling-of-controls create mode 120000 Lang/Perl-6/Handle-a-signal create mode 120000 Lang/Perl-6/Image-noise create mode 120000 Lang/Perl-6/K-means++-clustering create mode 120000 Lang/Perl-6/Simple-windowed-application create mode 120000 Lang/Perl-6/Speech-synthesis create mode 120000 Lang/Perl-6/Stable-marriage-problem create mode 120000 Lang/Perl-6/User-input-Graphical create mode 120000 Lang/Perl-6/Window-creation create mode 120000 Lang/Perl-6/Window-creation-X11 create mode 120000 Lang/Perl/Averages-Mean-angle create mode 120000 Lang/Perl/Call-a-function create mode 120000 Lang/Perl/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/Perl/Continued-fraction-Arithmetic-Construct-from-rational-number create mode 120000 Lang/Perl/Cut-a-rectangle create mode 120000 Lang/Perl/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Perl/Discordian-date create mode 120000 Lang/Perl/Dragon-curve create mode 120000 Lang/Perl/Find-largest-left-truncatable-prime-in-a-given-base create mode 120000 Lang/Perl/First-class-functions-Use-numbers-analogously create mode 120000 Lang/Perl/Four-bit-adder create mode 120000 Lang/Perl/Multiplicative-order create mode 120000 Lang/Perl/RIPEMD-160 create mode 120000 Lang/Perl/Rock-paper-scissors create mode 120000 Lang/Perl/Terminal-control-Cursor-positioning create mode 120000 Lang/Perl/Write-language-name-in-3D-ASCII create mode 120000 Lang/PicoLisp/Average-loop-length create mode 120000 Lang/PicoLisp/Balanced-ternary create mode 120000 Lang/PicoLisp/Bitcoin-address-validation create mode 120000 Lang/PicoLisp/CRC-32 create mode 120000 Lang/PicoLisp/Carmichael-3-strong-pseudoprimes create mode 120000 Lang/PicoLisp/MD4 create mode 120000 Lang/PicoLisp/Main-step-of-GOST-28147-89 create mode 120000 Lang/PicoLisp/Modular-inverse create mode 120000 Lang/PicoLisp/Permutations-by-swapping create mode 120000 Lang/PicoLisp/RIPEMD-160 create mode 120000 Lang/PicoLisp/SHA-256 create mode 120000 Lang/PicoLisp/String-comparison create mode 120000 Lang/PicoLisp/Universal-Turing-machine create mode 120000 Lang/PicoLisp/Write-language-name-in-3D-ASCII create mode 120000 Lang/PicoLisp/Zeckendorf-arithmetic create mode 120000 Lang/PicoLisp/Zeckendorf-number-representation create mode 120000 Lang/PlainTeX/Towers-of-Hanoi create mode 120000 Lang/PowerShell/Caesar-cipher create mode 120000 Lang/PowerShell/Concurrent-computing create mode 120000 Lang/PowerShell/Create-an-HTML-table create mode 120000 Lang/PowerShell/JSON create mode 120000 Lang/Prolog/24-game create mode 120000 Lang/Prolog/Arbitrary-precision-integers--included- create mode 120000 Lang/Prolog/Arithmetic-Integer create mode 120000 Lang/Prolog/Averages-Arithmetic-mean create mode 120000 Lang/Prolog/Binary-search create mode 120000 Lang/Prolog/Bitmap-Bresenhams-line-algorithm create mode 120000 Lang/Prolog/Check-that-file-exists create mode 120000 Lang/Prolog/Concurrent-computing create mode 120000 Lang/Prolog/Count-occurrences-of-a-substring create mode 120000 Lang/Prolog/Date-format create mode 120000 Lang/Prolog/Determine-if-a-string-is-numeric create mode 120000 Lang/Prolog/Empty-string create mode 120000 Lang/Prolog/Equilibrium-index create mode 120000 Lang/Prolog/Ethiopian-multiplication create mode 120000 Lang/Prolog/Exponentiation-operator create mode 120000 Lang/Prolog/Guess-the-number create mode 120000 Lang/Prolog/Guess-the-number-With-feedback create mode 120000 Lang/Prolog/Guess-the-number-With-feedback--player- create mode 120000 Lang/Prolog/JSON create mode 120000 Lang/Prolog/Loops-Foreach create mode 120000 Lang/Prolog/Menu create mode 120000 Lang/Prolog/Middle-three-digits create mode 120000 Lang/Prolog/Miller-Rabin-primality-test create mode 120000 Lang/Prolog/Pick-random-element create mode 120000 Lang/Prolog/Substring create mode 120000 Lang/Prolog/Top-rank-per-group create mode 120000 Lang/Prolog/Vector-products create mode 120000 Lang/PureBasic/Create-an-HTML-table create mode 120000 Lang/Python/GUI-component-interaction create mode 120000 Lang/Python/Metaprogramming create mode 120000 Lang/Python/Simulate-input-Keyboard create mode 120000 Lang/Python/Topic-variable create mode 120000 Lang/R/Call-a-function create mode 120000 Lang/R/Call-a-function-in-a-shared-library create mode 120000 Lang/R/DNS-query create mode 120000 Lang/R/Dragon-curve create mode 120000 Lang/R/Euler-method create mode 120000 Lang/R/Gray-code create mode 120000 Lang/R/Integer-sequence create mode 120000 Lang/R/One-of-n-lines-in-a-file create mode 120000 Lang/R/Roman-numerals-Decode create mode 120000 Lang/R/String-comparison create mode 120000 Lang/R/Sum-digits-of-an-integer create mode 120000 Lang/R/URL-decoding create mode 120000 Lang/R/URL-encoding create mode 120000 Lang/R/Unicode-variable-names create mode 120000 Lang/R/Word-wrap create mode 120000 Lang/R/Zebra-puzzle create mode 120000 Lang/REALbasic/Classes create mode 120000 Lang/REALbasic/Function-definition create mode 120000 Lang/REALbasic/Hello-world-Graphical create mode 120000 Lang/REALbasic/Variadic-function create mode 120000 Lang/REBOL/Dot-product create mode 120000 Lang/REBOL/Hello-world-Newline-omission create mode 120000 Lang/REBOL/Horners-rule-for-polynomial-evaluation create mode 120000 Lang/REBOL/Last-Friday-of-each-month create mode 120000 Lang/REBOL/Mad-Libs create mode 120000 Lang/REBOL/Number-reversal-game create mode 120000 Lang/REBOL/Runtime-evaluation create mode 120000 Lang/REBOL/Simple-database create mode 120000 Lang/REXX/Averages-Mean-time-of-day create mode 120000 Lang/REXX/Bulls-and-cows-Player create mode 120000 Lang/REXX/Colour-bars-Display create mode 120000 Lang/REXX/Extend-your-language create mode 120000 Lang/REXX/Include-a-file create mode 120000 Lang/REXX/LZW-compression create mode 120000 Lang/REXX/Man-or-boy-test create mode 120000 Lang/REXX/Mandelbrot-set create mode 120000 Lang/REXX/Ordered-Partitions create mode 120000 Lang/REXX/Set-puzzle create mode 120000 Lang/REXX/Simple-database create mode 120000 Lang/REXX/Sort-stability create mode 120000 Lang/REXX/Topic-variable create mode 120000 Lang/REXX/Truncate-a-file create mode 120000 Lang/REXX/Visualize-a-tree create mode 120000 Lang/REXX/Wireworld create mode 120000 Lang/REXX/XML-XPath create mode 120000 Lang/RPG/Substring create mode 120000 Lang/Racket/Bitmap-Histogram create mode 120000 Lang/Racket/Constrained-genericity create mode 120000 Lang/Racket/Delegates create mode 120000 Lang/Racket/Object-serialization create mode 120000 Lang/Racket/Resistor-mesh create mode 120000 Lang/RapidQ/100-doors create mode 120000 Lang/RapidQ/99-Bottles-of-Beer create mode 120000 Lang/RapidQ/Address-of-a-variable create mode 120000 Lang/RapidQ/Align-columns create mode 120000 Lang/RapidQ/Anagrams create mode 120000 Lang/RapidQ/Array-concatenation create mode 120000 Lang/RapidQ/Find-the-missing-permutation create mode 120000 Lang/RapidQ/Greatest-element-of-a-list create mode 120000 Lang/RapidQ/Greyscale-bars-Display create mode 120000 Lang/RapidQ/Guess-the-number create mode 120000 Lang/RapidQ/Read-a-configuration-file create mode 120000 Lang/RapidQ/Read-a-file-line-by-line create mode 120000 Lang/RapidQ/Repeat-a-string create mode 120000 Lang/RapidQ/Sleep create mode 120000 Lang/Ruby/Bitcoin-address-validation create mode 120000 Lang/Ruby/Color-of-a-screen-pixel create mode 120000 Lang/Ruby/Cut-a-rectangle create mode 120000 Lang/Ruby/Draw-a-cuboid create mode 120000 Lang/Ruby/Knapsack-problem-Continuous create mode 120000 Lang/Ruby/Nautical-bell create mode 120000 Lang/Ruby/Permutation-test create mode 120000 Lang/Ruby/Scope-modifiers create mode 120000 Lang/Ruby/Set-of-real-numbers create mode 120000 Lang/Ruby/Sokoban create mode 120000 Lang/Ruby/Start-from-a-main-routine create mode 120000 Lang/Ruby/Topic-variable create mode 120000 Lang/Ruby/Verify-distribution-uniformity-Chi-squared-test create mode 120000 Lang/Ruby/Visualize-a-tree create mode 120000 Lang/Ruby/Zebra-puzzle create mode 120000 Lang/Rust/Accumulator-factory create mode 120000 Lang/Rust/Align-columns create mode 120000 Lang/Rust/Arithmetic-Integer create mode 120000 Lang/Rust/Arithmetic-geometric-mean create mode 120000 Lang/Rust/Associative-array-Iteration create mode 120000 Lang/Rust/Averages-Arithmetic-mean create mode 120000 Lang/Rust/Binary-digits create mode 120000 Lang/Rust/Call-an-object-method create mode 120000 Lang/Rust/Catalan-numbers create mode 120000 Lang/Rust/Dot-product create mode 120000 Lang/Rust/Ethiopian-multiplication create mode 120000 Lang/Rust/Even-or-odd create mode 120000 Lang/Rust/Filter create mode 120000 Lang/Rust/Guess-the-number create mode 120000 Lang/Rust/Hailstone-sequence create mode 120000 Lang/Rust/Happy-numbers create mode 120000 Lang/Rust/Hello-world-Newline-omission create mode 120000 Lang/Rust/Hello-world-Standard-error create mode 120000 Lang/Rust/Hello-world-Web-server create mode 120000 Lang/Rust/Infinity create mode 120000 Lang/Rust/Integer-comparison create mode 120000 Lang/Rust/JSON create mode 120000 Lang/Rust/Knapsack-problem-0-1 create mode 120000 Lang/Rust/Langtons-ant create mode 120000 Lang/Rust/Letter-frequency create mode 120000 Lang/Rust/Loops-Infinite create mode 120000 Lang/Rust/Loops-While create mode 120000 Lang/Rust/Luhn-test-of-credit-card-numbers create mode 120000 Lang/Rust/Parametric-polymorphism create mode 120000 Lang/Rust/Playing-cards create mode 120000 Lang/Rust/Price-fraction create mode 120000 Lang/Rust/Primality-by-trial-division create mode 120000 Lang/Rust/Read-a-file-line-by-line create mode 120000 Lang/Rust/SHA-256 create mode 120000 Lang/Rust/Sort-an-integer-array create mode 120000 Lang/Rust/Sorting-algorithms-Quicksort create mode 120000 Lang/Rust/Sum-of-a-series create mode 120000 Lang/Rust/Sum-of-squares create mode 120000 Lang/SAS/Hailstone-sequence create mode 120000 Lang/SAS/Haversine-formula create mode 120000 Lang/SAS/Power-set create mode 120000 Lang/SAS/Stair-climbing-puzzle create mode 120000 Lang/SPARC-Assembly/Hello-world-Text create mode 120000 Lang/SQL/100-doors create mode 120000 Lang/SQL/Associative-array-Creation create mode 120000 Lang/SQL/Comments create mode 120000 Lang/SQL/Fibonacci-sequence create mode 120000 Lang/SQL/Gray-code create mode 120000 Lang/SQL/Middle-three-digits create mode 120000 Lang/SQL/N-queens-problem create mode 120000 Lang/Scala/Averages-Mean-angle create mode 120000 Lang/Scala/Averages-Mean-time-of-day create mode 120000 Lang/Scala/Bitmap-Flood-fill create mode 120000 Lang/Scala/Break-OO-privacy create mode 120000 Lang/Scala/Call-a-function create mode 120000 Lang/Scala/Call-a-function-in-a-shared-library create mode 120000 Lang/Scala/Color-of-a-screen-pixel create mode 120000 Lang/Scala/Conditional-structures create mode 120000 Lang/Scala/Create-a-file create mode 120000 Lang/Scala/Create-an-HTML-table create mode 120000 Lang/Scala/DNS-query create mode 120000 Lang/Scala/Define-a-primitive-data-type create mode 120000 Lang/Scala/Dutch-national-flag-problem create mode 120000 Lang/Scala/Exceptions create mode 120000 Lang/Scala/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Scala/Fibonacci-n-step-number-sequences create mode 120000 Lang/Scala/File-modification-time create mode 120000 Lang/Scala/File-size create mode 120000 Lang/Scala/Find-common-directory-path create mode 120000 Lang/Scala/Flow-control-structures create mode 120000 Lang/Scala/Fork create mode 120000 Lang/Scala/Handle-a-signal create mode 120000 Lang/Scala/Here-document create mode 120000 Lang/Scala/Host-introspection create mode 120000 Lang/Scala/I-before-E-except-after-C create mode 120000 Lang/Scala/Inverted-index create mode 120000 Lang/Scala/Last-letter-first-letter create mode 120000 Lang/Scala/Longest-string-challenge create mode 120000 Lang/Scala/Loops-N-plus-one-half create mode 120000 Lang/Scala/MD4 create mode 120000 Lang/Scala/Mad-Libs create mode 120000 Lang/Scala/Miller-Rabin-primality-test create mode 120000 Lang/Scala/Number-reversal-game create mode 120000 Lang/Scala/One-of-n-lines-in-a-file create mode 120000 Lang/Scala/OpenGL create mode 120000 Lang/Scala/Order-two-numerical-lists create mode 120000 Lang/Scala/Permutations-Derangements create mode 120000 Lang/Scala/Pick-random-element create mode 120000 Lang/Scala/Probabilistic-choice create mode 120000 Lang/Scala/Program-termination create mode 120000 Lang/Scala/RIPEMD-160 create mode 120000 Lang/Scala/Record-sound create mode 120000 Lang/Scala/Remove-lines-from-a-file create mode 120000 Lang/Scala/Rock-paper-scissors create mode 120000 Lang/Scala/Roots-of-a-function create mode 120000 Lang/Scala/SHA-256 create mode 120000 Lang/Scala/Send-an-unknown-method-call create mode 120000 Lang/Scala/Set-consolidation create mode 120000 Lang/Scala/Simple-database create mode 120000 Lang/Scala/Simulate-input-Mouse create mode 120000 Lang/Scala/Sockets create mode 120000 Lang/Scala/Sort-disjoint-sublist create mode 120000 Lang/Scala/Special-characters create mode 120000 Lang/Scala/Standard-deviation create mode 120000 Lang/Scala/Start-from-a-main-routine create mode 120000 Lang/Scala/String-comparison create mode 120000 Lang/Scala/Strip-block-comments create mode 120000 Lang/Scala/Sutherland-Hodgman-polygon-clipping create mode 120000 Lang/Scala/Temperature-conversion create mode 120000 Lang/Scala/Terminal-control-Clear-the-screen create mode 120000 Lang/Scala/Terminal-control-Display-an-extended-character create mode 120000 Lang/Scala/Terminal-control-Preserve-screen create mode 120000 Lang/Scala/Terminal-control-Unicode-output create mode 120000 Lang/Scala/Topswops create mode 120000 Lang/Scala/Trigonometric-functions create mode 120000 Lang/Scala/Truncate-a-file create mode 120000 Lang/Scala/URL-encoding create mode 120000 Lang/Scala/Variable-size-Get create mode 120000 Lang/Scala/Window-creation-X11 create mode 120000 Lang/Scala/Word-wrap create mode 120000 Lang/Scala/Write-float-arrays-to-a-text-file create mode 120000 Lang/Scala/Xiaolin-Wus-line-algorithm create mode 120000 Lang/Scala/Zebra-puzzle create mode 120000 Lang/Scheme/Associative-array-Iteration create mode 120000 Lang/Scheme/Count-occurrences-of-a-substring create mode 120000 Lang/Scheme/Formatted-numeric-output create mode 120000 Lang/Scheme/Huffman-coding create mode 120000 Lang/Scheme/Knights-tour create mode 120000 Lang/Scheme/Largest-int-from-concatenated-ints create mode 120000 Lang/Scheme/Multisplit create mode 120000 Lang/Scheme/Probabilistic-choice create mode 120000 Lang/Scheme/Pythagorean-triples create mode 120000 Lang/Scheme/Roman-numerals-Decode create mode 120000 Lang/Scheme/Same-Fringe create mode 120000 Lang/Scheme/Sort-disjoint-sublist create mode 120000 Lang/Scheme/Top-rank-per-group create mode 120000 Lang/Scilab/Ackermann-function create mode 120000 Lang/Scilab/Comments create mode 120000 Lang/Scilab/Empty-program create mode 120000 Lang/Scilab/Fibonacci-sequence create mode 120000 Lang/Scilab/Gamma-function create mode 120000 Lang/Scilab/Hailstone-sequence create mode 120000 Lang/Scilab/Lucas-Lehmer-test create mode 120000 Lang/Scilab/Monty-Hall-problem create mode 120000 Lang/Scilab/Sieve-of-Eratosthenes create mode 120000 Lang/Scilab/Sorting-algorithms-Bubble-sort create mode 120000 Lang/Scilab/Spiral-matrix create mode 120000 Lang/Scilab/Standard-deviation create mode 120000 Lang/Scilab/String-concatenation create mode 120000 Lang/ScriptBasic/Strip-a-set-of-characters-from-a-string create mode 120000 Lang/Sed/Globally-replace-text-in-several-files create mode 120000 Lang/Seed7/Abstract-type create mode 120000 Lang/Seed7/Anonymous-recursion create mode 120000 Lang/Seed7/Average-loop-length create mode 120000 Lang/Seed7/Bulls-and-cows create mode 120000 Lang/Seed7/Deal-cards-for-FreeCell create mode 120000 Lang/Seed7/Delete-a-file create mode 120000 Lang/Seed7/Determine-if-a-string-is-numeric create mode 120000 Lang/Seed7/Exceptions-Catch-an-exception-thrown-in-a-nested-call create mode 120000 Lang/Seed7/Find-the-missing-permutation create mode 120000 Lang/Seed7/Gray-code create mode 120000 Lang/Seed7/Hello-world-Line-printer create mode 120000 Lang/Seed7/Langtons-ant create mode 120000 Lang/Seed7/Nautical-bell create mode 120000 Lang/Seed7/Non-continuous-subsequences create mode 120000 Lang/Seed7/Parametrized-SQL-statement create mode 120000 Lang/Seed7/Solve-a-Hidato-puzzle create mode 120000 Lang/Seed7/Sorting-algorithms-Bead-sort create mode 120000 Lang/Seed7/Window-creation create mode 120000 Lang/Simula/Comments create mode 120000 Lang/Simula/Empty-program create mode 120000 Lang/Simula/Hello-world-Line-printer create mode 120000 Lang/Simula/Hello-world-Text create mode 120000 Lang/Simula/Loops-For create mode 120000 Lang/Smalltalk/Cholesky-decomposition create mode 120000 Lang/Smalltalk/Date-format create mode 120000 Lang/Smalltalk/Empty-string create mode 120000 Lang/Smalltalk/Environment-variables create mode 120000 Lang/Smalltalk/Hello-world-Newline-omission create mode 120000 Lang/Smalltalk/JSON create mode 120000 Lang/Smalltalk/Leap-year create mode 120000 Lang/Smalltalk/Least-common-multiple create mode 120000 Lang/Smalltalk/Mouse-position create mode 120000 Lang/Smalltalk/Read-a-specific-line-from-a-file create mode 120000 Lang/Smalltalk/SHA-256 create mode 120000 Lang/Smalltalk/Singleton create mode 120000 Lang/Smalltalk/Stack create mode 120000 Lang/Standard-ML/Abstract-type create mode 120000 Lang/Standard-ML/Anonymous-recursion create mode 120000 Lang/Standard-ML/Bitmap-Flood-fill create mode 120000 Lang/Standard-ML/Empty-string create mode 120000 Lang/Standard-ML/Sorting-algorithms-Heapsort create mode 120000 Lang/Standard-ML/Soundex create mode 120000 Lang/Standard-ML/Topic-variable create mode 120000 Lang/TI-83-BASIC/Conditional-structures create mode 120000 Lang/TI-83-BASIC/Factorial create mode 120000 Lang/TI-83-BASIC/Gamma-function create mode 120000 Lang/TI-83-BASIC/Hailstone-sequence create mode 120000 Lang/TI-83-BASIC/Loops-While create mode 120000 Lang/TI-83-BASIC/Lucas-Lehmer-test create mode 120000 Lang/TI-83-BASIC/Sieve-of-Eratosthenes create mode 120000 Lang/TI-83-BASIC/Spiral-matrix create mode 120000 Lang/TXR/Anonymous-recursion create mode 120000 Lang/TXR/First-class-functions create mode 120000 Lang/TXR/Self-referential-sequence create mode 120000 Lang/TorqueScript/Comments create mode 120000 Lang/TorqueScript/Loops-For-with-a-specified-step create mode 120000 Lang/TorqueScript/Window-creation create mode 120000 Lang/Transact-SQL/Hello-world-Newline-omission create mode 120000 Lang/Transact-SQL/Hello-world-Standard-error create mode 120000 Lang/Transact-SQL/SEDOLs create mode 120000 Lang/UBASIC/Haversine-formula create mode 120000 Lang/UNIX-Shell/24-game create mode 120000 Lang/UNIX-Shell/Anagrams create mode 120000 Lang/UNIX-Shell/Anagrams-Deranged-anagrams create mode 120000 Lang/UNIX-Shell/Arithmetic-Complex create mode 120000 Lang/UNIX-Shell/Arithmetic-geometric-mean create mode 120000 Lang/UNIX-Shell/Assertions create mode 120000 Lang/UNIX-Shell/Associative-array-Creation create mode 120000 Lang/UNIX-Shell/Balanced-brackets create mode 120000 Lang/UNIX-Shell/Bitmap create mode 120000 Lang/UNIX-Shell/Bitmap-Read-a-PPM-file create mode 120000 Lang/UNIX-Shell/Bitmap-Write-a-PPM-file create mode 120000 Lang/UNIX-Shell/CSV-to-HTML-translation create mode 120000 Lang/UNIX-Shell/Caesar-cipher create mode 120000 Lang/UNIX-Shell/Classes create mode 120000 Lang/UNIX-Shell/Collections create mode 120000 Lang/UNIX-Shell/Compound-data-type create mode 120000 Lang/UNIX-Shell/Create-an-HTML-table create mode 120000 Lang/UNIX-Shell/Define-a-primitive-data-type create mode 120000 Lang/UNIX-Shell/Five-weekends create mode 120000 Lang/UNIX-Shell/Generic-swap create mode 120000 Lang/UNIX-Shell/Globally-replace-text-in-several-files create mode 120000 Lang/UNIX-Shell/Guess-the-number-With-feedback--player- create mode 120000 Lang/UNIX-Shell/Hamming-numbers create mode 120000 Lang/UNIX-Shell/Hash-from-two-arrays create mode 120000 Lang/UNIX-Shell/Hello-world-Web-server create mode 120000 Lang/UNIX-Shell/Introspection create mode 120000 Lang/UNIX-Shell/Linear-congruential-generator create mode 120000 Lang/UNIX-Shell/Look-and-say-sequence create mode 120000 Lang/UNIX-Shell/Luhn-test-of-credit-card-numbers create mode 120000 Lang/UNIX-Shell/Multisplit create mode 120000 Lang/UNIX-Shell/Queue-Definition create mode 120000 Lang/UNIX-Shell/Queue-Usage create mode 120000 Lang/UNIX-Shell/Random-number-generator--device- create mode 120000 Lang/UNIX-Shell/Read-a-configuration-file create mode 120000 Lang/UNIX-Shell/Read-a-specific-line-from-a-file create mode 120000 Lang/UNIX-Shell/Real-constants-and-functions create mode 120000 Lang/UNIX-Shell/Regular-expressions create mode 120000 Lang/UNIX-Shell/Roman-numerals-Encode create mode 120000 Lang/UNIX-Shell/Runtime-evaluation create mode 120000 Lang/UNIX-Shell/Search-a-list create mode 120000 Lang/UNIX-Shell/Self-describing-numbers create mode 120000 Lang/VBA/Comments create mode 120000 Lang/VBA/Parsing-RPN-calculator-algorithm create mode 120000 Lang/VBA/Parsing-Shunting-yard-algorithm create mode 120000 Lang/VBScript/Comments create mode 120000 Lang/VBScript/Greatest-common-divisor create mode 120000 Lang/VBScript/Hello-world-Graphical create mode 120000 Lang/VBScript/Lucas-Lehmer-test create mode 120000 Lang/VBScript/Luhn-test-of-credit-card-numbers create mode 120000 Lang/VBScript/Sierpinski-carpet create mode 120000 Lang/VBScript/Sieve-of-Eratosthenes create mode 120000 Lang/VBScript/Sudoku create mode 120000 Lang/VBScript/URL-decoding create mode 120000 Lang/VBScript/URL-encoding create mode 120000 Lang/VBScript/Van-der-Corput-sequence create mode 120000 Lang/Vim-Script/Apply-a-callback-to-an-array create mode 120000 Lang/Vim-Script/Arithmetic-Integer create mode 120000 Lang/Vim-Script/Arrays create mode 120000 Lang/Vim-Script/Associative-array-Creation create mode 120000 Lang/Vim-Script/Associative-array-Iteration create mode 120000 Lang/Vim-Script/Averages-Arithmetic-mean create mode 120000 Lang/Vim-Script/Binary-digits create mode 120000 Lang/Vim-Script/Boolean-values create mode 120000 Lang/Vim-Script/Character-codes create mode 120000 Lang/Vim-Script/Comments create mode 120000 Lang/Vim-Script/Compound-data-type create mode 120000 Lang/Vim-Script/Copy-a-string create mode 120000 Lang/Vim-Script/Count-in-octal create mode 120000 Lang/Vim-Script/Create-a-two-dimensional-array-at-runtime create mode 120000 Lang/Vim-Script/FizzBuzz create mode 120000 Lang/Vim-Script/Greatest-element-of-a-list create mode 120000 Lang/Vim-Script/Hello-world-Newline-omission create mode 120000 Lang/Vim-Script/Hello-world-Text create mode 120000 Lang/Vim-Script/Hostname create mode 120000 Lang/Vim-Script/Loops-For-with-a-specified-step create mode 120000 Lang/Vim-Script/Loops-Foreach create mode 120000 Lang/Vim-Script/Loops-N-plus-one-half create mode 120000 Lang/Vim-Script/Loops-While create mode 120000 Lang/Visual-Basic-.NET/Align-columns create mode 120000 Lang/Visual-Basic-.NET/Arrays create mode 120000 Lang/Visual-Basic-.NET/Dragon-curve create mode 120000 Lang/Visual-Basic-.NET/Lucas-Lehmer-test create mode 120000 Lang/Visual-Basic/Ackermann-function create mode 120000 Lang/Visual-Basic/Align-columns create mode 120000 Lang/Visual-Basic/Dragon-curve create mode 120000 Lang/Visual-Basic/Empty-program create mode 120000 Lang/Visual-Basic/Fibonacci-sequence create mode 120000 Lang/Visual-Basic/Hailstone-sequence create mode 120000 Lang/Visual-Basic/Knapsack-problem-Unbounded create mode 120000 Lang/Visual-Basic/Multiplication-tables create mode 120000 Lang/Visual-Basic/Sieve-of-Eratosthenes create mode 120000 Lang/Visual-Basic/Standard-deviation create mode 120000 Lang/Whitespace/Terminal-control-Cursor-positioning create mode 120000 Lang/XSLT/Averages-Arithmetic-mean create mode 120000 Lang/XSLT/Call-a-function create mode 120000 Lang/XSLT/Create-an-HTML-table create mode 120000 Lang/XSLT/FizzBuzz create mode 120000 Lang/XSLT/Greatest-element-of-a-list create mode 120000 Lang/XSLT/Hello-world-Graphical create mode 120000 Lang/XSLT/Here-document create mode 120000 Lang/Yacas/Apply-a-callback-to-an-array create mode 120000 Lang/Yacas/Array-concatenation create mode 120000 Lang/Yacas/Averages-Root-mean-square create mode 120000 Lang/Yacas/Greatest-element-of-a-list create mode 120000 Lang/Z80-Assembly/Mandelbrot-set create mode 120000 Lang/ZED/Sorting-algorithms-Merge-sort create mode 100644 Task/100-doors/ATS/100-doors.ats create mode 100644 Task/100-doors/ColdFusion/100-doors-4.cfm create mode 100644 Task/100-doors/Haskell/100-doors-4.hs create mode 100644 Task/100-doors/JavaScript/100-doors-5.js create mode 100644 Task/100-doors/JavaScript/100-doors-6.js create mode 100644 Task/100-doors/Mathematica/100-doors-8.math create mode 100644 Task/100-doors/Objective-C/100-doors-1.m create mode 100644 Task/100-doors/Objective-C/100-doors-2.m create mode 100644 Task/100-doors/Perl/100-doors-5.pl create mode 100644 Task/100-doors/PowerShell/100-doors-6.psh create mode 100644 Task/100-doors/PowerShell/100-doors-7.psh create mode 100644 Task/100-doors/Prolog/100-doors-3.pro create mode 100644 Task/100-doors/Python/100-doors-6.py create mode 100644 Task/100-doors/RapidQ/100-doors.rapidq create mode 100644 Task/100-doors/SQL/100-doors.sql create mode 100644 Task/100-doors/Scheme/100-doors-3.ss create mode 100644 Task/24-game-Solve/C++/24-game-solve.cpp create mode 100644 Task/24-game-Solve/CoffeeScript/24-game-solve.coffee create mode 100644 Task/24-game-Solve/Haskell/24-game-solve-3.hs create mode 100644 Task/24-game-Solve/Java/24-game-solve.java create mode 100644 Task/24-game-Solve/ProDOS/24-game-solve.dos rename Task/24-game-Solve/Prolog/{24-game-solve.pro => 24-game-solve-1.pro} (100%) create mode 100644 Task/24-game-Solve/Prolog/24-game-solve-2.pro create mode 100644 Task/24-game/Batch-File/24-game.bat create mode 100644 Task/24-game/Java/24-game.java create mode 100644 Task/24-game/Prolog/24-game.pro create mode 100644 Task/24-game/REXX/24-game-3.rexx create mode 100644 Task/24-game/UNIX-Shell/24-game.sh rename Task/99-Bottles-of-Beer/Clojure/{99-bottles-of-beer.clj => 99-bottles-of-beer-1.clj} (64%) create mode 100644 Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-2.clj rename Task/99-Bottles-of-Beer/Go/{99-bottles-of-beer.go => 99-bottles-of-beer-1.go} (100%) create mode 100644 Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-2.go create mode 100644 Task/99-Bottles-of-Beer/J/99-bottles-of-beer.j rename Task/99-Bottles-of-Beer/Lua/{99-bottles-of-beer.lua => 99-bottles-of-beer-1.lua} (100%) create mode 100644 Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-2.lua create mode 100644 Task/99-Bottles-of-Beer/OOC/99-bottles-of-beer.ooc rename Task/99-Bottles-of-Beer/REBOL/{99-bottles-of-beer.rebol => 99-bottles-of-beer-1.rebol} (100%) create mode 100644 Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-2.rebol create mode 100644 Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-3.rebol create mode 100644 Task/99-Bottles-of-Beer/RapidQ/99-bottles-of-beer.rapidq create mode 100644 Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-3.sql create mode 100644 Task/A+B/00META.yaml rename Task/A+B/BASIC/{a+b.basic => a+b-1.basic} (100%) create mode 100644 Task/A+B/BASIC/a+b-2.basic create mode 100644 Task/A+B/C/a+b-3.c create mode 100644 Task/A+B/Gema/a+b.gema create mode 100644 Task/A+B/Kite/a+b.kite create mode 100644 Task/A+B/M4/a+b.m4 create mode 100644 Task/Abstract-type/Mathematica/abstract-type.math create mode 100644 Task/Abstract-type/Oberon-2/abstract-type.oberon-2 create mode 100644 Task/Abstract-type/Seed7/abstract-type.seed7 create mode 100644 Task/Abstract-type/Standard-ML/abstract-type-1.ml create mode 100644 Task/Abstract-type/Standard-ML/abstract-type-2.ml create mode 100644 Task/Accumulator-factory/AppleScript/accumulator-factory.applescript create mode 100644 Task/Accumulator-factory/Java/accumulator-factory-4.java create mode 100644 Task/Accumulator-factory/Rust/accumulator-factory.rust rename Task/Accumulator-factory/TXR/{accumulator-factory.txr => accumulator-factory-1.txr} (100%) create mode 100644 Task/Accumulator-factory/TXR/accumulator-factory-2.txr create mode 100644 Task/Ackermann-function/C++/ackermann-function-1.cpp create mode 100644 Task/Ackermann-function/C++/ackermann-function-2.cpp delete mode 100644 Task/Ackermann-function/C++/ackermann-function.cpp create mode 100644 Task/Ackermann-function/Elixir/ackermann-function.elixir create mode 100644 Task/Ackermann-function/Julia/ackermann-function-3.julia create mode 100644 Task/Ackermann-function/OOC/ackermann-function.ooc create mode 100644 Task/Ackermann-function/Perl/ackermann-function-4.pl rename Task/Ackermann-function/Rust/{ackermann-function.rust => ackermann-function-1.rust} (100%) create mode 100644 Task/Ackermann-function/Rust/ackermann-function-2.rust create mode 100644 Task/Ackermann-function/Scilab/ackermann-function.scilab create mode 100644 Task/Ackermann-function/Visual-Basic/ackermann-function.vb create mode 100644 Task/Active-Directory-Connect/ColdFusion/active-directory-connect.cfm create mode 100644 Task/Address-of-a-variable/RapidQ/address-of-a-variable.rapidq rename Task/Align-columns/JavaScript/{align-columns.js => align-columns-1.js} (100%) create mode 100644 Task/Align-columns/JavaScript/align-columns-2.js create mode 100644 Task/Align-columns/Oberon-2/align-columns.oberon-2 create mode 100644 Task/Align-columns/RapidQ/align-columns.rapidq create mode 100644 Task/Align-columns/Rust/align-columns.rust create mode 100644 Task/Align-columns/Visual-Basic-.NET/align-columns.visual create mode 100644 Task/Align-columns/Visual-Basic/align-columns-1.vb create mode 100644 Task/Align-columns/Visual-Basic/align-columns-2.vb create mode 100644 Task/Anagrams-Deranged-anagrams/AWK/anagrams-deranged-anagrams.awk create mode 100644 Task/Anagrams-Deranged-anagrams/Groovy/anagrams-deranged-anagrams.groovy create mode 100644 Task/Anagrams-Deranged-anagrams/UNIX-Shell/anagrams-deranged-anagrams.sh create mode 100644 Task/Anagrams/JavaScript/anagrams-1.js create mode 100644 Task/Anagrams/JavaScript/anagrams-2.js delete mode 100644 Task/Anagrams/JavaScript/anagrams.js create mode 100644 Task/Anagrams/RapidQ/anagrams.rapidq create mode 100644 Task/Anagrams/UNIX-Shell/anagrams.sh create mode 100644 Task/Animate-a-pendulum/Common-Lisp/animate-a-pendulum.lisp create mode 100644 Task/Animate-a-pendulum/Fortran/animate-a-pendulum.f rename Task/Animate-a-pendulum/J/{animate-a-pendulum.j => animate-a-pendulum-1.j} (94%) create mode 100644 Task/Animate-a-pendulum/J/animate-a-pendulum-2.j create mode 100644 Task/Animation/MAXScript/animation.max create mode 100644 Task/Anonymous-recursion/PARI-GP/anonymous-recursion-1.pari create mode 100644 Task/Anonymous-recursion/PARI-GP/anonymous-recursion-2.pari create mode 100644 Task/Anonymous-recursion/Seed7/anonymous-recursion.seed7 create mode 100644 Task/Anonymous-recursion/Standard-ML/anonymous-recursion-1.ml create mode 100644 Task/Anonymous-recursion/Standard-ML/anonymous-recursion-2.ml create mode 100644 Task/Anonymous-recursion/Standard-ML/anonymous-recursion-3.ml create mode 100644 Task/Anonymous-recursion/TXR/anonymous-recursion.txr create mode 100644 Task/Apply-a-callback-to-an-array/AppleScript/apply-a-callback-to-an-array.applescript create mode 100644 Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-1.pb create mode 100644 Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-2.pb create mode 100644 Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb create mode 100644 Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat create mode 100644 Task/Apply-a-callback-to-an-array/Vim-Script/apply-a-callback-to-an-array.vim create mode 100644 Task/Apply-a-callback-to-an-array/Yacas/apply-a-callback-to-an-array.yacas create mode 100644 Task/Arbitrary-precision-integers--included-/Prolog/arbitrary-precision-integers--included--1.pro create mode 100644 Task/Arbitrary-precision-integers--included-/Prolog/arbitrary-precision-integers--included--2.pro create mode 100644 Task/Arena-storage-pool/Go/arena-storage-pool.go create mode 100644 Task/Arithmetic-Complex/Bracmat/arithmetic-complex.bracmat create mode 100644 Task/Arithmetic-Complex/Clojure/arithmetic-complex.clj create mode 100644 Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex.coffee create mode 100644 Task/Arithmetic-Complex/Groovy/arithmetic-complex-3.groovy create mode 100644 Task/Arithmetic-Complex/Haskell/arithmetic-complex.hs create mode 100644 Task/Arithmetic-Complex/UNIX-Shell/arithmetic-complex.sh create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-1.excel create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-2.excel create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-3.excel create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-4.excel create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-5.excel create mode 100644 Task/Arithmetic-Integer/Excel/arithmetic-integer-6.excel create mode 100644 Task/Arithmetic-Integer/Julia/arithmetic-integer.julia create mode 100644 Task/Arithmetic-Integer/Prolog/arithmetic-integer-1.pro create mode 100644 Task/Arithmetic-Integer/Prolog/arithmetic-integer-2.pro create mode 100644 Task/Arithmetic-Integer/Rust/arithmetic-integer.rust create mode 100644 Task/Arithmetic-Integer/Vim-Script/arithmetic-integer.vim create mode 100644 Task/Arithmetic-Rational/Groovy/arithmetic-rational-4.groovy create mode 100644 Task/Arithmetic-Rational/PL-I/arithmetic-rational.pli create mode 100644 Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-1.groovy create mode 100644 Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-2.groovy create mode 100644 Task/Arithmetic-geometric-mean/Lua/arithmetic-geometric-mean.lua create mode 100644 Task/Arithmetic-geometric-mean/OOC/arithmetic-geometric-mean.ooc rename Task/Arithmetic-geometric-mean/Ruby/{arithmetic-geometric-mean.rb => arithmetic-geometric-mean-1.rb} (92%) create mode 100644 Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-2.rb create mode 100644 Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust create mode 100644 Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-1.sh create mode 100644 Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-2.sh create mode 100644 Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-3.sh rename Task/Array-concatenation/Fortran/{array-concatenation.f => array-concatenation-1.f} (100%) create mode 100644 Task/Array-concatenation/Fortran/array-concatenation-2.f create mode 100644 Task/Array-concatenation/Oberon-2/array-concatenation.oberon-2 create mode 100644 Task/Array-concatenation/RapidQ/array-concatenation.rapidq create mode 100644 Task/Array-concatenation/Yacas/array-concatenation.yacas create mode 100644 Task/Arrays/Babel/arrays-1.pb create mode 100644 Task/Arrays/Babel/arrays-2.pb create mode 100644 Task/Arrays/Babel/arrays-3.pb create mode 100644 Task/Arrays/Babel/arrays-4.pb create mode 100644 Task/Arrays/Babel/arrays-5.pb create mode 100644 Task/Arrays/Babel/arrays-6.pb create mode 100644 Task/Arrays/Babel/arrays-7.pb create mode 100644 Task/Arrays/Babel/arrays-8.pb create mode 100644 Task/Arrays/Boo/arrays.boo create mode 100644 Task/Arrays/Bracmat/arrays.bracmat create mode 100644 Task/Arrays/C++/arrays.cpp create mode 100644 Task/Arrays/Oberon-2/arrays.oberon-2 create mode 100644 Task/Arrays/Vim-Script/arrays.vim create mode 100644 Task/Arrays/Visual-Basic-.NET/arrays.visual create mode 100644 Task/Assertions/UNIX-Shell/assertions.sh create mode 100644 Task/Associative-array-Creation/Babel/associative-array-creation.pb create mode 100644 Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-1.l create mode 100644 Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-2.l create mode 100644 Task/Associative-array-Creation/Julia/associative-array-creation.julia create mode 100644 Task/Associative-array-Creation/MATLAB/associative-array-creation-4.m create mode 100644 Task/Associative-array-Creation/MATLAB/associative-array-creation-5.m create mode 100644 Task/Associative-array-Creation/MATLAB/associative-array-creation-6.m create mode 100644 Task/Associative-array-Creation/MATLAB/associative-array-creation-7.m create mode 100644 Task/Associative-array-Creation/Oberon-2/associative-array-creation.oberon-2 create mode 100644 Task/Associative-array-Creation/SQL/associative-array-creation.sql create mode 100644 Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh create mode 100644 Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh create mode 100644 Task/Associative-array-Creation/Vim-Script/associative-array-creation.vim create mode 100644 Task/Associative-array-Iteration/Babel/associative-array-iteration.pb rename Task/Associative-array-Iteration/Forth/{associative-array-iteration.fth => associative-array-iteration-1.fth} (100%) create mode 100644 Task/Associative-array-Iteration/Forth/associative-array-iteration-2.fth rename Task/Associative-array-Iteration/Java/{associative-array-iteration.java => associative-array-iteration-1.java} (100%) create mode 100644 Task/Associative-array-Iteration/Java/associative-array-iteration-2.java create mode 100644 Task/Associative-array-Iteration/Maple/associative-array-iteration-1.maple create mode 100644 Task/Associative-array-Iteration/Maple/associative-array-iteration-2.maple create mode 100644 Task/Associative-array-Iteration/Maple/associative-array-iteration-3.maple create mode 100644 Task/Associative-array-Iteration/Maple/associative-array-iteration-4.maple delete mode 100644 Task/Associative-array-Iteration/Maple/associative-array-iteration.maple create mode 100644 Task/Associative-array-Iteration/NewLISP/associative-array-iteration.newlisp create mode 100644 Task/Associative-array-Iteration/Oberon-2/associative-array-iteration.oberon-2 rename Task/Associative-array-Iteration/Ruby/{associative-array-iteration.rb => associative-array-iteration-1.rb} (100%) create mode 100644 Task/Associative-array-Iteration/Ruby/associative-array-iteration-2.rb create mode 100644 Task/Associative-array-Iteration/Rust/associative-array-iteration.rust create mode 100644 Task/Associative-array-Iteration/Scheme/associative-array-iteration-1.ss create mode 100644 Task/Associative-array-Iteration/Scheme/associative-array-iteration-2.ss create mode 100644 Task/Associative-array-Iteration/Vim-Script/associative-array-iteration.vim create mode 100644 Task/Average-loop-length/Haskell/average-loop-length.hs create mode 100644 Task/Average-loop-length/PicoLisp/average-loop-length.l create mode 100644 Task/Average-loop-length/Seed7/average-loop-length.seed7 create mode 100644 Task/Averages-Arithmetic-mean/Babel/averages-arithmetic-mean.pb create mode 100644 Task/Averages-Arithmetic-mean/Elixir/averages-arithmetic-mean.elixir create mode 100644 Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-3.js create mode 100644 Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-4.js create mode 100644 Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-5.js create mode 100644 Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-1.mercury create mode 100644 Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-2.mercury create mode 100644 Task/Averages-Arithmetic-mean/Prolog/averages-arithmetic-mean.pro create mode 100644 Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust create mode 100644 Task/Averages-Arithmetic-mean/Vim-Script/averages-arithmetic-mean.vim create mode 100644 Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-1.xslt create mode 100644 Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-2.xslt create mode 100644 Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-3.xslt create mode 100644 Task/Averages-Mean-angle/Euphoria/averages-mean-angle.euphoria rename Task/Averages-Mean-angle/Haskell/{averages-mean-angle.hs => averages-mean-angle-1.hs} (100%) create mode 100644 Task/Averages-Mean-angle/Haskell/averages-mean-angle-2.hs create mode 100644 Task/Averages-Mean-angle/Logo/averages-mean-angle.logo create mode 100644 Task/Averages-Mean-angle/Pascal/averages-mean-angle.pascal create mode 100644 Task/Averages-Mean-angle/Perl/averages-mean-angle.pl create mode 100644 Task/Averages-Mean-angle/Scala/averages-mean-angle.scala create mode 100644 Task/Averages-Mean-time-of-day/C-sharp/averages-mean-time-of-day.cs create mode 100644 Task/Averages-Mean-time-of-day/D/averages-mean-time-of-day.d create mode 100644 Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.euphoria create mode 100644 Task/Averages-Mean-time-of-day/PL-I/averages-mean-time-of-day.pli create mode 100644 Task/Averages-Mean-time-of-day/REXX/averages-mean-time-of-day.rexx create mode 100644 Task/Averages-Mean-time-of-day/Scala/averages-mean-time-of-day.scala create mode 100644 Task/Averages-Median/Elixir/averages-median.elixir create mode 100644 Task/Averages-Mode/Maple/averages-mode.maple create mode 100644 Task/Averages-Pythagorean-means/Elixir/averages-pythagorean-means.elixir create mode 100644 Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means.erl create mode 100644 Task/Averages-Pythagorean-means/Julia/averages-pythagorean-means.julia create mode 100644 Task/Averages-Pythagorean-means/Maple/averages-pythagorean-means.maple create mode 100644 Task/Averages-Pythagorean-means/Objeck/averages-pythagorean-means.objeck create mode 100644 Task/Averages-Root-mean-square/Elixir/averages-root-mean-square.elixir create mode 100644 Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-1.l create mode 100644 Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l create mode 100644 Task/Averages-Root-mean-square/Excel/averages-root-mean-square.excel create mode 100644 Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-1.max create mode 100644 Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-2.max create mode 100644 Task/Averages-Root-mean-square/Maple/averages-root-mean-square.maple rename Task/Averages-Root-mean-square/Perl-6/{averages-root-mean-square.pl6 => averages-root-mean-square-1.pl6} (100%) create mode 100644 Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-2.pl6 create mode 100644 Task/Averages-Root-mean-square/Yacas/averages-root-mean-square.yacas create mode 100644 Task/Averages-Simple-moving-average/Bracmat/averages-simple-moving-average.bracmat create mode 100644 Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average.coffee create mode 100644 Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-1.hs rename Task/Averages-Simple-moving-average/Haskell/{averages-simple-moving-average.hs => averages-simple-moving-average-2.hs} (100%) create mode 100644 Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-3.hs rename Task/Averages-Simple-moving-average/JavaScript/{averages-simple-moving-average.js => averages-simple-moving-average-1.js} (100%) create mode 100644 Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-2.js create mode 100644 Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia create mode 100644 Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia rename Task/Averages-Simple-moving-average/PL-I/{averages-simple-moving-average.pli => averages-simple-moving-average-1.pli} (100%) create mode 100644 Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-2.pli create mode 100644 Task/Balanced-brackets/Perl/balanced-brackets-4.pl create mode 100644 Task/Balanced-brackets/Scala/balanced-brackets-3.scala create mode 100644 Task/Balanced-brackets/UNIX-Shell/balanced-brackets.sh create mode 100644 Task/Balanced-ternary/ATS/balanced-ternary.ats create mode 100644 Task/Balanced-ternary/Icon/balanced-ternary.icon create mode 100644 Task/Balanced-ternary/PicoLisp/balanced-ternary.l create mode 100644 Task/Binary-digits/Oberon-2/binary-digits.oberon-2 create mode 100644 Task/Binary-digits/Rust/binary-digits.rust create mode 100644 Task/Binary-digits/Vim-Script/binary-digits.vim create mode 100644 Task/Binary-search/CoffeeScript/binary-search-1.coffee create mode 100644 Task/Binary-search/CoffeeScript/binary-search-2.coffee create mode 100644 Task/Binary-search/CoffeeScript/binary-search-3.coffee delete mode 100644 Task/Binary-search/CoffeeScript/binary-search.coffee create mode 100644 Task/Binary-search/Eiffel/binary-search.e create mode 100644 Task/Binary-search/Prolog/binary-search.pro rename Task/Binary-search/Scala/{binary-search.scala => binary-search-1.scala} (100%) create mode 100644 Task/Binary-search/Scala/binary-search-2.scala create mode 100644 Task/Binary-search/Scala/binary-search-3.scala create mode 100644 Task/Bitcoin-address-validation/00META.yaml create mode 100644 Task/Bitcoin-address-validation/PicoLisp/bitcoin-address-validation.l create mode 100644 Task/Bitcoin-address-validation/Ruby/bitcoin-address-validation.rb create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Batch-File/bitmap-bresenhams-line-algorithm.bat create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/PL-I/bitmap-bresenhams-line-algorithm-3.pli create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/Prolog/bitmap-bresenhams-line-algorithm.pro create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx create mode 100644 Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-2.rexx delete mode 100644 Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm.rexx create mode 100644 Task/Bitmap-Flood-fill/Scala/bitmap-flood-fill.scala create mode 100644 Task/Bitmap-Flood-fill/Standard-ML/bitmap-flood-fill.ml create mode 100644 Task/Bitmap-Histogram/Racket/bitmap-histogram.rkt create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 create mode 100644 Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm.pli create mode 100644 Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-1.sh create mode 100644 Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-2.sh create mode 100644 Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-3.sh create mode 100644 Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-4.mod3 create mode 100644 Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-1.sh create mode 100644 Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-2.sh create mode 100644 Task/Bitmap/Go/bitmap-1.go rename Task/Bitmap/Go/{bitmap.go => bitmap-2.go} (100%) create mode 100644 Task/Bitmap/REXX/bitmap-1.rexx create mode 100644 Task/Bitmap/REXX/bitmap-2.rexx delete mode 100644 Task/Bitmap/REXX/bitmap.rexx create mode 100644 Task/Bitmap/UNIX-Shell/bitmap.sh create mode 100644 Task/Bitwise-operations/Babel/bitwise-operations-1.pb create mode 100644 Task/Bitwise-operations/Babel/bitwise-operations-2.pb create mode 100644 Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 create mode 100644 Task/Boolean-values/Oberon-2/boolean-values.oberon-2 create mode 100644 Task/Boolean-values/PL-I/boolean-values-1.pli create mode 100644 Task/Boolean-values/PL-I/boolean-values-2.pli delete mode 100644 Task/Boolean-values/PL-I/boolean-values.pli create mode 100644 Task/Boolean-values/Vim-Script/boolean-values.vim rename Task/Box-the-compass/D/{box-the-compass.d => box-the-compass-1.d} (100%) create mode 100644 Task/Box-the-compass/D/box-the-compass-2.d create mode 100644 Task/Box-the-compass/OCaml/box-the-compass.ocaml create mode 100644 Task/Box-the-compass/OoRexx/box-the-compass.rexx create mode 100644 Task/Break-OO-privacy/00META.yaml create mode 100644 Task/Break-OO-privacy/Clojure/break-oo-privacy-1.clj create mode 100644 Task/Break-OO-privacy/Clojure/break-oo-privacy-2.clj create mode 100644 Task/Break-OO-privacy/Go/break-oo-privacy-1.go create mode 100644 Task/Break-OO-privacy/Go/break-oo-privacy-2.go create mode 100644 Task/Break-OO-privacy/Scala/break-oo-privacy.scala rename Task/Brownian-tree/Java/{brownian-tree.java => brownian-tree-1.java} (100%) create mode 100644 Task/Brownian-tree/Java/brownian-tree-2.java create mode 100644 Task/Bulls-and-cows-Player/Common-Lisp/bulls-and-cows-player.lisp create mode 100644 Task/Bulls-and-cows-Player/MATLAB/bulls-and-cows-player.m create mode 100644 Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx create mode 100644 Task/Bulls-and-cows/Go/bulls-and-cows.go create mode 100644 Task/Bulls-and-cows/MATLAB/bulls-and-cows.m create mode 100644 Task/Bulls-and-cows/MAXScript/bulls-and-cows-1.max create mode 100644 Task/Bulls-and-cows/MAXScript/bulls-and-cows-2.max create mode 100644 Task/Bulls-and-cows/Seed7/bulls-and-cows.seed7 create mode 100644 Task/CRC-32/Oberon-2/crc-32.oberon-2 create mode 100644 Task/CRC-32/PicoLisp/crc-32.l create mode 100644 Task/CSV-to-HTML-translation/Oberon-2/csv-to-html-translation.oberon-2 create mode 100644 Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx create mode 100644 Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-1.sh create mode 100644 Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-2.sh create mode 100644 Task/Caesar-cipher/Babel/caesar-cipher.pb create mode 100644 Task/Caesar-cipher/Eiffel/caesar-cipher.e create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-1.groovy create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-2.groovy create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-3.groovy create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-4.groovy create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-5.groovy create mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher-6.groovy delete mode 100644 Task/Caesar-cipher/Groovy/caesar-cipher.groovy create mode 100644 Task/Caesar-cipher/OOC/caesar-cipher.ooc create mode 100644 Task/Caesar-cipher/Oberon-2/caesar-cipher.oberon-2 create mode 100644 Task/Caesar-cipher/PowerShell/caesar-cipher.psh create mode 100644 Task/Caesar-cipher/UNIX-Shell/caesar-cipher.sh create mode 100644 Task/Calendar/Haskell/calendar.hs create mode 100644 Task/Calendar/Java/calendar.java create mode 100644 Task/Call-a-foreign-language-function/Lua/call-a-foreign-language-function.lua create mode 100644 Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-1.r create mode 100644 Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-2.r create mode 100644 Task/Call-a-function-in-a-shared-library/Scala/call-a-function-in-a-shared-library.scala create mode 100644 Task/Call-a-function/ALGOL-68/call-a-function.alg create mode 100644 Task/Call-a-function/D/call-a-function.d create mode 100644 Task/Call-a-function/Forth/call-a-function.fth create mode 100644 Task/Call-a-function/Fortran/call-a-function.f create mode 100644 Task/Call-a-function/Go/call-a-function-1.go create mode 100644 Task/Call-a-function/Go/call-a-function-2.go create mode 100644 Task/Call-a-function/Go/call-a-function-3.go create mode 100644 Task/Call-a-function/Go/call-a-function-4.go create mode 100644 Task/Call-a-function/Go/call-a-function-5.go create mode 100644 Task/Call-a-function/Go/call-a-function-6.go create mode 100644 Task/Call-a-function/Go/call-a-function-7.go create mode 100644 Task/Call-a-function/Go/call-a-function-8.go create mode 100644 Task/Call-a-function/Maple/call-a-function-1.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-2.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-3.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-4.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-5.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-6.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-7.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-8.maple create mode 100644 Task/Call-a-function/Maple/call-a-function-9.maple create mode 100644 Task/Call-a-function/Perl/call-a-function-1.pl create mode 100644 Task/Call-a-function/Perl/call-a-function-2.pl create mode 100644 Task/Call-a-function/Perl/call-a-function-3.pl create mode 100644 Task/Call-a-function/Perl/call-a-function-4.pl create mode 100644 Task/Call-a-function/Perl/call-a-function-5.pl create mode 100644 Task/Call-a-function/R/call-a-function.r create mode 100644 Task/Call-a-function/Scala/call-a-function.scala create mode 100644 Task/Call-a-function/XSLT/call-a-function.xslt create mode 100644 Task/Call-an-object-method/Clojure/call-an-object-method.clj create mode 100644 Task/Call-an-object-method/Maple/call-an-object-method-1.maple create mode 100644 Task/Call-an-object-method/Maple/call-an-object-method-2.maple create mode 100644 Task/Call-an-object-method/Rust/call-an-object-method.rust create mode 100644 Task/Canny-edge-detector/00META.yaml create mode 100644 Task/Carmichael-3-strong-pseudoprimes/C/carmichael-3-strong-pseudoprimes.c create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Icon/carmichael-3-strong-pseudoprimes.icon create mode 100644 Task/Carmichael-3-strong-pseudoprimes/Perl/carmichael-3-strong-pseudoprimes.pl create mode 100644 Task/Carmichael-3-strong-pseudoprimes/PicoLisp/carmichael-3-strong-pseudoprimes.l create mode 100644 Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx create mode 100644 Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir create mode 100644 Task/Case-sensitivity-of-identifiers/Oberon-2/case-sensitivity-of-identifiers.oberon-2 create mode 100644 Task/Catalan-numbers/Eiffel/catalan-numbers-1.e create mode 100644 Task/Catalan-numbers/Eiffel/catalan-numbers-2.e create mode 100644 Task/Catalan-numbers/Maple/catalan-numbers.maple create mode 100644 Task/Catalan-numbers/Perl/catalan-numbers-3.pl create mode 100644 Task/Catalan-numbers/REXX/catalan-numbers-1.rexx create mode 100644 Task/Catalan-numbers/REXX/catalan-numbers-2.rexx delete mode 100644 Task/Catalan-numbers/REXX/catalan-numbers.rexx create mode 100644 Task/Catalan-numbers/Rust/catalan-numbers.rust create mode 100644 Task/Character-codes/Babel/character-codes-1.pb create mode 100644 Task/Character-codes/Babel/character-codes-2.pb create mode 100644 Task/Character-codes/Eiffel/character-codes.e create mode 100644 Task/Character-codes/Vim-Script/character-codes.vim rename Task/Chat-server/Haskell/{chat-server.hs => chat-server-1.hs} (100%) create mode 100644 Task/Chat-server/Haskell/chat-server-2.hs create mode 100644 Task/Check-Machin-like-formulas/PARI-GP/check-machin-like-formulas.pari create mode 100644 Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.l create mode 100644 Task/Check-that-file-exists/NewLISP/check-that-file-exists.newlisp create mode 100644 Task/Check-that-file-exists/Prolog/check-that-file-exists.pro create mode 100644 Task/Cholesky-decomposition/Smalltalk/cholesky-decomposition.st create mode 100644 Task/Classes/Clojure/classes.clj rename Task/Classes/Java/{classes.java => classes-1.java} (74%) create mode 100644 Task/Classes/Java/classes-2.java create mode 100644 Task/Classes/REALbasic/classes-1.realbasic create mode 100644 Task/Classes/REALbasic/classes-2.realbasic create mode 100644 Task/Classes/UNIX-Shell/classes.sh create mode 100644 Task/Closest-pair-problem/C++/closest-pair-problem.cpp create mode 100644 Task/Collections/Maple/collections-1.maple create mode 100644 Task/Collections/Maple/collections-2.maple create mode 100644 Task/Collections/Maple/collections-3.maple create mode 100644 Task/Collections/Maple/collections-4.maple create mode 100644 Task/Collections/Ruby/collections-4.rb create mode 100644 Task/Collections/Ruby/collections-5.rb create mode 100644 Task/Collections/Ruby/collections-6.rb rename Task/Collections/Scala/{collections.scala => collections-1.scala} (100%) create mode 100644 Task/Collections/Scala/collections-2.scala create mode 100644 Task/Collections/UNIX-Shell/collections-1.sh create mode 100644 Task/Collections/UNIX-Shell/collections-2.sh create mode 100644 Task/Collections/UNIX-Shell/collections-3.sh create mode 100644 Task/Collections/UNIX-Shell/collections-4.sh create mode 100644 Task/Color-of-a-screen-pixel/Ruby/color-of-a-screen-pixel.rb create mode 100644 Task/Color-of-a-screen-pixel/Scala/color-of-a-screen-pixel.scala rename Task/Color-quantization/D/{color-quantization.d => color-quantization-1.d} (73%) create mode 100644 Task/Color-quantization/D/color-quantization-2.d create mode 100644 Task/Color-quantization/Haskell/color-quantization.hs create mode 100644 Task/Colour-bars-Display/Factor/colour-bars-display.factor create mode 100644 Task/Colour-bars-Display/REXX/colour-bars-display.rexx create mode 100644 Task/Colour-pinstripe-Display/Java/colour-pinstripe-display.java create mode 100644 Task/Combinations-with-repetitions/AWK/combinations-with-repetitions.awk create mode 100644 Task/Combinations-with-repetitions/Bracmat/combinations-with-repetitions.bracmat create mode 100644 Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions.clj create mode 100644 Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions.coffee create mode 100644 Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions.erl create mode 100644 Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions.js create mode 100644 Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia create mode 100644 Task/Combinations-with-repetitions/Lua/combinations-with-repetitions.lua create mode 100644 Task/Combinations-with-repetitions/PHP/combinations-with-repetitions.php rename Task/Combinations-with-repetitions/Perl/{combinations-with-repetitions.pl => combinations-with-repetitions-1.pl} (100%) create mode 100644 Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-2.pl create mode 100644 Task/Combinations/AppleScript/combinations.applescript create mode 100644 Task/Combinations/CoffeeScript/combinations.coffee create mode 100644 Task/Combinations/Eiffel/combinations-1.e create mode 100644 Task/Combinations/Eiffel/combinations-2.e rename Task/Combinations/Erlang/{combinations.erl => combinations-1.erl} (100%) create mode 100644 Task/Combinations/Erlang/combinations-2.erl create mode 100644 Task/Combinations/Maple/combinations.maple create mode 100644 Task/Combinations/Perl-6/combinations-3.pl6 create mode 100644 Task/Combinations/Perl/combinations-1.pl create mode 100644 Task/Combinations/Perl/combinations-2.pl create mode 100644 Task/Combinations/Perl/combinations-3.pl delete mode 100644 Task/Combinations/Perl/combinations.pl create mode 100644 Task/Combinations/Scala/combinations-3.scala create mode 100644 Task/Combinations/Scala/combinations-4.scala rename Task/Command-line-arguments/TXR/{command-line-arguments.txr => command-line-arguments-1.txr} (100%) create mode 100644 Task/Command-line-arguments/TXR/command-line-arguments-2.txr create mode 100644 Task/Comments/ALGOL-60/comments.alg create mode 100644 Task/Comments/ALGOL-W/comments.alg create mode 100644 Task/Comments/Elixir/comments.elixir rename Task/Comments/JCL/{comments.jcl => comments-1.jcl} (100%) create mode 100644 Task/Comments/JCL/comments-2.jcl create mode 100644 Task/Comments/Oberon-2/comments.oberon-2 rename Task/Comments/PL-I/{comments.pli => comments-1.pli} (100%) create mode 100644 Task/Comments/PL-I/comments-2.pli create mode 100644 Task/Comments/SQL/comments-1.sql create mode 100644 Task/Comments/SQL/comments-2.sql create mode 100644 Task/Comments/SQL/comments-3.sql create mode 100644 Task/Comments/Scilab/comments.scilab create mode 100644 Task/Comments/Simula/comments.simula create mode 100644 Task/Comments/TorqueScript/comments.torque create mode 100644 Task/Comments/VBA/comments.vba create mode 100644 Task/Comments/VBScript/comments.vb create mode 100644 Task/Comments/Vim-Script/comments.vim create mode 100644 Task/Compile-time-calculation/Oberon-2/compile-time-calculation.oberon-2 create mode 100644 Task/Compound-data-type/Euphoria/compound-data-type.euphoria create mode 100644 Task/Compound-data-type/UNIX-Shell/compound-data-type-1.sh create mode 100644 Task/Compound-data-type/UNIX-Shell/compound-data-type-2.sh create mode 100644 Task/Compound-data-type/Vim-Script/compound-data-type.vim create mode 100644 Task/Concurrent-computing/PowerShell/concurrent-computing-1.psh create mode 100644 Task/Concurrent-computing/PowerShell/concurrent-computing-2.psh create mode 100644 Task/Concurrent-computing/Prolog/concurrent-computing.pro create mode 100644 Task/Conditional-structures/360-Assembly/conditional-structures.360 create mode 100644 Task/Conditional-structures/AWK/conditional-structures-3.awk create mode 100644 Task/Conditional-structures/Babel/conditional-structures-1.pb create mode 100644 Task/Conditional-structures/Babel/conditional-structures-2.pb create mode 100644 Task/Conditional-structures/Babel/conditional-structures-3.pb create mode 100644 Task/Conditional-structures/Batch-File/conditional-structures-1.bat create mode 100644 Task/Conditional-structures/Batch-File/conditional-structures-2.bat create mode 100644 Task/Conditional-structures/PL-I/conditional-structures-4.pli create mode 100644 Task/Conditional-structures/Scala/conditional-structures.scala create mode 100644 Task/Conditional-structures/TI-83-BASIC/conditional-structures-1.ti-83 create mode 100644 Task/Conditional-structures/TI-83-BASIC/conditional-structures-2.ti-83 create mode 100644 Task/Conditional-structures/TI-83-BASIC/conditional-structures-3.ti-83 create mode 100644 Task/Conditional-structures/TI-83-BASIC/conditional-structures-4.ti-83 create mode 100644 Task/Conditional-structures/VBScript/conditional-structures-1.vb create mode 100644 Task/Conditional-structures/VBScript/conditional-structures-2.vb create mode 100644 Task/Conditional-structures/VBScript/conditional-structures-3.vb delete mode 100644 Task/Conditional-structures/VBScript/conditional-structures.vb create mode 100644 Task/Constrained-genericity/Racket/constrained-genericity.rkt create mode 100644 Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir create mode 100644 Task/Constrained-random-points-on-a-circle/Falcon/constrained-random-points-on-a-circle.falcon create mode 100644 Task/Constrained-random-points-on-a-circle/Maple/constrained-random-points-on-a-circle.maple rename Task/Constrained-random-points-on-a-circle/PL-I/{constrained-random-points-on-a-circle.pli => constrained-random-points-on-a-circle-1.pli} (100%) create mode 100644 Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-2.pli create mode 100644 Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx create mode 100644 Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-4.rexx rename Task/Constrained-random-points-on-a-circle/Ruby/{constrained-random-points-on-a-circle.rb => constrained-random-points-on-a-circle-1.rb} (51%) create mode 100644 Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb create mode 100644 Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Perl/continued-fraction-arithmetic-construct-from-rational-number.pl create mode 100644 Task/Continued-fraction/AutoHotkey/continued-fraction-1.ahk create mode 100644 Task/Continued-fraction/AutoHotkey/continued-fraction-2.ahk create mode 100644 Task/Continued-fraction/AutoHotkey/continued-fraction-3.ahk create mode 100644 Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 rename Task/Conways-Game-of-Life/BASIC256/{conways-game-of-life.basic256 => conways-game-of-life-2.basic256} (87%) create mode 100644 Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia create mode 100644 Task/Conways-Game-of-Life/Pascal/conways-game-of-life.pascal create mode 100644 Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx create mode 100644 Task/Conways-Game-of-Life/REXX/conways-game-of-life-2.rexx delete mode 100644 Task/Conways-Game-of-Life/REXX/conways-game-of-life.rexx create mode 100644 Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit create mode 100644 Task/Copy-a-string/Babel/copy-a-string.pb create mode 100644 Task/Copy-a-string/Ruby/copy-a-string-1.rb create mode 100644 Task/Copy-a-string/Ruby/copy-a-string-2.rb delete mode 100644 Task/Copy-a-string/Ruby/copy-a-string.rb create mode 100644 Task/Copy-a-string/Vim-Script/copy-a-string.vim create mode 100644 Task/Count-in-factors/C++/count-in-factors.cpp create mode 100644 Task/Count-in-factors/Eiffel/count-in-factors.e create mode 100644 Task/Count-in-factors/Perl/count-in-factors-1.pl create mode 100644 Task/Count-in-factors/Perl/count-in-factors-2.pl create mode 100644 Task/Count-in-factors/Perl/count-in-factors-3.pl create mode 100644 Task/Count-in-factors/Perl/count-in-factors-4.pl create mode 100644 Task/Count-in-factors/Perl/count-in-factors-5.pl create mode 100644 Task/Count-in-factors/Perl/count-in-factors-6.pl delete mode 100644 Task/Count-in-factors/Perl/count-in-factors.pl create mode 100644 Task/Count-in-octal/00META.yaml create mode 100644 Task/Count-in-octal/Vim-Script/count-in-octal.vim rename Task/Count-occurrences-of-a-substring/BASIC/{count-occurrences-of-a-substring.basic => count-occurrences-of-a-substring-1.basic} (100%) create mode 100644 Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-2.basic create mode 100644 Task/Count-occurrences-of-a-substring/PARI-GP/count-occurrences-of-a-substring.pari create mode 100644 Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-1.pro create mode 100644 Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-2.pro rename Task/Count-occurrences-of-a-substring/Scala/{count-occurrences-of-a-substring.scala => count-occurrences-of-a-substring-1.scala} (71%) create mode 100644 Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala create mode 100644 Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala create mode 100644 Task/Count-occurrences-of-a-substring/Scheme/count-occurrences-of-a-substring.ss create mode 100644 Task/Count-the-coins/ALGOL-68/count-the-coins.alg create mode 100644 Task/Count-the-coins/Clojure/count-the-coins.clj create mode 100644 Task/Count-the-coins/Common-Lisp/count-the-coins-1.lisp create mode 100644 Task/Count-the-coins/Common-Lisp/count-the-coins-2.lisp delete mode 100644 Task/Count-the-coins/Common-Lisp/count-the-coins.lisp create mode 100644 Task/Count-the-coins/D/count-the-coins-5.d create mode 100644 Task/Count-the-coins/REXX/count-the-coins-1.rexx create mode 100644 Task/Count-the-coins/REXX/count-the-coins-2.rexx delete mode 100644 Task/Count-the-coins/REXX/count-the-coins.rexx create mode 100644 Task/Create-a-file-on-magnetic-tape/COBOL/create-a-file-on-magnetic-tape.cobol create mode 100644 Task/Create-a-file-on-magnetic-tape/Clojure/create-a-file-on-magnetic-tape.clj create mode 100644 Task/Create-a-file-on-magnetic-tape/Go/create-a-file-on-magnetic-tape.go create mode 100644 Task/Create-a-file-on-magnetic-tape/Icon/create-a-file-on-magnetic-tape.icon create mode 100644 Task/Create-a-file/Maple/create-a-file.maple create mode 100644 Task/Create-a-file/Scala/create-a-file.scala create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-5.c create mode 100644 Task/Create-a-two-dimensional-array-at-runtime/Vim-Script/create-a-two-dimensional-array-at-runtime.vim create mode 100644 Task/Create-an-HTML-table/Clojure/create-an-html-table.clj create mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh create mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh create mode 100644 Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh create mode 100644 Task/Create-an-HTML-table/PureBasic/create-an-html-table-1.purebasic create mode 100644 Task/Create-an-HTML-table/PureBasic/create-an-html-table-2.purebasic create mode 100644 Task/Create-an-HTML-table/Scala/create-an-html-table.scala create mode 100644 Task/Create-an-HTML-table/UNIX-Shell/create-an-html-table.sh create mode 100644 Task/Create-an-HTML-table/XSLT/create-an-html-table-1.xslt create mode 100644 Task/Create-an-HTML-table/XSLT/create-an-html-table-2.xslt create mode 100644 Task/Create-an-HTML-table/XSLT/create-an-html-table-3.xslt create mode 100644 Task/Cut-a-rectangle/Go/cut-a-rectangle.go create mode 100644 Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 create mode 100644 Task/Cut-a-rectangle/Perl/cut-a-rectangle.pl create mode 100644 Task/Cut-a-rectangle/Ruby/cut-a-rectangle-1.rb create mode 100644 Task/Cut-a-rectangle/Ruby/cut-a-rectangle-2.rb create mode 100644 Task/DNS-query/R/dns-query-1.r create mode 100644 Task/DNS-query/R/dns-query-2.r create mode 100644 Task/DNS-query/Scala/dns-query.scala create mode 100644 Task/Date-format/Prolog/date-format.pro create mode 100644 Task/Date-format/REXX/date-format-1.rexx create mode 100644 Task/Date-format/REXX/date-format-2.rexx create mode 100644 Task/Date-format/REXX/date-format-3.rexx delete mode 100644 Task/Date-format/REXX/date-format.rexx create mode 100644 Task/Date-format/Smalltalk/date-format.st create mode 100644 Task/Date-manipulation/J/date-manipulation-1.j create mode 100644 Task/Date-manipulation/J/date-manipulation-2.j create mode 100644 Task/Date-manipulation/Ruby/date-manipulation-3.rb create mode 100644 Task/Day-of-the-week/00META.yaml create mode 100644 Task/Day-of-the-week/Bracmat/day-of-the-week.bracmat create mode 100644 Task/Deal-cards-for-FreeCell/Fortran/deal-cards-for-freecell.f create mode 100644 Task/Deal-cards-for-FreeCell/Seed7/deal-cards-for-freecell.seed7 create mode 100644 Task/Death-Star/JavaScript/death-star.js create mode 100644 Task/Deconvolution-1D/C/deconvolution-1d.c create mode 100644 Task/Deepcopy/Babel/deepcopy.pb create mode 100644 Task/Define-a-primitive-data-type/Clojure/define-a-primitive-data-type.clj create mode 100644 Task/Define-a-primitive-data-type/Scala/define-a-primitive-data-type.scala create mode 100644 Task/Define-a-primitive-data-type/UNIX-Shell/define-a-primitive-data-type.sh rename Task/Delegates/Java/{delegates.java => delegates-1.java} (100%) create mode 100644 Task/Delegates/Java/delegates-2.java create mode 100644 Task/Delegates/Java/delegates-3.java create mode 100644 Task/Delegates/Java/delegates-4.java create mode 100644 Task/Delegates/Java/delegates-5.java create mode 100644 Task/Delegates/Java/delegates-6.java create mode 100644 Task/Delegates/Racket/delegates.rkt create mode 100644 Task/Delete-a-file/Groovy/delete-a-file.groovy create mode 100644 Task/Delete-a-file/Maple/delete-a-file.maple create mode 100644 Task/Delete-a-file/NewLISP/delete-a-file.newlisp create mode 100644 Task/Delete-a-file/Seed7/delete-a-file.seed7 create mode 100644 Task/Detect-division-by-zero/00META.yaml create mode 100644 Task/Detect-division-by-zero/Emacs-Lisp/detect-division-by-zero.l create mode 100644 Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-1.pari rename Task/Detect-division-by-zero/PARI-GP/{detect-division-by-zero.pari => detect-division-by-zero-2.pari} (100%) create mode 100644 Task/Determine-if-a-string-is-numeric/Batch-File/determine-if-a-string-is-numeric.bat create mode 100644 Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-1.pro create mode 100644 Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-2.pro create mode 100644 Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-3.pro create mode 100644 Task/Determine-if-a-string-is-numeric/Seed7/determine-if-a-string-is-numeric.seed7 create mode 100644 Task/Digital-root/Ada/digital-root-1.ada create mode 100644 Task/Digital-root/Ada/digital-root-2.ada create mode 100644 Task/Digital-root/Ada/digital-root-3.ada delete mode 100644 Task/Digital-root/Ada/digital-root.ada create mode 100644 Task/Digital-root/Eiffel/digital-root.e create mode 100644 Task/Digital-root/Fortran/digital-root.f create mode 100644 Task/Digital-root/JavaScript/digital-root.js create mode 100644 Task/Digital-root/Lua/digital-root.lua rename Task/Digital-root/PL-I/{digital-root.pli => digital-root-1.pli} (100%) create mode 100644 Task/Digital-root/PL-I/digital-root-2.pli create mode 100644 Task/Dinesmans-multiple-dwelling-problem/00META.yaml create mode 100644 Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem.c create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-1.pl6 rename Task/Dinesmans-multiple-dwelling-problem/Perl-6/{dinesmans-multiple-dwelling-problem.pl6 => dinesmans-multiple-dwelling-problem-2.pl6} (58%) create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-1.pl create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-2.pl create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-3.scala create mode 100644 Task/Discordian-date/00META.yaml create mode 100644 Task/Discordian-date/Clojure/discordian-date.clj create mode 100644 Task/Discordian-date/Java/discordian-date.java create mode 100644 Task/Discordian-date/Perl/discordian-date.pl create mode 100644 Task/Documentation/Emacs-Lisp/documentation-1.l create mode 100644 Task/Documentation/Emacs-Lisp/documentation-2.l create mode 100644 Task/Dot-product/Eiffel/dot-product.e rename Task/Dot-product/JavaScript/{dot-product.js => dot-product-1.js} (100%) create mode 100644 Task/Dot-product/JavaScript/dot-product-2.js create mode 100644 Task/Dot-product/REBOL/dot-product.rebol create mode 100644 Task/Dot-product/Rust/dot-product.rust rename Task/Doubly-linked-list-Definition/Go/{doubly-linked-list-definition.go => doubly-linked-list-definition-1.go} (100%) create mode 100644 Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-2.go rename Task/Doubly-linked-list-Element-definition/Go/{doubly-linked-list-element-definition.go => doubly-linked-list-element-definition-1.go} (100%) create mode 100644 Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-2.go create mode 100644 Task/Dragon-curve/PARI-GP/dragon-curve-1.pari create mode 100644 Task/Dragon-curve/PARI-GP/dragon-curve-2.pari create mode 100644 Task/Dragon-curve/Perl/dragon-curve.pl create mode 100644 Task/Dragon-curve/R/dragon-curve.r create mode 100644 Task/Dragon-curve/Visual-Basic-.NET/dragon-curve.visual create mode 100644 Task/Dragon-curve/Visual-Basic/dragon-curve.vb create mode 100644 Task/Draw-a-cuboid/C/draw-a-cuboid.c create mode 100644 Task/Draw-a-cuboid/Clojure/draw-a-cuboid.clj create mode 100644 Task/Draw-a-cuboid/Java/draw-a-cuboid.java rename Task/Draw-a-cuboid/Python/{draw-a-cuboid.py => draw-a-cuboid-1.py} (100%) create mode 100644 Task/Draw-a-cuboid/Python/draw-a-cuboid-2.py create mode 100644 Task/Draw-a-cuboid/Python/draw-a-cuboid-3.py create mode 100644 Task/Draw-a-cuboid/Retro/draw-a-cuboid.retro create mode 100644 Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb create mode 100644 Task/Draw-a-sphere/Clojure/draw-a-sphere.clj create mode 100644 Task/Draw-a-sphere/JavaScript/draw-a-sphere.js create mode 100644 Task/Draw-a-sphere/Python/draw-a-sphere-3.py create mode 100644 Task/Draw-a-sphere/Python/draw-a-sphere-4.py create mode 100644 Task/Draw-a-sphere/Python/draw-a-sphere-5.py create mode 100644 Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-3.d create mode 100644 Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java create mode 100644 Task/Dutch-national-flag-problem/Scala/dutch-national-flag-problem.scala create mode 100644 Task/Dynamic-variable-names/Emacs-Lisp/dynamic-variable-names.l rename Task/Echo-server/Haskell/{echo-server.hs => echo-server-1.hs} (100%) create mode 100644 Task/Echo-server/Haskell/echo-server-2.hs create mode 100644 Task/Element-wise-operations/Haskell/element-wise-operations-1.hs create mode 100644 Task/Element-wise-operations/Haskell/element-wise-operations-2.hs create mode 100644 Task/Element-wise-operations/MATLAB/element-wise-operations.m create mode 100644 Task/Empty-directory/C-sharp/empty-directory.cs create mode 100644 Task/Empty-directory/Ruby/empty-directory.rb create mode 100644 Task/Empty-program/360-Assembly/empty-program.360 create mode 100644 Task/Empty-program/ALGOL-60/empty-program.alg rename Task/Empty-program/AWK/{empty-program.awk => empty-program-1.awk} (100%) create mode 100644 Task/Empty-program/AWK/empty-program-2.awk create mode 100644 Task/Empty-program/OOC/empty-program.ooc create mode 100644 Task/Empty-program/REXX/empty-program-5.rexx create mode 100644 Task/Empty-program/Scilab/empty-program.scilab create mode 100644 Task/Empty-program/Simula/empty-program.simula create mode 100644 Task/Empty-program/Visual-Basic/empty-program.vb create mode 100644 Task/Empty-string/Elixir/empty-string.elixir create mode 100644 Task/Empty-string/JavaScript/empty-string-1.js create mode 100644 Task/Empty-string/JavaScript/empty-string-2.js create mode 100644 Task/Empty-string/JavaScript/empty-string-3.js create mode 100644 Task/Empty-string/Maple/empty-string.maple create mode 100644 Task/Empty-string/Prolog/empty-string.pro create mode 100644 Task/Empty-string/Smalltalk/empty-string.st create mode 100644 Task/Empty-string/Standard-ML/empty-string.ml create mode 100644 Task/Enforced-immutability/00META.yaml create mode 100644 Task/Enforced-immutability/Fortran/enforced-immutability-1.f create mode 100644 Task/Enforced-immutability/Fortran/enforced-immutability-2.f create mode 100644 Task/Enforced-immutability/PL-I/enforced-immutability.pli rename Task/Enforced-immutability/Ruby/{enforced-immutability.rb => enforced-immutability-1.rb} (85%) create mode 100644 Task/Enforced-immutability/Ruby/enforced-immutability-2.rb create mode 100644 Task/Entropy/ALGOL-68/entropy.alg create mode 100644 Task/Entropy/C-sharp/entropy-1.cs create mode 100644 Task/Entropy/C-sharp/entropy-2.cs create mode 100644 Task/Entropy/JavaScript/entropy.js create mode 100644 Task/Entropy/Julia/entropy.julia create mode 100644 Task/Entropy/OCaml/entropy.ocaml create mode 100644 Task/Entropy/PL-I/entropy.pli create mode 100644 Task/Entropy/Pascal/entropy.pascal rename Task/Enumerations/C++/{enumerations.cpp => enumerations-1.cpp} (100%) create mode 100644 Task/Enumerations/C++/enumerations-2.cpp create mode 100644 Task/Enumerations/C++/enumerations-3.cpp create mode 100644 Task/Enumerations/C++/enumerations-4.cpp rename Task/Enumerations/C/{enumerations.c => enumerations-1.c} (100%) create mode 100644 Task/Enumerations/C/enumerations-2.c create mode 100644 Task/Enumerations/Go/enumerations-3.go create mode 100644 Task/Enumerations/Go/enumerations-4.go create mode 100644 Task/Enumerations/Objective-C/enumerations.m create mode 100644 Task/Enumerations/Python/enumerations-3.py create mode 100644 Task/Enumerations/Ruby/enumerations-1.rb create mode 100644 Task/Enumerations/Ruby/enumerations-2.rb delete mode 100644 Task/Enumerations/Ruby/enumerations.rb create mode 100644 Task/Environment-variables/Make/environment-variables-1.make create mode 100644 Task/Environment-variables/Make/environment-variables-2.make create mode 100644 Task/Environment-variables/Make/environment-variables-3.make rename Task/Environment-variables/Perl/{environment-variables.pl => environment-variables-1.pl} (100%) create mode 100644 Task/Environment-variables/Perl/environment-variables-2.pl create mode 100644 Task/Environment-variables/Smalltalk/environment-variables.st create mode 100644 Task/Equilibrium-index/Prolog/equilibrium-index-1.pro create mode 100644 Task/Equilibrium-index/Prolog/equilibrium-index-2.pro create mode 100644 Task/Equilibrium-index/REXX/equilibrium-index-1.rexx create mode 100644 Task/Equilibrium-index/REXX/equilibrium-index-2.rexx delete mode 100644 Task/Equilibrium-index/REXX/equilibrium-index.rexx create mode 100644 Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication.as create mode 100644 Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e create mode 100644 Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-4.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia create mode 100644 Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia create mode 100644 Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-1.pro create mode 100644 Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-2.pro create mode 100644 Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-3.pro create mode 100644 Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-4.pro create mode 100644 Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust create mode 100644 Task/Euler-method/JavaScript/euler-method.js create mode 100644 Task/Euler-method/R/euler-method.r create mode 100644 Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients.c create mode 100644 Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients.coffee create mode 100644 Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f create mode 100644 Task/Evaluate-binomial-coefficients/Haskell/evaluate-binomial-coefficients-4.hs create mode 100644 Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-3.java create mode 100644 Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients.pli create mode 100644 Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-1.pl create mode 100644 Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-2.pl create mode 100644 Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-3.pl delete mode 100644 Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl create mode 100644 Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients.r rename Task/Evaluate-binomial-coefficients/REXX/{evaluate-binomial-coefficients.rexx => evaluate-binomial-coefficients-1.rexx} (58%) create mode 100644 Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx create mode 100644 Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss create mode 100644 Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-1.seed7 create mode 100644 Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-2.seed7 delete mode 100644 Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients.seed7 create mode 100644 Task/Even-or-odd/6502-Assembly/even-or-odd.6502 create mode 100644 Task/Even-or-odd/ALGOL-68/even-or-odd.alg create mode 100644 Task/Even-or-odd/ColdFusion/even-or-odd.cfm create mode 100644 Task/Even-or-odd/JavaScript/even-or-odd-1.js rename Task/Even-or-odd/JavaScript/{even-or-odd.js => even-or-odd-2.js} (100%) create mode 100644 Task/Even-or-odd/M4/even-or-odd.m4 create mode 100644 Task/Even-or-odd/Maple/even-or-odd.maple create mode 100644 Task/Even-or-odd/NewLISP/even-or-odd.newlisp create mode 100644 Task/Even-or-odd/OOC/even-or-odd.ooc create mode 100644 Task/Even-or-odd/Rust/even-or-odd-1.rust create mode 100644 Task/Even-or-odd/Rust/even-or-odd-2.rust create mode 100644 Task/Events/Perl-6/events.pl6 create mode 100644 Task/Evolutionary-algorithm/ColdFusion/evolutionary-algorithm.cfm create mode 100644 Task/Evolutionary-algorithm/OoRexx/evolutionary-algorithm.rexx create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00META.yaml create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call.c rename Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/{exceptions-catch-an-exception-thrown-in-a-nested-call.go => exceptions-catch-an-exception-thrown-in-a-nested-call-1.go} (100%) create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-2.go create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Scala/exceptions-catch-an-exception-thrown-in-a-nested-call.scala create mode 100644 Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Seed7/exceptions-catch-an-exception-thrown-in-a-nested-call.seed7 create mode 100644 Task/Exceptions/Logtalk/exceptions.logtalk create mode 100644 Task/Exceptions/Scala/exceptions.scala rename Task/Execute-Brain----/PicoLisp/{execute-brain----.l => execute-brain-----1.l} (100%) create mode 100644 Task/Execute-Brain----/PicoLisp/execute-brain-----2.l create mode 100644 Task/Execute-HQ9+/Haxe/execute-hq9+.haxe create mode 100644 Task/Execute-SNUSP/J/execute-snusp-1.j create mode 100644 Task/Execute-SNUSP/J/execute-snusp-2.j create mode 100644 Task/Execute-a-Markov-algorithm/Java/execute-a-markov-algorithm.java create mode 100644 Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria create mode 100644 Task/Execute-a-system-command/NewLISP/execute-a-system-command.newlisp rename Task/Exponentiation-operator/C/{exponentiation-operator.c => exponentiation-operator-1.c} (100%) create mode 100644 Task/Exponentiation-operator/C/exponentiation-operator-2.c rename Task/Exponentiation-operator/Perl/{exponentiation-operator.pl => exponentiation-operator-1.pl} (100%) create mode 100644 Task/Exponentiation-operator/Perl/exponentiation-operator-2.pl create mode 100644 Task/Exponentiation-operator/Prolog/exponentiation-operator-1.pro create mode 100644 Task/Exponentiation-operator/Prolog/exponentiation-operator-2.pro create mode 100644 Task/Exponentiation-operator/Prolog/exponentiation-operator-3.pro create mode 100644 Task/Exponentiation-operator/Prolog/exponentiation-operator-4.pro create mode 100644 Task/Extend-your-language/Ada/extend-your-language.ada create mode 100644 Task/Extend-your-language/Mathematica/extend-your-language-1.math create mode 100644 Task/Extend-your-language/Mathematica/extend-your-language-2.math delete mode 100644 Task/Extend-your-language/Mathematica/extend-your-language.math create mode 100644 Task/Extend-your-language/REXX/extend-your-language-1.rexx create mode 100644 Task/Extend-your-language/REXX/extend-your-language-2.rexx create mode 100644 Task/Extreme-floating-point-values/00META.yaml create mode 100644 Task/Extreme-floating-point-values/Clojure/extreme-floating-point-values.clj create mode 100644 Task/Extreme-floating-point-values/Eiffel/extreme-floating-point-values.e create mode 100644 Task/Factorial/360-Assembly/factorial.360 create mode 100644 Task/Factorial/Babel/factorial-1.pb create mode 100644 Task/Factorial/Babel/factorial-2.pb delete mode 100644 Task/Factorial/Babel/factorial.pb create mode 100644 Task/Factorial/Elixir/factorial.elixir rename Task/Factorial/Forth/{factorial.fth => factorial-1.fth} (100%) create mode 100644 Task/Factorial/Forth/factorial-2.fth create mode 100644 Task/Factorial/Haskell/factorial-6.hs create mode 100644 Task/Factorial/Haskell/factorial-7.hs create mode 100644 Task/Factorial/Mercury/factorial-1.mercury create mode 100644 Task/Factorial/Mercury/factorial-2.mercury create mode 100644 Task/Factorial/Mercury/factorial-3.mercury create mode 100644 Task/Factorial/Perl/factorial-4.pl create mode 100644 Task/Factorial/Perl/factorial-5.pl create mode 100644 Task/Factorial/Perl/factorial-6.pl create mode 100644 Task/Factorial/Perl/factorial-7.pl rename Task/Factorial/Scilab/{factorial.scilab => factorial-1.scilab} (100%) create mode 100644 Task/Factorial/Scilab/factorial-2.scilab create mode 100644 Task/Factorial/Scilab/factorial-3.scilab create mode 100644 Task/Factorial/TI-83-BASIC/factorial.ti-83 create mode 100644 Task/Factors-of-a-Mersenne-number/Bracmat/factors-of-a-mersenne-number.bracmat create mode 100644 Task/Factors-of-an-integer/Befunge/factors-of-an-integer.bf create mode 100644 Task/Factors-of-an-integer/Frink/factors-of-an-integer.frink create mode 100644 Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs create mode 100644 Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs create mode 100644 Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-1.max create mode 100644 Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-2.max rename Task/Factors-of-an-integer/Pascal/{factors-of-an-integer.pascal => factors-of-an-integer-1.pascal} (100%) create mode 100644 Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal rename Task/Factors-of-an-integer/Perl/{factors-of-an-integer.pl => factors-of-an-integer-1.pl} (71%) create mode 100644 Task/Factors-of-an-integer/Perl/factors-of-an-integer-2.pl create mode 100644 Task/Factors-of-an-integer/Perl/factors-of-an-integer-3.pl create mode 100644 Task/Factors-of-an-integer/Prolog/factors-of-an-integer-1.pro create mode 100644 Task/Factors-of-an-integer/Prolog/factors-of-an-integer-2.pro create mode 100644 Task/Factors-of-an-integer/Prolog/factors-of-an-integer-3.pro delete mode 100644 Task/Factors-of-an-integer/Prolog/factors-of-an-integer.pro create mode 100644 Task/Fast-Fourier-transform/C/fast-fourier-transform.c create mode 100644 Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-1.js create mode 100644 Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-2.js create mode 100644 Task/Fast-Fourier-transform/Racket/fast-fourier-transform.rkt create mode 100644 Task/Fast-Fourier-transform/Scala/fast-fourier-transform-1.scala create mode 100644 Task/Fast-Fourier-transform/Scala/fast-fourier-transform-2.scala create mode 100644 Task/Fast-Fourier-transform/Scala/fast-fourier-transform-3.scala delete mode 100644 Task/Fast-Fourier-transform/Scala/fast-fourier-transform.scala create mode 100644 Task/Fibonacci-n-step-number-sequences/Bracmat/fibonacci-n-step-number-sequences.bracmat rename Task/Fibonacci-n-step-number-sequences/C++/{fibonacci-n-step-number-sequences.cpp => fibonacci-n-step-number-sequences-1.cpp} (100%) create mode 100644 Task/Fibonacci-n-step-number-sequences/C++/fibonacci-n-step-number-sequences-2.cpp create mode 100644 Task/Fibonacci-n-step-number-sequences/C-sharp/fibonacci-n-step-number-sequences.cs create mode 100644 Task/Fibonacci-n-step-number-sequences/Common-Lisp/fibonacci-n-step-number-sequences.lisp create mode 100644 Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-4.d create mode 100644 Task/Fibonacci-n-step-number-sequences/Fortran/fibonacci-n-step-number-sequences.f create mode 100644 Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-1.icon create mode 100644 Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-2.icon rename Task/Fibonacci-n-step-number-sequences/Pascal/{fibonacci-n-step-number-sequences.pascal => fibonacci-n-step-number-sequences-1.pascal} (100%) create mode 100644 Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-2.pascal create mode 100644 Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-1.rust create mode 100644 Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-2.rust delete mode 100644 Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust create mode 100644 Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala create mode 100644 Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala create mode 100644 Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala create mode 100644 Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-4.scala create mode 100644 Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 create mode 100644 Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl create mode 100644 Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl create mode 100644 Task/Fibonacci-sequence/ATS/fibonacci-sequence-1.ats create mode 100644 Task/Fibonacci-sequence/ATS/fibonacci-sequence-2.ats create mode 100644 Task/Fibonacci-sequence/ATS/fibonacci-sequence-3.ats create mode 100644 Task/Fibonacci-sequence/ATS/fibonacci-sequence-4.ats create mode 100644 Task/Fibonacci-sequence/Clojure/fibonacci-sequence-7.clj create mode 100644 Task/Fibonacci-sequence/Clojure/fibonacci-sequence-8.clj create mode 100644 Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp create mode 100644 Task/Fibonacci-sequence/Fortran/fibonacci-sequence-4.f create mode 100644 Task/Fibonacci-sequence/Fortran/fibonacci-sequence-5.f create mode 100644 Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go create mode 100644 Task/Fibonacci-sequence/Java/fibonacci-sequence-5.java create mode 100644 Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js create mode 100644 Task/Fibonacci-sequence/Lush/fibonacci-sequence.lush create mode 100644 Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-3.m create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-3.math create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-4.math create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-5.math create mode 100644 Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-6.math create mode 100644 Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-12.pari create mode 100644 Task/Fibonacci-sequence/Pascal/fibonacci-sequence-3.pascal create mode 100644 Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl create mode 100644 Task/Fibonacci-sequence/Python/fibonacci-sequence-10.py create mode 100644 Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py create mode 100644 Task/Fibonacci-sequence/Racket/fibonacci-sequence-1.rkt create mode 100644 Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt delete mode 100644 Task/Fibonacci-sequence/Racket/fibonacci-sequence.rkt create mode 100644 Task/Fibonacci-sequence/SQL/fibonacci-sequence.sql create mode 100644 Task/Fibonacci-sequence/Scilab/fibonacci-sequence.scilab create mode 100644 Task/Fibonacci-sequence/Visual-Basic/fibonacci-sequence.vb create mode 100644 Task/File-modification-time/AWK/file-modification-time.awk create mode 100644 Task/File-modification-time/Emacs-Lisp/file-modification-time.l create mode 100644 Task/File-modification-time/NewLISP/file-modification-time.newlisp create mode 100644 Task/File-modification-time/Scala/file-modification-time.scala create mode 100644 Task/File-size/AWK/file-size.awk create mode 100644 Task/File-size/Lua/file-size-1.lua create mode 100644 Task/File-size/Lua/file-size-2.lua delete mode 100644 Task/File-size/Lua/file-size.lua create mode 100644 Task/File-size/NewLISP/file-size.newlisp create mode 100644 Task/File-size/Scala/file-size.scala create mode 100644 Task/File-size/UNIX-Shell/file-size-5.sh rename Task/Filter/AWK/{filter.awk => filter-1.awk} (91%) create mode 100644 Task/Filter/AWK/filter-2.awk create mode 100644 Task/Filter/CoffeeScript/filter.coffee create mode 100644 Task/Filter/Lua/filter-1.lua create mode 100644 Task/Filter/Lua/filter-2.lua delete mode 100644 Task/Filter/Lua/filter.lua create mode 100644 Task/Filter/Rust/filter.rust create mode 100644 Task/Find-common-directory-path/00META.yaml create mode 100644 Task/Find-common-directory-path/Perl/find-common-directory-path-1.pl create mode 100644 Task/Find-common-directory-path/Perl/find-common-directory-path-2.pl create mode 100644 Task/Find-common-directory-path/Perl/find-common-directory-path-3.pl delete mode 100644 Task/Find-common-directory-path/Perl/find-common-directory-path.pl create mode 100644 Task/Find-common-directory-path/Scala/find-common-directory-path-1.scala create mode 100644 Task/Find-common-directory-path/Scala/find-common-directory-path-2.scala create mode 100644 Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl/find-largest-left-truncatable-prime-in-a-given-base.pl create mode 100644 Task/Find-limit-of-recursion/Fortran/find-limit-of-recursion.f create mode 100644 Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation.coffee create mode 100644 Task/Find-the-missing-permutation/R/find-the-missing-permutation.r create mode 100644 Task/Find-the-missing-permutation/RapidQ/find-the-missing-permutation.rapidq create mode 100644 Task/Find-the-missing-permutation/Seed7/find-the-missing-permutation.seed7 create mode 100644 Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-1.pl create mode 100644 Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-2.pl create mode 100644 Task/First-class-functions/AppleScript/first-class-functions.applescript create mode 100644 Task/First-class-functions/Bracmat/first-class-functions.bracmat create mode 100644 Task/First-class-functions/TXR/first-class-functions.txr create mode 100644 Task/Five-weekends/00META.yaml create mode 100644 Task/Five-weekends/AWK/five-weekends.awk create mode 100644 Task/Five-weekends/Racket/five-weekends.rkt create mode 100644 Task/Five-weekends/UNIX-Shell/five-weekends.sh rename Task/FizzBuzz/APL/{fizzbuzz.apl => fizzbuzz-1.apl} (100%) create mode 100644 Task/FizzBuzz/APL/fizzbuzz-2.apl create mode 100644 Task/FizzBuzz/C++/fizzbuzz-6.cpp create mode 100644 Task/FizzBuzz/C/fizzbuzz-5.c create mode 100644 Task/FizzBuzz/C/fizzbuzz-6.c create mode 100644 Task/FizzBuzz/Clojure/fizzbuzz-7.clj create mode 100644 Task/FizzBuzz/Clojure/fizzbuzz-8.clj create mode 100644 Task/FizzBuzz/ColdFusion/fizzbuzz.cfm create mode 100644 Task/FizzBuzz/Eiffel/fizzbuzz.e rename Task/FizzBuzz/Elixir/{fizzbuzz.elixir => fizzbuzz-1.elixir} (100%) create mode 100644 Task/FizzBuzz/Elixir/fizzbuzz-2.elixir create mode 100644 Task/FizzBuzz/Julia/fizzbuzz-4.julia create mode 100644 Task/FizzBuzz/Julia/fizzbuzz-5.julia create mode 100644 Task/FizzBuzz/Julia/fizzbuzz-6.julia create mode 100644 Task/FizzBuzz/Maple/fizzbuzz-1.maple create mode 100644 Task/FizzBuzz/Maple/fizzbuzz-2.maple create mode 100644 Task/FizzBuzz/Maple/fizzbuzz-3.maple create mode 100644 Task/FizzBuzz/Maple/fizzbuzz-4.maple create mode 100644 Task/FizzBuzz/Mirah/fizzbuzz-1.mirah rename Task/FizzBuzz/Mirah/{fizzbuzz.mirah => fizzbuzz-2.mirah} (51%) create mode 100644 Task/FizzBuzz/NewLISP/fizzbuzz.newlisp create mode 100644 Task/FizzBuzz/OCaml/fizzbuzz-1.ocaml create mode 100644 Task/FizzBuzz/OCaml/fizzbuzz-2.ocaml delete mode 100644 Task/FizzBuzz/OCaml/fizzbuzz.ocaml create mode 100644 Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 create mode 100644 Task/FizzBuzz/REXX/fizzbuzz-4.rexx create mode 100644 Task/FizzBuzz/Ruby/fizzbuzz-10.rb create mode 100644 Task/FizzBuzz/Ruby/fizzbuzz-11.rb create mode 100644 Task/FizzBuzz/Rust/fizzbuzz-6.rust create mode 100644 Task/FizzBuzz/Rust/fizzbuzz-7.rust create mode 100644 Task/FizzBuzz/Rust/fizzbuzz-8.rust rename Task/FizzBuzz/Scheme/{fizzbuzz.ss => fizzbuzz-1.ss} (100%) create mode 100644 Task/FizzBuzz/Scheme/fizzbuzz-2.ss create mode 100644 Task/FizzBuzz/Vim-Script/fizzbuzz.vim create mode 100644 Task/FizzBuzz/XSLT/fizzbuzz-1.xslt create mode 100644 Task/FizzBuzz/XSLT/fizzbuzz-2.xslt create mode 100644 Task/FizzBuzz/XSLT/fizzbuzz-3.xslt create mode 100644 Task/Flatten-a-list/Elixir/flatten-a-list.elixir create mode 100644 Task/Flatten-a-list/Mercury/flatten-a-list.mercury create mode 100644 Task/Flow-control-structures/Scala/flow-control-structures.scala create mode 100644 Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg create mode 100644 Task/Floyds-triangle/C-sharp/floyds-triangle.cs create mode 100644 Task/Forest-fire/Lua/forest-fire.lua create mode 100644 Task/Fork/J/fork.j create mode 100644 Task/Fork/NewLISP/fork.newlisp create mode 100644 Task/Fork/Scala/fork-1.scala create mode 100644 Task/Fork/Scala/fork-2.scala create mode 100644 Task/Formatted-numeric-output/Scheme/formatted-numeric-output.ss create mode 100644 Task/Forward-difference/HicEst/forward-difference.hicest create mode 100644 Task/Forward-difference/Julia/forward-difference.julia create mode 100644 Task/Forward-difference/MATLAB/forward-difference.m create mode 100644 Task/Four-bit-adder/Perl/four-bit-adder.pl create mode 100644 Task/Fractal-tree/BBC-BASIC/fractal-tree-1.bbc rename Task/Fractal-tree/BBC-BASIC/{fractal-tree.bbc => fractal-tree-2.bbc} (83%) create mode 100644 Task/Function-composition/AppleScript/function-composition.applescript create mode 100644 Task/Function-composition/C++/function-composition-4.cpp rename Task/Function-composition/CoffeeScript/{function-composition.coffee => function-composition-1.coffee} (78%) create mode 100644 Task/Function-composition/CoffeeScript/function-composition-2.coffee create mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-1.l create mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-2.l create mode 100644 Task/Function-composition/Emacs-Lisp/function-composition-3.l create mode 100644 Task/Function-composition/UNIX-Shell/function-composition-4.sh create mode 100644 Task/Function-definition/Eiffel/function-definition.e create mode 100644 Task/Function-definition/Emacs-Lisp/function-definition-1.l create mode 100644 Task/Function-definition/Emacs-Lisp/function-definition-2.l create mode 100644 Task/Function-definition/Gnuplot/function-definition.gnuplot create mode 100644 Task/Function-definition/OOC/function-definition.ooc create mode 100644 Task/Function-definition/REALbasic/function-definition.realbasic create mode 100644 Task/Function-definition/X86-Assembly/function-definition-4.x86 create mode 100644 Task/Function-prototype/ALGOL-68/function-prototype.alg create mode 100644 Task/Function-prototype/C++/function-prototype.cpp create mode 100644 Task/Function-prototype/Clojure/function-prototype.clj create mode 100644 Task/GUI-Maximum-window-dimensions/Java/gui-maximum-window-dimensions.java create mode 100644 Task/GUI-component-interaction/J/gui-component-interaction-3.j create mode 100644 Task/GUI-component-interaction/Python/gui-component-interaction.py create mode 100644 Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-3.j rename Task/GUI-enabling-disabling-of-controls/Java/{gui-enabling-disabling-of-controls.java => gui-enabling-disabling-of-controls-1.java} (100%) create mode 100644 Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java create mode 100644 Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 create mode 100644 Task/Galton-box-animation/00META.yaml create mode 100644 Task/Gamma-function/360-Assembly/gamma-function.360 create mode 100644 Task/Gamma-function/C-sharp/gamma-function.cs create mode 100644 Task/Gamma-function/F-Sharp/gamma-function.fs rename Task/Gamma-function/Haskell/{gamma-function.hs => gamma-function-1.hs} (100%) create mode 100644 Task/Gamma-function/Haskell/gamma-function-2.hs create mode 100644 Task/Gamma-function/JavaScript/gamma-function.js rename Task/Gamma-function/Ruby/{gamma-function.rb => gamma-function-1.rb} (100%) create mode 100644 Task/Gamma-function/Ruby/gamma-function-2.rb create mode 100644 Task/Gamma-function/Scilab/gamma-function.scilab create mode 100644 Task/Gamma-function/TI-83-BASIC/gamma-function-1.ti-83 create mode 100644 Task/Gamma-function/TI-83-BASIC/gamma-function-2.ti-83 create mode 100644 Task/Generator-Exponential/D/generator-exponential-5.d create mode 100644 Task/Generator-Exponential/Julia/generator-exponential.julia create mode 100644 Task/Generator-Exponential/Ruby/generator-exponential-3.rb create mode 100644 Task/Generator-Exponential/Scheme/generator-exponential.ss create mode 100644 Task/Generic-swap/Aime/generic-swap.aime create mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-1.l create mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-2.l create mode 100644 Task/Generic-swap/Emacs-Lisp/generic-swap-3.l create mode 100644 Task/Generic-swap/NewLISP/generic-swap.newlisp create mode 100644 Task/Generic-swap/UNIX-Shell/generic-swap-1.sh create mode 100644 Task/Generic-swap/UNIX-Shell/generic-swap-2.sh create mode 100644 Task/Globally-replace-text-in-several-files/Clojure/globally-replace-text-in-several-files.clj create mode 100644 Task/Globally-replace-text-in-several-files/Mathematica/globally-replace-text-in-several-files.math create mode 100644 Task/Globally-replace-text-in-several-files/Sed/globally-replace-text-in-several-files.sed rename Task/Globally-replace-text-in-several-files/TXR/{globally-replace-text-in-several-files.txr => globally-replace-text-in-several-files-1.txr} (77%) create mode 100644 Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-2.txr create mode 100644 Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-1.sh create mode 100644 Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-2.sh create mode 100644 Task/Gray-code/MATLAB/gray-code.m create mode 100644 Task/Gray-code/R/gray-code.r create mode 100644 Task/Gray-code/SQL/gray-code.sql create mode 100644 Task/Gray-code/Seed7/gray-code.seed7 create mode 100644 Task/Greatest-common-divisor/C++/greatest-common-divisor.cpp create mode 100644 Task/Greatest-common-divisor/Frink/greatest-common-divisor.frink create mode 100644 Task/Greatest-common-divisor/Mercury/greatest-common-divisor-1.mercury create mode 100644 Task/Greatest-common-divisor/Mercury/greatest-common-divisor-2.mercury create mode 100644 Task/Greatest-common-divisor/Mercury/greatest-common-divisor-3.mercury create mode 100644 Task/Greatest-common-divisor/Oberon-2/greatest-common-divisor.oberon-2 create mode 100644 Task/Greatest-common-divisor/REXX/greatest-common-divisor-3.rexx create mode 100644 Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb create mode 100644 Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list.apl rename Task/Greatest-element-of-a-list/AWK/{greatest-element-of-a-list.awk => greatest-element-of-a-list-1.awk} (100%) create mode 100644 Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-2.awk create mode 100644 Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-1.cfm create mode 100644 Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-2.cfm create mode 100644 Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-1.oberon-2 create mode 100644 Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-2.oberon-2 create mode 100644 Task/Greatest-element-of-a-list/RapidQ/greatest-element-of-a-list.rapidq create mode 100644 Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-1.vim create mode 100644 Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-2.vim create mode 100644 Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-1.xslt create mode 100644 Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-2.xslt create mode 100644 Task/Greatest-element-of-a-list/Yacas/greatest-element-of-a-list.yacas create mode 100644 Task/Greatest-subsequential-sum/ATS/greatest-subsequential-sum.ats create mode 100644 Task/Greatest-subsequential-sum/Component-Pascal/greatest-subsequential-sum.component create mode 100644 Task/Greatest-subsequential-sum/Oberon-2/greatest-subsequential-sum.oberon-2 create mode 100644 Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-3.rb create mode 100644 Task/Greyscale-bars-Display/Frink/greyscale-bars-display.frink create mode 100644 Task/Greyscale-bars-Display/MAXScript/greyscale-bars-display.max create mode 100644 Task/Greyscale-bars-Display/RapidQ/greyscale-bars-display.rapidq create mode 100644 Task/Guess-the-number-With-feedback--player-/C-sharp/guess-the-number-with-feedback--player-.cs create mode 100644 Task/Guess-the-number-With-feedback--player-/MATLAB/guess-the-number-with-feedback--player-.m create mode 100644 Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--1.max create mode 100644 Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--2.max create mode 100644 Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--1.pro create mode 100644 Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--2.pro create mode 100644 Task/Guess-the-number-With-feedback--player-/UNIX-Shell/guess-the-number-with-feedback--player-.sh create mode 100644 Task/Guess-the-number-With-feedback/ALGOL-68/guess-the-number-with-feedback.alg create mode 100644 Task/Guess-the-number-With-feedback/Batch-File/guess-the-number-with-feedback.bat create mode 100644 Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir create mode 100644 Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-1.max create mode 100644 Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-2.max create mode 100644 Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-1.pro create mode 100644 Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-2.pro create mode 100644 Task/Guess-the-number/Eiffel/guess-the-number.e create mode 100644 Task/Guess-the-number/Elixir/guess-the-number.elixir create mode 100644 Task/Guess-the-number/MAXScript/guess-the-number.max create mode 100644 Task/Guess-the-number/Oberon-2/guess-the-number.oberon-2 create mode 100644 Task/Guess-the-number/Prolog/guess-the-number-1.pro create mode 100644 Task/Guess-the-number/Prolog/guess-the-number-2.pro create mode 100644 Task/Guess-the-number/RapidQ/guess-the-number.rapidq create mode 100644 Task/Guess-the-number/Rust/guess-the-number.rust create mode 100644 Task/HTTP/JavaScript/http-1.js create mode 100644 Task/HTTP/JavaScript/http-2.js delete mode 100644 Task/HTTP/JavaScript/http.js create mode 100644 Task/HTTP/Maple/http-1.maple create mode 100644 Task/HTTP/Maple/http-2.maple delete mode 100644 Task/HTTP/Maple/http.maple create mode 100644 Task/HTTPS/Maple/https.maple create mode 100644 Task/Hailstone-sequence/Aime/hailstone-sequence.aime create mode 100644 Task/Hailstone-sequence/D/hailstone-sequence-4.d create mode 100644 Task/Hailstone-sequence/D/hailstone-sequence-5.d create mode 100644 Task/Hailstone-sequence/Pascal/hailstone-sequence.pascal create mode 100644 Task/Hailstone-sequence/R/hailstone-sequence.r create mode 100644 Task/Hailstone-sequence/Rust/hailstone-sequence.rust create mode 100644 Task/Hailstone-sequence/SAS/hailstone-sequence.sas create mode 100644 Task/Hailstone-sequence/Scilab/hailstone-sequence.scilab create mode 100644 Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-1.ti-83 create mode 100644 Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-2.ti-83 create mode 100644 Task/Hailstone-sequence/Visual-Basic/hailstone-sequence.vb create mode 100644 Task/Hamming-numbers/ATS/hamming-numbers.ats create mode 100644 Task/Hamming-numbers/D/hamming-numbers-4.d create mode 100644 Task/Hamming-numbers/Java/hamming-numbers-3.java create mode 100644 Task/Hamming-numbers/Julia/hamming-numbers.julia create mode 100644 Task/Hamming-numbers/MATLAB/hamming-numbers.m rename Task/Hamming-numbers/Oz/{hamming-numbers.oz => hamming-numbers-1.oz} (100%) create mode 100644 Task/Hamming-numbers/Oz/hamming-numbers-2.oz create mode 100644 Task/Hamming-numbers/Pascal/hamming-numbers-1.pascal create mode 100644 Task/Hamming-numbers/Pascal/hamming-numbers-2.pascal create mode 100644 Task/Hamming-numbers/UNIX-Shell/hamming-numbers.sh create mode 100644 Task/Handle-a-signal/JavaScript/handle-a-signal.js create mode 100644 Task/Handle-a-signal/MATLAB/handle-a-signal-1.m create mode 100644 Task/Handle-a-signal/MATLAB/handle-a-signal-2.m create mode 100644 Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp create mode 100644 Task/Handle-a-signal/Perl-6/handle-a-signal.pl6 create mode 100644 Task/Handle-a-signal/Python/handle-a-signal-4.py create mode 100644 Task/Handle-a-signal/Scala/handle-a-signal.scala create mode 100644 Task/Happy-numbers/Eiffel/happy-numbers.e create mode 100644 Task/Happy-numbers/Groovy/happy-numbers.groovy create mode 100644 Task/Happy-numbers/MATLAB/happy-numbers.m create mode 100644 Task/Happy-numbers/MAXScript/happy-numbers-1.max create mode 100644 Task/Happy-numbers/MAXScript/happy-numbers-2.max create mode 100644 Task/Happy-numbers/Mercury/happy-numbers.mercury rename Task/Happy-numbers/Pascal/{happy-numbers.pascal => happy-numbers-1.pascal} (100%) create mode 100644 Task/Happy-numbers/Pascal/happy-numbers-2.pascal create mode 100644 Task/Happy-numbers/Ruby/happy-numbers-4.rb create mode 100644 Task/Happy-numbers/Rust/happy-numbers.rust create mode 100644 Task/Harshad-or-Niven-series/ColdFusion/harshad-or-niven-series.cfm create mode 100644 Task/Harshad-or-Niven-series/Common-Lisp/harshad-or-niven-series.lisp create mode 100644 Task/Harshad-or-Niven-series/Eiffel/harshad-or-niven-series.e create mode 100644 Task/Harshad-or-Niven-series/Pascal/harshad-or-niven-series.pascal rename Task/Hash-from-two-arrays/JavaScript/{hash-from-two-arrays.js => hash-from-two-arrays-1.js} (70%) create mode 100644 Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-2.js create mode 100644 Task/Hash-from-two-arrays/MATLAB/hash-from-two-arrays.m create mode 100644 Task/Hash-from-two-arrays/Maple/hash-from-two-arrays.maple create mode 100644 Task/Hash-from-two-arrays/Oberon-2/hash-from-two-arrays.oberon-2 create mode 100644 Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-3.rb create mode 100644 Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-1.txr create mode 100644 Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-2.txr create mode 100644 Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-3.txr delete mode 100644 Task/Hash-from-two-arrays/TXR/hash-from-two-arrays.txr create mode 100644 Task/Hash-from-two-arrays/UNIX-Shell/hash-from-two-arrays.sh create mode 100644 Task/Haversine-formula/ATS/haversine-formula.ats create mode 100644 Task/Haversine-formula/CoffeeScript/haversine-formula.coffee create mode 100644 Task/Haversine-formula/JavaScript/haversine-formula.js create mode 100644 Task/Haversine-formula/Oberon-2/haversine-formula.oberon-2 rename Task/Haversine-formula/REXX/{haversine-formula.rexx => haversine-formula-1.rexx} (64%) create mode 100644 Task/Haversine-formula/REXX/haversine-formula-2.rexx create mode 100644 Task/Haversine-formula/SAS/haversine-formula.sas create mode 100644 Task/Haversine-formula/UBASIC/haversine-formula.ubasic create mode 100644 Task/Hello-world-Graphical/AWK/hello-world-graphical.awk rename Task/Hello-world-Graphical/Forth/{hello-world-graphical.fth => hello-world-graphical-1.fth} (100%) create mode 100644 Task/Hello-world-Graphical/Forth/hello-world-graphical-2.fth rename Task/Hello-world-Graphical/Lua/{hello-world-graphical.lua => hello-world-graphical-1.lua} (100%) create mode 100644 Task/Hello-world-Graphical/Lua/hello-world-graphical-2.lua create mode 100644 Task/Hello-world-Graphical/Perl/hello-world-graphical-6.pl create mode 100644 Task/Hello-world-Graphical/Python/hello-world-graphical-6.py create mode 100644 Task/Hello-world-Graphical/REALbasic/hello-world-graphical.realbasic create mode 100644 Task/Hello-world-Graphical/VBScript/hello-world-graphical.vb create mode 100644 Task/Hello-world-Graphical/XSLT/hello-world-graphical-1.xslt create mode 100644 Task/Hello-world-Graphical/XSLT/hello-world-graphical-2.xslt create mode 100644 Task/Hello-world-Graphical/XSLT/hello-world-graphical-3.xslt create mode 100644 Task/Hello-world-Line-printer/00META.yaml create mode 100644 Task/Hello-world-Line-printer/C-sharp/hello-world-line-printer.cs create mode 100644 Task/Hello-world-Line-printer/Icon/hello-world-line-printer.icon create mode 100644 Task/Hello-world-Line-printer/Seed7/hello-world-line-printer.seed7 create mode 100644 Task/Hello-world-Line-printer/Simula/hello-world-line-printer.simula create mode 100644 Task/Hello-world-Newline-omission/Elixir/hello-world-newline-omission.elixir create mode 100644 Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-1.falcon create mode 100644 Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-2.falcon create mode 100644 Task/Hello-world-Newline-omission/OOC/hello-world-newline-omission.ooc create mode 100644 Task/Hello-world-Newline-omission/Oberon-2/hello-world-newline-omission.oberon-2 create mode 100644 Task/Hello-world-Newline-omission/REBOL/hello-world-newline-omission.rebol create mode 100644 Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust create mode 100644 Task/Hello-world-Newline-omission/Smalltalk/hello-world-newline-omission.st create mode 100644 Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql create mode 100644 Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql create mode 100644 Task/Hello-world-Newline-omission/Vim-Script/hello-world-newline-omission.vim create mode 100644 Task/Hello-world-Standard-error/Frink/hello-world-standard-error.frink create mode 100644 Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust create mode 100644 Task/Hello-world-Standard-error/Transact-SQL/hello-world-standard-error.sql create mode 100644 Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 create mode 100644 Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 delete mode 100644 Task/Hello-world-Text/360-Assembly/hello-world-text.360 create mode 100644 Task/Hello-world-Text/ALGOL-60/hello-world-text.alg create mode 100644 Task/Hello-world-Text/C/hello-world-text-3.c rename Task/Hello-world-Text/CoffeeScript/{hello-world-text.coffee => hello-world-text-1.coffee} (100%) create mode 100644 Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee create mode 100644 Task/Hello-world-Text/Elixir/hello-world-text.elixir create mode 100644 Task/Hello-world-Text/Falcon/hello-world-text-1.falcon rename Task/Hello-world-Text/Falcon/{hello-world-text.falcon => hello-world-text-2.falcon} (100%) create mode 100644 Task/Hello-world-Text/GML/hello-world-text.gml create mode 100644 Task/Hello-world-Text/Gentee/hello-world-text.gentee rename Task/Hello-world-Text/Glee/{hello-world-text.glee => hello-world-text-1.glee} (100%) create mode 100644 Task/Hello-world-Text/Glee/hello-world-text-2.glee create mode 100644 Task/Hello-world-Text/Glee/hello-world-text-3.glee create mode 100644 Task/Hello-world-Text/Glee/hello-world-text-4.glee create mode 100644 Task/Hello-world-Text/Haxe/hello-world-text.haxe rename Task/Hello-world-Text/OOC/{hello-world-text.ooc => hello-world-text-1.ooc} (100%) create mode 100644 Task/Hello-world-Text/OOC/hello-world-text-2.ooc create mode 100644 Task/Hello-world-Text/Ruby/hello-world-text-3.rb create mode 100644 Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc create mode 100644 Task/Hello-world-Text/Scheme/hello-world-text-4.ss create mode 100644 Task/Hello-world-Text/Simula/hello-world-text.simula create mode 100644 Task/Hello-world-Text/Vim-Script/hello-world-text.vim create mode 100644 Task/Hello-world-Web-server/Clojure/hello-world-web-server.clj create mode 100644 Task/Hello-world-Web-server/Rust/hello-world-web-server.rust rename Task/Hello-world-Web-server/Smalltalk/{hello-world-web-server.st => hello-world-web-server-1.st} (100%) create mode 100644 Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-2.st create mode 100644 Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-3.st rename Task/Hello-world-Web-server/Tcl/{hello-world-web-server.tcl => hello-world-web-server-1.tcl} (100%) create mode 100644 Task/Hello-world-Web-server/Tcl/hello-world-web-server-2.tcl create mode 100644 Task/Hello-world-Web-server/UNIX-Shell/hello-world-web-server.sh create mode 100644 Task/Here-document/00META.yaml create mode 100644 Task/Here-document/C++/here-document.cpp create mode 100644 Task/Here-document/Factor/here-document.factor create mode 100644 Task/Here-document/Scala/here-document.scala create mode 100644 Task/Here-document/XSLT/here-document.xslt create mode 100644 Task/Higher-order-functions/ATS/higher-order-functions.ats create mode 100644 Task/Higher-order-functions/AppleScript/higher-order-functions.applescript create mode 100644 Task/Higher-order-functions/Oberon-2/higher-order-functions.oberon-2 create mode 100644 Task/History-variables/Clojure/history-variables.clj create mode 100644 Task/Hofstadter-Conway-$10,000-sequence/Pascal/hofstadter-conway-$10,000-sequence.pascal create mode 100644 Task/Hofstadter-Q-sequence/Bracmat/hofstadter-q-sequence.bracmat create mode 100644 Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e create mode 100644 Task/Hofstadter-Q-sequence/Oberon-2/hofstadter-q-sequence.oberon-2 create mode 100644 Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence.ss create mode 100644 Task/Holidays-related-to-Easter/Java/holidays-related-to-easter.java create mode 100644 Task/Honeycombs/Haskell/honeycombs.hs create mode 100644 Task/Honeycombs/Java/honeycombs-1.java create mode 100644 Task/Honeycombs/Java/honeycombs-2.java create mode 100644 Task/Honeycombs/MATLAB/honeycombs.m create mode 100644 Task/Horizontal-sundial-calculations/Euphoria/horizontal-sundial-calculations.euphoria create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-3.julia create mode 100644 Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-4.julia rename Task/Horners-rule-for-polynomial-evaluation/R/{horners-rule-for-polynomial-evaluation.r => horners-rule-for-polynomial-evaluation-1.r} (100%) create mode 100644 Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-2.r create mode 100644 Task/Horners-rule-for-polynomial-evaluation/REBOL/horners-rule-for-polynomial-evaluation.rebol rename Task/Horners-rule-for-polynomial-evaluation/REXX/{horners-rule-for-polynomial-evaluation.rexx => horners-rule-for-polynomial-evaluation-1.rexx} (64%) create mode 100644 Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx create mode 100644 Task/Host-introspection/R/host-introspection.r create mode 100644 Task/Host-introspection/Scala/host-introspection.scala create mode 100644 Task/Hostname/AppleScript/hostname.applescript create mode 100644 Task/Hostname/Batch-File/hostname.bat rename Task/Hostname/Haskell/{hostname.hs => hostname-1.hs} (100%) create mode 100644 Task/Hostname/Haskell/hostname-2.hs create mode 100644 Task/Hostname/Oberon-2/hostname.oberon-2 create mode 100644 Task/Hostname/Vim-Script/hostname.vim create mode 100644 Task/Hough-transform/Haskell/hough-transform-1.hs create mode 100644 Task/Hough-transform/Haskell/hough-transform-2.hs create mode 100644 Task/Huffman-coding/CoffeeScript/huffman-coding.coffee create mode 100644 Task/Huffman-coding/Eiffel/huffman-coding.e create mode 100644 Task/Huffman-coding/Groovy/huffman-coding-1.groovy create mode 100644 Task/Huffman-coding/Groovy/huffman-coding-2.groovy create mode 100644 Task/Huffman-coding/Mathematica/huffman-coding.math create mode 100644 Task/Huffman-coding/Perl/huffman-coding.pl create mode 100644 Task/Huffman-coding/Scheme/huffman-coding.ss create mode 100644 Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala create mode 100644 Task/Identity-matrix/ATS/identity-matrix.ats create mode 100644 Task/Identity-matrix/Eiffel/identity-matrix.e create mode 100644 Task/Identity-matrix/JavaScript/identity-matrix.js create mode 100644 Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 rename Task/Identity-matrix/Ruby/{identity-matrix.rb => identity-matrix-1.rb} (100%) create mode 100644 Task/Identity-matrix/Ruby/identity-matrix-2.rb create mode 100644 Task/Image-convolution/MATLAB/image-convolution.m create mode 100644 Task/Image-noise/00META.yaml create mode 100644 Task/Image-noise/Haskell/image-noise.hs create mode 100644 Task/Image-noise/MAXScript/image-noise.max create mode 100644 Task/Image-noise/Perl-6/image-noise.pl6 create mode 100644 Task/Include-a-file/JavaScript/include-a-file-3.js create mode 100644 Task/Include-a-file/JavaScript/include-a-file-4.js create mode 100644 Task/Include-a-file/JavaScript/include-a-file-5.js create mode 100644 Task/Include-a-file/NewLISP/include-a-file.newlisp create mode 100644 Task/Include-a-file/REXX/include-a-file.rexx create mode 100644 Task/Increment-a-numerical-string/C/increment-a-numerical-string.c create mode 100644 Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e create mode 100644 Task/Increment-a-numerical-string/Neko/increment-a-numerical-string.neko create mode 100644 Task/Increment-a-numerical-string/NewLISP/increment-a-numerical-string.newlisp create mode 100644 Task/Increment-a-numerical-string/Rascal/increment-a-numerical-string.rascal create mode 100644 Task/Infinity/Rust/infinity.rust create mode 100644 Task/Inheritance-Single/Oberon-2/inheritance-single.oberon-2 create mode 100644 Task/Input-loop/Bracmat/input-loop.bracmat create mode 100644 Task/Input-loop/D/input-loop-3.d create mode 100644 Task/Input-loop/Go/input-loop-1.go create mode 100644 Task/Input-loop/Go/input-loop-2.go delete mode 100644 Task/Input-loop/Go/input-loop.go create mode 100644 Task/Input-loop/Oberon-2/input-loop.oberon-2 create mode 100644 Task/Input-loop/REXX/input-loop-4.rexx create mode 100644 Task/Input-loop/REXX/input-loop-5.rexx create mode 100644 Task/Integer-comparison/360-Assembly/integer-comparison.360 rename Task/Integer-comparison/BASIC/{integer-comparison.basic => integer-comparison-1.basic} (100%) create mode 100644 Task/Integer-comparison/BASIC/integer-comparison-2.basic create mode 100644 Task/Integer-comparison/Brat/integer-comparison.brat create mode 100644 Task/Integer-comparison/Excel/integer-comparison-1.excel create mode 100644 Task/Integer-comparison/Excel/integer-comparison-2.excel create mode 100644 Task/Integer-comparison/Julia/integer-comparison.julia create mode 100644 Task/Integer-comparison/Rust/integer-comparison.rust create mode 100644 Task/Integer-sequence/C++/integer-sequence-1.cpp create mode 100644 Task/Integer-sequence/C++/integer-sequence-2.cpp delete mode 100644 Task/Integer-sequence/C++/integer-sequence.cpp create mode 100644 Task/Integer-sequence/NewLISP/integer-sequence.newlisp create mode 100644 Task/Integer-sequence/Oberon-2/integer-sequence.oberon-2 rename Task/Integer-sequence/Perl/{integer-sequence.pl => integer-sequence-1.pl} (100%) create mode 100644 Task/Integer-sequence/Perl/integer-sequence-2.pl create mode 100644 Task/Integer-sequence/R/integer-sequence.r create mode 100644 Task/Interactive-programming/CoffeeScript/interactive-programming.coffee rename Task/Introspection/Forth/{introspection.fth => introspection-1.fth} (100%) create mode 100644 Task/Introspection/Forth/introspection-2.fth create mode 100644 Task/Introspection/Julia/introspection.julia create mode 100644 Task/Introspection/UNIX-Shell/introspection-1.sh create mode 100644 Task/Introspection/UNIX-Shell/introspection-2.sh create mode 100644 Task/Inverted-index/Scala/inverted-index.scala create mode 100644 Task/Inverted-syntax/C++/inverted-syntax.cpp create mode 100644 Task/JSON/Bracmat/json-1.bracmat create mode 100644 Task/JSON/Bracmat/json-2.bracmat create mode 100644 Task/JSON/Bracmat/json-3.bracmat create mode 100644 Task/JSON/Bracmat/json-4.bracmat create mode 100644 Task/JSON/Bracmat/json-5.bracmat create mode 100644 Task/JSON/Bracmat/json-6.bracmat rename Task/JSON/Haskell/{json.hs => json-1.hs} (100%) create mode 100644 Task/JSON/Haskell/json-2.hs create mode 100644 Task/JSON/Lua/json.lua create mode 100644 Task/JSON/PowerShell/json-1.psh create mode 100644 Task/JSON/PowerShell/json-2.psh create mode 100644 Task/JSON/Prolog/json-1.pro create mode 100644 Task/JSON/Prolog/json-2.pro create mode 100644 Task/JSON/Rust/json.rust create mode 100644 Task/JSON/Smalltalk/json.st rename Task/Josephus-problem/Python/{josephus-problem.py => josephus-problem-1.py} (100%) create mode 100644 Task/Josephus-problem/Python/josephus-problem-2.py create mode 100644 Task/Josephus-problem/Python/josephus-problem-3.py create mode 100644 Task/K-means++-clustering/Mathematica/k-means++-clustering.math create mode 100644 Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6 create mode 100644 Task/Kaprekar-numbers/C-sharp/kaprekar-numbers.cs create mode 100644 Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia create mode 100644 Task/Kaprekar-numbers/Perl/kaprekar-numbers-1.pl create mode 100644 Task/Kaprekar-numbers/Perl/kaprekar-numbers-2.pl delete mode 100644 Task/Kaprekar-numbers/Perl/kaprekar-numbers.pl create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-3.basic create mode 100644 Task/Keyboard-input-Flush-the-keyboard-buffer/Go/keyboard-input-flush-the-keyboard-buffer.go create mode 100644 Task/Keyboard-input-Keypress-check/Go/keyboard-input-keypress-check.go create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/00META.yaml create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/keyboard-input-obtain-a-y-or-n-response.go create mode 100644 Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-3.rexx create mode 100644 Task/Keyboard-macros/Icon/keyboard-macros.icon create mode 100644 Task/Knapsack-problem-0-1/JavaScript/knapsack-problem-0-1.js create mode 100644 Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-1.max create mode 100644 Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-2.max create mode 100644 Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust create mode 100644 Task/Knapsack-problem-Continuous/Bracmat/knapsack-problem-continuous.bracmat rename Task/Knapsack-problem-Continuous/C++/{knapsack-problem-continuous.cpp => knapsack-problem-continuous-1.cpp} (100%) create mode 100644 Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-2.cpp create mode 100644 Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj create mode 100644 Task/Knapsack-problem-Continuous/PL-I/knapsack-problem-continuous.pli create mode 100644 Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-1.rexx create mode 100644 Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-2.rexx delete mode 100644 Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous.rexx create mode 100644 Task/Knapsack-problem-Continuous/Ruby/knapsack-problem-continuous.rb create mode 100644 Task/Knapsack-problem-Unbounded/Visual-Basic/knapsack-problem-unbounded.vb create mode 100644 Task/Knights-tour/ALGOL-68/knights-tour.alg create mode 100644 Task/Knights-tour/AWK/knights-tour.awk rename Task/Knights-tour/D/{knights-tour.d => knights-tour-1.d} (100%) create mode 100644 Task/Knights-tour/D/knights-tour-2.d rename Task/Knights-tour/Prolog/{knights-tour.pro => knights-tour-1.pro} (100%) create mode 100644 Task/Knights-tour/Prolog/knights-tour-2.pro create mode 100644 Task/Knights-tour/Scheme/knights-tour.ss create mode 100644 Task/Knuth-shuffle/Eiffel/knuth-shuffle.e create mode 100644 Task/Knuth-shuffle/Frink/knuth-shuffle.frink create mode 100644 Task/Knuth-shuffle/Objective-C/knuth-shuffle.m rename Task/LU-decomposition/Ruby/{lu-decomposition.rb => lu-decomposition-1.rb} (62%) create mode 100644 Task/LU-decomposition/Ruby/lu-decomposition-2.rb create mode 100644 Task/LZW-compression/CoffeeScript/lzw-compression.coffee create mode 100644 Task/LZW-compression/D/lzw-compression-3.d create mode 100644 Task/LZW-compression/JavaScript/lzw-compression.js create mode 100644 Task/LZW-compression/Liberty-BASIC/lzw-compression.liberty create mode 100644 Task/LZW-compression/REXX/lzw-compression.rexx create mode 100644 Task/Langtons-ant/AWK/langtons-ant.awk create mode 100644 Task/Langtons-ant/Fortran/langtons-ant.f create mode 100644 Task/Langtons-ant/Logo/langtons-ant.logo create mode 100644 Task/Langtons-ant/Lua/langtons-ant.lua rename Task/Langtons-ant/Ruby/{langtons-ant.rb => langtons-ant-1.rb} (100%) create mode 100644 Task/Langtons-ant/Ruby/langtons-ant-2.rb create mode 100644 Task/Langtons-ant/Rust/langtons-ant.rust create mode 100644 Task/Langtons-ant/Seed7/langtons-ant.seed7 create mode 100644 Task/Largest-int-from-concatenated-ints/Lua/largest-int-from-concatenated-ints.lua create mode 100644 Task/Largest-int-from-concatenated-ints/Mathematica/largest-int-from-concatenated-ints.math create mode 100644 Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-1.pascal create mode 100644 Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-2.pascal create mode 100644 Task/Largest-int-from-concatenated-ints/Scheme/largest-int-from-concatenated-ints.ss create mode 100644 Task/Last-Friday-of-each-month/00META.yaml create mode 100644 Task/Last-Friday-of-each-month/Clojure/last-friday-of-each-month.clj create mode 100644 Task/Last-Friday-of-each-month/Common-Lisp/last-friday-of-each-month.lisp create mode 100644 Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs create mode 100644 Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-1.rebol create mode 100644 Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-2.rebol create mode 100644 Task/Last-Friday-of-each-month/Racket/last-friday-of-each-month.rkt create mode 100644 Task/Last-letter-first-letter/Scala/last-letter-first-letter-1.scala create mode 100644 Task/Last-letter-first-letter/Scala/last-letter-first-letter-2.scala create mode 100644 Task/Last-letter-first-letter/Scala/last-letter-first-letter-3.scala create mode 100644 Task/Leap-year/C++/leap-year.cpp rename Task/Leap-year/D/{leap-year.d => leap-year-1.d} (100%) create mode 100644 Task/Leap-year/D/leap-year-2.d create mode 100644 Task/Leap-year/Excel/leap-year.excel create mode 100644 Task/Leap-year/REXX/leap-year-4.rexx create mode 100644 Task/Leap-year/Smalltalk/leap-year.st create mode 100644 Task/Least-common-multiple/Groovy/least-common-multiple.groovy create mode 100644 Task/Least-common-multiple/REXX/least-common-multiple-1.rexx create mode 100644 Task/Least-common-multiple/REXX/least-common-multiple-2.rexx create mode 100644 Task/Least-common-multiple/REXX/least-common-multiple-3.rexx delete mode 100644 Task/Least-common-multiple/REXX/least-common-multiple.rexx create mode 100644 Task/Least-common-multiple/Smalltalk/least-common-multiple.st create mode 100644 Task/Letter-frequency/00META.yaml create mode 100644 Task/Letter-frequency/Eiffel/letter-frequency.e create mode 100644 Task/Letter-frequency/Euphoria/letter-frequency.euphoria create mode 100644 Task/Letter-frequency/Julia/letter-frequency.julia create mode 100644 Task/Letter-frequency/Rust/letter-frequency.rust create mode 100644 Task/Letter-frequency/Scheme/letter-frequency-1.ss create mode 100644 Task/Letter-frequency/Scheme/letter-frequency-2.ss delete mode 100644 Task/Letter-frequency/Scheme/letter-frequency.ss rename Task/Levenshtein-distance/Clojure/{levenshtein-distance.clj => levenshtein-distance-1.clj} (100%) create mode 100644 Task/Levenshtein-distance/Clojure/levenshtein-distance-2.clj create mode 100644 Task/Levenshtein-distance/Julia/levenshtein-distance.julia create mode 100644 Task/Levenshtein-distance/Objeck/levenshtein-distance.objeck create mode 100644 Task/Levenshtein-distance/PL-I/levenshtein-distance-1.pli create mode 100644 Task/Levenshtein-distance/PL-I/levenshtein-distance-2.pli rename Task/Levenshtein-distance/REXX/{levenshtein-distance.rexx => levenshtein-distance-1.rexx} (100%) create mode 100644 Task/Levenshtein-distance/REXX/levenshtein-distance-2.rexx create mode 100644 Task/Levenshtein-distance/REXX/levenshtein-distance-3.rexx create mode 100644 Task/Levenshtein-distance/REXX/levenshtein-distance-4.rexx rename Task/Levenshtein-distance/Ruby/{levenshtein-distance.rb => levenshtein-distance-1.rb} (96%) create mode 100644 Task/Levenshtein-distance/Ruby/levenshtein-distance-2.rb create mode 100644 Task/Linear-congruential-generator/UNIX-Shell/linear-congruential-generator.sh create mode 100644 Task/List-comprehensions/REXX/list-comprehensions-1.rexx create mode 100644 Task/List-comprehensions/REXX/list-comprehensions-2.rexx delete mode 100644 Task/List-comprehensions/REXX/list-comprehensions.rexx create mode 100644 Task/Literals-Floating-point/Eiffel/literals-floating-point.e create mode 100644 Task/Literals-Floating-point/Euphoria/literals-floating-point.euphoria create mode 100644 Task/Literals-Integer/Eiffel/literals-integer-1.e create mode 100644 Task/Literals-Integer/Eiffel/literals-integer-2.e create mode 100644 Task/Literals-Integer/Euphoria/literals-integer.euphoria create mode 100644 Task/Literals-Integer/Julia/literals-integer.julia create mode 100644 Task/Literals-Integer/Mercury/literals-integer.mercury create mode 100644 Task/Literals-String/Emacs-Lisp/literals-string-1.l create mode 100644 Task/Literals-String/Emacs-Lisp/literals-string-2.l create mode 100644 Task/Literals-String/REXX/literals-string-4.rexx create mode 100644 Task/Logical-operations/Excel/logical-operations-1.excel create mode 100644 Task/Logical-operations/Excel/logical-operations-2.excel create mode 100644 Task/Logical-operations/Excel/logical-operations-3.excel create mode 100644 Task/Logical-operations/OOC/logical-operations.ooc create mode 100644 Task/Logical-operations/Perl-6/logical-operations.pl6 create mode 100644 Task/Logical-operations/Rascal/logical-operations.rascal create mode 100644 Task/Logical-operations/Slate/logical-operations.slate create mode 100644 Task/Longest-common-subsequence/APL/longest-common-subsequence.apl create mode 100644 Task/Longest-common-subsequence/C++/longest-common-subsequence-1.cpp create mode 100644 Task/Longest-common-subsequence/C++/longest-common-subsequence-2.cpp create mode 100644 Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-4.lisp create mode 100644 Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-5.lisp create mode 100644 Task/Longest-common-subsequence/Erlang/longest-common-subsequence-3.erl create mode 100644 Task/Longest-common-subsequence/OCaml/longest-common-subsequence-4.ocaml create mode 100644 Task/Longest-string-challenge/Java/longest-string-challenge.java create mode 100644 Task/Longest-string-challenge/Lua/longest-string-challenge-1.lua create mode 100644 Task/Longest-string-challenge/Lua/longest-string-challenge-2.lua rename Task/Longest-string-challenge/Ruby/{longest-string-challenge.rb => longest-string-challenge-1.rb} (100%) create mode 100644 Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb create mode 100644 Task/Longest-string-challenge/Scala/longest-string-challenge.scala create mode 100644 Task/Look-and-say-sequence/Bracmat/look-and-say-sequence.bracmat create mode 100644 Task/Look-and-say-sequence/D/look-and-say-sequence-5.d rename Task/Look-and-say-sequence/JavaScript/{look-and-say-sequence.js => look-and-say-sequence-1.js} (100%) create mode 100644 Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-2.js rename Task/Look-and-say-sequence/Pascal/{look-and-say-sequence.pascal => look-and-say-sequence-1.pascal} (100%) create mode 100644 Task/Look-and-say-sequence/Pascal/look-and-say-sequence-2.pascal rename Task/Look-and-say-sequence/Scala/{look-and-say-sequence.scala => look-and-say-sequence-1.scala} (100%) create mode 100644 Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala create mode 100644 Task/Look-and-say-sequence/UNIX-Shell/look-and-say-sequence.sh create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/C/loop-over-multiple-arrays-simultaneously.c create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/Oberon-2/loop-over-multiple-arrays-simultaneously.oberon-2 create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx create mode 100644 Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx create mode 100644 Task/Loops-Break/ColdFusion/loops-break.cfm create mode 100644 Task/Loops-Break/MAXScript/loops-break.max create mode 100644 Task/Loops-Break/NewLISP/loops-break.newlisp create mode 100644 Task/Loops-Break/Oberon-2/loops-break.oberon-2 create mode 100644 Task/Loops-Break/Ruby/loops-break-1.rb create mode 100644 Task/Loops-Break/Ruby/loops-break-2.rb delete mode 100644 Task/Loops-Break/Ruby/loops-break.rb create mode 100644 Task/Loops-Continue/Applesoft-BASIC/loops-continue.applesoft create mode 100644 Task/Loops-Continue/Clojure/loops-continue-1.clj create mode 100644 Task/Loops-Continue/Clojure/loops-continue-2.clj delete mode 100644 Task/Loops-Continue/Clojure/loops-continue.clj create mode 100644 Task/Loops-Continue/NewLISP/loops-continue.newlisp create mode 100644 Task/Loops-Do-while/360-Assembly/loops-do-while.360 create mode 100644 Task/Loops-Do-while/Emacs-Lisp/loops-do-while.l create mode 100644 Task/Loops-Do-while/Euphoria/loops-do-while.euphoria create mode 100644 Task/Loops-Do-while/NewLISP/loops-do-while.newlisp create mode 100644 Task/Loops-Do-while/Oberon-2/loops-do-while.oberon-2 create mode 100644 Task/Loops-Do-while/OpenEdge-Progress/loops-do-while.openedge rename Task/Loops-Do-while/PARI-GP/{loops-do-while.pari => loops-do-while-1.pari} (56%) create mode 100644 Task/Loops-Do-while/PARI-GP/loops-do-while-2.pari create mode 100644 Task/Loops-Do-while/Suneido/loops-do-while.suneido create mode 100644 Task/Loops-Downward-for/NewLISP/loops-downward-for.newlisp create mode 100644 Task/Loops-For-with-a-specified-step/ColdFusion/loops-for-with-a-specified-step.cfm create mode 100644 Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-4.j create mode 100644 Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-5.j create mode 100644 Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-6.j create mode 100644 Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-1.max create mode 100644 Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-2.max create mode 100644 Task/Loops-For-with-a-specified-step/NewLISP/loops-for-with-a-specified-step.newlisp create mode 100644 Task/Loops-For-with-a-specified-step/Oberon-2/loops-for-with-a-specified-step.oberon-2 create mode 100644 Task/Loops-For-with-a-specified-step/TorqueScript/loops-for-with-a-specified-step.torque create mode 100644 Task/Loops-For-with-a-specified-step/Vim-Script/loops-for-with-a-specified-step.vim create mode 100644 Task/Loops-For/ALGOL-60/loops-for.alg create mode 100644 Task/Loops-For/AppleScript/loops-for.applescript create mode 100644 Task/Loops-For/Oberon-2/loops-for.oberon-2 create mode 100644 Task/Loops-For/PL-I/loops-for-1.pli rename Task/Loops-For/PL-I/{loops-for.pli => loops-for-2.pli} (100%) create mode 100644 Task/Loops-For/PL-I/loops-for-3.pli create mode 100644 Task/Loops-For/Ruby/loops-for-6.rb create mode 100644 Task/Loops-For/Simula/loops-for.simula create mode 100644 Task/Loops-Foreach/C++/loops-foreach-6.cpp create mode 100644 Task/Loops-Foreach/ColdFusion/loops-foreach.cfm create mode 100644 Task/Loops-Foreach/Emacs-Lisp/loops-foreach-1.l create mode 100644 Task/Loops-Foreach/Emacs-Lisp/loops-foreach-2.l create mode 100644 Task/Loops-Foreach/Euphoria/loops-foreach.euphoria create mode 100644 Task/Loops-Foreach/NewLISP/loops-foreach.newlisp create mode 100644 Task/Loops-Foreach/Prolog/loops-foreach.pro create mode 100644 Task/Loops-Foreach/Python/loops-foreach-3.py create mode 100644 Task/Loops-Foreach/Python/loops-foreach-4.py create mode 100644 Task/Loops-Foreach/Vim-Script/loops-foreach.vim create mode 100644 Task/Loops-Infinite/360-Assembly/loops-infinite.360 create mode 100644 Task/Loops-Infinite/BASIC/loops-infinite-4.basic create mode 100644 Task/Loops-Infinite/Intercal/loops-infinite.ical create mode 100644 Task/Loops-Infinite/LOLCODE/loops-infinite.lol create mode 100644 Task/Loops-Infinite/NewLISP/loops-infinite.newlisp create mode 100644 Task/Loops-Infinite/Oberon-2/loops-infinite.oberon-2 create mode 100644 Task/Loops-Infinite/REXX/loops-infinite-4.rexx create mode 100644 Task/Loops-Infinite/Rust/loops-infinite.rust rename Task/Loops-N-plus-one-half/AWK/{loops-n-plus-one-half.awk => loops-n-plus-one-half-1.awk} (70%) create mode 100644 Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-2.awk create mode 100644 Task/Loops-N-plus-one-half/Julia/loops-n-plus-one-half-1.julia create mode 100644 Task/Loops-N-plus-one-half/Julia/loops-n-plus-one-half-2.julia create mode 100644 Task/Loops-N-plus-one-half/Maple/loops-n-plus-one-half.maple create mode 100644 Task/Loops-N-plus-one-half/NewLISP/loops-n-plus-one-half.newlisp create mode 100644 Task/Loops-N-plus-one-half/REXX/loops-n-plus-one-half-3.rexx create mode 100644 Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-1.rb create mode 100644 Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-2.rb delete mode 100644 Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half.rb create mode 100644 Task/Loops-N-plus-one-half/Scala/loops-n-plus-one-half.scala create mode 100644 Task/Loops-N-plus-one-half/Vim-Script/loops-n-plus-one-half.vim create mode 100644 Task/Loops-Nested/ColdFusion/loops-nested.cfm create mode 100644 Task/Loops-Nested/MAXScript/loops-nested-1.max create mode 100644 Task/Loops-Nested/MAXScript/loops-nested-2.max create mode 100644 Task/Loops-Nested/NewLISP/loops-nested.newlisp create mode 100644 Task/Loops-Nested/OoRexx/loops-nested.rexx rename Task/Loops-Nested/Ruby/{loops-nested.rb => loops-nested-1.rb} (97%) create mode 100644 Task/Loops-Nested/Ruby/loops-nested-2.rb create mode 100644 Task/Loops-While/360-Assembly/loops-while.360 create mode 100644 Task/Loops-While/ALGOL-60/loops-while.alg create mode 100644 Task/Loops-While/Bracmat/loops-while.bracmat create mode 100644 Task/Loops-While/Emacs-Lisp/loops-while.l create mode 100644 Task/Loops-While/Fortran/loops-while-3.f create mode 100644 Task/Loops-While/NewLISP/loops-while.newlisp create mode 100644 Task/Loops-While/OOC/loops-while.ooc create mode 100644 Task/Loops-While/Prolog/loops-while-1.pro create mode 100644 Task/Loops-While/Prolog/loops-while-2.pro delete mode 100644 Task/Loops-While/Prolog/loops-while.pro create mode 100644 Task/Loops-While/Rust/loops-while.rust create mode 100644 Task/Loops-While/TI-83-BASIC/loops-while.ti-83 create mode 100644 Task/Loops-While/Vim-Script/loops-while.vim create mode 100644 Task/Lucas-Lehmer-test/360-Assembly/lucas-lehmer-test.360 create mode 100644 Task/Lucas-Lehmer-test/C/lucas-lehmer-test-1.c rename Task/Lucas-Lehmer-test/C/{lucas-lehmer-test.c => lucas-lehmer-test-2.c} (100%) create mode 100644 Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-1.pl create mode 100644 Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-2.pl create mode 100644 Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-3.pl rename Task/Lucas-Lehmer-test/Perl/{lucas-lehmer-test.pl => lucas-lehmer-test-4.pl} (100%) create mode 100644 Task/Lucas-Lehmer-test/Scilab/lucas-lehmer-test.scilab create mode 100644 Task/Lucas-Lehmer-test/TI-83-BASIC/lucas-lehmer-test.ti-83 create mode 100644 Task/Lucas-Lehmer-test/VBScript/lucas-lehmer-test.vb create mode 100644 Task/Lucas-Lehmer-test/Visual-Basic-.NET/lucas-lehmer-test.visual create mode 100644 Task/Luhn-test-of-credit-card-numbers/00META.yaml create mode 100644 Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-3.d create mode 100644 Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-4.k create mode 100644 Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-5.k rename Task/Luhn-test-of-credit-card-numbers/Mathematica/{luhn-test-of-credit-card-numbers.math => luhn-test-of-credit-card-numbers-1.math} (100%) create mode 100644 Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-2.math create mode 100644 Task/Luhn-test-of-credit-card-numbers/OpenEdge-Progress/luhn-test-of-credit-card-numbers.openedge create mode 100644 Task/Luhn-test-of-credit-card-numbers/R/luhn-test-of-credit-card-numbers.r create mode 100644 Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb create mode 100644 Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust create mode 100644 Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh create mode 100644 Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb create mode 100644 Task/MD4/Clojure/md4.clj create mode 100644 Task/MD4/D/md4.d create mode 100644 Task/MD4/PicoLisp/md4.l create mode 100644 Task/MD4/Racket/md4.rkt create mode 100644 Task/MD4/Scala/md4.scala create mode 100644 Task/MD5/Maple/md5.maple create mode 100644 Task/MD5/NewLISP/md5.newlisp create mode 100644 Task/Mad-Libs/ALGOL-68/mad-libs.alg create mode 100644 Task/Mad-Libs/C-sharp/mad-libs.cs create mode 100644 Task/Mad-Libs/Haskell/mad-libs.hs create mode 100644 Task/Mad-Libs/Mathematica/mad-libs.math create mode 100644 Task/Mad-Libs/REBOL/mad-libs.rebol create mode 100644 Task/Mad-Libs/Scala/mad-libs.scala create mode 100644 Task/Main-step-of-GOST-28147-89/PicoLisp/main-step-of-gost-28147-89.l create mode 100644 Task/Man-or-boy-test/Dylan/man-or-boy-test.dylan create mode 100644 Task/Man-or-boy-test/Io/man-or-boy-test.io create mode 100644 Task/Man-or-boy-test/Java/man-or-boy-test-1.java rename Task/Man-or-boy-test/Java/{man-or-boy-test.java => man-or-boy-test-2.java} (100%) create mode 100644 Task/Man-or-boy-test/Pascal/man-or-boy-test.pascal create mode 100644 Task/Man-or-boy-test/REXX/man-or-boy-test.rexx create mode 100644 Task/Mandelbrot-set/JavaScript/mandelbrot-set.js create mode 100644 Task/Mandelbrot-set/Pascal/mandelbrot-set.pascal create mode 100644 Task/Mandelbrot-set/REXX/mandelbrot-set.rexx create mode 100644 Task/Mandelbrot-set/Z80-Assembly/mandelbrot-set.z80 rename Task/Map-range/Pascal/{map-range.pascal => map-range-1.pascal} (100%) create mode 100644 Task/Map-range/Pascal/map-range-2.pascal create mode 100644 Task/Map-range/Ruby/map-range-1.rb create mode 100644 Task/Map-range/Ruby/map-range-2.rb delete mode 100644 Task/Map-range/Ruby/map-range.rb rename Task/Matrix-multiplication/Fortran/{matrix-multiplication.f => matrix-multiplication-1.f} (100%) create mode 100644 Task/Matrix-multiplication/Fortran/matrix-multiplication-2.f create mode 100644 Task/Matrix-multiplication/Mathematica/matrix-multiplication-5.math create mode 100644 Task/Matrix-multiplication/Mathematica/matrix-multiplication-6.math create mode 100644 Task/Matrix-multiplication/Mathematica/matrix-multiplication-7.math create mode 100644 Task/Matrix-multiplication/Mathematica/matrix-multiplication-8.math create mode 100644 Task/Matrix-multiplication/Mathematica/matrix-multiplication-9.math rename Task/Matrix-multiplication/TI-83-BASIC/{matrix-multiplication.ti-83 => matrix-multiplication-1.ti-83} (100%) create mode 100644 Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-2.ti-83 create mode 100644 Task/Matrix-transposition/Clojure/matrix-transposition.clj create mode 100644 Task/Matrix-transposition/HicEst/matrix-transposition.hicest create mode 100644 Task/Maze-generation/Lua/maze-generation-1.lua create mode 100644 Task/Maze-generation/Lua/maze-generation-2.lua create mode 100644 Task/Maze-generation/Lua/maze-generation-3.lua create mode 100644 Task/Maze-generation/Lua/maze-generation-4.lua create mode 100644 Task/Memory-allocation/Maple/memory-allocation-1.maple create mode 100644 Task/Memory-allocation/Maple/memory-allocation-2.maple create mode 100644 Task/Memory-allocation/Maple/memory-allocation-3.maple create mode 100644 Task/Menu/Prolog/menu-1.pro create mode 100644 Task/Menu/Prolog/menu-2.pro create mode 100644 Task/Metaprogramming/Mathematica/metaprogramming.math create mode 100644 Task/Metaprogramming/Python/metaprogramming-1.py create mode 100644 Task/Metaprogramming/Python/metaprogramming-2.py create mode 100644 Task/Metronome/Go/metronome.go create mode 100644 Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg create mode 100644 Task/Middle-three-digits/Prolog/middle-three-digits-1.pro create mode 100644 Task/Middle-three-digits/Prolog/middle-three-digits-2.pro create mode 100644 Task/Middle-three-digits/Ruby/middle-three-digits-1.rb create mode 100644 Task/Middle-three-digits/Ruby/middle-three-digits-2.rb delete mode 100644 Task/Middle-three-digits/Ruby/middle-three-digits.rb create mode 100644 Task/Middle-three-digits/SQL/middle-three-digits.sql rename Task/Miller-Rabin-primality-test/Java/{miller-rabin-primality-test.java => miller-rabin-primality-test-1.java} (100%) create mode 100644 Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java create mode 100644 Task/Miller-Rabin-primality-test/Mercury/miller-rabin-primality-test.mercury create mode 100644 Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz rename Task/Miller-Rabin-primality-test/Perl/{miller-rabin-primality-test.pl => miller-rabin-primality-test-1.pl} (100%) create mode 100644 Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl create mode 100644 Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl create mode 100644 Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro create mode 100644 Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala create mode 100644 Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala create mode 100644 Task/Minesweeper-game/C++/minesweeper-game.cpp create mode 100644 Task/Minesweeper-game/Julia/minesweeper-game-1.julia create mode 100644 Task/Minesweeper-game/Julia/minesweeper-game-2.julia create mode 100644 Task/Minesweeper-game/MATLAB/minesweeper-game.m create mode 100644 Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx create mode 100644 Task/Modular-exponentiation/REXX/modular-exponentiation-2.rexx delete mode 100644 Task/Modular-exponentiation/REXX/modular-exponentiation.rexx create mode 100644 Task/Modular-exponentiation/Racket/modular-exponentiation.rkt create mode 100644 Task/Modular-inverse/AWK/modular-inverse.awk create mode 100644 Task/Modular-inverse/Ada/modular-inverse-1.ada rename Task/Modular-inverse/Ada/{modular-inverse.ada => modular-inverse-2.ada} (80%) create mode 100644 Task/Modular-inverse/Ada/modular-inverse-3.ada create mode 100644 Task/Modular-inverse/C/modular-inverse-1.c create mode 100644 Task/Modular-inverse/C/modular-inverse-2.c delete mode 100644 Task/Modular-inverse/C/modular-inverse.c create mode 100644 Task/Modular-inverse/Common-Lisp/modular-inverse.lisp rename Task/Modular-inverse/Mathematica/{modular-inverse.math => modular-inverse-1.math} (100%) create mode 100644 Task/Modular-inverse/Mathematica/modular-inverse-2.math create mode 100644 Task/Modular-inverse/PL-I/modular-inverse.pli create mode 100644 Task/Modular-inverse/Perl/modular-inverse-1.pl create mode 100644 Task/Modular-inverse/Perl/modular-inverse-2.pl delete mode 100644 Task/Modular-inverse/Perl/modular-inverse.pl create mode 100644 Task/Modular-inverse/PicoLisp/modular-inverse.l rename Task/Monte-Carlo-methods/Java/{monte-carlo-methods.java => monte-carlo-methods-1.java} (100%) create mode 100644 Task/Monte-Carlo-methods/Java/monte-carlo-methods-2.java delete mode 100644 Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 rename Task/Monty-Hall-problem/Python/{monty-hall-problem.py => monty-hall-problem-1.py} (100%) create mode 100644 Task/Monty-Hall-problem/Python/monty-hall-problem-2.py create mode 100644 Task/Monty-Hall-problem/Scilab/monty-hall-problem.scilab create mode 100644 Task/Mouse-position/MAXScript/mouse-position.max create mode 100644 Task/Mouse-position/Smalltalk/mouse-position.st create mode 100644 Task/Multifactorial/Java/multifactorial.java rename Task/Multiple-distinct-objects/J/{multiple-distinct-objects.j => multiple-distinct-objects-1.j} (100%) create mode 100644 Task/Multiple-distinct-objects/J/multiple-distinct-objects-2.j create mode 100644 Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects.pl6 create mode 100644 Task/Multiple-regression/Ruby/multiple-regression-3.rb create mode 100644 Task/Multiplication-tables/C/multiplication-tables.c create mode 100644 Task/Multiplication-tables/CoffeeScript/multiplication-tables.coffee create mode 100644 Task/Multiplication-tables/R/multiplication-tables.r create mode 100644 Task/Multiplication-tables/Visual-Basic/multiplication-tables.vb create mode 100644 Task/Multiplicative-order/Maple/multiplicative-order-1.maple create mode 100644 Task/Multiplicative-order/Maple/multiplicative-order-2.maple create mode 100644 Task/Multiplicative-order/Perl/multiplicative-order-1.pl create mode 100644 Task/Multiplicative-order/Perl/multiplicative-order-2.pl create mode 100644 Task/Multisplit/00META.yaml create mode 100644 Task/Multisplit/Haskell/multisplit.hs create mode 100644 Task/Multisplit/Java/multisplit.java create mode 100644 Task/Multisplit/Scheme/multisplit.ss create mode 100644 Task/Multisplit/UNIX-Shell/multisplit.sh create mode 100644 Task/Mutual-recursion/Elixir/mutual-recursion.elixir create mode 100644 Task/N-queens-problem/ABAP/n-queens-problem.abap create mode 100644 Task/N-queens-problem/Bracmat/n-queens-problem.bracmat create mode 100644 Task/N-queens-problem/C++/n-queens-problem-3.cpp create mode 100644 Task/N-queens-problem/C++/n-queens-problem-4.cpp create mode 100644 Task/N-queens-problem/Curry/n-queens-problem-4.curry create mode 100644 Task/N-queens-problem/Eiffel/n-queens-problem.e create mode 100644 Task/N-queens-problem/Fortran/n-queens-problem-4.f create mode 100644 Task/N-queens-problem/MUMPS/n-queens-problem-1.mumps rename Task/N-queens-problem/MUMPS/{n-queens-problem.mumps => n-queens-problem-2.mumps} (88%) create mode 100644 Task/N-queens-problem/Mathematica/n-queens-problem-4.math rename Task/N-queens-problem/Pascal/{n-queens-problem.pascal => n-queens-problem-1.pascal} (100%) create mode 100644 Task/N-queens-problem/Pascal/n-queens-problem-2.pascal create mode 100644 Task/N-queens-problem/Prolog/n-queens-problem-5.pro create mode 100644 Task/N-queens-problem/Python/n-queens-problem-5.py create mode 100644 Task/N-queens-problem/SQL/n-queens-problem.sql create mode 100644 Task/Named-parameters/Forth/named-parameters.fth create mode 100644 Task/Named-parameters/Perl/named-parameters-3.pl rename Task/Named-parameters/REXX/{named-parameters.rexx => named-parameters-1.rexx} (100%) create mode 100644 Task/Named-parameters/REXX/named-parameters-2.rexx create mode 100644 Task/Narcissist/AutoHotkey/narcissist-1.ahk create mode 100644 Task/Narcissist/AutoHotkey/narcissist-2.ahk create mode 100644 Task/Narcissist/C-sharp/narcissist.cs create mode 100644 Task/Narcissist/Haskell/narcissist.hs rename Task/Narcissist/JavaScript/{narcissist.js => narcissist-1.js} (100%) create mode 100644 Task/Narcissist/JavaScript/narcissist-2.js create mode 100644 Task/Nautical-bell/Haskell/nautical-bell.hs create mode 100644 Task/Nautical-bell/J/nautical-bell.j create mode 100644 Task/Nautical-bell/Java/nautical-bell.java create mode 100644 Task/Nautical-bell/Ruby/nautical-bell.rb create mode 100644 Task/Nautical-bell/Seed7/nautical-bell.seed7 create mode 100644 Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp create mode 100644 Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences.coffee create mode 100644 Task/Non-continuous-subsequences/D/non-continuous-subsequences-3.d create mode 100644 Task/Non-continuous-subsequences/Java/non-continuous-subsequences.java create mode 100644 Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences.pop11 create mode 100644 Task/Non-continuous-subsequences/Seed7/non-continuous-subsequences.seed7 create mode 100644 Task/Non-decimal-radices-Convert/Perl/non-decimal-radices-convert-3.pl create mode 100644 Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx create mode 100644 Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx delete mode 100644 Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx create mode 100644 Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert.rb create mode 100644 Task/Non-decimal-radices-Output/Bc/non-decimal-radices-output.bc create mode 100644 Task/Non-decimal-radices-Output/C-sharp/non-decimal-radices-output.cs create mode 100644 Task/Nth-root/NewLISP/nth-root.newlisp create mode 100644 Task/Nth-root/Objeck/nth-root.objeck create mode 100644 Task/Null-object/Eiffel/null-object.e create mode 100644 Task/Number-names/CoffeeScript/number-names.coffee create mode 100644 Task/Number-names/Objective-C/number-names.m create mode 100644 Task/Number-reversal-game/Eiffel/number-reversal-game-1.e create mode 100644 Task/Number-reversal-game/Eiffel/number-reversal-game-2.e create mode 100644 Task/Number-reversal-game/MATLAB/number-reversal-game.m create mode 100644 Task/Number-reversal-game/REBOL/number-reversal-game.rebol create mode 100644 Task/Number-reversal-game/Scala/number-reversal-game.scala create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-1.axiom create mode 100644 Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-2.axiom create mode 100644 Task/Numerical-integration/Chapel/numerical-integration-1.chapel create mode 100644 Task/Numerical-integration/Chapel/numerical-integration-2.chapel create mode 100644 Task/Object-serialization/Racket/object-serialization-1.rkt create mode 100644 Task/Object-serialization/Racket/object-serialization-2.rkt create mode 100644 Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee rename Task/One-dimensional-cellular-automata/Racket/{one-dimensional-cellular-automata.rkt => one-dimensional-cellular-automata-1.rkt} (100%) create mode 100644 Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-2.rkt create mode 100644 Task/One-of-n-lines-in-a-file/Mathematica/one-of-n-lines-in-a-file.math rename Task/One-of-n-lines-in-a-file/Pascal/{one-of-n-lines-in-a-file.pascal => one-of-n-lines-in-a-file-1.pascal} (100%) create mode 100644 Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-2.pascal create mode 100644 Task/One-of-n-lines-in-a-file/R/one-of-n-lines-in-a-file.r create mode 100644 Task/One-of-n-lines-in-a-file/Scala/one-of-n-lines-in-a-file.scala create mode 100644 Task/OpenGL/Common-Lisp/opengl.lisp create mode 100644 Task/OpenGL/Euphoria/opengl.euphoria create mode 100644 Task/OpenGL/Scala/opengl.scala create mode 100644 Task/Operator-precedence/AWK/operator-precedence.awk create mode 100644 Task/Optional-parameters/Bracmat/optional-parameters.bracmat create mode 100644 Task/Optional-parameters/Groovy/optional-parameters-1.groovy create mode 100644 Task/Optional-parameters/Groovy/optional-parameters-2.groovy create mode 100644 Task/Optional-parameters/Groovy/optional-parameters-3.groovy create mode 100644 Task/Optional-parameters/Groovy/optional-parameters-4.groovy create mode 100644 Task/Optional-parameters/Haskell/optional-parameters-1.hs create mode 100644 Task/Optional-parameters/Haskell/optional-parameters-2.hs create mode 100644 Task/Optional-parameters/Maple/optional-parameters-1.maple create mode 100644 Task/Optional-parameters/Maple/optional-parameters-2.maple create mode 100644 Task/Order-two-numerical-lists/AWK/order-two-numerical-lists.awk create mode 100644 Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-1.lua create mode 100644 Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-2.lua create mode 100644 Task/Order-two-numerical-lists/PL-I/order-two-numerical-lists.pli create mode 100644 Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-1.scala create mode 100644 Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-2.scala create mode 100644 Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-3.scala create mode 100644 Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-4.scala create mode 100644 Task/Ordered-Partitions/D/ordered-partitions-1.d create mode 100644 Task/Ordered-Partitions/D/ordered-partitions-2.d delete mode 100644 Task/Ordered-Partitions/D/ordered-partitions.d create mode 100644 Task/Ordered-Partitions/REXX/ordered-partitions.rexx create mode 100644 Task/Ordered-Partitions/Ruby/ordered-partitions-1.rb create mode 100644 Task/Ordered-Partitions/Ruby/ordered-partitions-2.rb create mode 100644 Task/Ordered-Partitions/Ruby/ordered-partitions-3.rb delete mode 100644 Task/Ordered-Partitions/Ruby/ordered-partitions.rb create mode 100644 Task/Palindrome-detection/Batch-File/palindrome-detection-1.bat create mode 100644 Task/Palindrome-detection/Batch-File/palindrome-detection-2.bat create mode 100644 Task/Palindrome-detection/Bracmat/palindrome-detection.bracmat create mode 100644 Task/Palindrome-detection/Eiffel/palindrome-detection.e create mode 100644 Task/Palindrome-detection/Elixir/palindrome-detection.elixir create mode 100644 Task/Palindrome-detection/FBSL/palindrome-detection.fbsl rename Task/Palindrome-detection/Frink/{palindrome-detection.frink => palindrome-detection-1.frink} (100%) create mode 100644 Task/Palindrome-detection/Frink/palindrome-detection-2.frink create mode 100644 Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty create mode 100644 Task/Palindrome-detection/PL-I/palindrome-detection-1.pli rename Task/Palindrome-detection/PL-I/{palindrome-detection.pli => palindrome-detection-2.pli} (100%) create mode 100644 Task/Pangram-checker/00META.yaml rename Task/Pangram-checker/AWK/{pangram-checker.awk => pangram-checker-1.awk} (69%) create mode 100644 Task/Pangram-checker/AWK/pangram-checker-2.awk create mode 100644 Task/Parallel-calculations/Factor/parallel-calculations-1.factor create mode 100644 Task/Parallel-calculations/Factor/parallel-calculations-2.factor create mode 100644 Task/Parallel-calculations/Java/parallel-calculations.java rename Task/Parallel-calculations/Python/{parallel-calculations.py => parallel-calculations-1.py} (86%) create mode 100644 Task/Parallel-calculations/Python/parallel-calculations-2.py create mode 100644 Task/Parametric-polymorphism/Groovy/parametric-polymorphism.groovy create mode 100644 Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust create mode 100644 Task/Parametrized-SQL-statement/Go/parametrized-sql-statement.go create mode 100644 Task/Parametrized-SQL-statement/Seed7/parametrized-sql-statement.seed7 create mode 100644 Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg create mode 100644 Task/Parsing-RPN-calculator-algorithm/Julia/parsing-rpn-calculator-algorithm.julia create mode 100644 Task/Parsing-RPN-calculator-algorithm/VBA/parsing-rpn-calculator-algorithm.vba create mode 100644 Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java create mode 100644 Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java create mode 100644 Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js create mode 100644 Task/Parsing-Shunting-yard-algorithm/VBA/parsing-shunting-yard-algorithm.vba create mode 100644 Task/Partial-function-application/Bracmat/partial-function-application.bracmat create mode 100644 Task/Partial-function-application/Go/partial-function-application.go create mode 100644 Task/Partial-function-application/Lua/partial-function-application.lua create mode 100644 Task/Pascals-triangle-Puzzle/Curry/pascals-triangle-puzzle.curry create mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-1.ada create mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-2.ada create mode 100644 Task/Pascals-triangle/Ada/pascals-triangle-3.ada delete mode 100644 Task/Pascals-triangle/Ada/pascals-triangle.ada create mode 100644 Task/Pascals-triangle/Clojure/pascals-triangle-4.clj create mode 100644 Task/Pascals-triangle/Clojure/pascals-triangle-5.clj create mode 100644 Task/Pascals-triangle/Clojure/pascals-triangle-6.clj create mode 100644 Task/Pascals-triangle/Perl/pascals-triangle-3.pl create mode 100644 Task/Pattern-matching/Erlang/pattern-matching.erl create mode 100644 Task/Percentage-difference-between-images/Haskell/percentage-difference-between-images.hs create mode 100644 Task/Perfect-numbers/Eiffel/perfect-numbers-1.e create mode 100644 Task/Perfect-numbers/Eiffel/perfect-numbers-2.e create mode 100644 Task/Perfect-numbers/Elixir/perfect-numbers.elixir create mode 100644 Task/Perfect-numbers/MATLAB/perfect-numbers-1.m create mode 100644 Task/Perfect-numbers/MATLAB/perfect-numbers-2.m create mode 100644 Task/Perfect-numbers/Perl/perfect-numbers-3.pl create mode 100644 Task/Perfect-numbers/Perl/perfect-numbers-4.pl create mode 100644 Task/Perfect-numbers/Perl/perfect-numbers-5.pl create mode 100644 Task/Perfect-numbers/REXX/perfect-numbers-7.rexx create mode 100644 Task/Perfect-numbers/Ruby/perfect-numbers-5.rb rename Task/Perfect-numbers/Scala/{perfect-numbers.scala => perfect-numbers-1.scala} (100%) create mode 100644 Task/Perfect-numbers/Scala/perfect-numbers-2.scala create mode 100644 Task/Permutation-test/Ruby/permutation-test.rb create mode 100644 Task/Permutations-Derangements/BBC-BASIC/permutations-derangements.bbc create mode 100644 Task/Permutations-Derangements/Bracmat/permutations-derangements.bracmat create mode 100644 Task/Permutations-Derangements/Scala/permutations-derangements.scala create mode 100644 Task/Permutations-by-swapping/Icon/permutations-by-swapping.icon create mode 100644 Task/Permutations-by-swapping/PicoLisp/permutations-by-swapping.l create mode 100644 Task/Permutations/Eiffel/permutations.e rename Task/Permutations/Lua/{permutations.lua => permutations-1.lua} (100%) create mode 100644 Task/Permutations/Lua/permutations-2.lua create mode 100644 Task/Permutations/Perl/permutations-1.pl create mode 100644 Task/Permutations/Perl/permutations-2.pl delete mode 100644 Task/Permutations/Perl/permutations.pl create mode 100644 Task/Pi/Perl/pi-3.pl create mode 100644 Task/Pi/Perl/pi-4.pl create mode 100644 Task/Pi/Racket/pi-1.rkt create mode 100644 Task/Pi/Racket/pi-2.rkt delete mode 100644 Task/Pi/Racket/pi.rkt create mode 100644 Task/Pick-random-element/ALGOL-68/pick-random-element.alg create mode 100644 Task/Pick-random-element/C-sharp/pick-random-element.cs create mode 100644 Task/Pick-random-element/Elixir/pick-random-element.elixir create mode 100644 Task/Pick-random-element/Falcon/pick-random-element.falcon create mode 100644 Task/Pick-random-element/Haskell/pick-random-element-3.hs create mode 100644 Task/Pick-random-element/Maxima/pick-random-element.maxima create mode 100644 Task/Pick-random-element/Prolog/pick-random-element.pro create mode 100644 Task/Pick-random-element/Scala/pick-random-element.scala create mode 100644 Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e create mode 100644 Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e create mode 100644 Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e create mode 100644 Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml create mode 100644 Task/Pinstripe-Display/C-sharp/pinstripe-display.cs create mode 100644 Task/Pinstripe-Display/Java/pinstripe-display.java create mode 100644 Task/Playing-cards/Go/playing-cards-1.go create mode 100644 Task/Playing-cards/Go/playing-cards-2.go delete mode 100644 Task/Playing-cards/Go/playing-cards.go create mode 100644 Task/Playing-cards/Rust/playing-cards.rust create mode 100644 Task/Plot-coordinate-pairs/Clojure/plot-coordinate-pairs.clj rename Task/Plot-coordinate-pairs/Python/{plot-coordinate-pairs.py => plot-coordinate-pairs-1.py} (100%) create mode 100644 Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-2.py create mode 100644 Task/Polymorphic-copy/Groovy/polymorphic-copy-1.groovy create mode 100644 Task/Polymorphic-copy/Groovy/polymorphic-copy-2.groovy create mode 100644 Task/Polymorphism/AutoHotkey/polymorphism.ahk create mode 100644 Task/Polymorphism/Ruby/polymorphism-1.rb create mode 100644 Task/Polymorphism/Ruby/polymorphism-2.rb delete mode 100644 Task/Polymorphism/Ruby/polymorphism.rb create mode 100644 Task/Polynomial-regression/HicEst/polynomial-regression.hicest create mode 100644 Task/Polynomial-regression/Julia/polynomial-regression.julia create mode 100644 Task/Polynomial-regression/R/polynomial-regression.r create mode 100644 Task/Power-set/Perl/power-set-7.pl create mode 100644 Task/Power-set/SAS/power-set-1.sas create mode 100644 Task/Power-set/SAS/power-set-2.sas create mode 100644 Task/Power-set/Scala/power-set-1.scala create mode 100644 Task/Power-set/Scala/power-set-2.scala delete mode 100644 Task/Power-set/Scala/power-set.scala create mode 100644 Task/Price-fraction/Clojure/price-fraction.clj create mode 100644 Task/Price-fraction/Factor/price-fraction.factor create mode 100644 Task/Price-fraction/K/price-fraction.k create mode 100644 Task/Price-fraction/Rust/price-fraction.rust rename Task/Primality-by-trial-division/Ada/{primality-by-trial-division.ada => primality-by-trial-division-1.ada} (100%) create mode 100644 Task/Primality-by-trial-division/Ada/primality-by-trial-division-2.ada create mode 100644 Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp create mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-1.l create mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-2.l create mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-3.l create mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-4.l create mode 100644 Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-5.l create mode 100644 Task/Primality-by-trial-division/Oz/primality-by-trial-division.oz rename Task/Primality-by-trial-division/Pascal/{primality-by-trial-division.pascal => primality-by-trial-division-1.pascal} (100%) create mode 100644 Task/Primality-by-trial-division/Pascal/primality-by-trial-division-2.pascal create mode 100644 Task/Primality-by-trial-division/Perl/primality-by-trial-division-3.pl create mode 100644 Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust create mode 100644 Task/Prime-decomposition/Eiffel/prime-decomposition.e create mode 100644 Task/Prime-decomposition/J/prime-decomposition-3.j rename Task/Prime-decomposition/Perl/{prime-decomposition.pl => prime-decomposition-1.pl} (100%) create mode 100644 Task/Prime-decomposition/Perl/prime-decomposition-2.pl create mode 100644 Task/Prime-decomposition/Perl/prime-decomposition-3.pl create mode 100644 Task/Prime-decomposition/Perl/prime-decomposition-4.pl create mode 100644 Task/Priority-queue/C-sharp/priority-queue.cs create mode 100644 Task/Priority-queue/Clojure/priority-queue.clj create mode 100644 Task/Priority-queue/Lua/priority-queue-1.lua create mode 100644 Task/Priority-queue/Lua/priority-queue-2.lua create mode 100644 Task/Probabilistic-choice/Erlang/probabilistic-choice.erl create mode 100644 Task/Probabilistic-choice/MATLAB/probabilistic-choice-1.m create mode 100644 Task/Probabilistic-choice/MATLAB/probabilistic-choice-2.m create mode 100644 Task/Probabilistic-choice/Scala/probabilistic-choice.scala create mode 100644 Task/Probabilistic-choice/Scheme/probabilistic-choice.ss create mode 100644 Task/Program-name/Mercury/program-name.mercury create mode 100644 Task/Program-name/Oberon-2/program-name.oberon-2 rename Task/Program-name/Perl/{program-name.pl => program-name-1.pl} (100%) create mode 100644 Task/Program-name/Perl/program-name-2.pl create mode 100644 Task/Program-name/Scala/program-name.scala rename Task/Program-termination/AWK/{program-termination.awk => program-termination-1.awk} (100%) create mode 100644 Task/Program-termination/AWK/program-termination-2.awk create mode 100644 Task/Program-termination/D/program-termination-1.d create mode 100644 Task/Program-termination/D/program-termination-2.d create mode 100644 Task/Program-termination/Emacs-Lisp/program-termination.l create mode 100644 Task/Program-termination/Gnuplot/program-termination.gnuplot create mode 100644 Task/Program-termination/Oberon-2/program-termination.oberon-2 create mode 100644 Task/Program-termination/Scala/program-termination.scala create mode 100644 Task/Pythagorean-triples/D/pythagorean-triples-3.d create mode 100644 Task/Pythagorean-triples/D/pythagorean-triples-4.d create mode 100644 Task/Pythagorean-triples/Eiffel/pythagorean-triples.e create mode 100644 Task/Pythagorean-triples/Groovy/pythagorean-triples-1.groovy create mode 100644 Task/Pythagorean-triples/Groovy/pythagorean-triples-2.groovy create mode 100644 Task/Pythagorean-triples/Scheme/pythagorean-triples.ss create mode 100644 Task/Quaternion-type/Axiom/quaternion-type.axiom create mode 100644 Task/Queue-Definition/Bracmat/queue-definition.bracmat create mode 100644 Task/Queue-Definition/CoffeeScript/queue-definition.coffee create mode 100644 Task/Queue-Definition/UNIX-Shell/queue-definition-1.sh create mode 100644 Task/Queue-Definition/UNIX-Shell/queue-definition-2.sh create mode 100644 Task/Queue-Usage/Bracmat/queue-usage.bracmat rename Task/Queue-Usage/Lua/{queue-usage.lua => queue-usage-1.lua} (100%) create mode 100644 Task/Queue-Usage/Lua/queue-usage-2.lua create mode 100644 Task/Queue-Usage/UNIX-Shell/queue-usage.sh rename Task/Quine/Frink/{quine.frink => quine-1.frink} (100%) create mode 100644 Task/Quine/Frink/quine-2.frink create mode 100644 Task/Quine/J/quine-1.j rename Task/Quine/J/{quine.j => quine-2.j} (100%) create mode 100644 Task/Quine/JavaScript/quine-4.js create mode 100644 Task/Quine/Mathematica/quine-4.math create mode 100644 Task/Quine/Mathematica/quine-5.math rename Task/Quine/Pascal/{quine.pascal => quine-1.pascal} (100%) create mode 100644 Task/Quine/Pascal/quine-2.pascal rename Task/Quine/Perl-6/{quine.pl6 => quine-1.pl6} (100%) create mode 100644 Task/Quine/Perl-6/quine-2.pl6 rename Task/Quine/Prolog/{quine.pro => quine-1.pro} (100%) create mode 100644 Task/Quine/Prolog/quine-2.pro create mode 100644 Task/Quine/Python/quine-8.py create mode 100644 Task/Quine/Ruby/quine-4.rb rename Task/Quine/Rust/{quine.rust => quine-1.rust} (98%) create mode 100644 Task/Quine/Rust/quine-2.rust rename Task/Quine/Standard-ML/{quine.ml => quine-1.ml} (100%) create mode 100644 Task/Quine/Standard-ML/quine-2.ml create mode 100644 Task/RIPEMD-160/Clojure/ripemd-160.clj create mode 100644 Task/RIPEMD-160/Perl/ripemd-160-1.pl create mode 100644 Task/RIPEMD-160/Perl/ripemd-160-2.pl create mode 100644 Task/RIPEMD-160/PicoLisp/ripemd-160.l create mode 100644 Task/RIPEMD-160/Scala/ripemd-160.scala create mode 100644 Task/Random-number-generator--device-/C/random-number-generator--device--6.c create mode 100644 Task/Random-number-generator--device-/Fortran/random-number-generator--device-.f create mode 100644 Task/Random-number-generator--device-/Mathematica/random-number-generator--device--1.math create mode 100644 Task/Random-number-generator--device-/Mathematica/random-number-generator--device--2.math create mode 100644 Task/Random-number-generator--device-/Perl/random-number-generator--device--1.pl create mode 100644 Task/Random-number-generator--device-/Perl/random-number-generator--device--2.pl rename Task/Random-number-generator--device-/Perl/{random-number-generator--device-.pl => random-number-generator--device--3.pl} (100%) create mode 100644 Task/Random-number-generator--device-/UNIX-Shell/random-number-generator--device-.sh create mode 100644 Task/Random-number-generator--included-/Elixir/random-number-generator--included-.elixir rename Task/Random-numbers/AWK/{random-numbers.awk => random-numbers-1.awk} (100%) create mode 100644 Task/Random-numbers/AWK/random-numbers-2.awk create mode 100644 Task/Random-numbers/Elixir/random-numbers.elixir create mode 100644 Task/Random-numbers/Pascal/random-numbers.pascal create mode 100644 Task/Random-numbers/Python/random-numbers-3.py create mode 100644 Task/Range-expansion/COBOL/range-expansion.cobol create mode 100644 Task/Range-expansion/Lua/range-expansion.lua create mode 100644 Task/Range-expansion/R/range-expansion.r rename Task/Range-extraction/C-sharp/{range-extraction.cs => range-extraction-1.cs} (100%) create mode 100644 Task/Range-extraction/C-sharp/range-extraction-2.cs create mode 100644 Task/Range-extraction/C/range-extraction.c create mode 100644 Task/Range-extraction/Eiffel/range-extraction.e create mode 100644 Task/Range-extraction/Emacs-Lisp/range-extraction.l create mode 100644 Task/Range-extraction/K/range-extraction.k create mode 100644 Task/Range-extraction/Objective-C/range-extraction.m create mode 100644 Task/Range-extraction/Oz/range-extraction.oz rename Task/Range-extraction/Perl/{range-extraction.pl => range-extraction-1.pl} (100%) create mode 100644 Task/Range-extraction/Perl/range-extraction-2.pl create mode 100644 Task/Range-extraction/Perl/range-extraction-3.pl create mode 100644 Task/Rate-counter/Haskell/rate-counter.hs create mode 100644 Task/Rate-counter/Mathematica/rate-counter.math create mode 100644 Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj create mode 100644 Task/Read-a-configuration-file/Mathematica/read-a-configuration-file.math create mode 100644 Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file.l create mode 100644 Task/Read-a-configuration-file/RapidQ/read-a-configuration-file.rapidq create mode 100644 Task/Read-a-configuration-file/UNIX-Shell/read-a-configuration-file.sh rename Task/Read-a-file-line-by-line/AWK/{read-a-file-line-by-line.awk => read-a-file-line-by-line-1.awk} (100%) create mode 100644 Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-2.awk create mode 100644 Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-3.awk create mode 100644 Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c create mode 100644 Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-4.pl create mode 100644 Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-5.pl create mode 100644 Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-6.pl rename Task/Read-a-file-line-by-line/REXX/{read-a-file-line-by-line.rexx => read-a-file-line-by-line-1.rexx} (70%) create mode 100644 Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-2.rexx create mode 100644 Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx create mode 100644 Task/Read-a-file-line-by-line/RapidQ/read-a-file-line-by-line.rapidq create mode 100644 Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust create mode 100644 Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-4.st create mode 100644 Task/Read-a-specific-line-from-a-file/ALGOL-68/read-a-specific-line-from-a-file.alg rename Task/Read-a-specific-line-from-a-file/C/{read-a-specific-line-from-a-file.c => read-a-specific-line-from-a-file-1.c} (100%) create mode 100644 Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-2.c create mode 100644 Task/Read-a-specific-line-from-a-file/Clojure/read-a-specific-line-from-a-file.clj create mode 100644 Task/Read-a-specific-line-from-a-file/Lua/read-a-specific-line-from-a-file.lua create mode 100644 Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-1.py create mode 100644 Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-2.py create mode 100644 Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-3.py delete mode 100644 Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file.py create mode 100644 Task/Read-a-specific-line-from-a-file/Smalltalk/read-a-specific-line-from-a-file.st create mode 100644 Task/Read-a-specific-line-from-a-file/UNIX-Shell/read-a-specific-line-from-a-file.sh rename Task/Read-entire-file/AWK/{read-entire-file.awk => read-entire-file-1.awk} (100%) create mode 100644 Task/Read-entire-file/AWK/read-entire-file-2.awk create mode 100644 Task/Read-entire-file/Emacs-Lisp/read-entire-file.l create mode 100644 Task/Read-entire-file/M4/read-entire-file.m4 create mode 100644 Task/Read-entire-file/Make/read-entire-file.make create mode 100644 Task/Read-entire-file/Perl/read-entire-file-6.pl create mode 100644 Task/Read-entire-file/Perl/read-entire-file-7.pl create mode 100644 Task/Read-entire-file/Perl/read-entire-file-8.pl create mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx create mode 100644 Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx create mode 100644 Task/Real-constants-and-functions/UNIX-Shell/real-constants-and-functions.sh create mode 100644 Task/Record-sound/00META.yaml create mode 100644 Task/Record-sound/C++/record-sound.cpp create mode 100644 Task/Record-sound/Scala/record-sound.scala create mode 100644 Task/Reduced-row-echelon-form/Icon/reduced-row-echelon-form.icon create mode 100644 Task/Regular-expressions/MAXScript/regular-expressions.max create mode 100644 Task/Regular-expressions/UNIX-Shell/regular-expressions-1.sh create mode 100644 Task/Regular-expressions/UNIX-Shell/regular-expressions-2.sh create mode 100644 Task/Regular-expressions/UNIX-Shell/regular-expressions-3.sh create mode 100644 Task/Regular-expressions/UNIX-Shell/regular-expressions-4.sh create mode 100644 Task/Remove-duplicate-elements/Go/remove-duplicate-elements-4.go create mode 100644 Task/Remove-duplicate-elements/Python/remove-duplicate-elements-4.py create mode 100644 Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-1.rb create mode 100644 Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-2.rb create mode 100644 Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb delete mode 100644 Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements.rb create mode 100644 Task/Remove-lines-from-a-file/Frink/remove-lines-from-a-file.frink create mode 100644 Task/Remove-lines-from-a-file/Mathematica/remove-lines-from-a-file.math create mode 100644 Task/Remove-lines-from-a-file/Scala/remove-lines-from-a-file.scala create mode 100644 Task/Rename-a-file/OpenEdge-Progress/rename-a-file.openedge create mode 100644 Task/Repeat-a-string/ATS/repeat-a-string.ats create mode 100644 Task/Repeat-a-string/ColdFusion/repeat-a-string.cfm create mode 100644 Task/Repeat-a-string/Common-Lisp/repeat-a-string-3.lisp create mode 100644 Task/Repeat-a-string/Common-Lisp/repeat-a-string-4.lisp create mode 100644 Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi create mode 100644 Task/Repeat-a-string/Eiffel/repeat-a-string.e create mode 100644 Task/Repeat-a-string/Elixir/repeat-a-string.elixir create mode 100644 Task/Repeat-a-string/Haskell/repeat-a-string-5.hs create mode 100644 Task/Repeat-a-string/JavaScript/repeat-a-string-1.js create mode 100644 Task/Repeat-a-string/JavaScript/repeat-a-string-2.js delete mode 100644 Task/Repeat-a-string/JavaScript/repeat-a-string.js rename Task/Repeat-a-string/PARI-GP/{repeat-a-string.pari => repeat-a-string-1.pari} (100%) create mode 100644 Task/Repeat-a-string/PARI-GP/repeat-a-string-2.pari create mode 100644 Task/Repeat-a-string/RapidQ/repeat-a-string.rapidq create mode 100644 Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-1.visual create mode 100644 Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-2.visual delete mode 100644 Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string.visual create mode 100644 Task/Resistor-mesh/00META.yaml create mode 100644 Task/Resistor-mesh/Octave/resistor-mesh.octave rename Task/Resistor-mesh/Python/{resistor-mesh.py => resistor-mesh-1.py} (100%) create mode 100644 Task/Resistor-mesh/Python/resistor-mesh-2.py create mode 100644 Task/Resistor-mesh/Racket/resistor-mesh.rkt create mode 100644 Task/Respond-to-an-unknown-method-call/Go/respond-to-an-unknown-method-call.go create mode 100644 Task/Respond-to-an-unknown-method-call/Groovy/respond-to-an-unknown-method-call-1.groovy create mode 100644 Task/Respond-to-an-unknown-method-call/Groovy/respond-to-an-unknown-method-call-2.groovy create mode 100644 Task/Respond-to-an-unknown-method-call/Groovy/respond-to-an-unknown-method-call-3.groovy create mode 100644 Task/Respond-to-an-unknown-method-call/Groovy/respond-to-an-unknown-method-call-4.groovy create mode 100644 Task/Return-multiple-values/ALGOL-68/return-multiple-values.alg create mode 100644 Task/Return-multiple-values/Eiffel/return-multiple-values-1.e create mode 100644 Task/Return-multiple-values/Eiffel/return-multiple-values-2.e create mode 100644 Task/Return-multiple-values/Frink/return-multiple-values.frink create mode 100644 Task/Reverse-a-string/ATS/reverse-a-string.ats create mode 100644 Task/Reverse-a-string/AWK/reverse-a-string-3.awk create mode 100644 Task/Reverse-a-string/Dart/reverse-a-string-1.dart create mode 100644 Task/Reverse-a-string/Dart/reverse-a-string-2.dart delete mode 100644 Task/Reverse-a-string/Dart/reverse-a-string.dart create mode 100644 Task/Reverse-a-string/Elixir/reverse-a-string.elixir rename Task/Reverse-a-string/Julia/{reverse-a-string.julia => reverse-a-string-1.julia} (100%) create mode 100644 Task/Reverse-a-string/Julia/reverse-a-string-2.julia create mode 100644 Task/Reverse-a-string/OOC/reverse-a-string.ooc create mode 100644 Task/Reverse-a-string/Pascal/reverse-a-string-4.pascal create mode 100644 Task/Reverse-a-string/Scala/reverse-a-string-4.scala create mode 100644 Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg create mode 100644 Task/Rock-paper-scissors/BASIC/rock-paper-scissors.basic create mode 100644 Task/Rock-paper-scissors/Clojure/rock-paper-scissors.clj create mode 100644 Task/Rock-paper-scissors/D/rock-paper-scissors.d rename Task/Rock-paper-scissors/Go/{rock-paper-scissors.go => rock-paper-scissors-1.go} (100%) create mode 100644 Task/Rock-paper-scissors/Go/rock-paper-scissors-2.go create mode 100644 Task/Rock-paper-scissors/Perl/rock-paper-scissors-1.pl create mode 100644 Task/Rock-paper-scissors/Perl/rock-paper-scissors-2.pl create mode 100644 Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx create mode 100644 Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx delete mode 100644 Task/Rock-paper-scissors/REXX/rock-paper-scissors.rexx create mode 100644 Task/Rock-paper-scissors/Scala/rock-paper-scissors-1.scala create mode 100644 Task/Rock-paper-scissors/Scala/rock-paper-scissors-2.scala create mode 100644 Task/Roman-numerals-Decode/Eiffel/roman-numerals-decode.e create mode 100644 Task/Roman-numerals-Decode/R/roman-numerals-decode-1.r create mode 100644 Task/Roman-numerals-Decode/R/roman-numerals-decode-2.r create mode 100644 Task/Roman-numerals-Decode/R/roman-numerals-decode-3.r create mode 100644 Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-1.ss create mode 100644 Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-2.ss create mode 100644 Task/Roman-numerals-Encode/00META.yaml create mode 100644 Task/Roman-numerals-Encode/Eiffel/roman-numerals-encode.e create mode 100644 Task/Roman-numerals-Encode/Haskell/roman-numerals-encode.hs create mode 100644 Task/Roman-numerals-Encode/Maple/roman-numerals-encode.maple create mode 100644 Task/Roman-numerals-Encode/Perl/roman-numerals-encode-4.pl rename Task/Roman-numerals-Encode/Ruby/{roman-numerals-encode.rb => roman-numerals-encode-1.rb} (100%) create mode 100644 Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-2.rb create mode 100644 Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-3.rb create mode 100644 Task/Roman-numerals-Encode/UNIX-Shell/roman-numerals-encode.sh create mode 100644 Task/Roots-of-a-function/ATS/roots-of-a-function.ats create mode 100644 Task/Roots-of-a-function/Icon/roots-of-a-function.icon create mode 100644 Task/Roots-of-a-function/JavaScript/roots-of-a-function.js create mode 100644 Task/Roots-of-a-function/Scala/roots-of-a-function.scala rename Task/Roots-of-unity/PARI-GP/{roots-of-unity.pari => roots-of-unity-1.pari} (100%) create mode 100644 Task/Roots-of-unity/PARI-GP/roots-of-unity-2.pari create mode 100644 Task/Roots-of-unity/PARI-GP/roots-of-unity-3.pari create mode 100644 Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat create mode 100644 Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck create mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math create mode 100644 Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat create mode 100644 Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck create mode 100644 Task/Rot-13/Clojure/rot-13.clj create mode 100644 Task/Rot-13/NewLISP/rot-13.newlisp create mode 100644 Task/Rot-13/Python/rot-13-3.py create mode 100644 Task/Rot-13/Python/rot-13-4.py create mode 100644 Task/Rot-13/Python/rot-13-5.py create mode 100644 Task/Rot-13/SQL/rot-13-1.sql rename Task/Rot-13/SQL/{rot-13.sql => rot-13-2.sql} (100%) rename Task/Rot-13/TXR/{rot-13.txr => rot-13-1.txr} (96%) create mode 100644 Task/Rot-13/TXR/rot-13-2.txr create mode 100644 Task/Runtime-evaluation-In-an-environment/Bracmat/runtime-evaluation-in-an-environment.bracmat rename Task/Runtime-evaluation-In-an-environment/Lua/{runtime-evaluation-in-an-environment.lua => runtime-evaluation-in-an-environment-1.lua} (100%) create mode 100644 Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-2.lua create mode 100644 Task/Runtime-evaluation-In-an-environment/MATLAB/runtime-evaluation-in-an-environment.m rename Task/Runtime-evaluation/ALGOL-68/{runtime-evaluation.alg => runtime-evaluation-1.alg} (100%) create mode 100644 Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-2.alg create mode 100644 Task/Runtime-evaluation/Frink/runtime-evaluation.frink rename Task/Runtime-evaluation/Lua/{runtime-evaluation.lua => runtime-evaluation-1.lua} (100%) create mode 100644 Task/Runtime-evaluation/Lua/runtime-evaluation-2.lua create mode 100644 Task/Runtime-evaluation/MATLAB/runtime-evaluation.m create mode 100644 Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol create mode 100644 Task/Runtime-evaluation/UNIX-Shell/runtime-evaluation.sh create mode 100644 Task/SEDOLs/Clojure/sedols.clj create mode 100644 Task/SEDOLs/Delphi/sedols.delphi create mode 100644 Task/SEDOLs/Transact-SQL/sedols.sql create mode 100644 Task/SHA-1/Haskell/sha-1.hs create mode 100644 Task/SHA-1/NewLISP/sha-1.newlisp create mode 100644 Task/SHA-1/Pascal/sha-1.pascal create mode 100644 Task/SHA-256/Clojure/sha-256.clj create mode 100644 Task/SHA-256/D/sha-256-1.d rename Task/SHA-256/D/{sha-256.d => sha-256-2.d} (91%) create mode 100644 Task/SHA-256/Emacs-Lisp/sha-256.l create mode 100644 Task/SHA-256/NewLISP/sha-256.newlisp create mode 100644 Task/SHA-256/PicoLisp/sha-256.l create mode 100644 Task/SHA-256/Rust/sha-256.rust create mode 100644 Task/SHA-256/Scala/sha-256.scala create mode 100644 Task/SHA-256/Smalltalk/sha-256.st create mode 100644 Task/SQL-based-authentication/Go/sql-based-authentication.go create mode 100644 Task/SQL-based-authentication/Objeck/sql-based-authentication.objeck create mode 100644 Task/Same-Fringe/D/same-fringe-3.d create mode 100644 Task/Same-Fringe/Scheme/same-fringe.ss create mode 100644 Task/Scope-Function-names-and-labels/Eiffel/scope-function-names-and-labels.e create mode 100644 Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-1.go create mode 100644 Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-2.go create mode 100644 Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-3.go create mode 100644 Task/Scope-modifiers/Eiffel/scope-modifiers.e create mode 100644 Task/Scope-modifiers/Ruby/scope-modifiers.rb create mode 100644 Task/Search-a-list/Maxima/search-a-list.maxima create mode 100644 Task/Search-a-list/UNIX-Shell/search-a-list.sh create mode 100644 Task/Secure-temporary-file/Emacs-Lisp/secure-temporary-file.l create mode 100644 Task/Secure-temporary-file/Icon/secure-temporary-file.icon rename Task/Self-describing-numbers/C++/{self-describing-numbers.cpp => self-describing-numbers-1.cpp} (94%) create mode 100644 Task/Self-describing-numbers/C++/self-describing-numbers-2.cpp create mode 100644 Task/Self-describing-numbers/PHP/self-describing-numbers.php create mode 100644 Task/Self-describing-numbers/UNIX-Shell/self-describing-numbers.sh create mode 100644 Task/Self-referential-sequence/Java/self-referential-sequence.java create mode 100644 Task/Self-referential-sequence/TXR/self-referential-sequence-1.txr create mode 100644 Task/Self-referential-sequence/TXR/self-referential-sequence-2.txr create mode 100644 Task/Self-referential-sequence/TXR/self-referential-sequence-3.txr create mode 100644 Task/Semordnilap/Eiffel/semordnilap-1.e create mode 100644 Task/Semordnilap/Eiffel/semordnilap-2.e create mode 100644 Task/Send-an-unknown-method-call/J/send-an-unknown-method-call.j create mode 100644 Task/Send-an-unknown-method-call/Mathematica/send-an-unknown-method-call.math create mode 100644 Task/Send-an-unknown-method-call/Scala/send-an-unknown-method-call.scala create mode 100644 Task/Send-email/Clojure/send-email.clj rename Task/Send-email/Go/{send-email.go => send-email-1.go} (100%) create mode 100644 Task/Send-email/Go/send-email-2.go create mode 100644 Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares.coffee create mode 100644 Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e rename Task/Sequence-of-non-squares/Pascal/{sequence-of-non-squares.pascal => sequence-of-non-squares-1.pascal} (100%) create mode 100644 Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-2.pascal create mode 100644 Task/Set-consolidation/Scala/set-consolidation.scala create mode 100644 Task/Set-of-real-numbers/Clojure/set-of-real-numbers.clj create mode 100644 Task/Set-of-real-numbers/D/set-of-real-numbers.d create mode 100644 Task/Set-of-real-numbers/Go/set-of-real-numbers-1.go create mode 100644 Task/Set-of-real-numbers/Go/set-of-real-numbers-2.go create mode 100644 Task/Set-of-real-numbers/Go/set-of-real-numbers-3.go create mode 100644 Task/Set-of-real-numbers/Mathematica/set-of-real-numbers.math create mode 100644 Task/Set-of-real-numbers/Ruby/set-of-real-numbers-1.rb create mode 100644 Task/Set-of-real-numbers/Ruby/set-of-real-numbers-2.rb create mode 100644 Task/Set-of-real-numbers/Ruby/set-of-real-numbers-3.rb create mode 100644 Task/Set-puzzle/00META.yaml create mode 100644 Task/Set-puzzle/Ada/set-puzzle-1.ada create mode 100644 Task/Set-puzzle/Ada/set-puzzle-2.ada create mode 100644 Task/Set-puzzle/Ada/set-puzzle-3.ada rename Task/Set-puzzle/D/{set-puzzle.d => set-puzzle-1.d} (64%) create mode 100644 Task/Set-puzzle/D/set-puzzle-2.d create mode 100644 Task/Set-puzzle/Mathematica/set-puzzle.math rename Task/Set-puzzle/Python/{set-puzzle.py => set-puzzle-1.py} (100%) create mode 100644 Task/Set-puzzle/Python/set-puzzle-2.py create mode 100644 Task/Set-puzzle/REXX/set-puzzle.rexx rename Task/Set/Prolog/{set.pro => set-1.pro} (100%) create mode 100644 Task/Set/Prolog/set-2.pro create mode 100644 Task/Seven-sided-dice-from-five-sided-dice/Julia/seven-sided-dice-from-five-sided-dice.julia create mode 100644 Task/Shell-one-liner/Maple/shell-one-liner.maple create mode 100644 Task/Sierpinski-carpet/Euphoria/sierpinski-carpet.euphoria create mode 100644 Task/Sierpinski-carpet/J/sierpinski-carpet-4.j create mode 100644 Task/Sierpinski-carpet/J/sierpinski-carpet-5.j create mode 100644 Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia create mode 100644 Task/Sierpinski-carpet/Objeck/sierpinski-carpet.objeck create mode 100644 Task/Sierpinski-carpet/VBScript/sierpinski-carpet.vb create mode 100644 Task/Sierpinski-triangle-Graphical/Java/sierpinski-triangle-graphical.java create mode 100644 Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py rename Task/Sierpinski-triangle-Graphical/Python/{sierpinski-triangle-graphical.py => sierpinski-triangle-graphical-2.py} (68%) create mode 100644 Task/Sierpinski-triangle/ATS/sierpinski-triangle.ats create mode 100644 Task/Sierpinski-triangle/D/sierpinski-triangle-3.d create mode 100644 Task/Sierpinski-triangle/D/sierpinski-triangle-4.d create mode 100644 Task/Sierpinski-triangle/Python/sierpinski-triangle-3.py create mode 100644 Task/Sieve-of-Eratosthenes/360-Assembly/sieve-of-eratosthenes.360 create mode 100644 Task/Sieve-of-Eratosthenes/ALGOL-60/sieve-of-eratosthenes.alg create mode 100644 Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk create mode 100644 Task/Sieve-of-Eratosthenes/Batch-File/sieve-of-eratosthenes.bat create mode 100644 Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-1.c create mode 100644 Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c create mode 100644 Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-3.c delete mode 100644 Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c create mode 100644 Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes.cmake create mode 100644 Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-1.dart create mode 100644 Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-2.dart create mode 100644 Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-3.dart delete mode 100644 Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart create mode 100644 Task/Sieve-of-Eratosthenes/Delphi/sieve-of-eratosthenes.delphi create mode 100644 Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-1.l create mode 100644 Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-2.l create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs create mode 100644 Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs create mode 100644 Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-10.hs create mode 100644 Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs create mode 100644 Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs create mode 100644 Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs create mode 100644 Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-1.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-10.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-11.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-12.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-2.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-3.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-4.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-5.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-6.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-7.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-8.j create mode 100644 Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-9.j create mode 100644 Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-4.java create mode 100644 Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-5.java create mode 100644 Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java create mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-1.js create mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-2.js create mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-3.js create mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-4.js create mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-5.js delete mode 100644 Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js create mode 100644 Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua create mode 100644 Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-2.lua create mode 100644 Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-3.lua delete mode 100644 Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua create mode 100644 Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-1.math create mode 100644 Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-2.math create mode 100644 Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-3.math delete mode 100644 Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes.math rename Task/Sieve-of-Eratosthenes/Pascal/{sieve-of-eratosthenes.pascal => sieve-of-eratosthenes-1.pascal} (100%) create mode 100644 Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-2.pascal create mode 100644 Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl create mode 100644 Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py create mode 100644 Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py create mode 100644 Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py create mode 100644 Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-4.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-5.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-6.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-7.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-8.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-9.scala create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss create mode 100644 Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab create mode 100644 Task/Sieve-of-Eratosthenes/TI-83-BASIC/sieve-of-eratosthenes.ti-83 create mode 100644 Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb create mode 100644 Task/Sieve-of-Eratosthenes/Visual-Basic/sieve-of-eratosthenes.vb create mode 100644 Task/Simple-database/Bracmat/simple-database.bracmat create mode 100644 Task/Simple-database/Java/simple-database.java create mode 100644 Task/Simple-database/REBOL/simple-database.rebol create mode 100644 Task/Simple-database/REXX/simple-database.rexx create mode 100644 Task/Simple-database/Scala/simple-database.scala rename Task/Simple-windowed-application/HicEst/{simple-windowed-application.hicest => simple-windowed-application-1.hicest} (100%) create mode 100644 Task/Simple-windowed-application/HicEst/simple-windowed-application-2.hicest create mode 100644 Task/Simple-windowed-application/J/simple-windowed-application-1.j rename Task/Simple-windowed-application/J/{simple-windowed-application.j => simple-windowed-application-2.j} (100%) create mode 100644 Task/Simple-windowed-application/Perl-6/simple-windowed-application.pl6 create mode 100644 Task/Simulate-input-Keyboard/Python/simulate-input-keyboard.py create mode 100644 Task/Simulate-input-Mouse/Scala/simulate-input-mouse.scala create mode 100644 Task/Singleton/Smalltalk/singleton.st create mode 100644 Task/Singly-linked-list-Element-definition/Clojure/singly-linked-list-element-definition.clj create mode 100644 Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-3.lisp create mode 100644 Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-4.lisp create mode 100644 Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-5.lisp create mode 100644 Task/Singly-linked-list-Traversal/NewLISP/singly-linked-list-traversal.newlisp create mode 100644 Task/Sleep/360-Assembly/sleep.360 create mode 100644 Task/Sleep/ALGOL-68/sleep.alg create mode 100644 Task/Sleep/Perl/sleep-3.pl rename Task/Sleep/REXX/{sleep.rexx => sleep-1.rexx} (59%) create mode 100644 Task/Sleep/REXX/sleep-2.rexx create mode 100644 Task/Sleep/RapidQ/sleep.rapidq create mode 100644 Task/Sockets/Scala/sockets.scala create mode 100644 Task/Sokoban/Haskell/sokoban.hs create mode 100644 Task/Sokoban/Ruby/sokoban-1.rb create mode 100644 Task/Sokoban/Ruby/sokoban-2.rb create mode 100644 Task/Sokoban/Ruby/sokoban-3.rb create mode 100644 Task/Solve-a-Hidato-puzzle/Curry/solve-a-hidato-puzzle.curry create mode 100644 Task/Solve-a-Hidato-puzzle/Java/solve-a-hidato-puzzle.java rename Task/Solve-a-Hidato-puzzle/Racket/{solve-a-hidato-puzzle.rkt => solve-a-hidato-puzzle-1.rkt} (100%) create mode 100644 Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle-2.rkt create mode 100644 Task/Solve-a-Hidato-puzzle/Seed7/solve-a-hidato-puzzle.seed7 create mode 100644 Task/Sort-an-integer-array/Frink/sort-an-integer-array.frink create mode 100644 Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust create mode 100644 Task/Sort-an-integer-array/Scala/sort-an-integer-array-1.scala create mode 100644 Task/Sort-an-integer-array/Scala/sort-an-integer-array-2.scala delete mode 100644 Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala create mode 100644 Task/Sort-disjoint-sublist/Clojure/sort-disjoint-sublist.clj create mode 100644 Task/Sort-disjoint-sublist/Scala/sort-disjoint-sublist.scala create mode 100644 Task/Sort-disjoint-sublist/Scheme/sort-disjoint-sublist.ss create mode 100644 Task/Sort-stability/REXX/sort-stability.rexx create mode 100644 Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.ada create mode 100644 Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-3.ss create mode 100644 Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e create mode 100644 Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e rename Task/Sorting-algorithms-Bead-sort/PL-I/{sorting-algorithms-bead-sort.pli => sorting-algorithms-bead-sort-1.pli} (100%) create mode 100644 Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-2.pli create mode 100644 Task/Sorting-algorithms-Bead-sort/Seed7/sorting-algorithms-bead-sort.seed7 create mode 100644 Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort.cpp create mode 100644 Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-1.e create mode 100644 Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e create mode 100644 Task/Sorting-algorithms-Bogosort/PL-I/sorting-algorithms-bogosort.pli create mode 100644 Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-4.py create mode 100644 Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-1.rexx create mode 100644 Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-2.rexx delete mode 100644 Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx create mode 100644 Task/Sorting-algorithms-Bubble-sort/360-Assembly/sorting-algorithms-bubble-sort.360 create mode 100644 Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-3.hs create mode 100644 Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort.m create mode 100644 Task/Sorting-algorithms-Bubble-sort/Objective-C/sorting-algorithms-bubble-sort.m rename Task/Sorting-algorithms-Bubble-sort/Prolog/{sorting-algorithms-bubble-sort.pro => sorting-algorithms-bubble-sort-1.pro} (100%) create mode 100644 Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-2.pro create mode 100644 Task/Sorting-algorithms-Bubble-sort/Scilab/sorting-algorithms-bubble-sort.scilab rename Task/Sorting-algorithms-Cocktail-sort/C++/{sorting-algorithms-cocktail-sort.cpp => sorting-algorithms-cocktail-sort-1.cpp} (78%) create mode 100644 Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-2.cpp create mode 100644 Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-1.d create mode 100644 Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-2.d delete mode 100644 Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e create mode 100644 Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e create mode 100644 Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e create mode 100644 Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e create mode 100644 Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-1.max create mode 100644 Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-2.max rename Task/Sorting-algorithms-Counting-sort/C++/{sorting-algorithms-counting-sort.cpp => sorting-algorithms-counting-sort-1.cpp} (99%) create mode 100644 Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-2.cpp create mode 100644 Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e create mode 100644 Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e create mode 100644 Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-1.max create mode 100644 Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-2.max create mode 100644 Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-1.rexx create mode 100644 Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-2.rexx delete mode 100644 Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx create mode 100644 Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat create mode 100644 Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e create mode 100644 Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e create mode 100644 Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max create mode 100644 Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-2.max create mode 100644 Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx create mode 100644 Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-2.rexx delete mode 100644 Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx create mode 100644 Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp rename Task/Sorting-algorithms-Heapsort/Forth/{sorting-algorithms-heapsort.fth => sorting-algorithms-heapsort-1.fth} (100%) create mode 100644 Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-2.fth create mode 100644 Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-1.max create mode 100644 Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-2.max create mode 100644 Task/Sorting-algorithms-Heapsort/Standard-ML/sorting-algorithms-heapsort.ml rename Task/Sorting-algorithms-Insertion-sort/Common-Lisp/{sorting-algorithms-insertion-sort.lisp => sorting-algorithms-insertion-sort-1.lisp} (100%) create mode 100644 Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-2.lisp rename Task/Sorting-algorithms-Insertion-sort/D/{sorting-algorithms-insertion-sort.d => sorting-algorithms-insertion-sort-1.d} (61%) create mode 100644 Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-2.d create mode 100644 Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-1.max create mode 100644 Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-2.max rename Task/Sorting-algorithms-Insertion-sort/R/{sorting-algorithms-insertion-sort.r => sorting-algorithms-insertion-sort-1.r} (100%) create mode 100644 Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-2.r create mode 100644 Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e create mode 100644 Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e create mode 100644 Task/Sorting-algorithms-Merge-sort/MAXScript/sorting-algorithms-merge-sort-1.max create mode 100644 Task/Sorting-algorithms-Merge-sort/MAXScript/sorting-algorithms-merge-sort-2.max rename Task/Sorting-algorithms-Merge-sort/Pascal/{sorting-algorithms-merge-sort.pascal => sorting-algorithms-merge-sort-1.pascal} (100%) create mode 100644 Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal create mode 100644 Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed create mode 100644 Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e create mode 100644 Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e create mode 100644 Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-1.max create mode 100644 Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-2.max create mode 100644 Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-1.max create mode 100644 Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-2.max create mode 100644 Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-1.julia create mode 100644 Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-2.julia create mode 100644 Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-3.julia delete mode 100644 Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia create mode 100644 Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-6.py create mode 100644 Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-7.py create mode 100644 Task/Sorting-algorithms-Quicksort/Ruby/sorting-algorithms-quicksort-4.rb create mode 100644 Task/Sorting-algorithms-Quicksort/Rust/sorting-algorithms-quicksort.rust create mode 100644 Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-1.math create mode 100644 Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-2.math create mode 100644 Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e create mode 100644 Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e create mode 100644 Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp create mode 100644 Task/Sorting-algorithms-Sleep-sort/Clojure/sorting-algorithms-sleep-sort-1.clj create mode 100644 Task/Sorting-algorithms-Sleep-sort/Clojure/sorting-algorithms-sleep-sort-2.clj create mode 100644 Task/Sorting-algorithms-Sleep-sort/Common-Lisp/sorting-algorithms-sleep-sort.lisp create mode 100644 Task/Sorting-algorithms-Sleep-sort/Dart/sorting-algorithms-sleep-sort.dart create mode 100644 Task/Sorting-algorithms-Sleep-sort/Groovy/sorting-algorithms-sleep-sort.groovy create mode 100644 Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-1.lua create mode 100644 Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-2.lua create mode 100644 Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e create mode 100644 Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e create mode 100644 Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max create mode 100644 Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-2.max create mode 100644 Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-1.max create mode 100644 Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-2.max create mode 100644 Task/Soundex/Standard-ML/soundex.ml create mode 100644 Task/Special-characters/Scala/special-characters.scala create mode 100644 Task/Special-variables/Clojure/special-variables.clj create mode 100644 Task/Special-variables/Common-Lisp/special-variables.lisp create mode 100644 Task/Special-variables/Julia/special-variables.julia create mode 100644 Task/Special-variables/Lua/special-variables.lua create mode 100644 Task/Special-variables/REXX/special-variables-1.rexx create mode 100644 Task/Special-variables/REXX/special-variables-2.rexx delete mode 100644 Task/Special-variables/REXX/special-variables.rexx create mode 100644 Task/Special-variables/Tcl/special-variables-1.tcl rename Task/Special-variables/Tcl/{special-variables.tcl => special-variables-2.tcl} (100%) create mode 100644 Task/Speech-synthesis/Clojure/speech-synthesis.clj create mode 100644 Task/Speech-synthesis/Perl-6/speech-synthesis.pl6 create mode 100644 Task/Spiral-matrix/360-Assembly/spiral-matrix.360 rename Task/Spiral-matrix/C++/{spiral-matrix.cpp => spiral-matrix-1.cpp} (100%) create mode 100644 Task/Spiral-matrix/C++/spiral-matrix-2.cpp rename Task/Spiral-matrix/C/{spiral-matrix.c => spiral-matrix-1.c} (100%) create mode 100644 Task/Spiral-matrix/C/spiral-matrix-2.c rename Task/Spiral-matrix/Haskell/{spiral-matrix.hs => spiral-matrix-1.hs} (79%) create mode 100644 Task/Spiral-matrix/Haskell/spiral-matrix-2.hs create mode 100644 Task/Spiral-matrix/Haskell/spiral-matrix-3.hs create mode 100644 Task/Spiral-matrix/Pascal/spiral-matrix.pascal create mode 100644 Task/Spiral-matrix/Python/spiral-matrix-5.py create mode 100644 Task/Spiral-matrix/Python/spiral-matrix-6.py create mode 100644 Task/Spiral-matrix/REXX/spiral-matrix-1.rexx create mode 100644 Task/Spiral-matrix/REXX/spiral-matrix-2.rexx delete mode 100644 Task/Spiral-matrix/REXX/spiral-matrix.rexx rename Task/Spiral-matrix/Ruby/{spiral-matrix.rb => spiral-matrix-1.rb} (79%) create mode 100644 Task/Spiral-matrix/Ruby/spiral-matrix-2.rb create mode 100644 Task/Spiral-matrix/Scilab/spiral-matrix.scilab create mode 100644 Task/Spiral-matrix/TI-83-BASIC/spiral-matrix.ti-83 create mode 100644 Task/Spiral-matrix/Visual-Basic/spiral-matrix-4.vb create mode 100644 Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-1.cfm create mode 100644 Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-2.cfm create mode 100644 Task/Stable-marriage-problem/Perl-6/stable-marriage-problem.pl6 create mode 100644 Task/Stack-traces/Clojure/stack-traces.clj create mode 100644 Task/Stack-traces/Ruby/stack-traces-3.rb create mode 100644 Task/Stack/JavaScript/stack-3.js create mode 100644 Task/Stack/Smalltalk/stack.st create mode 100644 Task/Stair-climbing-puzzle/SAS/stair-climbing-puzzle.sas create mode 100644 Task/Standard-deviation/360-Assembly/standard-deviation.360 create mode 100644 Task/Standard-deviation/Lua/standard-deviation.lua create mode 100644 Task/Standard-deviation/Pascal/standard-deviation.pascal create mode 100644 Task/Standard-deviation/Scala/standard-deviation.scala create mode 100644 Task/Standard-deviation/Scilab/standard-deviation.scilab create mode 100644 Task/Standard-deviation/Visual-Basic/standard-deviation.vb create mode 100644 Task/Start-from-a-main-routine/Ruby/start-from-a-main-routine.rb create mode 100644 Task/Start-from-a-main-routine/Scala/start-from-a-main-routine.scala create mode 100644 Task/Stem-and-leaf-plot/AWK/stem-and-leaf-plot.awk create mode 100644 Task/Stem-and-leaf-plot/Maple/stem-and-leaf-plot.maple create mode 100644 Task/String-case/Elixir/string-case-1.elixir create mode 100644 Task/String-case/Elixir/string-case-2.elixir rename Task/String-case/Rust/{string-case.rust => string-case-1.rust} (100%) create mode 100644 Task/String-case/Rust/string-case-2.rust create mode 100644 Task/String-comparison/Aime/string-comparison.aime create mode 100644 Task/String-comparison/Common-Lisp/string-comparison-1.lisp create mode 100644 Task/String-comparison/Common-Lisp/string-comparison-2.lisp create mode 100644 Task/String-comparison/Common-Lisp/string-comparison-3.lisp create mode 100644 Task/String-comparison/Haskell/string-comparison.hs create mode 100644 Task/String-comparison/Java/string-comparison.java create mode 100644 Task/String-comparison/Mathematica/string-comparison.math create mode 100644 Task/String-comparison/PicoLisp/string-comparison.l create mode 100644 Task/String-comparison/R/string-comparison-1.r create mode 100644 Task/String-comparison/R/string-comparison-2.r create mode 100644 Task/String-comparison/Scala/string-comparison.scala create mode 100644 Task/String-concatenation/Elixir/string-concatenation.elixir create mode 100644 Task/String-concatenation/Lua/string-concatenation.lua create mode 100644 Task/String-concatenation/NewLISP/string-concatenation.newlisp create mode 100644 Task/String-concatenation/Scilab/string-concatenation.scilab create mode 100644 Task/String-interpolation--included-/Delphi/string-interpolation--included-.delphi create mode 100644 Task/String-interpolation--included-/Elixir/string-interpolation--included-.elixir create mode 100644 Task/String-interpolation--included-/Frink/string-interpolation--included-.frink create mode 100644 Task/String-interpolation--included-/OOC/string-interpolation--included-.ooc create mode 100644 Task/String-length/Elixir/string-length-1.elixir create mode 100644 Task/String-length/Elixir/string-length-2.elixir create mode 100644 Task/String-length/Elixir/string-length-3.elixir create mode 100644 Task/String-length/Maple/string-length-1.maple create mode 100644 Task/String-length/Maple/string-length-2.maple create mode 100644 Task/String-length/Mercury/string-length-1.mercury create mode 100644 Task/String-length/Mercury/string-length-2.mercury create mode 100644 Task/Strip-a-set-of-characters-from-a-string/ColdFusion/strip-a-set-of-characters-from-a-string.cfm create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir create mode 100644 Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir create mode 100644 Task/Strip-a-set-of-characters-from-a-string/NewLISP/strip-a-set-of-characters-from-a-string.newlisp create mode 100644 Task/Strip-a-set-of-characters-from-a-string/ScriptBasic/strip-a-set-of-characters-from-a-string.scriptbasic create mode 100644 Task/Strip-block-comments/Scala/strip-block-comments-1.scala create mode 100644 Task/Strip-block-comments/Scala/strip-block-comments-2.scala create mode 100644 Task/Strip-block-comments/Scala/strip-block-comments-3.scala create mode 100644 Task/Strip-comments-from-a-string/Maple/strip-comments-from-a-string.maple create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Clojure/strip-control-codes-and-extended-characters-from-a-string.clj create mode 100644 Task/Strip-control-codes-and-extended-characters-from-a-string/Java/strip-control-codes-and-extended-characters-from-a-string.java create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/ALGOL-68/strip-whitespace-from-a-string-top-and-tail.alg create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Clojure/strip-whitespace-from-a-string-top-and-tail.clj create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir create mode 100644 Task/Strip-whitespace-from-a-string-Top-and-tail/NewLISP/strip-whitespace-from-a-string-top-and-tail.newlisp create mode 100644 Task/Substring-Top-and-tail/Clojure/substring-top-and-tail.clj create mode 100644 Task/Substring-Top-and-tail/NewLISP/substring-top-and-tail.newlisp create mode 100644 Task/Substring/Go/substring-1.go create mode 100644 Task/Substring/Go/substring-2.go delete mode 100644 Task/Substring/Go/substring.go create mode 100644 Task/Substring/Maple/substring-1.maple create mode 100644 Task/Substring/Maple/substring-2.maple create mode 100644 Task/Substring/Maple/substring-3.maple create mode 100644 Task/Substring/Maple/substring-4.maple create mode 100644 Task/Substring/Prolog/substring-1.pro create mode 100644 Task/Substring/Prolog/substring-2.pro create mode 100644 Task/Substring/RPG/substring.rpg create mode 100644 Task/Subtractive-generator/Fortran/subtractive-generator.f rename Task/Sudoku/Curry/{sudoku.curry => sudoku-1.curry} (100%) create mode 100644 Task/Sudoku/Curry/sudoku-2.curry rename Task/Sudoku/D/{sudoku.d => sudoku-1.d} (82%) create mode 100644 Task/Sudoku/D/sudoku-2.d create mode 100644 Task/Sudoku/D/sudoku-3.d create mode 100644 Task/Sudoku/PL-I/sudoku-1.pli create mode 100644 Task/Sudoku/PL-I/sudoku-2.pli rename Task/Sudoku/Perl-6/{sudoku.pl6 => sudoku-1.pl6} (100%) create mode 100644 Task/Sudoku/Perl-6/sudoku-2.pl6 rename Task/Sudoku/Prolog/{sudoku.pro => sudoku-1.pro} (100%) create mode 100644 Task/Sudoku/Prolog/sudoku-2.pro create mode 100644 Task/Sudoku/VBScript/sudoku.vb create mode 100644 Task/Sum-and-product-of-an-array/Bracmat/sum-and-product-of-an-array.bracmat create mode 100644 Task/Sum-and-product-of-an-array/CoffeeScript/sum-and-product-of-an-array.coffee create mode 100644 Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e rename Task/Sum-and-product-of-an-array/Java/{sum-and-product-of-an-array.java => sum-and-product-of-an-array-1.java} (100%) create mode 100644 Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-2.java create mode 100644 Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.newlisp create mode 100644 Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-3.rb create mode 100644 Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer.alg create mode 100644 Task/Sum-digits-of-an-integer/ATS/sum-digits-of-an-integer.ats create mode 100644 Task/Sum-digits-of-an-integer/Clojure/sum-digits-of-an-integer.clj create mode 100644 Task/Sum-digits-of-an-integer/Factor/sum-digits-of-an-integer.factor create mode 100644 Task/Sum-digits-of-an-integer/Logo/sum-digits-of-an-integer.logo create mode 100644 Task/Sum-digits-of-an-integer/Lua/sum-digits-of-an-integer.lua create mode 100644 Task/Sum-digits-of-an-integer/Pascal/sum-digits-of-an-integer.pascal rename Task/Sum-digits-of-an-integer/Python/{sum-digits-of-an-integer.py => sum-digits-of-an-integer-1.py} (100%) create mode 100644 Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-2.py create mode 100644 Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r create mode 100644 Task/Sum-of-a-series/NewLISP/sum-of-a-series.newlisp create mode 100644 Task/Sum-of-a-series/Rust/sum-of-a-series.rust create mode 100644 Task/Sum-of-squares/Aime/sum-of-squares.aime create mode 100644 Task/Sum-of-squares/Bracmat/sum-of-squares.bracmat rename Task/Sum-of-squares/Python/{sum-of-squares.py => sum-of-squares-1.py} (100%) create mode 100644 Task/Sum-of-squares/Python/sum-of-squares-2.py create mode 100644 Task/Sum-of-squares/Rust/sum-of-squares.rust create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-1.cs create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-2.cs create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-3.cs create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Java/sutherland-hodgman-polygon-clipping.java create mode 100644 Task/Sutherland-Hodgman-polygon-clipping/Scala/sutherland-hodgman-polygon-clipping.scala rename Task/Symmetric-difference/Lua/{symmetric-difference.lua => symmetric-difference-1.lua} (100%) create mode 100644 Task/Symmetric-difference/Lua/symmetric-difference-2.lua create mode 100644 Task/Symmetric-difference/Maple/symmetric-difference-1.maple create mode 100644 Task/Symmetric-difference/Maple/symmetric-difference-2.maple create mode 100644 Task/Symmetric-difference/Python/symmetric-difference-3.py create mode 100644 Task/Synchronous-concurrency/C-sharp/synchronous-concurrency.cs create mode 100644 Task/Synchronous-concurrency/J/synchronous-concurrency-1.j create mode 100644 Task/Synchronous-concurrency/J/synchronous-concurrency-2.j create mode 100644 Task/Synchronous-concurrency/Mercury/synchronous-concurrency.mercury rename Task/System-time/AWK/{system-time.awk => system-time-1.awk} (53%) create mode 100644 Task/System-time/AWK/system-time-2.awk create mode 100644 Task/System-time/Excel/system-time.excel create mode 100644 Task/System-time/Io/system-time.io create mode 100644 Task/System-time/NewLISP/system-time.newlisp create mode 100644 Task/Take-notes-on-the-command-line/Delphi/take-notes-on-the-command-line.delphi create mode 100644 Task/Take-notes-on-the-command-line/PL-I/take-notes-on-the-command-line.pli rename Task/Temperature-conversion/AWK/{temperature-conversion.awk => temperature-conversion-1.awk} (100%) create mode 100644 Task/Temperature-conversion/AWK/temperature-conversion-2.awk create mode 100644 Task/Temperature-conversion/Clojure/temperature-conversion.clj create mode 100644 Task/Temperature-conversion/Common-Lisp/temperature-conversion.lisp create mode 100644 Task/Temperature-conversion/Delphi/temperature-conversion.delphi create mode 100644 Task/Temperature-conversion/Euphoria/temperature-conversion.euphoria create mode 100644 Task/Temperature-conversion/Excel/temperature-conversion.excel create mode 100644 Task/Temperature-conversion/Fortran/temperature-conversion.f create mode 100644 Task/Temperature-conversion/Haskell/temperature-conversion.hs create mode 100644 Task/Temperature-conversion/Lua/temperature-conversion.lua create mode 100644 Task/Temperature-conversion/OCaml/temperature-conversion.ocaml create mode 100644 Task/Temperature-conversion/Scala/temperature-conversion.scala rename Task/Terminal-control-Clear-the-screen/Go/{terminal-control-clear-the-screen.go => terminal-control-clear-the-screen-1.go} (100%) create mode 100644 Task/Terminal-control-Clear-the-screen/Go/terminal-control-clear-the-screen-2.go create mode 100644 Task/Terminal-control-Clear-the-screen/Go/terminal-control-clear-the-screen-3.go create mode 100644 Task/Terminal-control-Clear-the-screen/Haskell/terminal-control-clear-the-screen.hs create mode 100644 Task/Terminal-control-Clear-the-screen/Java/terminal-control-clear-the-screen-1.java create mode 100644 Task/Terminal-control-Clear-the-screen/Java/terminal-control-clear-the-screen-2.java rename Task/Terminal-control-Clear-the-screen/Ruby/{terminal-control-clear-the-screen.rb => terminal-control-clear-the-screen-1.rb} (100%) create mode 100644 Task/Terminal-control-Clear-the-screen/Ruby/terminal-control-clear-the-screen-2.rb create mode 100644 Task/Terminal-control-Clear-the-screen/Scala/terminal-control-clear-the-screen.scala create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-1.go create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-2.go create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-3.go create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-4.go create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-5.go create mode 100644 Task/Terminal-control-Coloured-text/Go/terminal-control-coloured-text-6.go rename Task/Terminal-control-Cursor-movement/BASIC/{terminal-control-cursor-movement.basic => terminal-control-cursor-movement-1.basic} (100%) create mode 100644 Task/Terminal-control-Cursor-movement/BASIC/terminal-control-cursor-movement-2.basic create mode 100644 Task/Terminal-control-Cursor-movement/Go/terminal-control-cursor-movement-1.go create mode 100644 Task/Terminal-control-Cursor-movement/Go/terminal-control-cursor-movement-2.go create mode 100644 Task/Terminal-control-Cursor-movement/Go/terminal-control-cursor-movement-3.go create mode 100644 Task/Terminal-control-Cursor-positioning/Go/terminal-control-cursor-positioning-1.go create mode 100644 Task/Terminal-control-Cursor-positioning/Go/terminal-control-cursor-positioning-2.go create mode 100644 Task/Terminal-control-Cursor-positioning/Go/terminal-control-cursor-positioning-3.go create mode 100644 Task/Terminal-control-Cursor-positioning/Perl/terminal-control-cursor-positioning.pl create mode 100644 Task/Terminal-control-Cursor-positioning/Whitespace/terminal-control-cursor-positioning-1.ws create mode 100644 Task/Terminal-control-Cursor-positioning/Whitespace/terminal-control-cursor-positioning-2.ws create mode 100644 Task/Terminal-control-Dimensions/Applesoft-BASIC/terminal-control-dimensions.applesoft create mode 100644 Task/Terminal-control-Dimensions/Go/terminal-control-dimensions-1.go create mode 100644 Task/Terminal-control-Dimensions/Go/terminal-control-dimensions-2.go create mode 100644 Task/Terminal-control-Dimensions/Go/terminal-control-dimensions-3.go create mode 100644 Task/Terminal-control-Display-an-extended-character/Clojure/terminal-control-display-an-extended-character.clj create mode 100644 Task/Terminal-control-Display-an-extended-character/Scala/terminal-control-display-an-extended-character.scala create mode 100644 Task/Terminal-control-Hiding-the-cursor/C++/terminal-control-hiding-the-cursor.cpp create mode 100644 Task/Terminal-control-Hiding-the-cursor/Go/terminal-control-hiding-the-cursor-1.go create mode 100644 Task/Terminal-control-Hiding-the-cursor/Go/terminal-control-hiding-the-cursor-2.go create mode 100644 Task/Terminal-control-Hiding-the-cursor/Go/terminal-control-hiding-the-cursor-3.go create mode 100644 Task/Terminal-control-Inverse-video/Go/terminal-control-inverse-video-1.go create mode 100644 Task/Terminal-control-Inverse-video/Go/terminal-control-inverse-video-2.go create mode 100644 Task/Terminal-control-Inverse-video/Go/terminal-control-inverse-video-3.go create mode 100644 Task/Terminal-control-Preserve-screen/Scala/terminal-control-preserve-screen.scala create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/Clojure/terminal-control-ringing-the-terminal-bell.clj create mode 100644 Task/Terminal-control-Ringing-the-terminal-bell/PHP/terminal-control-ringing-the-terminal-bell.php create mode 100644 Task/Terminal-control-Unicode-output/Clojure/terminal-control-unicode-output.clj create mode 100644 Task/Terminal-control-Unicode-output/Elixir/terminal-control-unicode-output.elixir create mode 100644 Task/Terminal-control-Unicode-output/Scala/terminal-control-unicode-output.scala create mode 100644 Task/Ternary-logic/Common-Lisp/ternary-logic.lisp create mode 100644 Task/Ternary-logic/Maple/ternary-logic-1.maple create mode 100644 Task/Ternary-logic/Maple/ternary-logic-2.maple create mode 100644 Task/Test-a-function/Icon/test-a-function.icon create mode 100644 Task/Text-processing-1/Java/text-processing-1.java create mode 100644 Task/Tic-tac-toe/Common-Lisp/tic-tac-toe.lisp create mode 100644 Task/Tic-tac-toe/Euphoria/tic-tac-toe.euphoria create mode 100644 Task/Tic-tac-toe/MATLAB/tic-tac-toe.m create mode 100644 Task/Time-a-function/Bracmat/time-a-function.bracmat create mode 100644 Task/Tokenize-a-string/Elixir/tokenize-a-string.elixir create mode 100644 Task/Tokenize-a-string/Java/tokenize-a-string-3.java create mode 100644 Task/Tokenize-a-string/Logtalk/tokenize-a-string.logtalk create mode 100644 Task/Tokenize-a-string/MATLAB/tokenize-a-string.m create mode 100644 Task/Tokenize-a-string/NewLISP/tokenize-a-string.newlisp rename Task/Tokenize-a-string/Perl/{tokenize-a-string.pl => tokenize-a-string-1.pl} (100%) create mode 100644 Task/Tokenize-a-string/Perl/tokenize-a-string-2.pl create mode 100644 Task/Tokenize-a-string/Perl/tokenize-a-string-3.pl rename Task/Tokenize-a-string/Prolog/{tokenize-a-string.pro => tokenize-a-string-1.pro} (100%) create mode 100644 Task/Tokenize-a-string/Prolog/tokenize-a-string-2.pro create mode 100644 Task/Tokenize-a-string/Scheme/tokenize-a-string-3.ss create mode 100644 Task/Top-rank-per-group/Forth/top-rank-per-group.fth create mode 100644 Task/Top-rank-per-group/Java/top-rank-per-group.java rename Task/Top-rank-per-group/JavaScript/{top-rank-per-group.js => top-rank-per-group-1.js} (98%) create mode 100644 Task/Top-rank-per-group/JavaScript/top-rank-per-group-2.js create mode 100644 Task/Top-rank-per-group/Prolog/top-rank-per-group.pro create mode 100644 Task/Top-rank-per-group/Scheme/top-rank-per-group.ss create mode 100644 Task/Topic-variable/Clojure/topic-variable.clj rename Task/Topic-variable/J/{topic-variable.j => topic-variable-1.j} (100%) create mode 100644 Task/Topic-variable/J/topic-variable-2.j create mode 100644 Task/Topic-variable/Python/topic-variable.py create mode 100644 Task/Topic-variable/REXX/topic-variable.rexx create mode 100644 Task/Topic-variable/Ruby/topic-variable-1.rb create mode 100644 Task/Topic-variable/Ruby/topic-variable-2.rb create mode 100644 Task/Topic-variable/Standard-ML/topic-variable.ml create mode 100644 Task/Topological-sort/C++/topological-sort.cpp create mode 100644 Task/Topological-sort/Go/topological-sort-1.go create mode 100644 Task/Topological-sort/Go/topological-sort-2.go delete mode 100644 Task/Topological-sort/Go/topological-sort.go create mode 100644 Task/Topological-sort/Perl-6/topological-sort.pl6 create mode 100644 Task/Topswops/Eiffel/topswops-1.e create mode 100644 Task/Topswops/Eiffel/topswops-2.e create mode 100644 Task/Topswops/Scala/topswops.scala create mode 100644 Task/Towers-of-Hanoi/Eiffel/towers-of-hanoi.e create mode 100644 Task/Towers-of-Hanoi/MATLAB/towers-of-hanoi.m create mode 100644 Task/Towers-of-Hanoi/PlainTeX/towers-of-hanoi.tex create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Common-Lisp/trabb-pardo-knuth-algorithm.lisp create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Fortran/trabb-pardo-knuth-algorithm.f create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Mathematica/trabb-pardo-knuth-algorithm.math create mode 100644 Task/Tree-traversal/PHP/tree-traversal.php create mode 100644 Task/Trigonometric-functions/Maple/trigonometric-functions-1.maple create mode 100644 Task/Trigonometric-functions/Maple/trigonometric-functions-2.maple create mode 100644 Task/Trigonometric-functions/Maple/trigonometric-functions-3.maple create mode 100644 Task/Trigonometric-functions/Maple/trigonometric-functions-4.maple create mode 100644 Task/Trigonometric-functions/Scala/trigonometric-functions.scala create mode 100644 Task/Truncatable-primes/Common-Lisp/truncatable-primes.lisp create mode 100644 Task/Truncate-a-file/Delphi/truncate-a-file-1.delphi create mode 100644 Task/Truncate-a-file/Delphi/truncate-a-file-2.delphi create mode 100644 Task/Truncate-a-file/Julia/truncate-a-file.julia create mode 100644 Task/Truncate-a-file/REXX/truncate-a-file.rexx create mode 100644 Task/Truncate-a-file/Scala/truncate-a-file.scala create mode 100644 Task/Twelve-statements/00META.yaml create mode 100644 Task/Twelve-statements/Common-Lisp/twelve-statements.lisp rename Task/URL-decoding/Ada/{url-decoding.ada => url-decoding-1.ada} (100%) create mode 100644 Task/URL-decoding/Ada/url-decoding-2.ada create mode 100644 Task/URL-decoding/Ada/url-decoding-3.ada create mode 100644 Task/URL-decoding/Ada/url-decoding-4.ada create mode 100644 Task/URL-decoding/Haskell/url-decoding.hs create mode 100644 Task/URL-decoding/Maple/url-decoding.maple create mode 100644 Task/URL-decoding/NewLISP/url-decoding.newlisp create mode 100644 Task/URL-decoding/R/url-decoding.r create mode 100644 Task/URL-decoding/VBScript/url-decoding.vb create mode 100644 Task/URL-encoding/00META.yaml create mode 100644 Task/URL-encoding/Clojure/url-encoding.clj create mode 100644 Task/URL-encoding/Haskell/url-encoding.hs create mode 100644 Task/URL-encoding/Maple/url-encoding.maple create mode 100644 Task/URL-encoding/NewLISP/url-encoding.newlisp create mode 100644 Task/URL-encoding/R/url-encoding-1.r create mode 100644 Task/URL-encoding/R/url-encoding-2.r create mode 100644 Task/URL-encoding/Scala/url-encoding.scala create mode 100644 Task/URL-encoding/VBScript/url-encoding.vb create mode 100644 Task/Unbias-a-random-generator/Elixir/unbias-a-random-generator.elixir create mode 100644 Task/Unicode-strings/Ruby/unicode-strings-1.rb rename Task/Unicode-strings/Ruby/{unicode-strings.rb => unicode-strings-2.rb} (100%) create mode 100644 Task/Unicode-strings/Ruby/unicode-strings-3.rb create mode 100644 Task/Unicode-variable-names/Clojure/unicode-variable-names.clj create mode 100644 Task/Unicode-variable-names/Emacs-Lisp/unicode-variable-names.l create mode 100644 Task/Unicode-variable-names/JavaScript/unicode-variable-names.js create mode 100644 Task/Unicode-variable-names/Julia/unicode-variable-names-1.julia create mode 100644 Task/Unicode-variable-names/Julia/unicode-variable-names-2.julia delete mode 100644 Task/Unicode-variable-names/Julia/unicode-variable-names.julia rename Task/Unicode-variable-names/Perl/{unicode-variable-names.pl => unicode-variable-names-1.pl} (61%) create mode 100644 Task/Unicode-variable-names/Perl/unicode-variable-names-2.pl create mode 100644 Task/Unicode-variable-names/Perl/unicode-variable-names-3.pl create mode 100644 Task/Unicode-variable-names/R/unicode-variable-names.r create mode 100644 Task/Universal-Turing-machine/Common-Lisp/universal-turing-machine-1.lisp create mode 100644 Task/Universal-Turing-machine/Common-Lisp/universal-turing-machine-2.lisp create mode 100644 Task/Universal-Turing-machine/Common-Lisp/universal-turing-machine-3.lisp create mode 100644 Task/Universal-Turing-machine/Go/universal-turing-machine-1.go create mode 100644 Task/Universal-Turing-machine/Go/universal-turing-machine-2.go create mode 100644 Task/Universal-Turing-machine/Mathematica/universal-turing-machine-1.math create mode 100644 Task/Universal-Turing-machine/Mathematica/universal-turing-machine-2.math create mode 100644 Task/Universal-Turing-machine/Mathematica/universal-turing-machine-3.math create mode 100644 Task/Universal-Turing-machine/PicoLisp/universal-turing-machine.l create mode 100644 Task/Update-a-configuration-file/Java/update-a-configuration-file.java create mode 100644 Task/User-input-Graphical/J/user-input-graphical-1.j rename Task/User-input-Graphical/J/{user-input-graphical.j => user-input-graphical-2.j} (100%) create mode 100644 Task/User-input-Graphical/Perl-6/user-input-graphical.pl6 rename Task/Vampire-number/Java/{vampire-number.java => vampire-number-1.java} (100%) create mode 100644 Task/Vampire-number/Java/vampire-number-2.java create mode 100644 Task/Vampire-number/Mathematica/vampire-number-1.math create mode 100644 Task/Vampire-number/Mathematica/vampire-number-2.math create mode 100644 Task/Van-der-Corput-sequence/C-sharp/van-der-corput-sequence.cs create mode 100644 Task/Van-der-Corput-sequence/C/van-der-corput-sequence.c create mode 100644 Task/Van-der-Corput-sequence/Clojure/van-der-corput-sequence.clj create mode 100644 Task/Van-der-Corput-sequence/Common-Lisp/van-der-corput-sequence.lisp create mode 100644 Task/Van-der-Corput-sequence/Lua/van-der-corput-sequence.lua create mode 100644 Task/Van-der-Corput-sequence/Pascal/van-der-corput-sequence.pascal create mode 100644 Task/Van-der-Corput-sequence/Ruby/van-der-corput-sequence.rb create mode 100644 Task/Van-der-Corput-sequence/VBScript/van-der-corput-sequence.vb create mode 100644 Task/Variable-length-quantity/PARI-GP/variable-length-quantity.pari create mode 100644 Task/Variable-size-Get/Scala/variable-size-get.scala create mode 100644 Task/Variable-size-Set/360-Assembly/variable-size-set.360 create mode 100644 Task/Variables/AWK/variables-4.awk create mode 100644 Task/Variables/Bracmat/variables.bracmat create mode 100644 Task/Variables/Common-Lisp/variables-1.lisp create mode 100644 Task/Variables/Common-Lisp/variables-2.lisp create mode 100644 Task/Variables/Common-Lisp/variables-3.lisp create mode 100644 Task/Variables/Common-Lisp/variables-4.lisp create mode 100644 Task/Variables/Common-Lisp/variables-5.lisp create mode 100644 Task/Variables/Common-Lisp/variables-6.lisp create mode 100644 Task/Variables/Common-Lisp/variables-7.lisp create mode 100644 Task/Variables/Eiffel/variables-1.e create mode 100644 Task/Variables/Eiffel/variables-2.e create mode 100644 Task/Variables/REXX/variables-5.rexx create mode 100644 Task/Variables/REXX/variables-6.rexx create mode 100644 Task/Variables/REXX/variables-7.rexx create mode 100644 Task/Variables/REXX/variables-8.rexx create mode 100644 Task/Variadic-function/Perl/variadic-function-4.pl create mode 100644 Task/Variadic-function/Perl/variadic-function-5.pl create mode 100644 Task/Variadic-function/Perl/variadic-function-6.pl create mode 100644 Task/Variadic-function/REALbasic/variadic-function-1.realbasic create mode 100644 Task/Variadic-function/REALbasic/variadic-function-2.realbasic create mode 100644 Task/Vector-products/Forth/vector-products.fth create mode 100644 Task/Vector-products/Prolog/vector-products.pro create mode 100644 Task/Verify-distribution-uniformity-Chi-squared-test/Ruby/verify-distribution-uniformity-chi-squared-test.rb create mode 100644 Task/Verify-distribution-uniformity-Naive/Racket/verify-distribution-uniformity-naive.rkt create mode 100644 Task/Video-display-modes/Applesoft-BASIC/video-display-modes.applesoft create mode 100644 Task/Video-display-modes/Icon/video-display-modes.icon create mode 100644 Task/Vigen-re-cipher/C/vigen-re-cipher.c create mode 100644 Task/Vigen-re-cipher/Common-Lisp/vigen-re-cipher.lisp create mode 100644 Task/Visualize-a-tree/Ada/visualize-a-tree.ada rename Task/Visualize-a-tree/Go/{visualize-a-tree.go => visualize-a-tree-1.go} (100%) create mode 100644 Task/Visualize-a-tree/Go/visualize-a-tree-2.go create mode 100644 Task/Visualize-a-tree/Java/visualize-a-tree.java create mode 100644 Task/Visualize-a-tree/REXX/visualize-a-tree.rexx create mode 100644 Task/Visualize-a-tree/Ruby/visualize-a-tree-1.rb create mode 100644 Task/Visualize-a-tree/Ruby/visualize-a-tree-2.rb rename Task/Voronoi-diagram/J/{voronoi-diagram.j => voronoi-diagram-1.j} (92%) create mode 100644 Task/Voronoi-diagram/J/voronoi-diagram-2.j create mode 100644 Task/Walk-a-directory-Recursively/Java/walk-a-directory-recursively-3.java create mode 100644 Task/Web-scraping/CoffeeScript/web-scraping.coffee create mode 100644 Task/Web-scraping/JavaScript/web-scraping.js create mode 100644 Task/Window-creation-X11/Pascal/window-creation-x11.pascal create mode 100644 Task/Window-creation-X11/Perl-6/window-creation-x11.pl6 create mode 100644 Task/Window-creation-X11/Scala/window-creation-x11.scala create mode 100644 Task/Window-creation/Frink/window-creation.frink create mode 100644 Task/Window-creation/Perl-6/window-creation.pl6 create mode 100644 Task/Window-creation/Perl/window-creation-7.pl create mode 100644 Task/Window-creation/Seed7/window-creation.seed7 create mode 100644 Task/Window-creation/TorqueScript/window-creation.torque create mode 100644 Task/Window-management/Java/window-management.java create mode 100644 Task/Window-management/Mathematica/window-management.math create mode 100644 Task/Wireworld/REXX/wireworld.rexx rename Task/Word-wrap/Haskell/{word-wrap.hs => word-wrap-1.hs} (100%) create mode 100644 Task/Word-wrap/Haskell/word-wrap-2.hs create mode 100644 Task/Word-wrap/Lua/word-wrap.lua create mode 100644 Task/Word-wrap/Mathematica/word-wrap-1.math create mode 100644 Task/Word-wrap/Mathematica/word-wrap-2.math create mode 100644 Task/Word-wrap/R/word-wrap.r create mode 100644 Task/Word-wrap/Scala/word-wrap.scala create mode 100644 Task/Write-float-arrays-to-a-text-file/00META.yaml create mode 100644 Task/Write-float-arrays-to-a-text-file/Scala/write-float-arrays-to-a-text-file.scala create mode 100644 Task/Write-language-name-in-3D-ASCII/Clojure/write-language-name-in-3d-ascii.clj rename Task/Write-language-name-in-3D-ASCII/J/{write-language-name-in-3d-ascii.j => write-language-name-in-3d-ascii-1.j} (100%) create mode 100644 Task/Write-language-name-in-3D-ASCII/J/write-language-name-in-3d-ascii-2.j create mode 100644 Task/Write-language-name-in-3D-ASCII/Perl/write-language-name-in-3d-ascii.pl create mode 100644 Task/Write-language-name-in-3D-ASCII/PicoLisp/write-language-name-in-3d-ascii.l create mode 100644 Task/Write-to-Windows-event-log/Clojure/write-to-windows-event-log.clj create mode 100644 Task/XML-DOM-serialization/Clojure/xml-dom-serialization.clj create mode 100644 Task/XML-Input/JavaScript/xml-input-3.js create mode 100644 Task/XML-Output/Bracmat/xml-output.bracmat create mode 100644 Task/XML-Output/Euphoria/xml-output.euphoria create mode 100644 Task/XML-XPath/Factor/xml-xpath.factor create mode 100644 Task/XML-XPath/Go/xml-xpath-1.go rename Task/XML-XPath/Go/{xml-xpath.go => xml-xpath-2.go} (100%) rename Task/XML-XPath/Python/{xml-xpath.py => xml-xpath-1.py} (100%) create mode 100644 Task/XML-XPath/Python/xml-xpath-2.py create mode 100644 Task/XML-XPath/Python/xml-xpath-3.py create mode 100644 Task/XML-XPath/REXX/xml-xpath-1.rexx create mode 100644 Task/XML-XPath/REXX/xml-xpath-2.rexx create mode 100644 Task/Xiaolin-Wus-line-algorithm/AutoHotkey/xiaolin-wus-line-algorithm.ahk create mode 100644 Task/Xiaolin-Wus-line-algorithm/Pascal/xiaolin-wus-line-algorithm.pascal create mode 100644 Task/Xiaolin-Wus-line-algorithm/Scala/xiaolin-wus-line-algorithm-1.scala create mode 100644 Task/Xiaolin-Wus-line-algorithm/Scala/xiaolin-wus-line-algorithm-2.scala rename Task/Y-combinator/C++/{y-combinator.cpp => y-combinator-1.cpp} (85%) create mode 100644 Task/Y-combinator/C++/y-combinator-2.cpp rename Task/Y-combinator/Go/{y-combinator.go => y-combinator-1.go} (87%) create mode 100644 Task/Y-combinator/Go/y-combinator-2.go create mode 100644 Task/Y-combinator/Java/y-combinator-8.java create mode 100644 Task/Y-combinator/Julia/y-combinator-1.julia create mode 100644 Task/Y-combinator/Julia/y-combinator-2.julia rename Task/Y-combinator/Objective-C/{y-combinator.m => y-combinator-1.m} (70%) create mode 100644 Task/Y-combinator/Objective-C/y-combinator-2.m create mode 100644 Task/Y-combinator/PARI-GP/y-combinator.pari create mode 100644 Task/Y-combinator/PHP/y-combinator-4.php rename Task/Y-combinator/Perl/{y-combinator.pl => y-combinator-1.pl} (100%) create mode 100644 Task/Y-combinator/Perl/y-combinator-2.pl rename Task/Y-combinator/Python/{y-combinator.py => y-combinator-1.py} (100%) create mode 100644 Task/Y-combinator/Python/y-combinator-2.py create mode 100644 Task/Y-combinator/Ruby/y-combinator-3.rb create mode 100644 Task/Y-combinator/Ruby/y-combinator-4.rb rename Task/Y-combinator/Scheme/{y-combinator.ss => y-combinator-1.ss} (85%) create mode 100644 Task/Y-combinator/Scheme/y-combinator-2.ss rename Task/Y-combinator/Smalltalk/{y-combinator.st => y-combinator-1.st} (100%) create mode 100644 Task/Y-combinator/Smalltalk/y-combinator-2.st rename Task/Y-combinator/Standard-ML/{y-combinator.ml => y-combinator-1.ml} (100%) create mode 100644 Task/Y-combinator/Standard-ML/y-combinator-2.ml create mode 100644 Task/Yin-and-yang/00META.yaml rename Task/Yin-and-yang/Java/{yin-and-yang.java => yin-and-yang-1.java} (100%) create mode 100644 Task/Yin-and-yang/Java/yin-and-yang-2.java create mode 100644 Task/Yin-and-yang/JavaScript/yin-and-yang-3.js create mode 100644 Task/Zebra-puzzle/Bracmat/zebra-puzzle.bracmat create mode 100644 Task/Zebra-puzzle/C++/zebra-puzzle.cpp create mode 100644 Task/Zebra-puzzle/Curry/zebra-puzzle.curry create mode 100644 Task/Zebra-puzzle/D/zebra-puzzle-3.d create mode 100644 Task/Zebra-puzzle/Go/zebra-puzzle.go rename Task/Zebra-puzzle/Haskell/{zebra-puzzle.hs => zebra-puzzle-1.hs} (95%) create mode 100644 Task/Zebra-puzzle/Haskell/zebra-puzzle-2.hs create mode 100644 Task/Zebra-puzzle/Java/zebra-puzzle-1.java create mode 100644 Task/Zebra-puzzle/Java/zebra-puzzle-2.java create mode 100644 Task/Zebra-puzzle/Java/zebra-puzzle-3.java create mode 100644 Task/Zebra-puzzle/Mathematica/zebra-puzzle.math create mode 100644 Task/Zebra-puzzle/Prolog/zebra-puzzle-4.pro create mode 100644 Task/Zebra-puzzle/R/zebra-puzzle.r create mode 100644 Task/Zebra-puzzle/Ruby/zebra-puzzle.rb create mode 100644 Task/Zebra-puzzle/Scala/zebra-puzzle.scala create mode 100644 Task/Zeckendorf-arithmetic/PicoLisp/zeckendorf-arithmetic.l create mode 100644 Task/Zeckendorf-number-representation/C-sharp/zeckendorf-number-representation.cs rename Task/Zeckendorf-number-representation/Java/{zeckendorf-number-representation.java => zeckendorf-number-representation-1.java} (100%) create mode 100644 Task/Zeckendorf-number-representation/Java/zeckendorf-number-representation-2.java create mode 100644 Task/Zeckendorf-number-representation/PHP/zeckendorf-number-representation.php create mode 100644 Task/Zeckendorf-number-representation/PicoLisp/zeckendorf-number-representation.l create mode 100644 Task/Zig-zag-matrix/C/zig-zag-matrix.c create mode 100644 Task/Zig-zag-matrix/CoffeeScript/zig-zag-matrix.coffee create mode 100644 Task/Zig-zag-matrix/MATLAB/zig-zag-matrix.m diff --git a/Conf/task.yaml b/Conf/task.yaml index fdc686c911..9c9e8a247b 100644 --- a/Conf/task.yaml +++ b/Conf/task.yaml @@ -379,7 +379,7 @@ Multiple regression: Multiplication tables: Multiplicative order: Multisplit: -Mutex: +# Mutex: Mutual recursion: N-queens problem: diff --git a/Lang/360-Assembly/00DESCRIPTION b/Lang/360-Assembly/00DESCRIPTION index a56af4e8bc..d10d4b2ac3 100644 --- a/Lang/360-Assembly/00DESCRIPTION +++ b/Lang/360-Assembly/00DESCRIPTION @@ -1,2 +1,19 @@ {{stub}}{{language}} -[[Category:Assembly]] \ No newline at end of file +[[Category:Assembly]] +IBM 360 assembly language. + +From Wikipedia, the free encyclopedia. + +ASM360, Assembler 360, 360 assembly, or Basic Assembly Language (BAL) are the commonly +used terms for a low-level programming language used on IBM System/360 +and successor mainframes. +Originally "Basic Assembly Language" applied only to an extremely restricted +dialect designed to run under control of IBM Basic Programming Support +(BPS/360) on systems with only 8KB of main memory, and only a card reader, +a card punch, and a printer for input/output — thus the word "Basic". +However, the full name and the initialism "BAL" almost immediately attached +themselves in popular use to all assembly-language dialects on the System/360 and +its descendants. The 360 assembly was introduced with the System/360 in 1964. + +==Wikipedia article== +http://en.wikipedia.org/wiki/IBM_Basic_assembly_language_and_successors \ No newline at end of file diff --git a/Lang/360-Assembly/Conditional-structures b/Lang/360-Assembly/Conditional-structures new file mode 120000 index 0000000000..162894f6ec --- /dev/null +++ b/Lang/360-Assembly/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Empty-program b/Lang/360-Assembly/Empty-program new file mode 120000 index 0000000000..0b45876b41 --- /dev/null +++ b/Lang/360-Assembly/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Factorial b/Lang/360-Assembly/Factorial new file mode 120000 index 0000000000..3a02d7516d --- /dev/null +++ b/Lang/360-Assembly/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Fibonacci-sequence b/Lang/360-Assembly/Fibonacci-sequence new file mode 120000 index 0000000000..2d5e123925 --- /dev/null +++ b/Lang/360-Assembly/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Gamma-function b/Lang/360-Assembly/Gamma-function new file mode 120000 index 0000000000..38ce1b1e76 --- /dev/null +++ b/Lang/360-Assembly/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Integer-comparison b/Lang/360-Assembly/Integer-comparison new file mode 120000 index 0000000000..749368a0f8 --- /dev/null +++ b/Lang/360-Assembly/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Do-while b/Lang/360-Assembly/Loops-Do-while new file mode 120000 index 0000000000..4056e221d8 --- /dev/null +++ b/Lang/360-Assembly/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-Infinite b/Lang/360-Assembly/Loops-Infinite new file mode 120000 index 0000000000..f0dad26caa --- /dev/null +++ b/Lang/360-Assembly/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Loops-While b/Lang/360-Assembly/Loops-While new file mode 120000 index 0000000000..8158a1623e --- /dev/null +++ b/Lang/360-Assembly/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Lucas-Lehmer-test b/Lang/360-Assembly/Lucas-Lehmer-test new file mode 120000 index 0000000000..f71df33d10 --- /dev/null +++ b/Lang/360-Assembly/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sieve-of-Eratosthenes b/Lang/360-Assembly/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..734f420185 --- /dev/null +++ b/Lang/360-Assembly/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sleep b/Lang/360-Assembly/Sleep new file mode 120000 index 0000000000..75b22faeb9 --- /dev/null +++ b/Lang/360-Assembly/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Sorting-algorithms-Bubble-sort b/Lang/360-Assembly/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..99d63ab19f --- /dev/null +++ b/Lang/360-Assembly/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Spiral-matrix b/Lang/360-Assembly/Spiral-matrix new file mode 120000 index 0000000000..b18f9ae6e8 --- /dev/null +++ b/Lang/360-Assembly/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Standard-deviation b/Lang/360-Assembly/Standard-deviation new file mode 120000 index 0000000000..6a3f3c840c --- /dev/null +++ b/Lang/360-Assembly/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/360-Assembly \ No newline at end of file diff --git a/Lang/360-Assembly/Variable-size-Set b/Lang/360-Assembly/Variable-size-Set new file mode 120000 index 0000000000..197c3c08a1 --- /dev/null +++ b/Lang/360-Assembly/Variable-size-Set @@ -0,0 +1 @@ +../../Task/Variable-size-Set/360-Assembly \ No newline at end of file diff --git a/Lang/6502-Assembly/Even-or-odd b/Lang/6502-Assembly/Even-or-odd new file mode 120000 index 0000000000..ba39b7ec5f --- /dev/null +++ b/Lang/6502-Assembly/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/6502-Assembly \ No newline at end of file diff --git a/Lang/ABAP/N-queens-problem b/Lang/ABAP/N-queens-problem new file mode 120000 index 0000000000..a9a28a2f79 --- /dev/null +++ b/Lang/ABAP/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/ABAP \ No newline at end of file diff --git a/Lang/ACL2/00DESCRIPTION b/Lang/ACL2/00DESCRIPTION index a40f260132..8e8ab10d72 100644 --- a/Lang/ACL2/00DESCRIPTION +++ b/Lang/ACL2/00DESCRIPTION @@ -7,4 +7,5 @@ |gc=yes |LCT=yes}} {{language programming paradigm|Functional}} +{{implementation|Lisp}} ACL2 is both a programming language in which you can model computer systems and a tool to help you prove properties of those models. \ No newline at end of file diff --git a/Lang/ALGOL-60/Comments b/Lang/ALGOL-60/Comments new file mode 120000 index 0000000000..f20b12a97a --- /dev/null +++ b/Lang/ALGOL-60/Comments @@ -0,0 +1 @@ +../../Task/Comments/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Empty-program b/Lang/ALGOL-60/Empty-program new file mode 120000 index 0000000000..20479bad57 --- /dev/null +++ b/Lang/ALGOL-60/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Hello-world-Text b/Lang/ALGOL-60/Hello-world-Text new file mode 120000 index 0000000000..0df901da00 --- /dev/null +++ b/Lang/ALGOL-60/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-For b/Lang/ALGOL-60/Loops-For new file mode 120000 index 0000000000..dde8a6dbf1 --- /dev/null +++ b/Lang/ALGOL-60/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Loops-While b/Lang/ALGOL-60/Loops-While new file mode 120000 index 0000000000..a6e2da40d6 --- /dev/null +++ b/Lang/ALGOL-60/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-60/Sieve-of-Eratosthenes b/Lang/ALGOL-60/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..0a3381d681 --- /dev/null +++ b/Lang/ALGOL-60/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/ALGOL-60 \ No newline at end of file diff --git a/Lang/ALGOL-68/Call-a-function b/Lang/ALGOL-68/Call-a-function new file mode 120000 index 0000000000..1fa38efcdf --- /dev/null +++ b/Lang/ALGOL-68/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Count-the-coins b/Lang/ALGOL-68/Count-the-coins new file mode 120000 index 0000000000..598ca91dc6 --- /dev/null +++ b/Lang/ALGOL-68/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Entropy b/Lang/ALGOL-68/Entropy new file mode 120000 index 0000000000..c512b3f9d4 --- /dev/null +++ b/Lang/ALGOL-68/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Even-or-odd b/Lang/ALGOL-68/Even-or-odd new file mode 120000 index 0000000000..1927b286cc --- /dev/null +++ b/Lang/ALGOL-68/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Floyds-triangle b/Lang/ALGOL-68/Floyds-triangle new file mode 120000 index 0000000000..5c3969c7e3 --- /dev/null +++ b/Lang/ALGOL-68/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Function-prototype b/Lang/ALGOL-68/Function-prototype new file mode 120000 index 0000000000..3d450fe92b --- /dev/null +++ b/Lang/ALGOL-68/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Guess-the-number-With-feedback b/Lang/ALGOL-68/Guess-the-number-With-feedback new file mode 120000 index 0000000000..9f83abd310 --- /dev/null +++ b/Lang/ALGOL-68/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Knights-tour b/Lang/ALGOL-68/Knights-tour new file mode 120000 index 0000000000..5fd3d10a11 --- /dev/null +++ b/Lang/ALGOL-68/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Mad-Libs b/Lang/ALGOL-68/Mad-Libs new file mode 120000 index 0000000000..9e2cfb5358 --- /dev/null +++ b/Lang/ALGOL-68/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Middle-three-digits b/Lang/ALGOL-68/Middle-three-digits new file mode 120000 index 0000000000..cde8788fd6 --- /dev/null +++ b/Lang/ALGOL-68/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Parsing-RPN-calculator-algorithm b/Lang/ALGOL-68/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..1df79b8373 --- /dev/null +++ b/Lang/ALGOL-68/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Pick-random-element b/Lang/ALGOL-68/Pick-random-element new file mode 120000 index 0000000000..01b131d3f4 --- /dev/null +++ b/Lang/ALGOL-68/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Read-a-specific-line-from-a-file b/Lang/ALGOL-68/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..156ebef13e --- /dev/null +++ b/Lang/ALGOL-68/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Return-multiple-values b/Lang/ALGOL-68/Return-multiple-values new file mode 120000 index 0000000000..4484f7f9da --- /dev/null +++ b/Lang/ALGOL-68/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Rock-paper-scissors b/Lang/ALGOL-68/Rock-paper-scissors new file mode 120000 index 0000000000..86c7a339fc --- /dev/null +++ b/Lang/ALGOL-68/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sleep b/Lang/ALGOL-68/Sleep new file mode 120000 index 0000000000..407258da60 --- /dev/null +++ b/Lang/ALGOL-68/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Strip-whitespace-from-a-string-Top-and-tail b/Lang/ALGOL-68/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..c6182371f8 --- /dev/null +++ b/Lang/ALGOL-68/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Sum-digits-of-an-integer b/Lang/ALGOL-68/Sum-digits-of-an-integer new file mode 120000 index 0000000000..da2a715195 --- /dev/null +++ b/Lang/ALGOL-68/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/Comments b/Lang/ALGOL-W/Comments new file mode 120000 index 0000000000..c5a47e974e --- /dev/null +++ b/Lang/ALGOL-W/Comments @@ -0,0 +1 @@ +../../Task/Comments/ALGOL-W \ No newline at end of file diff --git a/Lang/APL/Fibonacci-sequence b/Lang/APL/Fibonacci-sequence new file mode 120000 index 0000000000..b66a672e10 --- /dev/null +++ b/Lang/APL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/APL \ No newline at end of file diff --git a/Lang/APL/Longest-common-subsequence b/Lang/APL/Longest-common-subsequence new file mode 120000 index 0000000000..20d165d1df --- /dev/null +++ b/Lang/APL/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/APL \ No newline at end of file diff --git a/Lang/ATS/00DESCRIPTION b/Lang/ATS/00DESCRIPTION index c1ac018384..15be069a9e 100644 --- a/Lang/ATS/00DESCRIPTION +++ b/Lang/ATS/00DESCRIPTION @@ -7,7 +7,7 @@ |strength=strong |express=explicit |tags=ATS -|bnf=http://www.ats-lang.org/DOCUMENTATION/GRAMMAR/ats_grammar_desc.html +|bnf=http://ats-lang.sourceforge.net/htdocs-old/DOCUMENT/GRAMMAR/ats_grammar_desc.html |site=http://www.ats-lang.org/ |hopl=no }} diff --git a/Lang/ATS/100-doors b/Lang/ATS/100-doors new file mode 120000 index 0000000000..b46bd32a83 --- /dev/null +++ b/Lang/ATS/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/ATS \ No newline at end of file diff --git a/Lang/ATS/Balanced-ternary b/Lang/ATS/Balanced-ternary new file mode 120000 index 0000000000..7204520cc2 --- /dev/null +++ b/Lang/ATS/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/ATS \ No newline at end of file diff --git a/Lang/ATS/Fibonacci-sequence b/Lang/ATS/Fibonacci-sequence new file mode 120000 index 0000000000..0aacae653b --- /dev/null +++ b/Lang/ATS/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/ATS \ No newline at end of file diff --git a/Lang/ATS/Greatest-subsequential-sum b/Lang/ATS/Greatest-subsequential-sum new file mode 120000 index 0000000000..052afd2fb4 --- /dev/null +++ b/Lang/ATS/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/ATS \ No newline at end of file diff --git a/Lang/ATS/Hamming-numbers b/Lang/ATS/Hamming-numbers new file mode 120000 index 0000000000..0a57803032 --- /dev/null +++ b/Lang/ATS/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/ATS \ No newline at end of file diff --git a/Lang/ATS/Haversine-formula b/Lang/ATS/Haversine-formula new file mode 120000 index 0000000000..26aba364d1 --- /dev/null +++ b/Lang/ATS/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/ATS \ No newline at end of file diff --git a/Lang/ATS/Higher-order-functions b/Lang/ATS/Higher-order-functions new file mode 120000 index 0000000000..9e0f1fd23a --- /dev/null +++ b/Lang/ATS/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/ATS \ No newline at end of file diff --git a/Lang/ATS/Identity-matrix b/Lang/ATS/Identity-matrix new file mode 120000 index 0000000000..fcca6c007c --- /dev/null +++ b/Lang/ATS/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/ATS \ No newline at end of file diff --git a/Lang/ATS/Repeat-a-string b/Lang/ATS/Repeat-a-string new file mode 120000 index 0000000000..a655e92687 --- /dev/null +++ b/Lang/ATS/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/ATS \ No newline at end of file diff --git a/Lang/ATS/Reverse-a-string b/Lang/ATS/Reverse-a-string new file mode 120000 index 0000000000..e3d81225b3 --- /dev/null +++ b/Lang/ATS/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/ATS \ No newline at end of file diff --git a/Lang/ATS/Roots-of-a-function b/Lang/ATS/Roots-of-a-function new file mode 120000 index 0000000000..c691726273 --- /dev/null +++ b/Lang/ATS/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/ATS \ No newline at end of file diff --git a/Lang/ATS/Sierpinski-triangle b/Lang/ATS/Sierpinski-triangle new file mode 120000 index 0000000000..6e3e0bf674 --- /dev/null +++ b/Lang/ATS/Sierpinski-triangle @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle/ATS \ No newline at end of file diff --git a/Lang/ATS/Sum-digits-of-an-integer b/Lang/ATS/Sum-digits-of-an-integer new file mode 120000 index 0000000000..c803b60240 --- /dev/null +++ b/Lang/ATS/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/ATS \ No newline at end of file diff --git a/Lang/AWK/00DESCRIPTION b/Lang/AWK/00DESCRIPTION index fd026d3abd..fd06d8b1db 100644 --- a/Lang/AWK/00DESCRIPTION +++ b/Lang/AWK/00DESCRIPTION @@ -1,20 +1,30 @@ {{language |exec=interpreted |tag=awk -}} +}}{{CompileOnline}} AWK is a small but powerful programming language that can process and convert text files. AWK is part of every [[Unix]]-derived system. -Each AWK program consists of pattern-action statements. The program reads each input line, checks lines against patterns, and runs matching actions. For programs that never read input lines, the entire program can be one BEGIN { ... } block. +Each AWK program consists of pattern-action statements. +The program reads each input line, checks lines against patterns, and runs matching actions. +For programs that never read input lines, the entire program can be one BEGIN { ... } block. * ''List users who have /bin/ksh as a shell.''$ awk -F: '$7 == "/bin/ksh" { print $1 }' /etc/passwd -AWK has only three types of variables: they are strings, floating-point numbers, and associative arrays (where every array index is a string). Conversion between strings and numbers is automatic. AWK also has regular expressions, which appear in many AWK programs. There are a few built-in functions, like cos() and sprintf(). +AWK has only three types of variables: they are strings, floating-point numbers, and associative arrays (where every array index is a string). +Conversion between strings and numbers is automatic. AWK also has regular expressions, which appear in many AWK programs. +There are a few built-in functions, like cos() and sprintf(). * ''Find average line length.''$ awk '{ cnt += length($0) } END { print cnt / NR }' /etc/rc -The name "AWK" comes from the initials of Alfred Aho, Peter Weinberger and Brian Kernighan: they invented AWK during the 1970s. A few decades later, Kernighan continues to maintain the [[nawk|reference implementation]] of AWK. +The name "AWK" comes from the initials of Alfred Aho, Peter Weinberger and Brian Kernighan: they invented AWK during the 1970s. +A few decades later, Kernighan continues to maintain the [[nawk|reference implementation]] of AWK. ==Links== *[http://leaf.dragonflybsd.org/cgi/web-man?command=awk§ion=1 awk(1) manual page], short and brief *[[wp:AWK (programming language)|AWK in Wikipedia]] -*[http://awk.info AWK Community Portal] \ No newline at end of file +*[http://awk.info AWK Community Portal] + +==Online-Execution== +* [http://www.compileonline.com/execute_awk_online.php compileonline.com] - gawk 4.1.0 (2013) +* [http://codingground.tutorialspoint.com/ codingground.tutorialspoint.com] - gawk 4.1.0 (2013) +* [http://ideone.com ideone.com] - gawk 3.1.6 (2007), mawk 1.3.3 (Nov 1996) \ No newline at end of file diff --git a/Lang/AWK/Anagrams-Deranged-anagrams b/Lang/AWK/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..bb014ee3c3 --- /dev/null +++ b/Lang/AWK/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/AWK \ No newline at end of file diff --git a/Lang/AWK/Combinations-with-repetitions b/Lang/AWK/Combinations-with-repetitions new file mode 120000 index 0000000000..dcad2c2b5b --- /dev/null +++ b/Lang/AWK/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/AWK \ No newline at end of file diff --git a/Lang/AWK/File-modification-time b/Lang/AWK/File-modification-time new file mode 120000 index 0000000000..64633bbb27 --- /dev/null +++ b/Lang/AWK/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/AWK \ No newline at end of file diff --git a/Lang/AWK/File-size b/Lang/AWK/File-size new file mode 120000 index 0000000000..d67fa73c92 --- /dev/null +++ b/Lang/AWK/File-size @@ -0,0 +1 @@ +../../Task/File-size/AWK \ No newline at end of file diff --git a/Lang/AWK/Five-weekends b/Lang/AWK/Five-weekends new file mode 120000 index 0000000000..4889a506cc --- /dev/null +++ b/Lang/AWK/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/AWK \ No newline at end of file diff --git a/Lang/AWK/Hello-world-Graphical b/Lang/AWK/Hello-world-Graphical new file mode 120000 index 0000000000..45a490a85b --- /dev/null +++ b/Lang/AWK/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/AWK \ No newline at end of file diff --git a/Lang/AWK/Knights-tour b/Lang/AWK/Knights-tour new file mode 120000 index 0000000000..67c839d720 --- /dev/null +++ b/Lang/AWK/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/AWK \ No newline at end of file diff --git a/Lang/AWK/Langtons-ant b/Lang/AWK/Langtons-ant new file mode 120000 index 0000000000..5dd4a582fa --- /dev/null +++ b/Lang/AWK/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/AWK \ No newline at end of file diff --git a/Lang/AWK/Modular-inverse b/Lang/AWK/Modular-inverse new file mode 120000 index 0000000000..f03f87ad72 --- /dev/null +++ b/Lang/AWK/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/AWK \ No newline at end of file diff --git a/Lang/AWK/Operator-precedence b/Lang/AWK/Operator-precedence new file mode 120000 index 0000000000..df5fc4da10 --- /dev/null +++ b/Lang/AWK/Operator-precedence @@ -0,0 +1 @@ +../../Task/Operator-precedence/AWK \ No newline at end of file diff --git a/Lang/AWK/Order-two-numerical-lists b/Lang/AWK/Order-two-numerical-lists new file mode 120000 index 0000000000..884c19cb1f --- /dev/null +++ b/Lang/AWK/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/AWK \ No newline at end of file diff --git a/Lang/AWK/Sieve-of-Eratosthenes b/Lang/AWK/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9c1909a0a0 --- /dev/null +++ b/Lang/AWK/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/AWK \ No newline at end of file diff --git a/Lang/AWK/Stem-and-leaf-plot b/Lang/AWK/Stem-and-leaf-plot new file mode 120000 index 0000000000..a9cefe9960 --- /dev/null +++ b/Lang/AWK/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/AWK \ No newline at end of file diff --git a/Lang/Ada/Extend-your-language b/Lang/Ada/Extend-your-language new file mode 120000 index 0000000000..0ea45a630c --- /dev/null +++ b/Lang/Ada/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/Ada \ No newline at end of file diff --git a/Lang/Ada/Set-puzzle b/Lang/Ada/Set-puzzle new file mode 120000 index 0000000000..ef36455be6 --- /dev/null +++ b/Lang/Ada/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Ada \ No newline at end of file diff --git a/Lang/Ada/Visualize-a-tree b/Lang/Ada/Visualize-a-tree new file mode 120000 index 0000000000..7b1dde9c8b --- /dev/null +++ b/Lang/Ada/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Ada \ No newline at end of file diff --git a/Lang/Aime/Generic-swap b/Lang/Aime/Generic-swap new file mode 120000 index 0000000000..62cc2099c1 --- /dev/null +++ b/Lang/Aime/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Aime \ No newline at end of file diff --git a/Lang/Aime/Hailstone-sequence b/Lang/Aime/Hailstone-sequence new file mode 120000 index 0000000000..29c8900f75 --- /dev/null +++ b/Lang/Aime/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Aime \ No newline at end of file diff --git a/Lang/Aime/String-comparison b/Lang/Aime/String-comparison new file mode 120000 index 0000000000..10c1746ce7 --- /dev/null +++ b/Lang/Aime/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Aime \ No newline at end of file diff --git a/Lang/Aime/Sum-of-squares b/Lang/Aime/Sum-of-squares new file mode 120000 index 0000000000..6a26ce50d1 --- /dev/null +++ b/Lang/Aime/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Aime \ No newline at end of file diff --git a/Lang/AppleScript/Accumulator-factory b/Lang/AppleScript/Accumulator-factory new file mode 120000 index 0000000000..c05e6f93d2 --- /dev/null +++ b/Lang/AppleScript/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Apply-a-callback-to-an-array b/Lang/AppleScript/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..67952c7905 --- /dev/null +++ b/Lang/AppleScript/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/First-class-functions b/Lang/AppleScript/First-class-functions new file mode 120000 index 0000000000..99ab87275d --- /dev/null +++ b/Lang/AppleScript/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Function-composition b/Lang/AppleScript/Function-composition new file mode 120000 index 0000000000..0278a12d27 --- /dev/null +++ b/Lang/AppleScript/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Higher-order-functions b/Lang/AppleScript/Higher-order-functions new file mode 120000 index 0000000000..62aece9f70 --- /dev/null +++ b/Lang/AppleScript/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/AppleScript \ No newline at end of file diff --git a/Lang/AppleScript/Hostname b/Lang/AppleScript/Hostname new file mode 120000 index 0000000000..d114524838 --- /dev/null +++ b/Lang/AppleScript/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/AppleScript \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Loops-Continue b/Lang/Applesoft-BASIC/Loops-Continue new file mode 120000 index 0000000000..03727e8d35 --- /dev/null +++ b/Lang/Applesoft-BASIC/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Terminal-control-Dimensions b/Lang/Applesoft-BASIC/Terminal-control-Dimensions new file mode 120000 index 0000000000..e7793aa73a --- /dev/null +++ b/Lang/Applesoft-BASIC/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Applesoft-BASIC/Video-display-modes b/Lang/Applesoft-BASIC/Video-display-modes new file mode 120000 index 0000000000..2c77145c56 --- /dev/null +++ b/Lang/Applesoft-BASIC/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Applesoft-BASIC \ No newline at end of file diff --git a/Lang/Assembly/00DESCRIPTION b/Lang/Assembly/00DESCRIPTION index 40f2626a4f..6861d124a3 100644 --- a/Lang/Assembly/00DESCRIPTION +++ b/Lang/Assembly/00DESCRIPTION @@ -1,7 +1,14 @@ {{language}}{{assembler language}} -[[Category:Encyclopedia]]'''Assembly language''' (or just '''assembly'''; often abbreviated '''asm'''; sometimes called '''assembler''', although that more properly refers to the program that translates the assembly source into machine code) is a term used for a language which is as close to raw machine code as a language can get. +{{language programming paradigm|Imperative}} +[[Category:Encyclopedia]]'''Assembly language''' (or just '''assembly'''; often abbreviated '''asm'''; sometimes called '''assembler''', although that more properly refers to the program that translates the assembly source into machine code) is a term used for a language which is as close to raw machine code as a language can get. Writing in assembly typically requires strict knowledge of the underlying hardware, which lends itself well to implementing [[wp:Firmware|firmware]] due to size and speed constraints. -Usually assembly languages use textual "[[wp:mnemonic|mnemonic]]" instructions that correspond directly to binary machine code instructions (merely hiding details of bit-wise encoding), except for ''macros'' which expand to multiple instructions, and often give direct control over the overall layout of the assembled program on disk and in memory. Available instructions and codes are specific to the architecture being programmed on (although there are assemblers which provide an abstracted, non-architecture-specific language; the most notable one is the [[wp:GNU Assembler|GNU Assembler]]). Assembly programs are typically loaded directly into a computer's memory and run from there. +Assembly languages use textual "[[wp:Mnemonic|mnemonics]]" that correspond directly to machine instructions ([[wp:Opcode|opcodes]]). Writing in assembly often gives direct control over the overall layout of the assembled program on disk and in memory. Available instructions and codes are specific to the architecture being programmed on (although there are assemblers which provide an abstracted, non-architecture-specific language; the most notable of which is the [[wp:GNU Assembler|GNU Assembler]]). Assembly programs are typically loaded directly into a computer's memory and run from there. A software [[wp:Emulator|emulator]] can be used for testing purposes, or in the absence of hardware. + +High-level assemblers may include many useful abstractions such as: +* ''macros'' - inline functions which expand to multiple instructions +* generic instructions that match the most appropriate instruction +* optimisations such as rearranging code +* [[:Category:Programming_paradigm/Object-oriented|OOP]] paradigms such as classes and objects ==See also== *[[wp:Assembly language|Assembly language]] on Wikipedia (includes an in-depth discussion of assembly) diff --git a/Lang/AutoHotkey/Continued-fraction b/Lang/AutoHotkey/Continued-fraction new file mode 120000 index 0000000000..4e1d6a5b28 --- /dev/null +++ b/Lang/AutoHotkey/Continued-fraction @@ -0,0 +1 @@ +../../Task/Continued-fraction/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Narcissist b/Lang/AutoHotkey/Narcissist new file mode 120000 index 0000000000..882883a6ae --- /dev/null +++ b/Lang/AutoHotkey/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Polymorphism b/Lang/AutoHotkey/Polymorphism new file mode 120000 index 0000000000..a044190064 --- /dev/null +++ b/Lang/AutoHotkey/Polymorphism @@ -0,0 +1 @@ +../../Task/Polymorphism/AutoHotkey \ No newline at end of file diff --git a/Lang/AutoHotkey/Xiaolin-Wus-line-algorithm b/Lang/AutoHotkey/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..818b8315dc --- /dev/null +++ b/Lang/AutoHotkey/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/AutoHotkey \ No newline at end of file diff --git a/Lang/Axiom/Numerical-integration-Gauss-Legendre-Quadrature b/Lang/Axiom/Numerical-integration-Gauss-Legendre-Quadrature new file mode 120000 index 0000000000..40bd920eb4 --- /dev/null +++ b/Lang/Axiom/Numerical-integration-Gauss-Legendre-Quadrature @@ -0,0 +1 @@ +../../Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom \ No newline at end of file diff --git a/Lang/Axiom/Quaternion-type b/Lang/Axiom/Quaternion-type new file mode 120000 index 0000000000..483576377a --- /dev/null +++ b/Lang/Axiom/Quaternion-type @@ -0,0 +1 @@ +../../Task/Quaternion-type/Axiom \ No newline at end of file diff --git a/Lang/BASIC/00DESCRIPTION b/Lang/BASIC/00DESCRIPTION index d275a4d959..10d54e7703 100644 --- a/Lang/BASIC/00DESCRIPTION +++ b/Lang/BASIC/00DESCRIPTION @@ -11,5 +11,6 @@ BASIC became popular, with many different implementations for various computers. ==Links== *[[wp:BASIC|Wikipedia:BASIC]] +**[[wp:Rocky Mountain BASIC]] {{language programming paradigm|Procedural}} \ No newline at end of file diff --git a/Lang/Babel/00DESCRIPTION b/Lang/Babel/00DESCRIPTION index 6da7289d0c..764f570fac 100644 --- a/Lang/Babel/00DESCRIPTION +++ b/Lang/Babel/00DESCRIPTION @@ -1,6 +1,6 @@ {{alertbox|#ffffe0|''Were you looking for the [[Common Lisp]] library? That category has now been [[:Category:Babel (library)|renamed]].''}} {{language}}Babel is an interpreted language designed by Clayton Bauman. It is an untyped, stack-based, postfix language with support for arrays, lists and hashes (dictionaries). Babel 1.0 will support built-in crypto-based verification of code in order to enable safer remote code execution. -Babel is implemented in [[C]]. It is still under development with a v0.9 release planned for December 2013, so please excuse the dust and debris in the [https://github.com/claytonkb/Babel current implementation]. +Babel is implemented in [[C]]. It is still under development with a v0.9 release planned for December 2014, so please excuse the dust and debris in the [https://github.com/claytonkb/Babel current implementation]. Check out the README and the doc/ folder on github for more information. \ No newline at end of file diff --git a/Lang/Babel/Apply-a-callback-to-an-array b/Lang/Babel/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..0eb4ceeb37 --- /dev/null +++ b/Lang/Babel/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Babel \ No newline at end of file diff --git a/Lang/Babel/Arrays b/Lang/Babel/Arrays new file mode 120000 index 0000000000..6642467bce --- /dev/null +++ b/Lang/Babel/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Babel \ No newline at end of file diff --git a/Lang/Babel/Associative-array-Creation b/Lang/Babel/Associative-array-Creation new file mode 120000 index 0000000000..b9975b3ec1 --- /dev/null +++ b/Lang/Babel/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Babel \ No newline at end of file diff --git a/Lang/Babel/Associative-array-Iteration b/Lang/Babel/Associative-array-Iteration new file mode 120000 index 0000000000..eb32f14f92 --- /dev/null +++ b/Lang/Babel/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Babel \ No newline at end of file diff --git a/Lang/Babel/Averages-Arithmetic-mean b/Lang/Babel/Averages-Arithmetic-mean new file mode 120000 index 0000000000..286433a498 --- /dev/null +++ b/Lang/Babel/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Babel \ No newline at end of file diff --git a/Lang/Babel/Bitwise-operations b/Lang/Babel/Bitwise-operations new file mode 120000 index 0000000000..8240487751 --- /dev/null +++ b/Lang/Babel/Bitwise-operations @@ -0,0 +1 @@ +../../Task/Bitwise-operations/Babel \ No newline at end of file diff --git a/Lang/Babel/Caesar-cipher b/Lang/Babel/Caesar-cipher new file mode 120000 index 0000000000..7328d8f313 --- /dev/null +++ b/Lang/Babel/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Babel \ No newline at end of file diff --git a/Lang/Babel/Character-codes b/Lang/Babel/Character-codes new file mode 120000 index 0000000000..3ff9d54729 --- /dev/null +++ b/Lang/Babel/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Babel \ No newline at end of file diff --git a/Lang/Babel/Conditional-structures b/Lang/Babel/Conditional-structures new file mode 120000 index 0000000000..9e29dec42f --- /dev/null +++ b/Lang/Babel/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Babel \ No newline at end of file diff --git a/Lang/Babel/Copy-a-string b/Lang/Babel/Copy-a-string new file mode 120000 index 0000000000..87ebbbc90e --- /dev/null +++ b/Lang/Babel/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Babel \ No newline at end of file diff --git a/Lang/Babel/Deepcopy b/Lang/Babel/Deepcopy new file mode 120000 index 0000000000..c6086df470 --- /dev/null +++ b/Lang/Babel/Deepcopy @@ -0,0 +1 @@ +../../Task/Deepcopy/Babel \ No newline at end of file diff --git a/Lang/Batch-File/24-game b/Lang/Batch-File/24-game new file mode 120000 index 0000000000..9485b23e72 --- /dev/null +++ b/Lang/Batch-File/24-game @@ -0,0 +1 @@ +../../Task/24-game/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Bitmap-Bresenhams-line-algorithm b/Lang/Batch-File/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..d7da778e6b --- /dev/null +++ b/Lang/Batch-File/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Conditional-structures b/Lang/Batch-File/Conditional-structures new file mode 120000 index 0000000000..3f0866854e --- /dev/null +++ b/Lang/Batch-File/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Determine-if-a-string-is-numeric b/Lang/Batch-File/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..725e83cce2 --- /dev/null +++ b/Lang/Batch-File/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Guess-the-number-With-feedback b/Lang/Batch-File/Guess-the-number-With-feedback new file mode 120000 index 0000000000..d7dc2f59a8 --- /dev/null +++ b/Lang/Batch-File/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Hostname b/Lang/Batch-File/Hostname new file mode 120000 index 0000000000..b47c425cf6 --- /dev/null +++ b/Lang/Batch-File/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Palindrome-detection b/Lang/Batch-File/Palindrome-detection new file mode 120000 index 0000000000..95c5b5f5a3 --- /dev/null +++ b/Lang/Batch-File/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Sieve-of-Eratosthenes b/Lang/Batch-File/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..0bd205ccba --- /dev/null +++ b/Lang/Batch-File/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Batch-File \ No newline at end of file diff --git a/Lang/Batch-File/Sorting-algorithms-Gnome-sort b/Lang/Batch-File/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..801a17ac0b --- /dev/null +++ b/Lang/Batch-File/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Batch-File \ No newline at end of file diff --git a/Lang/Bc/00DESCRIPTION b/Lang/Bc/00DESCRIPTION index d20347e1f6..530a8881df 100644 --- a/Lang/Bc/00DESCRIPTION +++ b/Lang/Bc/00DESCRIPTION @@ -4,9 +4,16 @@ |hopl id=1854 }} -'''bc''' is the standard calculator for [[Unix]] systems. bc boasts unlimited precision, to handle numbers with very many digits. With the bc language, you can write programs that perform numeric calculations and print the results. (See also [[wp:Bc programming language|Bc programming language]] on Wikipedia.) +'''bc''' ("basic calculator") is the standard calculator for [[Unix]] systems.
+bc boasts unlimited precision, to handle numbers with very many digits.
+With the bc language, you can write programs that perform numeric calculations +and print the results. -bc has an interactive mode, which is convenient for brief calculations. +;See also : +* [[wp:Bc programming language|Bc programming language]] on Wikipedia +* [[:Category:Dc|dc]] - the unix '''d'''esktop '''c'''alculator. + +bc has an interactive mode, which is convenient for brief calculations: $ '''bc''' '''2 + 3''' @@ -23,7 +30,8 @@ bc has an interactive mode, which is convenient for brief calculations. '''FE80''' 1111111010000000 -Division and sqrt will not give an infinite number of digits. The special variable scale controls when to stop. +Division and sqrt will not give an infinite number of digits.
+The special variable scale controls when to stop. $ '''bc''' '''65.9 / 3''' @@ -37,17 +45,28 @@ Division and sqrt will not give an infinite number of digits. The speci '''sqrt(2)''' 1.414213562373095048801688724209698078569671875376948073176679 -bc language resembles [[C|C language]]: bc has most of the same operators and control structures ('if', 'while', 'for'). Expressions print themselves, unless they are assignments. The newline is a statement separator, like the semicolon. +bc language resembles [[C|C language]]: bc has most of the same operators +and control structures ('if', 'while', 'for').
+Expressions print themselves, unless they are assignments.
+The newline is a statement separator, like the semicolon. -bc has excellent numeric operations, but is a poor language. The original bc, the "Bell Calculator" of Unix V7, translated the program to [[dc]] and inherited the limitations of [[dc]]. +bc has excellent numeric operations, but is a poor language. +The original bc, the "Bell Calculator" of Unix V7, +translated the program to [[dc]] and inherited the limitations of [[dc]]. * Names of variables, and custom functions, may have only one letter. * There is no 'else' branch of an 'if' statement. * Relational operators (== <= => != < >) only work in the condition of an 'if', 'while' or 'for' statement. * There are no boolean operators (! && ||). -Some newer implementations, like [[GNU bc]] and [[OpenBSD bc]], discard these silly limitations, but users can still feel their effects. OpenBSD says, "a = b < c is interpreted as "(a = b) < c, which is probably not what the programmer intended," and "!a < b is interpreted as !(a < b)". +Some newer implementations, like [[GNU bc]] and [[OpenBSD bc]], +discard these silly limitations, but users can still feel their effects.
+OpenBSD says, "a = b < c is interpreted as "(a = b) < c, which is probably not what the programmer intended," and "!a < b is interpreted as !(a < b)". -bc can only print a string, and has no other string operations, so bc cannot do tasks like [[reverse a string]]. bc has no way to read user input, except to go to interactive mode after loading a program. +bc can only print a string, and has no other string operations, +so bc cannot do tasks like [[reverse a string]].
+bc has no way to read user input, except to go to interactive mode +after loading a program. -[[Category:Mathematical programming languages]] \ No newline at end of file +[[Category:Mathematical programming languages]] +[[Category:Utility]] \ No newline at end of file diff --git a/Lang/Bc/Non-decimal-radices-Output b/Lang/Bc/Non-decimal-radices-Output new file mode 120000 index 0000000000..aacc5f8b12 --- /dev/null +++ b/Lang/Bc/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/Bc \ No newline at end of file diff --git a/Lang/Befunge/Factors-of-an-integer b/Lang/Befunge/Factors-of-an-integer new file mode 120000 index 0000000000..e8714df57f --- /dev/null +++ b/Lang/Befunge/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Befunge \ No newline at end of file diff --git a/Lang/Boo/Arrays b/Lang/Boo/Arrays new file mode 120000 index 0000000000..81ad7e5813 --- /dev/null +++ b/Lang/Boo/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Boo \ No newline at end of file diff --git a/Lang/Bracmat/Apply-a-callback-to-an-array b/Lang/Bracmat/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..e35f9cbf6a --- /dev/null +++ b/Lang/Bracmat/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Arithmetic-Complex b/Lang/Bracmat/Arithmetic-Complex new file mode 120000 index 0000000000..87c7245752 --- /dev/null +++ b/Lang/Bracmat/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Arrays b/Lang/Bracmat/Arrays new file mode 120000 index 0000000000..fc9f7d5e83 --- /dev/null +++ b/Lang/Bracmat/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Averages-Simple-moving-average b/Lang/Bracmat/Averages-Simple-moving-average new file mode 120000 index 0000000000..ec50988fec --- /dev/null +++ b/Lang/Bracmat/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Combinations-with-repetitions b/Lang/Bracmat/Combinations-with-repetitions new file mode 120000 index 0000000000..43b109470d --- /dev/null +++ b/Lang/Bracmat/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Day-of-the-week b/Lang/Bracmat/Day-of-the-week new file mode 120000 index 0000000000..53119e2ce5 --- /dev/null +++ b/Lang/Bracmat/Day-of-the-week @@ -0,0 +1 @@ +../../Task/Day-of-the-week/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Factors-of-a-Mersenne-number b/Lang/Bracmat/Factors-of-a-Mersenne-number new file mode 120000 index 0000000000..8b29c2f93b --- /dev/null +++ b/Lang/Bracmat/Factors-of-a-Mersenne-number @@ -0,0 +1 @@ +../../Task/Factors-of-a-Mersenne-number/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Fibonacci-n-step-number-sequences b/Lang/Bracmat/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..103951625c --- /dev/null +++ b/Lang/Bracmat/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/First-class-functions b/Lang/Bracmat/First-class-functions new file mode 120000 index 0000000000..4105cc73fb --- /dev/null +++ b/Lang/Bracmat/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Hofstadter-Q-sequence b/Lang/Bracmat/Hofstadter-Q-sequence new file mode 120000 index 0000000000..9265c1e6d6 --- /dev/null +++ b/Lang/Bracmat/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Input-loop b/Lang/Bracmat/Input-loop new file mode 120000 index 0000000000..d9a8bdd31b --- /dev/null +++ b/Lang/Bracmat/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/JSON b/Lang/Bracmat/JSON new file mode 120000 index 0000000000..6778dd05c4 --- /dev/null +++ b/Lang/Bracmat/JSON @@ -0,0 +1 @@ +../../Task/JSON/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Knapsack-problem-Continuous b/Lang/Bracmat/Knapsack-problem-Continuous new file mode 120000 index 0000000000..c9d644d279 --- /dev/null +++ b/Lang/Bracmat/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Look-and-say-sequence b/Lang/Bracmat/Look-and-say-sequence new file mode 120000 index 0000000000..60e4094f1d --- /dev/null +++ b/Lang/Bracmat/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Loops-While b/Lang/Bracmat/Loops-While new file mode 120000 index 0000000000..86646c532b --- /dev/null +++ b/Lang/Bracmat/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/N-queens-problem b/Lang/Bracmat/N-queens-problem new file mode 120000 index 0000000000..790fe80c55 --- /dev/null +++ b/Lang/Bracmat/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Optional-parameters b/Lang/Bracmat/Optional-parameters new file mode 120000 index 0000000000..2c96c9482e --- /dev/null +++ b/Lang/Bracmat/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Palindrome-detection b/Lang/Bracmat/Palindrome-detection new file mode 120000 index 0000000000..9150d967ac --- /dev/null +++ b/Lang/Bracmat/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Partial-function-application b/Lang/Bracmat/Partial-function-application new file mode 120000 index 0000000000..8bbcbc40be --- /dev/null +++ b/Lang/Bracmat/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Permutations-Derangements b/Lang/Bracmat/Permutations-Derangements new file mode 120000 index 0000000000..074674a2dc --- /dev/null +++ b/Lang/Bracmat/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Queue-Definition b/Lang/Bracmat/Queue-Definition new file mode 120000 index 0000000000..f9f026da61 --- /dev/null +++ b/Lang/Bracmat/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Queue-Usage b/Lang/Bracmat/Queue-Usage new file mode 120000 index 0000000000..f78b261dc8 --- /dev/null +++ b/Lang/Bracmat/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Rosetta-Code-Count-examples b/Lang/Bracmat/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..1c8b3ee689 --- /dev/null +++ b/Lang/Bracmat/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity b/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..df80f1b8cb --- /dev/null +++ b/Lang/Bracmat/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Runtime-evaluation-In-an-environment b/Lang/Bracmat/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..f012bdd679 --- /dev/null +++ b/Lang/Bracmat/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Simple-database b/Lang/Bracmat/Simple-database new file mode 120000 index 0000000000..091e5e51af --- /dev/null +++ b/Lang/Bracmat/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sum-and-product-of-an-array b/Lang/Bracmat/Sum-and-product-of-an-array new file mode 120000 index 0000000000..11af9d2066 --- /dev/null +++ b/Lang/Bracmat/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Sum-of-squares b/Lang/Bracmat/Sum-of-squares new file mode 120000 index 0000000000..81f594d702 --- /dev/null +++ b/Lang/Bracmat/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Time-a-function b/Lang/Bracmat/Time-a-function new file mode 120000 index 0000000000..3df07b078a --- /dev/null +++ b/Lang/Bracmat/Time-a-function @@ -0,0 +1 @@ +../../Task/Time-a-function/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Variables b/Lang/Bracmat/Variables new file mode 120000 index 0000000000..d90f146cb6 --- /dev/null +++ b/Lang/Bracmat/Variables @@ -0,0 +1 @@ +../../Task/Variables/Bracmat \ No newline at end of file diff --git a/Lang/Bracmat/Zebra-puzzle b/Lang/Bracmat/Zebra-puzzle new file mode 120000 index 0000000000..893664973b --- /dev/null +++ b/Lang/Bracmat/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Bracmat \ No newline at end of file diff --git a/Lang/Brainf---/00DESCRIPTION b/Lang/Brainf---/00DESCRIPTION index 2c650ee8a6..7b702b4d45 100644 --- a/Lang/Brainf---/00DESCRIPTION +++ b/Lang/Brainf---/00DESCRIPTION @@ -1,6 +1,22 @@ -{{language|Brainf***|bnf=http://ninh.nl/blog/2008/10/25/brainfck-birds-of-a-feather-session-take-2/}}Also known as '''Brainfuck''', but identified as '''Brainf***''' for reasons described [[Rosetta Code:Brainf***|here]]. Created by Urban Müller in 1993 in an attempt to create the world's smallest Turing-complete compiler. It is noted as an [[:Category:Esoteric_Languages|esoteric programming language]], as it is not ordinarily used for applications development, but it also noted as being a minimalist language. +{{language|Brainf***|bnf=http://ninh.nl/blog/2008/10/25/brainfck-birds-of-a-feather-session-take-2/}} +Also known as '''Brainfuck''', but identified as '''Brainf***''' for reasons described [[Rosetta Code:Brainf***|here]].
+Created by Urban Müller in 1993 in an attempt to create the world's smallest Turing-complete compiler. +It is noted as an [[:Category:Esoteric_Languages|esoteric programming language]], +as it is not ordinarily used for applications development, +but it also noted as being a minimalist language. -The construct for the language is similar to a [[wp:Turing Machine|Turing Machine]]. The commands themselves act on an array or "tape" (usually a byte or integer array and usually "infinite" on one or both ends) and a pointer to a position in that array. The complete specification for the language can be summed up with the following eight symbols: +The construction of the language is similar to a [[wp:Turing Machine|Turing Machine]].
+As with the Turing Machine, Brainf*** is built from a finite state machine and an infinite tape of cells. +Each cell can be any size, including unbounded, but is frequently an eight bit byte. +The finite state machine is the program code with the program counter pointing at the current state.
+The strong similarity is one reason that a Brainf*** equivalent named ''Ρʺ'' +was suitable for use by Corrado Böhm in 1964 +to prove that structured programming using only ''while loops'' +was just a powerful as ''goto spagetti'' programming. + +The complete specification for the language +(the available state transitions of the Turing machine) +can be summed up with the following eight symbols: {| class="wikitable" !align="center"|Character @@ -13,31 +29,39 @@ The construct for the language is similar to a [[wp:Turing Machine|Turing Machin ||decrement the pointer (to point to the next cell to the left). |- |style="text-align:center"|+ -||increment (increase by one) the byte at the pointer. +||increment (increase by one) the cell at the pointer. |- |style="text-align:center"|- -||decrement (decrease by one) the byte at the pointer. -|- -|style="text-align:center"|. -||output the value of the byte at the pointer (usually interpreted to a character). -|- -|style="text-align:center"|, -||accept one byte of input (usually interpreted from a character), storing its value in the byte at the pointer. +||decrement (decrease by one) the cell at the pointer. |- |style="text-align:center"|[ -||jump forward to the command after the corresponding ] if the byte at the pointer is zero. +||jump forward to the command after the corresponding ] if the cell at the pointer is zero. |- |style="text-align:center"|] -||jump back to the command after the corresponding [ if the byte at the pointer is nonzero. +||jump back to the command after the corresponding [ if the cell at the pointer is nonzero. +|- +|style="text-align:center"|. +||output the value of the cell at the pointer as a character. +|- +|style="text-align:center"|, +||accept one character of input, storing its value in the cell at the pointer. |} -Alternatively, the ] command may instead be translated as an unconditional jump '''to''' the corresponding [ command, or vice versa; programs will behave the same but will run more slowly. +Alternatively, the ] command may instead be translated as an unconditional jump '''to''' the corresponding [ command, or vice versa; programs will behave the same but may run more slowly. All other symbols, including traditional whitespace characters, are interpreted as comments. -Due to this minimal instruction set, Brainf*** is used as an introduction to compilers and has even been successfully implemented as a microprocessor core and the foundation to an operating system using a slightly extended syntax for output. +The definition of the . and , in the above table still has some ambiguities due to the many ways of converting 'numbers' to 'characters'. +Urban Müller's ''smallest compiler'' converted between characters and numbers using the ASCII character set. +The newline character is number ''10'' and a end of file on input is signalled by the cell value being unchanged when the , command completes. +The , command uses line editing and waits for for the return key to be pressed. +Due to this minimal instruction set, Brainf*** is used as an introduction to compilers and has even been successfully implemented as a microprocessor core and the foundation to an operating system using a slightly extended syntax for output. +BUT due to vehement opposition to the name [http://esolangs.org/wiki/Cupid various] [http://esolangs.org/wiki/Category:Brainfuck_equivalents equivalents] are frequently used. + + ==See also== +* [[Rosetta Code:Brainf***]] ( why some people call it BF :) * [[RCBF]] - BF interpreters as a Rosetta Code task ==Citations== @@ -47,4 +71,5 @@ Due to this minimal instruction set, Brainf*** is used as an introduction to com * [http://dmoz.org/Computers/Programming/Languages/Brainfuck/ DMOZ Brainf*** category] * [http://www.iwriteiam.nl/Ha_BF.html Brainf*** tutorial] + [[Category:Esoteric_Languages]] \ No newline at end of file diff --git a/Lang/Brat/Integer-comparison b/Lang/Brat/Integer-comparison new file mode 120000 index 0000000000..cff7af7f9d --- /dev/null +++ b/Lang/Brat/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Brat \ No newline at end of file diff --git a/Lang/C++/00DESCRIPTION b/Lang/C++/00DESCRIPTION index 17ed7f4c2b..c10caeb0cf 100644 --- a/Lang/C++/00DESCRIPTION +++ b/Lang/C++/00DESCRIPTION @@ -22,7 +22,8 @@ If you can't find an implementation for your task in the C++ category below, ple * '''C++98''' is the version of C++ standardized by ISO in 1998. It is the most commonly used and supported version of the language. The term "C++" usually refers to C++98. * '''C++03''' is a minor improvement to C++98, standardized by ISO in 2003. * '''TR1''' (Technical Report 1) is a proposal for extensions to the C++ standard library. It was published in 2007. Many of its proposals made it into C++11. Many compilers support it, but put its headers in a different directory. -* '''C++11''' (formerly called '''C++0x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. It is not completely supported by many, if any, compilers, but most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. +* '''C++11''' (formerly called '''C++0x''') is a significant improvement, adding many new language features and libraries. It was standardized by ISO in 2011. Most of its features are available in [[GCC]] [http://gcc.gnu.org/projects/cxx0x.html] and [[Clang]] [http://clang.llvm.org/cxx_status.html]. +* '''C++14''' (formerly called '''C++1y''') is a minor improvement to C++11, standardized by ISO in 2014. Most of its features are available in [[Clang]] [http://clang.llvm.org/cxx_status.html] and [[GCC]] [http://gcc.gnu.org/projects/cxx1y.html]. {{language programming paradigm|Imperative}} {{language programming paradigm|Object-oriented}} diff --git a/Lang/C++/24-game-Solve b/Lang/C++/24-game-Solve new file mode 120000 index 0000000000..6f89b57bda --- /dev/null +++ b/Lang/C++/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/C++ \ No newline at end of file diff --git a/Lang/C++/Closest-pair-problem b/Lang/C++/Closest-pair-problem new file mode 120000 index 0000000000..b160822f05 --- /dev/null +++ b/Lang/C++/Closest-pair-problem @@ -0,0 +1 @@ +../../Task/Closest-pair-problem/C++ \ No newline at end of file diff --git a/Lang/C++/Count-in-factors b/Lang/C++/Count-in-factors new file mode 120000 index 0000000000..89d23d2909 --- /dev/null +++ b/Lang/C++/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/C++ \ No newline at end of file diff --git a/Lang/C++/Function-prototype b/Lang/C++/Function-prototype new file mode 120000 index 0000000000..96aea939b0 --- /dev/null +++ b/Lang/C++/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/C++ \ No newline at end of file diff --git a/Lang/C++/Greatest-common-divisor b/Lang/C++/Greatest-common-divisor new file mode 120000 index 0000000000..17c9174488 --- /dev/null +++ b/Lang/C++/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/C++ \ No newline at end of file diff --git a/Lang/C++/Here-document b/Lang/C++/Here-document new file mode 120000 index 0000000000..4760ec6e39 --- /dev/null +++ b/Lang/C++/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/C++ \ No newline at end of file diff --git a/Lang/C++/Inverted-syntax b/Lang/C++/Inverted-syntax new file mode 120000 index 0000000000..d3c9d19f69 --- /dev/null +++ b/Lang/C++/Inverted-syntax @@ -0,0 +1 @@ +../../Task/Inverted-syntax/C++ \ No newline at end of file diff --git a/Lang/C++/Leap-year b/Lang/C++/Leap-year new file mode 120000 index 0000000000..bf99118c8a --- /dev/null +++ b/Lang/C++/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/C++ \ No newline at end of file diff --git a/Lang/C++/Longest-common-subsequence b/Lang/C++/Longest-common-subsequence new file mode 120000 index 0000000000..62ddfa37df --- /dev/null +++ b/Lang/C++/Longest-common-subsequence @@ -0,0 +1 @@ +../../Task/Longest-common-subsequence/C++ \ No newline at end of file diff --git a/Lang/C++/Minesweeper-game b/Lang/C++/Minesweeper-game new file mode 120000 index 0000000000..0f2d622c23 --- /dev/null +++ b/Lang/C++/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/C++ \ No newline at end of file diff --git a/Lang/C++/Non-continuous-subsequences b/Lang/C++/Non-continuous-subsequences new file mode 120000 index 0000000000..a52f93229c --- /dev/null +++ b/Lang/C++/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/C++ \ No newline at end of file diff --git a/Lang/C++/Record-sound b/Lang/C++/Record-sound new file mode 120000 index 0000000000..1908d5bcc4 --- /dev/null +++ b/Lang/C++/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/C++ \ No newline at end of file diff --git a/Lang/C++/Sorting-algorithms-Sleep-sort b/Lang/C++/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..1f095fdf25 --- /dev/null +++ b/Lang/C++/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Terminal-control-Hiding-the-cursor b/Lang/C++/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..65330a3f4f --- /dev/null +++ b/Lang/C++/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/C++ \ No newline at end of file diff --git a/Lang/C++/Topological-sort b/Lang/C++/Topological-sort new file mode 120000 index 0000000000..054a04d543 --- /dev/null +++ b/Lang/C++/Topological-sort @@ -0,0 +1 @@ +../../Task/Topological-sort/C++ \ No newline at end of file diff --git a/Lang/C++/Zebra-puzzle b/Lang/C++/Zebra-puzzle new file mode 120000 index 0000000000..ca8fcdf997 --- /dev/null +++ b/Lang/C++/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/C++ \ No newline at end of file diff --git a/Lang/C-sharp/Averages-Mean-time-of-day b/Lang/C-sharp/Averages-Mean-time-of-day new file mode 120000 index 0000000000..0b379926d4 --- /dev/null +++ b/Lang/C-sharp/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Empty-directory b/Lang/C-sharp/Empty-directory new file mode 120000 index 0000000000..c89c5dc031 --- /dev/null +++ b/Lang/C-sharp/Empty-directory @@ -0,0 +1 @@ +../../Task/Empty-directory/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Entropy b/Lang/C-sharp/Entropy new file mode 120000 index 0000000000..c4b8e0b96f --- /dev/null +++ b/Lang/C-sharp/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Fibonacci-n-step-number-sequences b/Lang/C-sharp/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..efd4c8bc62 --- /dev/null +++ b/Lang/C-sharp/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Floyds-triangle b/Lang/C-sharp/Floyds-triangle new file mode 120000 index 0000000000..fe77a2dc85 --- /dev/null +++ b/Lang/C-sharp/Floyds-triangle @@ -0,0 +1 @@ +../../Task/Floyds-triangle/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Gamma-function b/Lang/C-sharp/Gamma-function new file mode 120000 index 0000000000..9b80ed3d50 --- /dev/null +++ b/Lang/C-sharp/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Guess-the-number-With-feedback--player- b/Lang/C-sharp/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..703ffe1f34 --- /dev/null +++ b/Lang/C-sharp/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Hello-world-Line-printer b/Lang/C-sharp/Hello-world-Line-printer new file mode 120000 index 0000000000..03eecb50ee --- /dev/null +++ b/Lang/C-sharp/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Kaprekar-numbers b/Lang/C-sharp/Kaprekar-numbers new file mode 120000 index 0000000000..a38e989dea --- /dev/null +++ b/Lang/C-sharp/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Mad-Libs b/Lang/C-sharp/Mad-Libs new file mode 120000 index 0000000000..5886d05e95 --- /dev/null +++ b/Lang/C-sharp/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Narcissist b/Lang/C-sharp/Narcissist new file mode 120000 index 0000000000..0457bd1533 --- /dev/null +++ b/Lang/C-sharp/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Non-decimal-radices-Output b/Lang/C-sharp/Non-decimal-radices-Output new file mode 120000 index 0000000000..05f8721f03 --- /dev/null +++ b/Lang/C-sharp/Non-decimal-radices-Output @@ -0,0 +1 @@ +../../Task/Non-decimal-radices-Output/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Pick-random-element b/Lang/C-sharp/Pick-random-element new file mode 120000 index 0000000000..403ca64fc6 --- /dev/null +++ b/Lang/C-sharp/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Pinstripe-Display b/Lang/C-sharp/Pinstripe-Display new file mode 120000 index 0000000000..4923cde825 --- /dev/null +++ b/Lang/C-sharp/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Priority-queue b/Lang/C-sharp/Priority-queue new file mode 120000 index 0000000000..a491fdcc54 --- /dev/null +++ b/Lang/C-sharp/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Sutherland-Hodgman-polygon-clipping b/Lang/C-sharp/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..28cfa595b1 --- /dev/null +++ b/Lang/C-sharp/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Synchronous-concurrency b/Lang/C-sharp/Synchronous-concurrency new file mode 120000 index 0000000000..5879d57a1e --- /dev/null +++ b/Lang/C-sharp/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Van-der-Corput-sequence b/Lang/C-sharp/Van-der-Corput-sequence new file mode 120000 index 0000000000..106297dd98 --- /dev/null +++ b/Lang/C-sharp/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/C-sharp \ No newline at end of file diff --git a/Lang/C-sharp/Zeckendorf-number-representation b/Lang/C-sharp/Zeckendorf-number-representation new file mode 120000 index 0000000000..cf853010e5 --- /dev/null +++ b/Lang/C-sharp/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/C-sharp \ No newline at end of file diff --git a/Lang/C/Carmichael-3-strong-pseudoprimes b/Lang/C/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..1c91d5fa93 --- /dev/null +++ b/Lang/C/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/C \ No newline at end of file diff --git a/Lang/CMake/00DESCRIPTION b/Lang/CMake/00DESCRIPTION index 4bfb8f4457..556b082355 100644 --- a/Lang/CMake/00DESCRIPTION +++ b/Lang/CMake/00DESCRIPTION @@ -3,10 +3,21 @@ |site=http://www.cmake.org/ |hopl=no |tags=cmake}} +[[Category:Utility]] -CMake is a cross-platform make system, for compiling [[C]], [[C++]] or [[Fortran]] programs. CMake uses a configuration file (CMakeLists.txt) to run configure tests, find libraries, create targets, and generate a build system for [[make|Unix make]] or another build tool. This configuration file runs commands in CMake's own scripting language. +CMake is a cross-platform make system, for compiling [[C]], [[C++]] or [[Fortran]] programs. +CMake uses a configuration file (CMakeLists.txt) to run configure tests, +find libraries, create targets, and generate a build system for +[[make|Unix make]] or another build tool.
+This configuration file runs commands in CMake's own scripting language. -For Rosetta Code, most examples work with ''CMake 2.6'' or later in ''process script mode'' (cmake -P myscript.cmake). Many examples use features from 2.6, especially function(). In cmake -P mode, CMake runs the script but never creates a project. So there are no configure tests and no targets. +For Rosetta Code, most examples work with ''CMake 2.6'' or later +in ''process script mode'' (cmake -P myscript.cmake). + +Many examples use features from 2.6, especially function(). + +In cmake -P mode, CMake runs the script but never creates a project. +So there are no configure tests and no targets. ==Simple project== This example builds a small C program after checking if #include provides clock_gettime() or gettimeofday(). @@ -73,7 +84,8 @@ main() return 0; } -If the three files CMakeLists.txt, config.h.in and simpletime.c are in .., then cmake .. configures the project. +If the three files CMakeLists.txt, config.h.in and simpletime.c are in .., +then cmake .. configures the project. $ cmake .. -- The C compiler identification is GNU diff --git a/Lang/COBOL/Create-a-file-on-magnetic-tape b/Lang/COBOL/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..0c6e415f67 --- /dev/null +++ b/Lang/COBOL/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/COBOL \ No newline at end of file diff --git a/Lang/COBOL/Range-expansion b/Lang/COBOL/Range-expansion new file mode 120000 index 0000000000..95ec12438e --- /dev/null +++ b/Lang/COBOL/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/COBOL \ No newline at end of file diff --git a/Lang/Chapel/Numerical-integration b/Lang/Chapel/Numerical-integration new file mode 120000 index 0000000000..37ce3b320d --- /dev/null +++ b/Lang/Chapel/Numerical-integration @@ -0,0 +1 @@ +../../Task/Numerical-integration/Chapel \ No newline at end of file diff --git a/Lang/Chef/00DESCRIPTION b/Lang/Chef/00DESCRIPTION index f4c7e4698d..c406e0df18 100644 --- a/Lang/Chef/00DESCRIPTION +++ b/Lang/Chef/00DESCRIPTION @@ -1,6 +1,13 @@ -{{stub}}{{language|Chef -|site=http://www.dangermouse.net/esoteric/chef.html}}[[Category:Esoteric Languages]] -'''Chef''' is an esoteric programming language designed by David Morgan-Mar. It is based on the manipulation of data values in a number of [[stack]]s (the same idea is used in assembly programming languages). The joke is that the variables tend to be named after basic foodstuffs, the stacks are called 'mixing bowls' and the instructions for manipulating them 'mix', 'stir', etc.. A program, then, reads much like a cooking recipe. +{{language|Chef +|site=http://www.dangermouse.net/esoteric/chef.html}} +[[Category:Esoteric Languages]] +'''Chef''' is an esoteric programming language designed by David Morgan-Mar. + +It is based on the manipulation of data values in a number of [[stack]]s (the same idea is used in assembly programming languages). + +The joke is that the variables tend to be named after basic foodstuffs, +the stacks are called 'mixing bowls' and the instructions for manipulating them 'mix', 'stir', etc..
+A program, then, reads much like a cooking recipe. ==External links== *[http://www.dangermouse.net/esoteric/ DM's Esoteric Programming Languages] diff --git a/Lang/Clojure/Break-OO-privacy b/Lang/Clojure/Break-OO-privacy new file mode 120000 index 0000000000..d2f846e60e --- /dev/null +++ b/Lang/Clojure/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Call-an-object-method b/Lang/Clojure/Call-an-object-method new file mode 120000 index 0000000000..92d23cf9d1 --- /dev/null +++ b/Lang/Clojure/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Classes b/Lang/Clojure/Classes new file mode 120000 index 0000000000..52bf582682 --- /dev/null +++ b/Lang/Clojure/Classes @@ -0,0 +1 @@ +../../Task/Classes/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Count-the-coins b/Lang/Clojure/Count-the-coins new file mode 120000 index 0000000000..c16c9591fe --- /dev/null +++ b/Lang/Clojure/Count-the-coins @@ -0,0 +1 @@ +../../Task/Count-the-coins/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Create-a-file-on-magnetic-tape b/Lang/Clojure/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..79c03f9e90 --- /dev/null +++ b/Lang/Clojure/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Create-an-HTML-table b/Lang/Clojure/Create-an-HTML-table new file mode 120000 index 0000000000..4a48d18e10 --- /dev/null +++ b/Lang/Clojure/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Define-a-primitive-data-type b/Lang/Clojure/Define-a-primitive-data-type new file mode 120000 index 0000000000..dc1f3c9890 --- /dev/null +++ b/Lang/Clojure/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Discordian-date b/Lang/Clojure/Discordian-date new file mode 120000 index 0000000000..359d306d70 --- /dev/null +++ b/Lang/Clojure/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Draw-a-cuboid b/Lang/Clojure/Draw-a-cuboid new file mode 120000 index 0000000000..7e0e095e65 --- /dev/null +++ b/Lang/Clojure/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Draw-a-sphere b/Lang/Clojure/Draw-a-sphere new file mode 120000 index 0000000000..f19b848b38 --- /dev/null +++ b/Lang/Clojure/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Extreme-floating-point-values b/Lang/Clojure/Extreme-floating-point-values new file mode 120000 index 0000000000..8cb6b61df7 --- /dev/null +++ b/Lang/Clojure/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Function-prototype b/Lang/Clojure/Function-prototype new file mode 120000 index 0000000000..29b67e3494 --- /dev/null +++ b/Lang/Clojure/Function-prototype @@ -0,0 +1 @@ +../../Task/Function-prototype/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Globally-replace-text-in-several-files b/Lang/Clojure/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..3690a8b2c2 --- /dev/null +++ b/Lang/Clojure/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Hello-world-Web-server b/Lang/Clojure/Hello-world-Web-server new file mode 120000 index 0000000000..e5e57c424c --- /dev/null +++ b/Lang/Clojure/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Clojure \ No newline at end of file diff --git a/Lang/Clojure/History-variables b/Lang/Clojure/History-variables new file mode 120000 index 0000000000..c6a6be5625 --- /dev/null +++ b/Lang/Clojure/History-variables @@ -0,0 +1 @@ +../../Task/History-variables/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Knapsack-problem-Continuous b/Lang/Clojure/Knapsack-problem-Continuous new file mode 120000 index 0000000000..7b5939a004 --- /dev/null +++ b/Lang/Clojure/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Last-Friday-of-each-month b/Lang/Clojure/Last-Friday-of-each-month new file mode 120000 index 0000000000..9e5415c4dd --- /dev/null +++ b/Lang/Clojure/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Clojure \ No newline at end of file diff --git a/Lang/Clojure/MD4 b/Lang/Clojure/MD4 new file mode 120000 index 0000000000..d90f714eae --- /dev/null +++ b/Lang/Clojure/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Plot-coordinate-pairs b/Lang/Clojure/Plot-coordinate-pairs new file mode 120000 index 0000000000..f32b3b4142 --- /dev/null +++ b/Lang/Clojure/Plot-coordinate-pairs @@ -0,0 +1 @@ +../../Task/Plot-coordinate-pairs/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Price-fraction b/Lang/Clojure/Price-fraction new file mode 120000 index 0000000000..e6daa7d5bc --- /dev/null +++ b/Lang/Clojure/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Priority-queue b/Lang/Clojure/Priority-queue new file mode 120000 index 0000000000..a24bcff04e --- /dev/null +++ b/Lang/Clojure/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Clojure \ No newline at end of file diff --git a/Lang/Clojure/RIPEMD-160 b/Lang/Clojure/RIPEMD-160 new file mode 120000 index 0000000000..e6cb1a383a --- /dev/null +++ b/Lang/Clojure/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Read-a-configuration-file b/Lang/Clojure/Read-a-configuration-file new file mode 120000 index 0000000000..68506c865a --- /dev/null +++ b/Lang/Clojure/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Read-a-specific-line-from-a-file b/Lang/Clojure/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..d991722ea1 --- /dev/null +++ b/Lang/Clojure/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Rock-paper-scissors b/Lang/Clojure/Rock-paper-scissors new file mode 120000 index 0000000000..d6253549c2 --- /dev/null +++ b/Lang/Clojure/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Clojure \ No newline at end of file diff --git a/Lang/Clojure/SEDOLs b/Lang/Clojure/SEDOLs new file mode 120000 index 0000000000..453f23f47e --- /dev/null +++ b/Lang/Clojure/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Clojure \ No newline at end of file diff --git a/Lang/Clojure/SHA-256 b/Lang/Clojure/SHA-256 new file mode 120000 index 0000000000..f90da404a9 --- /dev/null +++ b/Lang/Clojure/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Send-email b/Lang/Clojure/Send-email new file mode 120000 index 0000000000..8d02b035f2 --- /dev/null +++ b/Lang/Clojure/Send-email @@ -0,0 +1 @@ +../../Task/Send-email/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Set-of-real-numbers b/Lang/Clojure/Set-of-real-numbers new file mode 120000 index 0000000000..ab0afbffb7 --- /dev/null +++ b/Lang/Clojure/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Singly-linked-list-Element-definition b/Lang/Clojure/Singly-linked-list-Element-definition new file mode 120000 index 0000000000..0abac5cd66 --- /dev/null +++ b/Lang/Clojure/Singly-linked-list-Element-definition @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Element-definition/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sort-disjoint-sublist b/Lang/Clojure/Sort-disjoint-sublist new file mode 120000 index 0000000000..eae20ca93c --- /dev/null +++ b/Lang/Clojure/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sorting-algorithms-Sleep-sort b/Lang/Clojure/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..67f3ef7759 --- /dev/null +++ b/Lang/Clojure/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Special-variables b/Lang/Clojure/Special-variables new file mode 120000 index 0000000000..154928f7eb --- /dev/null +++ b/Lang/Clojure/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Speech-synthesis b/Lang/Clojure/Speech-synthesis new file mode 120000 index 0000000000..2b681c7f84 --- /dev/null +++ b/Lang/Clojure/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Stack-traces b/Lang/Clojure/Stack-traces new file mode 120000 index 0000000000..de4a9f8da2 --- /dev/null +++ b/Lang/Clojure/Stack-traces @@ -0,0 +1 @@ +../../Task/Stack-traces/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Clojure/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..c7b45f6769 --- /dev/null +++ b/Lang/Clojure/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Clojure/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..15035f4c83 --- /dev/null +++ b/Lang/Clojure/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Substring-Top-and-tail b/Lang/Clojure/Substring-Top-and-tail new file mode 120000 index 0000000000..f045cde4c0 --- /dev/null +++ b/Lang/Clojure/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Sum-digits-of-an-integer b/Lang/Clojure/Sum-digits-of-an-integer new file mode 120000 index 0000000000..69b147d372 --- /dev/null +++ b/Lang/Clojure/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Temperature-conversion b/Lang/Clojure/Temperature-conversion new file mode 120000 index 0000000000..a31ab1fb17 --- /dev/null +++ b/Lang/Clojure/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Terminal-control-Display-an-extended-character b/Lang/Clojure/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..e029131d04 --- /dev/null +++ b/Lang/Clojure/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Terminal-control-Ringing-the-terminal-bell b/Lang/Clojure/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..b27d10377d --- /dev/null +++ b/Lang/Clojure/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Terminal-control-Unicode-output b/Lang/Clojure/Terminal-control-Unicode-output new file mode 120000 index 0000000000..dd69daa37a --- /dev/null +++ b/Lang/Clojure/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Topic-variable b/Lang/Clojure/Topic-variable new file mode 120000 index 0000000000..7c14c8a6c8 --- /dev/null +++ b/Lang/Clojure/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Clojure \ No newline at end of file diff --git a/Lang/Clojure/URL-encoding b/Lang/Clojure/URL-encoding new file mode 120000 index 0000000000..59ef04db6d --- /dev/null +++ b/Lang/Clojure/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Unicode-variable-names b/Lang/Clojure/Unicode-variable-names new file mode 120000 index 0000000000..c5c4ec690f --- /dev/null +++ b/Lang/Clojure/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Write-language-name-in-3D-ASCII b/Lang/Clojure/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..432e111b9a --- /dev/null +++ b/Lang/Clojure/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Clojure \ No newline at end of file diff --git a/Lang/Clojure/Write-to-Windows-event-log b/Lang/Clojure/Write-to-Windows-event-log new file mode 120000 index 0000000000..e3c063b958 --- /dev/null +++ b/Lang/Clojure/Write-to-Windows-event-log @@ -0,0 +1 @@ +../../Task/Write-to-Windows-event-log/Clojure \ No newline at end of file diff --git a/Lang/Clojure/XML-DOM-serialization b/Lang/Clojure/XML-DOM-serialization new file mode 120000 index 0000000000..41e848b73f --- /dev/null +++ b/Lang/Clojure/XML-DOM-serialization @@ -0,0 +1 @@ +../../Task/XML-DOM-serialization/Clojure \ No newline at end of file diff --git a/Lang/CoffeeScript/Filter b/Lang/CoffeeScript/Filter new file mode 120000 index 0000000000..5431857beb --- /dev/null +++ b/Lang/CoffeeScript/Filter @@ -0,0 +1 @@ +../../Task/Filter/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Haversine-formula b/Lang/CoffeeScript/Haversine-formula new file mode 120000 index 0000000000..8ed82f732d --- /dev/null +++ b/Lang/CoffeeScript/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Interactive-programming b/Lang/CoffeeScript/Interactive-programming new file mode 120000 index 0000000000..468d30baf4 --- /dev/null +++ b/Lang/CoffeeScript/Interactive-programming @@ -0,0 +1 @@ +../../Task/Interactive-programming/CoffeeScript \ No newline at end of file diff --git a/Lang/CoffeeScript/Sum-and-product-of-an-array b/Lang/CoffeeScript/Sum-and-product-of-an-array new file mode 120000 index 0000000000..e952962782 --- /dev/null +++ b/Lang/CoffeeScript/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/CoffeeScript \ No newline at end of file diff --git a/Lang/ColdFusion/Active-Directory-Connect b/Lang/ColdFusion/Active-Directory-Connect new file mode 120000 index 0000000000..80633e2f28 --- /dev/null +++ b/Lang/ColdFusion/Active-Directory-Connect @@ -0,0 +1 @@ +../../Task/Active-Directory-Connect/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Even-or-odd b/Lang/ColdFusion/Even-or-odd new file mode 120000 index 0000000000..036a0beeaa --- /dev/null +++ b/Lang/ColdFusion/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Evolutionary-algorithm b/Lang/ColdFusion/Evolutionary-algorithm new file mode 120000 index 0000000000..829ebbb64f --- /dev/null +++ b/Lang/ColdFusion/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/FizzBuzz b/Lang/ColdFusion/FizzBuzz new file mode 120000 index 0000000000..a43b796fb2 --- /dev/null +++ b/Lang/ColdFusion/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Greatest-element-of-a-list b/Lang/ColdFusion/Greatest-element-of-a-list new file mode 120000 index 0000000000..51905503fd --- /dev/null +++ b/Lang/ColdFusion/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Harshad-or-Niven-series b/Lang/ColdFusion/Harshad-or-Niven-series new file mode 120000 index 0000000000..9b1cc1adb8 --- /dev/null +++ b/Lang/ColdFusion/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Loops-Break b/Lang/ColdFusion/Loops-Break new file mode 120000 index 0000000000..6e70fc3ae0 --- /dev/null +++ b/Lang/ColdFusion/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Loops-For-with-a-specified-step b/Lang/ColdFusion/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..0295f5bf9f --- /dev/null +++ b/Lang/ColdFusion/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Loops-Foreach b/Lang/ColdFusion/Loops-Foreach new file mode 120000 index 0000000000..9ff00685e4 --- /dev/null +++ b/Lang/ColdFusion/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Loops-Nested b/Lang/ColdFusion/Loops-Nested new file mode 120000 index 0000000000..dde55a13de --- /dev/null +++ b/Lang/ColdFusion/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Repeat-a-string b/Lang/ColdFusion/Repeat-a-string new file mode 120000 index 0000000000..902cfc04aa --- /dev/null +++ b/Lang/ColdFusion/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Stable-marriage-problem b/Lang/ColdFusion/Stable-marriage-problem new file mode 120000 index 0000000000..315db532a6 --- /dev/null +++ b/Lang/ColdFusion/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/ColdFusion \ No newline at end of file diff --git a/Lang/ColdFusion/Strip-a-set-of-characters-from-a-string b/Lang/ColdFusion/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..c6f22dd9db --- /dev/null +++ b/Lang/ColdFusion/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/ColdFusion \ No newline at end of file diff --git a/Lang/Common-Lisp/Animate-a-pendulum b/Lang/Common-Lisp/Animate-a-pendulum new file mode 120000 index 0000000000..f7c0ea9dd4 --- /dev/null +++ b/Lang/Common-Lisp/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Bulls-and-cows-Player b/Lang/Common-Lisp/Bulls-and-cows-Player new file mode 120000 index 0000000000..3224441481 --- /dev/null +++ b/Lang/Common-Lisp/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Fibonacci-n-step-number-sequences b/Lang/Common-Lisp/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..ba5f9ce26b --- /dev/null +++ b/Lang/Common-Lisp/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Harshad-or-Niven-series b/Lang/Common-Lisp/Harshad-or-Niven-series new file mode 120000 index 0000000000..2e782db8a7 --- /dev/null +++ b/Lang/Common-Lisp/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Last-Friday-of-each-month b/Lang/Common-Lisp/Last-Friday-of-each-month new file mode 120000 index 0000000000..b2781be3c4 --- /dev/null +++ b/Lang/Common-Lisp/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Modular-inverse b/Lang/Common-Lisp/Modular-inverse new file mode 120000 index 0000000000..a8c5f6d7fe --- /dev/null +++ b/Lang/Common-Lisp/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/OpenGL b/Lang/Common-Lisp/OpenGL new file mode 120000 index 0000000000..ca3fde31a3 --- /dev/null +++ b/Lang/Common-Lisp/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Sorting-algorithms-Sleep-sort b/Lang/Common-Lisp/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..d203c8fc22 --- /dev/null +++ b/Lang/Common-Lisp/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Special-variables b/Lang/Common-Lisp/Special-variables new file mode 120000 index 0000000000..ae535c2f46 --- /dev/null +++ b/Lang/Common-Lisp/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/String-comparison b/Lang/Common-Lisp/String-comparison new file mode 120000 index 0000000000..7cc5ff9107 --- /dev/null +++ b/Lang/Common-Lisp/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Temperature-conversion b/Lang/Common-Lisp/Temperature-conversion new file mode 120000 index 0000000000..637c67539a --- /dev/null +++ b/Lang/Common-Lisp/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Tic-tac-toe b/Lang/Common-Lisp/Tic-tac-toe new file mode 120000 index 0000000000..de662c0731 --- /dev/null +++ b/Lang/Common-Lisp/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Trabb-Pardo-Knuth-algorithm b/Lang/Common-Lisp/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..f6412dcdd0 --- /dev/null +++ b/Lang/Common-Lisp/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Truncatable-primes b/Lang/Common-Lisp/Truncatable-primes new file mode 120000 index 0000000000..5d9f45c9b4 --- /dev/null +++ b/Lang/Common-Lisp/Truncatable-primes @@ -0,0 +1 @@ +../../Task/Truncatable-primes/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Twelve-statements b/Lang/Common-Lisp/Twelve-statements new file mode 120000 index 0000000000..66cbf6679c --- /dev/null +++ b/Lang/Common-Lisp/Twelve-statements @@ -0,0 +1 @@ +../../Task/Twelve-statements/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Universal-Turing-machine b/Lang/Common-Lisp/Universal-Turing-machine new file mode 120000 index 0000000000..259f32a187 --- /dev/null +++ b/Lang/Common-Lisp/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Common-Lisp \ No newline at end of file diff --git a/Lang/Common-Lisp/Variables b/Lang/Common-Lisp/Variables new file mode 120000 index 0000000000..47d57bcef9 --- /dev/null +++ b/Lang/Common-Lisp/Variables @@ -0,0 +1 @@ +../../Task/Variables/Common-Lisp \ No newline at end of file diff --git a/Lang/Component-Pascal/Greatest-subsequential-sum b/Lang/Component-Pascal/Greatest-subsequential-sum new file mode 120000 index 0000000000..7358215d71 --- /dev/null +++ b/Lang/Component-Pascal/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Component-Pascal \ No newline at end of file diff --git a/Lang/Curry/Pascals-triangle-Puzzle b/Lang/Curry/Pascals-triangle-Puzzle new file mode 120000 index 0000000000..55b76b5232 --- /dev/null +++ b/Lang/Curry/Pascals-triangle-Puzzle @@ -0,0 +1 @@ +../../Task/Pascals-triangle-Puzzle/Curry \ No newline at end of file diff --git a/Lang/Curry/Solve-a-Hidato-puzzle b/Lang/Curry/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..7ff54d9f13 --- /dev/null +++ b/Lang/Curry/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Curry \ No newline at end of file diff --git a/Lang/Curry/Zebra-puzzle b/Lang/Curry/Zebra-puzzle new file mode 120000 index 0000000000..6b9ff19eea --- /dev/null +++ b/Lang/Curry/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Curry \ No newline at end of file diff --git a/Lang/D/Averages-Mean-time-of-day b/Lang/D/Averages-Mean-time-of-day new file mode 120000 index 0000000000..ac534c6c3a --- /dev/null +++ b/Lang/D/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/D \ No newline at end of file diff --git a/Lang/D/Call-a-function b/Lang/D/Call-a-function new file mode 120000 index 0000000000..1928532b6a --- /dev/null +++ b/Lang/D/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/D \ No newline at end of file diff --git a/Lang/D/MD4 b/Lang/D/MD4 new file mode 120000 index 0000000000..3f7c6f7ec9 --- /dev/null +++ b/Lang/D/MD4 @@ -0,0 +1 @@ +../../Task/MD4/D \ No newline at end of file diff --git a/Lang/D/Program-termination b/Lang/D/Program-termination new file mode 120000 index 0000000000..59901a1ce8 --- /dev/null +++ b/Lang/D/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/D \ No newline at end of file diff --git a/Lang/DCL/00DESCRIPTION b/Lang/DCL/00DESCRIPTION index 1a188356c3..ed4ecdefbe 100644 --- a/Lang/DCL/00DESCRIPTION +++ b/Lang/DCL/00DESCRIPTION @@ -1,3 +1,4 @@ +{{language}} 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/Dart/Sorting-algorithms-Sleep-sort b/Lang/Dart/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..85034eba6b --- /dev/null +++ b/Lang/Dart/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Dart \ No newline at end of file diff --git a/Lang/Dc/00DESCRIPTION b/Lang/Dc/00DESCRIPTION index c5626dd439..98c71ead61 100644 --- a/Lang/Dc/00DESCRIPTION +++ b/Lang/Dc/00DESCRIPTION @@ -4,7 +4,14 @@ |hopl id=1957 }} {{language programming paradigm|concatenative}} -dc is the unix desktop calculator. It uses a reverse polish notation and is turing complete. +[[Category:Utility]] + +[[wp:dc (computer program)|dc]] is the unix '''d'''esktop '''c'''alculator.
+It uses a reverse polish notation and is turing complete. + +;See also +* [[:Category:Bc|bc]] - '''b'''asic '''c'''alculator + == Quick reference == Commands in [[AT&T dc]] diff --git a/Lang/Delphi/Bitmap-Bresenhams-line-algorithm b/Lang/Delphi/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..16c95c0400 --- /dev/null +++ b/Lang/Delphi/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Delphi \ No newline at end of file diff --git a/Lang/Delphi/SEDOLs b/Lang/Delphi/SEDOLs new file mode 120000 index 0000000000..58097ee50e --- /dev/null +++ b/Lang/Delphi/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Sieve-of-Eratosthenes b/Lang/Delphi/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..5df8b987b7 --- /dev/null +++ b/Lang/Delphi/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Delphi \ No newline at end of file diff --git a/Lang/Delphi/String-interpolation--included- b/Lang/Delphi/String-interpolation--included- new file mode 120000 index 0000000000..77a12ff19f --- /dev/null +++ b/Lang/Delphi/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Take-notes-on-the-command-line b/Lang/Delphi/Take-notes-on-the-command-line new file mode 120000 index 0000000000..7261d9cca0 --- /dev/null +++ b/Lang/Delphi/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Temperature-conversion b/Lang/Delphi/Temperature-conversion new file mode 120000 index 0000000000..ffcbb79015 --- /dev/null +++ b/Lang/Delphi/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Delphi \ No newline at end of file diff --git a/Lang/Delphi/Truncate-a-file b/Lang/Delphi/Truncate-a-file new file mode 120000 index 0000000000..f62b05a53c --- /dev/null +++ b/Lang/Delphi/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Delphi \ No newline at end of file diff --git a/Lang/Dylan/Man-or-boy-test b/Lang/Dylan/Man-or-boy-test new file mode 120000 index 0000000000..7988afa5d5 --- /dev/null +++ b/Lang/Dylan/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Dylan \ No newline at end of file diff --git a/Lang/Eiffel/Binary-search b/Lang/Eiffel/Binary-search new file mode 120000 index 0000000000..9b9d6d3fbd --- /dev/null +++ b/Lang/Eiffel/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Caesar-cipher b/Lang/Eiffel/Caesar-cipher new file mode 120000 index 0000000000..349fb98237 --- /dev/null +++ b/Lang/Eiffel/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Catalan-numbers b/Lang/Eiffel/Catalan-numbers new file mode 120000 index 0000000000..94e73b8c83 --- /dev/null +++ b/Lang/Eiffel/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Character-codes b/Lang/Eiffel/Character-codes new file mode 120000 index 0000000000..ecede9611c --- /dev/null +++ b/Lang/Eiffel/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Combinations b/Lang/Eiffel/Combinations new file mode 120000 index 0000000000..8fb464ee8f --- /dev/null +++ b/Lang/Eiffel/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Count-in-factors b/Lang/Eiffel/Count-in-factors new file mode 120000 index 0000000000..ac41099736 --- /dev/null +++ b/Lang/Eiffel/Count-in-factors @@ -0,0 +1 @@ +../../Task/Count-in-factors/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Digital-root b/Lang/Eiffel/Digital-root new file mode 120000 index 0000000000..f552e091a7 --- /dev/null +++ b/Lang/Eiffel/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Dot-product b/Lang/Eiffel/Dot-product new file mode 120000 index 0000000000..bd61915df5 --- /dev/null +++ b/Lang/Eiffel/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Ethiopian-multiplication b/Lang/Eiffel/Ethiopian-multiplication new file mode 120000 index 0000000000..fd981e5446 --- /dev/null +++ b/Lang/Eiffel/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Extreme-floating-point-values b/Lang/Eiffel/Extreme-floating-point-values new file mode 120000 index 0000000000..d9141d7592 --- /dev/null +++ b/Lang/Eiffel/Extreme-floating-point-values @@ -0,0 +1 @@ +../../Task/Extreme-floating-point-values/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/FizzBuzz b/Lang/Eiffel/FizzBuzz new file mode 120000 index 0000000000..ee47379636 --- /dev/null +++ b/Lang/Eiffel/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Function-definition b/Lang/Eiffel/Function-definition new file mode 120000 index 0000000000..a0d2b70346 --- /dev/null +++ b/Lang/Eiffel/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Guess-the-number b/Lang/Eiffel/Guess-the-number new file mode 120000 index 0000000000..e6df1779e8 --- /dev/null +++ b/Lang/Eiffel/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Happy-numbers b/Lang/Eiffel/Happy-numbers new file mode 120000 index 0000000000..6f2e4613d4 --- /dev/null +++ b/Lang/Eiffel/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Harshad-or-Niven-series b/Lang/Eiffel/Harshad-or-Niven-series new file mode 120000 index 0000000000..59771df796 --- /dev/null +++ b/Lang/Eiffel/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Hofstadter-Q-sequence b/Lang/Eiffel/Hofstadter-Q-sequence new file mode 120000 index 0000000000..652a4c37aa --- /dev/null +++ b/Lang/Eiffel/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Huffman-coding b/Lang/Eiffel/Huffman-coding new file mode 120000 index 0000000000..939e7429d9 --- /dev/null +++ b/Lang/Eiffel/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Identity-matrix b/Lang/Eiffel/Identity-matrix new file mode 120000 index 0000000000..ede9d5ccb3 --- /dev/null +++ b/Lang/Eiffel/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Increment-a-numerical-string b/Lang/Eiffel/Increment-a-numerical-string new file mode 120000 index 0000000000..7f23c89575 --- /dev/null +++ b/Lang/Eiffel/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Knuth-shuffle b/Lang/Eiffel/Knuth-shuffle new file mode 120000 index 0000000000..150a888241 --- /dev/null +++ b/Lang/Eiffel/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Letter-frequency b/Lang/Eiffel/Letter-frequency new file mode 120000 index 0000000000..fded3dfa65 --- /dev/null +++ b/Lang/Eiffel/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Literals-Floating-point b/Lang/Eiffel/Literals-Floating-point new file mode 120000 index 0000000000..28f0bd6891 --- /dev/null +++ b/Lang/Eiffel/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Literals-Integer b/Lang/Eiffel/Literals-Integer new file mode 120000 index 0000000000..bcd34b9760 --- /dev/null +++ b/Lang/Eiffel/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/N-queens-problem b/Lang/Eiffel/N-queens-problem new file mode 120000 index 0000000000..8a293c87ae --- /dev/null +++ b/Lang/Eiffel/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Null-object b/Lang/Eiffel/Null-object new file mode 120000 index 0000000000..8ff31605b0 --- /dev/null +++ b/Lang/Eiffel/Null-object @@ -0,0 +1 @@ +../../Task/Null-object/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Number-reversal-game b/Lang/Eiffel/Number-reversal-game new file mode 120000 index 0000000000..97bf3af8e3 --- /dev/null +++ b/Lang/Eiffel/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Palindrome-detection b/Lang/Eiffel/Palindrome-detection new file mode 120000 index 0000000000..bb0b891cee --- /dev/null +++ b/Lang/Eiffel/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Perfect-numbers b/Lang/Eiffel/Perfect-numbers new file mode 120000 index 0000000000..5c027ea299 --- /dev/null +++ b/Lang/Eiffel/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Permutations b/Lang/Eiffel/Permutations new file mode 120000 index 0000000000..439f9a2e74 --- /dev/null +++ b/Lang/Eiffel/Permutations @@ -0,0 +1 @@ +../../Task/Permutations/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Pig-the-dice-game b/Lang/Eiffel/Pig-the-dice-game new file mode 120000 index 0000000000..5cbfc06117 --- /dev/null +++ b/Lang/Eiffel/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Prime-decomposition b/Lang/Eiffel/Prime-decomposition new file mode 120000 index 0000000000..1fbcf23377 --- /dev/null +++ b/Lang/Eiffel/Prime-decomposition @@ -0,0 +1 @@ +../../Task/Prime-decomposition/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Pythagorean-triples b/Lang/Eiffel/Pythagorean-triples new file mode 120000 index 0000000000..3ee8945227 --- /dev/null +++ b/Lang/Eiffel/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Range-extraction b/Lang/Eiffel/Range-extraction new file mode 120000 index 0000000000..4d599339ae --- /dev/null +++ b/Lang/Eiffel/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Repeat-a-string b/Lang/Eiffel/Repeat-a-string new file mode 120000 index 0000000000..c57f1b9ba1 --- /dev/null +++ b/Lang/Eiffel/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Return-multiple-values b/Lang/Eiffel/Return-multiple-values new file mode 120000 index 0000000000..2b433983b9 --- /dev/null +++ b/Lang/Eiffel/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Roman-numerals-Decode b/Lang/Eiffel/Roman-numerals-Decode new file mode 120000 index 0000000000..2f550f0836 --- /dev/null +++ b/Lang/Eiffel/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Roman-numerals-Encode b/Lang/Eiffel/Roman-numerals-Encode new file mode 120000 index 0000000000..8379f5af78 --- /dev/null +++ b/Lang/Eiffel/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Scope-Function-names-and-labels b/Lang/Eiffel/Scope-Function-names-and-labels new file mode 120000 index 0000000000..deb9497c11 --- /dev/null +++ b/Lang/Eiffel/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Scope-modifiers b/Lang/Eiffel/Scope-modifiers new file mode 120000 index 0000000000..89a39cc662 --- /dev/null +++ b/Lang/Eiffel/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Semordnilap b/Lang/Eiffel/Semordnilap new file mode 120000 index 0000000000..a89f27b4cf --- /dev/null +++ b/Lang/Eiffel/Semordnilap @@ -0,0 +1 @@ +../../Task/Semordnilap/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sequence-of-non-squares b/Lang/Eiffel/Sequence-of-non-squares new file mode 120000 index 0000000000..6a46093d32 --- /dev/null +++ b/Lang/Eiffel/Sequence-of-non-squares @@ -0,0 +1 @@ +../../Task/Sequence-of-non-squares/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Bead-sort b/Lang/Eiffel/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..d7bd033e88 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Bogosort b/Lang/Eiffel/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..0c6ea1f9aa --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Cocktail-sort b/Lang/Eiffel/Sorting-algorithms-Cocktail-sort new file mode 120000 index 0000000000..0d2177fcc2 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Cocktail-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Cocktail-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Comb-sort b/Lang/Eiffel/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..408b0edb4a --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Counting-sort b/Lang/Eiffel/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..ba6c72ee75 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Gnome-sort b/Lang/Eiffel/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..080f6161cd --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Merge-sort b/Lang/Eiffel/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..8e82461186 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Pancake-sort b/Lang/Eiffel/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..3ce1b36377 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Selection-sort b/Lang/Eiffel/Sorting-algorithms-Selection-sort new file mode 120000 index 0000000000..f600cf5fda --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Selection-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Selection-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sorting-algorithms-Stooge-sort b/Lang/Eiffel/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..f24ef7f619 --- /dev/null +++ b/Lang/Eiffel/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Sum-and-product-of-an-array b/Lang/Eiffel/Sum-and-product-of-an-array new file mode 120000 index 0000000000..c6ea7c318d --- /dev/null +++ b/Lang/Eiffel/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Topswops b/Lang/Eiffel/Topswops new file mode 120000 index 0000000000..042a2a9838 --- /dev/null +++ b/Lang/Eiffel/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Towers-of-Hanoi b/Lang/Eiffel/Towers-of-Hanoi new file mode 120000 index 0000000000..31f690d43e --- /dev/null +++ b/Lang/Eiffel/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/Eiffel \ No newline at end of file diff --git a/Lang/Eiffel/Variables b/Lang/Eiffel/Variables new file mode 120000 index 0000000000..9e9143d01a --- /dev/null +++ b/Lang/Eiffel/Variables @@ -0,0 +1 @@ +../../Task/Variables/Eiffel \ No newline at end of file diff --git a/Lang/Elena/00DESCRIPTION b/Lang/Elena/00DESCRIPTION index a1372a9eac..42d4540b35 100644 --- a/Lang/Elena/00DESCRIPTION +++ b/Lang/Elena/00DESCRIPTION @@ -19,22 +19,224 @@ Every object may be formed up with other objects characterizing its internal sta All referring entities in the language are objects. A variable is a reference to the object allocated in the program heap. The literal and numeric constants are references to the objects allocated in the static memory. -== Object model == +== Namespaces == -Any object is an instance of one or another class. The classes form the hierarchy tree on the principle of inheritance. There is the common super class - Object. The class parent may be explicitly declared. When the parent is not specified, the class inherits Object. +Any ELENA program or library consists of modules (files with .NL extension) containing +classes and symbols. Every class or symbol may be referred by its namespace +(or to put it other way around a symbol namespace is a path to the symbol module). -A class is an abstract concept which means that no operations can be done with it except a declaration. So to create the object its symbol should be referenced. There are explicit and implicit, static and dynamic symbols. +All source files (files with .L extension) located in the same folder are compiled into +the corresponding module. A project file (a file with .PRJ extension) defines the root +namespace and the output type (stand-alone executable, VM executable or a library). +The project may produce several modules if it contains the files located in sub folders +(the new module namespace consists of the root one plus the folder relative path) -When a new class is declared simultaneously the appropriate explicit symbol is declared as well. The implicit symbol should be declared implicitly. In general the explicit symbol is the object in the initial state and the explicit one is the object in the particular state. +== Messaging == -A static symbol is the class instance which state is preserved. A static symbol is always implicit one. There could be only one instance of static symbol. +As in the most of dynamic object-oriented languages the main way to interact with objects in ELENA is sending a message. Unlike others the message name is structured and consists of a verb, a signature and a parameter counter. The verb defines a message action, for example read or write some data. There are only limited set of possible verbs (e.g. eval[uate], add, set, get, run, seek and so on). In general the signature is user defined and describes the message parameters. It can be used to define some custom +action as well (e.g. writeLine, which in fact is eval&writeLine(1)). If the signature is not provided the message is considered to be generic and can be qualified (for example by dispatching). -The class declaration can be named or unnamed (inline declaration) public or private (when the class name is a private name). Its body contains member declarations: fields, roles and methods. +If the object wants to handle the message it has to contain the method with the same name. If no method mapping was found the flow is considered to be broken and the control goes to the next alternative flow (exception handler) or the program is stopped. -The fields can be accessed only within the class and its descendants. They can be a normal ones (references to another objects) or meta ones (raw data). +The simple code to send a message looks like this: -The roles are alternative sets of methods which could be used to implement context-dependant object behavior. When it is applied the role overrides the appropriate object methods with its own ones (static mutation). + console write:"Hello World". -Methods maybe private or public depending on their name (public or private). All class methods are considered to be polymorphic. It is possible to dispatch the method call depending on its parameter (declarative multi-dispatching). The method has only one input (or nil) and output (or it should return itself) parameters. If the method requires several parameters a special proxy argument list object can be used. +Note: "write" is a generic message; a literal constant is a parameter. -It is possible to declare a special "Any" handler. It is a method which redirects any unhandled message (i.e. messages which are not mapped in the class or its base classes) to the specified target. The target could be a single object (actually mutation) or collection (group object). A group object is a collection of the objects accessible through the common instance reference. The content of the group can be changed dynamically during the object life time (self-modification). The member objects can be a part of different groups or be single. The group can be persistent or temporally created to solve the particular task. The group objects are treated like "normal" ones and no special routines are required to work with them. If two or more members have duplicate methods either the first message mapping is resolved (exclusive mode) or all duplicate methods are executed (broadcast mode) depending on the group type. \ No newline at end of file +Several messages can be send in one statement, the parameter itself may be result of object interactions: + + console write "2 + 2 =" write:(2 add:2). + +We could use operators to have the shorter code: + + console << "2+2=" << 2 + 2. + +Note: In most cases "<<" is a synonym to "write" and "+" to "add". + +Several parameters can be passed in the message as well: + + control foreach: (1,2,3) &do:printingLn. + +Ampersand is used to indicate that the signature has several arguments (subjects). The actual message name is eval&foreach&do(2). + +The generic message can have several parameters as well: + + consoleEx writeLine:”a+b=”: (a + b). + + +== Classes, Roles and Symbols == + +ELENA is an object-oriented language, so to create a program we have to declare new classes. + +A class encapsulates data (fields) with code (methods) to access it. In most cases it is not possible to get a direct access to the class content (it makes sense for dynamic languages when in the most cases code is generic and can be applied for different "types"). Usually the fields refer to another classes and so on until we reach "primitive" ones which content are considered as raw data (e.g. numeric or literal values). + +To work with the class we have to create its instance with the help of the special methods - constructors. A constructor is used mostly to initialize the class fields. There are special type of classes which do not have fields and constructors and can be used directly (roles). + +Classes form the inheritance tree. There is the common super class - system'Object. +ELENA does not support multiple inheritance, though it is possible to inherit the code using redirect handler (so called "horizontal inheritance"). When the parent is not provided the class inherits directly system'Object (the super class). + + #class BaseClass + { + #field theField1. + #field theField2. + + #method field1 = theField1. + + #method field2 = theField. + + } + + #class DerivedClass : BaseClass + { + #constructor new &field1:aField2 &field2:aField2 + [ + theField1 := aField1. + theField2 := aField2. + ] + + #method add &field1:aField2 &field2:aField2 + = MyClass new &Field1:(theField1 + aField1) &Field2:(theField2 + aField2). + } + +To create a class instance we have to send a message (usually new) to its symbol (a class symbol is declared implicitly for every class and can be used as a normal one) + + #var anObject := DerivedClass new &field1:1 &field2:1. // DerivedClass is a symbol + +Roles cannot have constructors and their symbols can be used directly + + #class(role)ClassHelper + { + #method sumOf:anObject1:anObject2 + = anObject1 add &field1::anObject2 &field2::anObject1. + } + + ... + + #var aSum := ClassHelper sumOf:anObject1:anObject2. + +In general the symbol is a named expression and can be used to declare initialized objects, constants, reusable expressions and so on. + + #symbol ZeroClass = DerivedClass new &field:0 &field:0. + +A static symbol is the class instance which state is preserved. There could be only one instance of static symbol. + + #static SingletonClass = DerivedClass new &field:0 &field:0. + +== Code blocks == + +ELENA code block consists of a sequence of statements. The block is enclosed in square brackets and may contain nested sub code blocks (which in fact are inline action classes). The statement terminator is a dot. + + #method printAckermann &n:n &m:m + [ + control forrange &int:0 &int:n &do: (&int:i) + [ + control forrange &int:0 &int:m &do: (&int:j) + [ + ... + + console writeLine. + ]. + ]. + ] + +When a method should return a result (other than self) return statement is used. It should be the last statement in the block. + + [ + ... + + ^ aRetVal / anArray length. + ] + +If the code block contains only return statement the simplified syntax can be used: + + #method Number = convertor toReal:theValue. + +or there is an alternative block expression + + [ convertor toReal:theValue ] + +Note: it should not end with the terminator symbol + +It is possible to declare the block variable and assigns the value to it. The variable name must be unique within the code block scope. + + #var aRetVal := Integer new:0. + + +== Conditional branching == + +ELENA like Smalltalk does not support any special language constructs to implement the conditional branching. Instead special Boolean symbols (system’true and system’false) are used. All conditional operations should return these symbols as a result. + +There are three branching methods : then[1] , then&else[2], else[1] + + (m == 0) then: + [ + n + 1 + ] + &else: [ + m + n + ]. + +Note that code in square brackets are in fact nested action classes ( an action class is a class supporting evaluate message). So this code is can be written in this form: + + (m == 0) then: + { + eval + [ + ^ n + 1. + ] + } + &else: + { + eval + [ + ^ m + n. + ] + }. + +This expression can be written using special operators + + (m == 0) + ? [ n + 1 ] + ! [ m + n ]. + +Note: the main difference between using explicit messages and conditional operators is that the compiler may optimize the resulting code in the later case. + +We could omit true or else part + + (m == 0) + ! [ m / n ]. + +Boolean symbols supports basic logical operations (AND, OR, XOR and NOT), so several conditions can be checked + + (aChar >= 48) and:(aChar < 58) + ? [ + theToken += aChar. + ] + ! [ + #throw Exception new:"Invalid expression". + ] + +Note that in this case both condition will be evaluated even if the first one is false If we want to use short-circuit evaluation expression brackets should be used + (x >= 0)and:[ array@x != 0] ? + [ + ... + ] + +A switch statement can be implemented using => operator + + ^ aBulls => + -1 ? [ consoleEx writeLine:"Not a valid guess.". ^ true. ] + 4 ? [ + consoleEx writeLine:"Congratulations! You have won!". + ^ false. + ] + ! [ + theAttempt += 1. + + consoleEx writeLine: + "Your Score is " : aBulls + : " bulls and " : aCows : " cows". + + ^ true. + ]. \ No newline at end of file diff --git a/Lang/Elixir/00DESCRIPTION b/Lang/Elixir/00DESCRIPTION index dea53dfdd5..391ae5b1b2 100644 --- a/Lang/Elixir/00DESCRIPTION +++ b/Lang/Elixir/00DESCRIPTION @@ -1,3 +1,4 @@ {{stub}} {{language -|site=http://elixir-lang.org}} \ No newline at end of file +|site=http://elixir-lang.org}} +{{implementation|Erlang}} \ No newline at end of file diff --git a/Lang/Elixir/Ackermann-function b/Lang/Elixir/Ackermann-function new file mode 120000 index 0000000000..ec51939c52 --- /dev/null +++ b/Lang/Elixir/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Averages-Arithmetic-mean b/Lang/Elixir/Averages-Arithmetic-mean new file mode 120000 index 0000000000..c87d0aa2ba --- /dev/null +++ b/Lang/Elixir/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Averages-Median b/Lang/Elixir/Averages-Median new file mode 120000 index 0000000000..74ec59313e --- /dev/null +++ b/Lang/Elixir/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Averages-Pythagorean-means b/Lang/Elixir/Averages-Pythagorean-means new file mode 120000 index 0000000000..f84de9fd57 --- /dev/null +++ b/Lang/Elixir/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Averages-Root-mean-square b/Lang/Elixir/Averages-Root-mean-square new file mode 120000 index 0000000000..d7f96b48b9 --- /dev/null +++ b/Lang/Elixir/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Case-sensitivity-of-identifiers b/Lang/Elixir/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..8445df8188 --- /dev/null +++ b/Lang/Elixir/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Comments b/Lang/Elixir/Comments new file mode 120000 index 0000000000..513195f986 --- /dev/null +++ b/Lang/Elixir/Comments @@ -0,0 +1 @@ +../../Task/Comments/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Constrained-random-points-on-a-circle b/Lang/Elixir/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..61b3fc11df --- /dev/null +++ b/Lang/Elixir/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Empty-string b/Lang/Elixir/Empty-string new file mode 120000 index 0000000000..8c4f0316a9 --- /dev/null +++ b/Lang/Elixir/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Factorial b/Lang/Elixir/Factorial new file mode 120000 index 0000000000..7d268c6114 --- /dev/null +++ b/Lang/Elixir/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Flatten-a-list b/Lang/Elixir/Flatten-a-list new file mode 120000 index 0000000000..39e1ed6935 --- /dev/null +++ b/Lang/Elixir/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Guess-the-number b/Lang/Elixir/Guess-the-number new file mode 120000 index 0000000000..ff7958f21a --- /dev/null +++ b/Lang/Elixir/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Guess-the-number-With-feedback b/Lang/Elixir/Guess-the-number-With-feedback new file mode 120000 index 0000000000..0b3587b688 --- /dev/null +++ b/Lang/Elixir/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hello-world-Newline-omission b/Lang/Elixir/Hello-world-Newline-omission new file mode 120000 index 0000000000..028d0f6412 --- /dev/null +++ b/Lang/Elixir/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Hello-world-Text b/Lang/Elixir/Hello-world-Text new file mode 120000 index 0000000000..8fe23656e3 --- /dev/null +++ b/Lang/Elixir/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Mutual-recursion b/Lang/Elixir/Mutual-recursion new file mode 120000 index 0000000000..f7407be599 --- /dev/null +++ b/Lang/Elixir/Mutual-recursion @@ -0,0 +1 @@ +../../Task/Mutual-recursion/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Palindrome-detection b/Lang/Elixir/Palindrome-detection new file mode 120000 index 0000000000..ebe440f641 --- /dev/null +++ b/Lang/Elixir/Palindrome-detection @@ -0,0 +1 @@ +../../Task/Palindrome-detection/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Perfect-numbers b/Lang/Elixir/Perfect-numbers new file mode 120000 index 0000000000..2821d42a1e --- /dev/null +++ b/Lang/Elixir/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Pick-random-element b/Lang/Elixir/Pick-random-element new file mode 120000 index 0000000000..d1b83c9764 --- /dev/null +++ b/Lang/Elixir/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Random-number-generator--included- b/Lang/Elixir/Random-number-generator--included- new file mode 120000 index 0000000000..ad03dec088 --- /dev/null +++ b/Lang/Elixir/Random-number-generator--included- @@ -0,0 +1 @@ +../../Task/Random-number-generator--included-/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Random-numbers b/Lang/Elixir/Random-numbers new file mode 120000 index 0000000000..e8bdfccda1 --- /dev/null +++ b/Lang/Elixir/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Repeat-a-string b/Lang/Elixir/Repeat-a-string new file mode 120000 index 0000000000..264376e4bb --- /dev/null +++ b/Lang/Elixir/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Reverse-a-string b/Lang/Elixir/Reverse-a-string new file mode 120000 index 0000000000..6cc017734b --- /dev/null +++ b/Lang/Elixir/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-case b/Lang/Elixir/String-case new file mode 120000 index 0000000000..4fdaf9a17c --- /dev/null +++ b/Lang/Elixir/String-case @@ -0,0 +1 @@ +../../Task/String-case/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-concatenation b/Lang/Elixir/String-concatenation new file mode 120000 index 0000000000..685bb12446 --- /dev/null +++ b/Lang/Elixir/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-interpolation--included- b/Lang/Elixir/String-interpolation--included- new file mode 120000 index 0000000000..bacfa7c457 --- /dev/null +++ b/Lang/Elixir/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Elixir \ No newline at end of file diff --git a/Lang/Elixir/String-length b/Lang/Elixir/String-length new file mode 120000 index 0000000000..a95ce4a6ec --- /dev/null +++ b/Lang/Elixir/String-length @@ -0,0 +1 @@ +../../Task/String-length/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Strip-a-set-of-characters-from-a-string b/Lang/Elixir/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..bc299da3a4 --- /dev/null +++ b/Lang/Elixir/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Strip-whitespace-from-a-string-Top-and-tail b/Lang/Elixir/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..3fe42a6224 --- /dev/null +++ b/Lang/Elixir/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Terminal-control-Unicode-output b/Lang/Elixir/Terminal-control-Unicode-output new file mode 120000 index 0000000000..b764373a11 --- /dev/null +++ b/Lang/Elixir/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Tokenize-a-string b/Lang/Elixir/Tokenize-a-string new file mode 120000 index 0000000000..9925e5916c --- /dev/null +++ b/Lang/Elixir/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/Elixir \ No newline at end of file diff --git a/Lang/Elixir/Unbias-a-random-generator b/Lang/Elixir/Unbias-a-random-generator new file mode 120000 index 0000000000..29c0a260ba --- /dev/null +++ b/Lang/Elixir/Unbias-a-random-generator @@ -0,0 +1 @@ +../../Task/Unbias-a-random-generator/Elixir \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Associative-array-Creation b/Lang/Emacs-Lisp/Associative-array-Creation new file mode 120000 index 0000000000..405d5b0e92 --- /dev/null +++ b/Lang/Emacs-Lisp/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Averages-Root-mean-square b/Lang/Emacs-Lisp/Averages-Root-mean-square new file mode 120000 index 0000000000..3e385fc3d4 --- /dev/null +++ b/Lang/Emacs-Lisp/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Check-that-file-exists b/Lang/Emacs-Lisp/Check-that-file-exists new file mode 120000 index 0000000000..b262a699fe --- /dev/null +++ b/Lang/Emacs-Lisp/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Detect-division-by-zero b/Lang/Emacs-Lisp/Detect-division-by-zero new file mode 120000 index 0000000000..974c90bdc2 --- /dev/null +++ b/Lang/Emacs-Lisp/Detect-division-by-zero @@ -0,0 +1 @@ +../../Task/Detect-division-by-zero/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Documentation b/Lang/Emacs-Lisp/Documentation new file mode 120000 index 0000000000..cf7c4b9526 --- /dev/null +++ b/Lang/Emacs-Lisp/Documentation @@ -0,0 +1 @@ +../../Task/Documentation/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Dynamic-variable-names b/Lang/Emacs-Lisp/Dynamic-variable-names new file mode 120000 index 0000000000..c48d743e15 --- /dev/null +++ b/Lang/Emacs-Lisp/Dynamic-variable-names @@ -0,0 +1 @@ +../../Task/Dynamic-variable-names/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/File-modification-time b/Lang/Emacs-Lisp/File-modification-time new file mode 120000 index 0000000000..eff2d0485a --- /dev/null +++ b/Lang/Emacs-Lisp/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Function-composition b/Lang/Emacs-Lisp/Function-composition new file mode 120000 index 0000000000..8d788b1fc0 --- /dev/null +++ b/Lang/Emacs-Lisp/Function-composition @@ -0,0 +1 @@ +../../Task/Function-composition/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Function-definition b/Lang/Emacs-Lisp/Function-definition new file mode 120000 index 0000000000..d6868aad8a --- /dev/null +++ b/Lang/Emacs-Lisp/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Generic-swap b/Lang/Emacs-Lisp/Generic-swap new file mode 120000 index 0000000000..1d742ea4ea --- /dev/null +++ b/Lang/Emacs-Lisp/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Literals-String b/Lang/Emacs-Lisp/Literals-String new file mode 120000 index 0000000000..3311d030dc --- /dev/null +++ b/Lang/Emacs-Lisp/Literals-String @@ -0,0 +1 @@ +../../Task/Literals-String/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Loops-Do-while b/Lang/Emacs-Lisp/Loops-Do-while new file mode 120000 index 0000000000..bcdc761a05 --- /dev/null +++ b/Lang/Emacs-Lisp/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Loops-Foreach b/Lang/Emacs-Lisp/Loops-Foreach new file mode 120000 index 0000000000..33f509e517 --- /dev/null +++ b/Lang/Emacs-Lisp/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Loops-While b/Lang/Emacs-Lisp/Loops-While new file mode 120000 index 0000000000..73ad490711 --- /dev/null +++ b/Lang/Emacs-Lisp/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Primality-by-trial-division b/Lang/Emacs-Lisp/Primality-by-trial-division new file mode 120000 index 0000000000..f58f457a2d --- /dev/null +++ b/Lang/Emacs-Lisp/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Program-termination b/Lang/Emacs-Lisp/Program-termination new file mode 120000 index 0000000000..a266f19270 --- /dev/null +++ b/Lang/Emacs-Lisp/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Range-extraction b/Lang/Emacs-Lisp/Range-extraction new file mode 120000 index 0000000000..e1c5534a6e --- /dev/null +++ b/Lang/Emacs-Lisp/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Read-entire-file b/Lang/Emacs-Lisp/Read-entire-file new file mode 120000 index 0000000000..958353a4df --- /dev/null +++ b/Lang/Emacs-Lisp/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/SHA-256 b/Lang/Emacs-Lisp/SHA-256 new file mode 120000 index 0000000000..5356854ce9 --- /dev/null +++ b/Lang/Emacs-Lisp/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Secure-temporary-file b/Lang/Emacs-Lisp/Secure-temporary-file new file mode 120000 index 0000000000..c66d0a6b55 --- /dev/null +++ b/Lang/Emacs-Lisp/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Sieve-of-Eratosthenes b/Lang/Emacs-Lisp/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..19dc6ac7c4 --- /dev/null +++ b/Lang/Emacs-Lisp/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Emacs-Lisp/Unicode-variable-names b/Lang/Emacs-Lisp/Unicode-variable-names new file mode 120000 index 0000000000..27e75bfad9 --- /dev/null +++ b/Lang/Emacs-Lisp/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/Emacs-Lisp \ No newline at end of file diff --git a/Lang/Erlang/Pattern-matching b/Lang/Erlang/Pattern-matching new file mode 120000 index 0000000000..74e16989a0 --- /dev/null +++ b/Lang/Erlang/Pattern-matching @@ -0,0 +1 @@ +../../Task/Pattern-matching/Erlang \ No newline at end of file diff --git a/Lang/Erlang/Probabilistic-choice b/Lang/Erlang/Probabilistic-choice new file mode 120000 index 0000000000..a4ed21ad1e --- /dev/null +++ b/Lang/Erlang/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Erlang \ No newline at end of file diff --git a/Lang/Euphoria/Averages-Mean-angle b/Lang/Euphoria/Averages-Mean-angle new file mode 120000 index 0000000000..04417864e4 --- /dev/null +++ b/Lang/Euphoria/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Averages-Mean-time-of-day b/Lang/Euphoria/Averages-Mean-time-of-day new file mode 120000 index 0000000000..a5531d8d25 --- /dev/null +++ b/Lang/Euphoria/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Compound-data-type b/Lang/Euphoria/Compound-data-type new file mode 120000 index 0000000000..0cc762c7d2 --- /dev/null +++ b/Lang/Euphoria/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Execute-a-system-command b/Lang/Euphoria/Execute-a-system-command new file mode 120000 index 0000000000..b82aeb8f8a --- /dev/null +++ b/Lang/Euphoria/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Horizontal-sundial-calculations b/Lang/Euphoria/Horizontal-sundial-calculations new file mode 120000 index 0000000000..1209b41bca --- /dev/null +++ b/Lang/Euphoria/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Letter-frequency b/Lang/Euphoria/Letter-frequency new file mode 120000 index 0000000000..08984708e0 --- /dev/null +++ b/Lang/Euphoria/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Literals-Floating-point b/Lang/Euphoria/Literals-Floating-point new file mode 120000 index 0000000000..42c9c31739 --- /dev/null +++ b/Lang/Euphoria/Literals-Floating-point @@ -0,0 +1 @@ +../../Task/Literals-Floating-point/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Literals-Integer b/Lang/Euphoria/Literals-Integer new file mode 120000 index 0000000000..94e0f53237 --- /dev/null +++ b/Lang/Euphoria/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Loops-Do-while b/Lang/Euphoria/Loops-Do-while new file mode 120000 index 0000000000..9d36688e53 --- /dev/null +++ b/Lang/Euphoria/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Loops-Foreach b/Lang/Euphoria/Loops-Foreach new file mode 120000 index 0000000000..f965b75802 --- /dev/null +++ b/Lang/Euphoria/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/OpenGL b/Lang/Euphoria/OpenGL new file mode 120000 index 0000000000..13054c3496 --- /dev/null +++ b/Lang/Euphoria/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Sierpinski-carpet b/Lang/Euphoria/Sierpinski-carpet new file mode 120000 index 0000000000..0fef17e019 --- /dev/null +++ b/Lang/Euphoria/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Temperature-conversion b/Lang/Euphoria/Temperature-conversion new file mode 120000 index 0000000000..158ca43276 --- /dev/null +++ b/Lang/Euphoria/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Euphoria \ No newline at end of file diff --git a/Lang/Euphoria/Tic-tac-toe b/Lang/Euphoria/Tic-tac-toe new file mode 120000 index 0000000000..5b05eb55f5 --- /dev/null +++ b/Lang/Euphoria/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/Euphoria \ No newline at end of file diff --git a/Lang/Excel/Arithmetic-Integer b/Lang/Excel/Arithmetic-Integer new file mode 120000 index 0000000000..4ebea267d6 --- /dev/null +++ b/Lang/Excel/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Excel \ No newline at end of file diff --git a/Lang/Excel/Averages-Root-mean-square b/Lang/Excel/Averages-Root-mean-square new file mode 120000 index 0000000000..c6ce8fcc6d --- /dev/null +++ b/Lang/Excel/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Excel \ No newline at end of file diff --git a/Lang/Excel/Integer-comparison b/Lang/Excel/Integer-comparison new file mode 120000 index 0000000000..37089d8691 --- /dev/null +++ b/Lang/Excel/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Excel \ No newline at end of file diff --git a/Lang/Excel/Logical-operations b/Lang/Excel/Logical-operations new file mode 120000 index 0000000000..49944c8b05 --- /dev/null +++ b/Lang/Excel/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/Excel \ No newline at end of file diff --git a/Lang/Excel/Temperature-conversion b/Lang/Excel/Temperature-conversion new file mode 120000 index 0000000000..2f86506cf5 --- /dev/null +++ b/Lang/Excel/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Excel \ No newline at end of file diff --git a/Lang/F-Sharp/Gamma-function b/Lang/F-Sharp/Gamma-function new file mode 120000 index 0000000000..a988e7731d --- /dev/null +++ b/Lang/F-Sharp/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/F-Sharp \ No newline at end of file diff --git a/Lang/F-Sharp/Sieve-of-Eratosthenes b/Lang/F-Sharp/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..23b5091ffb --- /dev/null +++ b/Lang/F-Sharp/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/F-Sharp \ No newline at end of file diff --git a/Lang/FBSL/00DESCRIPTION b/Lang/FBSL/00DESCRIPTION index f5cf6886a9..82febd9cab 100644 --- a/Lang/FBSL/00DESCRIPTION +++ b/Lang/FBSL/00DESCRIPTION @@ -1,3 +1,3 @@ {{language |site=http://www.fbsl.net/base/preview.html}} -"FBSL" stands for “Freestyle BASIC Script Language”. FBSL is a '''multi-syntax all-in-one''' high-level language (HLL) development environment. Its interpretative layer is a vastly extended superset of traditional BASIC that targets seamless integration of FBSL applications with Windows API and third-party dynamic link libraries. Its integrated Dynamic Assembler and Dynamic C JIT compiler layers enable the user to interleave BASIC code with literatim Intel-style assembly and ANSI C, respectively. Like many modern scripting languages, it contains flavours of Visual BASIC, [[QBasic]], [[C]], [[Pascal]] and [[PHP]], hence the “Freestyle”. It is especially designed for 32-bit [[Win32]] platforms and can run on Windows 95 SR2 through Windows 8.1. It is also compatible with, and completely functional under, [[Linux]] Wine and ReactOS. \ No newline at end of file +"FBSL" stands for “Freestyle BASIC Script Language”. FBSL is an embeddable, '''multi-syntax''', '''all-in-one''' high-level language. Its interpretative layer is a vastly extended superset of traditional BASIC that targets seamless integration of FBSL applications with Windows API and third-party dynamic link libraries. Its integrated Dynamic Assembler and Dynamic C JIT compiler layers enable the user to interleave BASIC code with Intel-style assembly and ANSI C, respectively. Like many modern scripting languages, it contains flavors of Visual BASIC, [[QBasic]], [[C]], [[Pascal]] and [[PHP]], hence the “Freestyle”. It is especially designed for 32-bit [[Win32]] platforms and can run on Windows 95 SR2 through Windows 8.1. It is also compatible with, and completely functional under, [[Linux]] Wine, Mac OS X Wine, and ReactOS. \ No newline at end of file diff --git a/Lang/Factor/Colour-bars-Display b/Lang/Factor/Colour-bars-Display new file mode 120000 index 0000000000..152377b44a --- /dev/null +++ b/Lang/Factor/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/Factor \ No newline at end of file diff --git a/Lang/Factor/Here-document b/Lang/Factor/Here-document new file mode 120000 index 0000000000..76a7e1502a --- /dev/null +++ b/Lang/Factor/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Factor \ No newline at end of file diff --git a/Lang/Factor/Parallel-calculations b/Lang/Factor/Parallel-calculations new file mode 120000 index 0000000000..7372859268 --- /dev/null +++ b/Lang/Factor/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Factor \ No newline at end of file diff --git a/Lang/Factor/Price-fraction b/Lang/Factor/Price-fraction new file mode 120000 index 0000000000..e8dc25837c --- /dev/null +++ b/Lang/Factor/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Factor \ No newline at end of file diff --git a/Lang/Factor/Sum-digits-of-an-integer b/Lang/Factor/Sum-digits-of-an-integer new file mode 120000 index 0000000000..015b2f0f9c --- /dev/null +++ b/Lang/Factor/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Factor \ No newline at end of file diff --git a/Lang/Factor/XML-XPath b/Lang/Factor/XML-XPath new file mode 120000 index 0000000000..c955895180 --- /dev/null +++ b/Lang/Factor/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/Factor \ No newline at end of file diff --git a/Lang/Falcon/Constrained-random-points-on-a-circle b/Lang/Falcon/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..5c0f1a3dcb --- /dev/null +++ b/Lang/Falcon/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Hello-world-Newline-omission b/Lang/Falcon/Hello-world-Newline-omission new file mode 120000 index 0000000000..3a6feba6f9 --- /dev/null +++ b/Lang/Falcon/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Falcon \ No newline at end of file diff --git a/Lang/Falcon/Pick-random-element b/Lang/Falcon/Pick-random-element new file mode 120000 index 0000000000..eacc6a6970 --- /dev/null +++ b/Lang/Falcon/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Falcon \ No newline at end of file diff --git a/Lang/Fexl/00DESCRIPTION b/Lang/Fexl/00DESCRIPTION index 51d6346397..a0a9daf4c7 100644 --- a/Lang/Fexl/00DESCRIPTION +++ b/Lang/Fexl/00DESCRIPTION @@ -6,30 +6,4 @@ Fexl has no keywords, so whenever you see a symbol in a Fexl program, that symbo A symbol may be defined within a Fexl program, or its definition may be left entirely open. The definitions of all open symbols are supplied by a ''context''. A context is a function which supplies definitions for symbols. A context function is itself written in Fexl. -A Fexl program may therefore be resolved inside an arbitrary context, giving whatever meanings you like to all its open symbols. This makes it easy to wrap a Fexl program in an enhanced or restricted context. For example, in a web context you probably don't want "delete_file" to be defined at all, at least not in its normal sense. So you would resolve the program in a highly restricted context which only provides a handful of safe functions, omitting all the dangerous ones. - -Ultimately the core functions of Fexl are written in the [[C]] programming language. To write a new core function named "X" within Fexl, you simply create an appropriate C routine named "fexl_X". It automatically becomes available as a built-in Fexl function. - -For example, here is the C routine which implements the classic '''S''' combinator (fusion), where (S x y z) = (x z) (y z): - -value fexl_S(value f) - { - if (!f->L || !f->L->L || !f->L->L->L) return f; - return A( A(f->L->L->R, f->R), A(f->L->R, f->R) ); - } - -Fexl functions may have side effects -- after all, they've gotta happen '''somewhere'''. For example here's the implementation of the char_put function, called as (char_put ch next), which prints the single character ch to stdout and then continues with next: - -value fexl_char_put(value f) - { - if (!f->L || !f->L->L) return f; - value x = f->L->R; - if (!arg(type_long,x)) return f; - - putchar(get_long(x)); - return f->R; - } - -Fexl is very free-wheeling about side effects, because of course they must happen '''somewhere'''. But you the Fexl programmer can easily isolate and confine side effects as diligently as you like, factoring them out systematically, applying monadic techniques, or whatever. - -Fexl has no built-in type inference system. You can check types at run-time however you like. Fexl also has reflective features which allow you to examine types and the internal data structures at run-time, for example if you want to print a value for testing or debugging purposes. \ No newline at end of file +A Fexl program may therefore be resolved inside an arbitrary context, giving whatever meanings you like to all its open symbols. This makes it easy to wrap a Fexl program in an enhanced or restricted context. For example, in a web context you probably don't want "delete_file" to be defined at all, at least not in its normal sense. So you would resolve the program in a highly restricted context which only provides a handful of safe functions, omitting all the dangerous ones. \ No newline at end of file diff --git a/Lang/Forth/Call-a-function b/Lang/Forth/Call-a-function new file mode 120000 index 0000000000..596b1c0e2e --- /dev/null +++ b/Lang/Forth/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Forth \ No newline at end of file diff --git a/Lang/Forth/Named-parameters b/Lang/Forth/Named-parameters new file mode 120000 index 0000000000..be7fa2905d --- /dev/null +++ b/Lang/Forth/Named-parameters @@ -0,0 +1 @@ +../../Task/Named-parameters/Forth \ No newline at end of file diff --git a/Lang/Forth/Top-rank-per-group b/Lang/Forth/Top-rank-per-group new file mode 120000 index 0000000000..e5153f16f0 --- /dev/null +++ b/Lang/Forth/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Forth \ No newline at end of file diff --git a/Lang/Forth/Vector-products b/Lang/Forth/Vector-products new file mode 120000 index 0000000000..5ad4a1b90e --- /dev/null +++ b/Lang/Forth/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Forth \ No newline at end of file diff --git a/Lang/Fortran/00DESCRIPTION b/Lang/Fortran/00DESCRIPTION index bfe7649547..3562d91fc6 100644 --- a/Lang/Fortran/00DESCRIPTION +++ b/Lang/Fortran/00DESCRIPTION @@ -7,10 +7,8 @@ |LCT=yes |tags=fortran |bnf=http://fortran.comsci.us/syntax/statement/index.html}}{{language programming paradigm|Imperative}} -Fortran is the oldest programming language still in widespread use. It was given substantial rework in the Fortran 90 standard. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95 etc.). +Fortran is the oldest programming language still in widespread use. The language has evolved considerably since it was first released in 1957. Fortran was original developed for scientific and engineering applications, and remains especially suited to numeric computation and scientific computing. By convention, versions before Fortran 90 are spelled with all uppercase letters (e.g. FORTRAN 66, FORTRAN 77), while starting with Fortran 90, the mixed case spelling is used (i.e. Fortran 90, Fortran 95, Fortran 2003 and Fortran 2008). The most recent standard is Fortran 2008 (ISO/IEC 1539-1:2010). -FORTRAN 77, being quite old, lacks almost everything one expects from a modern programming language. It uses a fixed-length line and column oriented line format which was motivated by punch cards. Due to its age, and since FORTRAN compilers generally gave very good performance for numerical code, a lot of code, especially scientific code, was written in FORTRAN. Also, for quite a while there was no free Fortran 90 compiler, which also caused a lot of FORTRAN 77 code to be written even quite some time after Fortran 90 was standardized. Because of the big body of code written in FORTRAN 77 it's still relevant. Indeed, every Fortran compiler still has to accept the old format. +FORTRAN 77, being quite old, lacks almost everything one expects from a modern programming language. It uses a fixed-length line and column oriented line format which was motivated by punch cards. Due to its age, and since FORTRAN compilers generally gave very good performance for numerical code, a lot of code, especially scientific code, was written in FORTRAN. Also, for quite a while there was no free Fortran 90 compiler, which also caused a lot of FORTRAN 77 code to be written even quite some time after Fortran 90 was standardized. Because of the large body of code written in FORTRAN 77 it remains relevant today. Indeed, every modern Fortran compiler still accepts FORTRAN 77 code. -Fortran 90 was a major step in the development of Fortran. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. - -Newer Fortran standards (Fortran 2003 and 2008) added further modern features, like support for object oriented programming, inheritance, and polymorphism. \ No newline at end of file +Fortran 90 was a major revision of the language. It introduced a new free-form source code format, modern programming language features like modules, pointers and user-defined types, an improved type system for built-in types and superiour built-in array handling. Newer Fortran standards (Fortran 2003 and Fortran 2008) added further modern features, like support for object oriented programming, inheritance, polymorphism, parallel processing, and interoperability with the C programming language. \ No newline at end of file diff --git a/Lang/Fortran/Animate-a-pendulum b/Lang/Fortran/Animate-a-pendulum new file mode 120000 index 0000000000..189d6ce5d0 --- /dev/null +++ b/Lang/Fortran/Animate-a-pendulum @@ -0,0 +1 @@ +../../Task/Animate-a-pendulum/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Call-a-function b/Lang/Fortran/Call-a-function new file mode 120000 index 0000000000..abe16f6ed5 --- /dev/null +++ b/Lang/Fortran/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Deal-cards-for-FreeCell b/Lang/Fortran/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..60df9bb1ce --- /dev/null +++ b/Lang/Fortran/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Digital-root b/Lang/Fortran/Digital-root new file mode 120000 index 0000000000..c42816f2dd --- /dev/null +++ b/Lang/Fortran/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Enforced-immutability b/Lang/Fortran/Enforced-immutability new file mode 120000 index 0000000000..7a11f0064a --- /dev/null +++ b/Lang/Fortran/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Fibonacci-n-step-number-sequences b/Lang/Fortran/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..6d943f170d --- /dev/null +++ b/Lang/Fortran/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Langtons-ant b/Lang/Fortran/Langtons-ant new file mode 120000 index 0000000000..00cd00bfab --- /dev/null +++ b/Lang/Fortran/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Random-number-generator--device- b/Lang/Fortran/Random-number-generator--device- new file mode 120000 index 0000000000..167e481d92 --- /dev/null +++ b/Lang/Fortran/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Subtractive-generator b/Lang/Fortran/Subtractive-generator new file mode 120000 index 0000000000..f7c6755058 --- /dev/null +++ b/Lang/Fortran/Subtractive-generator @@ -0,0 +1 @@ +../../Task/Subtractive-generator/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Temperature-conversion b/Lang/Fortran/Temperature-conversion new file mode 120000 index 0000000000..b5886a37b1 --- /dev/null +++ b/Lang/Fortran/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Fortran \ No newline at end of file diff --git a/Lang/Fortran/Trabb-Pardo-Knuth-algorithm b/Lang/Fortran/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..7eef558c40 --- /dev/null +++ b/Lang/Fortran/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Fortran \ No newline at end of file diff --git a/Lang/Frink/Factors-of-an-integer b/Lang/Frink/Factors-of-an-integer new file mode 120000 index 0000000000..8a2e0a7b26 --- /dev/null +++ b/Lang/Frink/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/Frink \ No newline at end of file diff --git a/Lang/Frink/Greyscale-bars-Display b/Lang/Frink/Greyscale-bars-Display new file mode 120000 index 0000000000..21f222881f --- /dev/null +++ b/Lang/Frink/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/Frink \ No newline at end of file diff --git a/Lang/Frink/Hello-world-Standard-error b/Lang/Frink/Hello-world-Standard-error new file mode 120000 index 0000000000..dde2fbb40b --- /dev/null +++ b/Lang/Frink/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Frink \ No newline at end of file diff --git a/Lang/Frink/Knuth-shuffle b/Lang/Frink/Knuth-shuffle new file mode 120000 index 0000000000..acd032ecce --- /dev/null +++ b/Lang/Frink/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Frink \ No newline at end of file diff --git a/Lang/Frink/Remove-lines-from-a-file b/Lang/Frink/Remove-lines-from-a-file new file mode 120000 index 0000000000..a73b7ebbc7 --- /dev/null +++ b/Lang/Frink/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Frink \ No newline at end of file diff --git a/Lang/Frink/Return-multiple-values b/Lang/Frink/Return-multiple-values new file mode 120000 index 0000000000..0a24ed1eea --- /dev/null +++ b/Lang/Frink/Return-multiple-values @@ -0,0 +1 @@ +../../Task/Return-multiple-values/Frink \ No newline at end of file diff --git a/Lang/Frink/Runtime-evaluation b/Lang/Frink/Runtime-evaluation new file mode 120000 index 0000000000..ddc6a025a4 --- /dev/null +++ b/Lang/Frink/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/Frink \ No newline at end of file diff --git a/Lang/Frink/Sort-an-integer-array b/Lang/Frink/Sort-an-integer-array new file mode 120000 index 0000000000..7690040264 --- /dev/null +++ b/Lang/Frink/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Frink \ No newline at end of file diff --git a/Lang/Frink/String-interpolation--included- b/Lang/Frink/String-interpolation--included- new file mode 120000 index 0000000000..a7fa31121c --- /dev/null +++ b/Lang/Frink/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/Frink \ No newline at end of file diff --git a/Lang/Frink/Window-creation b/Lang/Frink/Window-creation new file mode 120000 index 0000000000..07da8a902d --- /dev/null +++ b/Lang/Frink/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Frink \ No newline at end of file diff --git a/Lang/GML/Hello-world-Text b/Lang/GML/Hello-world-Text new file mode 120000 index 0000000000..c9faf11892 --- /dev/null +++ b/Lang/GML/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/GML \ No newline at end of file diff --git a/Lang/GUISS/00DESCRIPTION b/Lang/GUISS/00DESCRIPTION index a705605fb9..bc8f48e882 100644 --- a/Lang/GUISS/00DESCRIPTION +++ b/Lang/GUISS/00DESCRIPTION @@ -3,7 +3,7 @@ == History == -Graphical User Interface Support Script was originally called "Windows Support Script". On 16th January 2010, it was renamed to "Graphical User Interface Support Script" to reflect the fact that it can be used to describle the operation of graphical user interface systems other than Microsoft Windows. The project started in 1996 and its purpose was to provide a standard means of representing graphical user interface operations and interactions through written or spoken word. This would enable telephone support or written instructions to be given to end using coherent standardized language and terminology that could be understood by the end user. +Graphical User Interface Support Script was originally called "Windows Support Script". On 16th January 2010, it was renamed to "Graphical User Interface Support Script" to reflect the fact that it can be used to describe the operation of graphical user interface systems other than Microsoft Windows. The project started in 1996 and its purpose was to provide a standard means of representing graphical user interface operations and interactions through written or spoken word. This would enable telephone support or written instructions to be given to end using coherent standardized language and terminology that could be understood by the end user. == Interpreter == diff --git a/Lang/Gema/A+B b/Lang/Gema/A+B new file mode 120000 index 0000000000..8fb3eb4b63 --- /dev/null +++ b/Lang/Gema/A+B @@ -0,0 +1 @@ +../../Task/A+B/Gema \ No newline at end of file diff --git a/Lang/Gentee/Hello-world-Text b/Lang/Gentee/Hello-world-Text new file mode 120000 index 0000000000..9776adfe06 --- /dev/null +++ b/Lang/Gentee/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Gentee \ No newline at end of file diff --git a/Lang/Gnuplot/Function-definition b/Lang/Gnuplot/Function-definition new file mode 120000 index 0000000000..1828c87d72 --- /dev/null +++ b/Lang/Gnuplot/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/Gnuplot \ No newline at end of file diff --git a/Lang/Gnuplot/Program-termination b/Lang/Gnuplot/Program-termination new file mode 120000 index 0000000000..387e9a43c1 --- /dev/null +++ b/Lang/Gnuplot/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Gnuplot \ No newline at end of file diff --git a/Lang/Go/00DESCRIPTION b/Lang/Go/00DESCRIPTION index 2ab6130ff6..838664d138 100644 --- a/Lang/Go/00DESCRIPTION +++ b/Lang/Go/00DESCRIPTION @@ -2,25 +2,27 @@ |exec=machine |safety=safe |strength=strong +|compat=nominative |express=explicit |checking=static |parampass=value |gc=yes +|tags=go +|hopl=no |LCT=yes |site=http://golang.org/}} -{{language programming paradigm|concurrent}} -'''Go''' is a new programing language created by Robert Griesemer, Rob Pike and Ken Thompson at Google. +{{provides|Concurrency}}{{provides|File access}}{{provides|File system access}}{{provides|First class functions}}{{provides|Network access}}{{provides|Objects}}{{provides|Signal handling}}{{language programming paradigm|concurrent}}{{language programming paradigm|Imperative}} +'''Go''' is an open source project developed by a team at [[wp:Google|Google]] (including [[wp:Robert Griesemer|Robert Griesemer]], [[wp:Rob Pike|Rob Pike]] and [[wp:Ken Thompson|Ken Thompson]]) as well as many [http://golang.org/CONTRIBUTORS contributors] from the open source community. + +Go is distributed under a [http://golang.org/LICENSE BSD-style license]. Not to be confused with [[:Category:Go!|Go!]] ==Links== -* [http://go-lang.cat-v.org/ Go Language Resources] -* [http://tour.golang.org/ Go Tutorial] - -;Stable version -* [http://golang.org/doc/go1.html Go 1 Release Notes] +*[[wp:Go (programming language)|Go in Wikipedia]] +* [http://tour.golang.org/ Go Tour and Tutorial] +* [http://golang.org/doc/devel/release.html Release History] +** Release Notes: [http://golang.org/doc/go1.3 1.3], [http://golang.org/doc/go1.2 1.2], [http://golang.org/doc/go1.1 1.1], [http://golang.org/doc/go1 1.0] * [http://golang.org/ref/spec Go language specification] * [http://golang.org/pkg/ Go standard library documentation] -;Weekly version -* [http://weekly.golang.org/ref/spec Go language specification] -* [http://weekly.golang.org/pkg/ Go standard library documentation] \ No newline at end of file +* [http://go-lang.cat-v.org/ Go Language Resources] \ No newline at end of file diff --git a/Lang/Go/Arena-storage-pool b/Lang/Go/Arena-storage-pool new file mode 120000 index 0000000000..4d7e59c551 --- /dev/null +++ b/Lang/Go/Arena-storage-pool @@ -0,0 +1 @@ +../../Task/Arena-storage-pool/Go \ No newline at end of file diff --git a/Lang/Go/Break-OO-privacy b/Lang/Go/Break-OO-privacy new file mode 120000 index 0000000000..07d14f3ea9 --- /dev/null +++ b/Lang/Go/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Go \ No newline at end of file diff --git a/Lang/Go/Call-a-function b/Lang/Go/Call-a-function new file mode 120000 index 0000000000..f14e43e8cc --- /dev/null +++ b/Lang/Go/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Go \ No newline at end of file diff --git a/Lang/Go/Create-a-file-on-magnetic-tape b/Lang/Go/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..d347865ced --- /dev/null +++ b/Lang/Go/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Go \ No newline at end of file diff --git a/Lang/Go/Cut-a-rectangle b/Lang/Go/Cut-a-rectangle new file mode 120000 index 0000000000..51a5183ca8 --- /dev/null +++ b/Lang/Go/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Go \ No newline at end of file diff --git a/Lang/Go/Keyboard-input-Flush-the-keyboard-buffer b/Lang/Go/Keyboard-input-Flush-the-keyboard-buffer new file mode 120000 index 0000000000..973cca8eec --- /dev/null +++ b/Lang/Go/Keyboard-input-Flush-the-keyboard-buffer @@ -0,0 +1 @@ +../../Task/Keyboard-input-Flush-the-keyboard-buffer/Go \ No newline at end of file diff --git a/Lang/Go/Keyboard-input-Keypress-check b/Lang/Go/Keyboard-input-Keypress-check new file mode 120000 index 0000000000..21da4640f5 --- /dev/null +++ b/Lang/Go/Keyboard-input-Keypress-check @@ -0,0 +1 @@ +../../Task/Keyboard-input-Keypress-check/Go \ No newline at end of file diff --git a/Lang/Go/Keyboard-input-Obtain-a-Y-or-N-response b/Lang/Go/Keyboard-input-Obtain-a-Y-or-N-response new file mode 120000 index 0000000000..cf9b78ad1f --- /dev/null +++ b/Lang/Go/Keyboard-input-Obtain-a-Y-or-N-response @@ -0,0 +1 @@ +../../Task/Keyboard-input-Obtain-a-Y-or-N-response/Go \ No newline at end of file diff --git a/Lang/Go/Metronome b/Lang/Go/Metronome new file mode 120000 index 0000000000..de15375a44 --- /dev/null +++ b/Lang/Go/Metronome @@ -0,0 +1 @@ +../../Task/Metronome/Go \ No newline at end of file diff --git a/Lang/Go/Parametrized-SQL-statement b/Lang/Go/Parametrized-SQL-statement new file mode 120000 index 0000000000..88a8fdce8a --- /dev/null +++ b/Lang/Go/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Go \ No newline at end of file diff --git a/Lang/Go/Partial-function-application b/Lang/Go/Partial-function-application new file mode 120000 index 0000000000..8b0a56800c --- /dev/null +++ b/Lang/Go/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Go \ No newline at end of file diff --git a/Lang/Go/SQL-based-authentication b/Lang/Go/SQL-based-authentication new file mode 120000 index 0000000000..2a7423f9fa --- /dev/null +++ b/Lang/Go/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Go \ No newline at end of file diff --git a/Lang/Go/Scope-Function-names-and-labels b/Lang/Go/Scope-Function-names-and-labels new file mode 120000 index 0000000000..f3bc060a49 --- /dev/null +++ b/Lang/Go/Scope-Function-names-and-labels @@ -0,0 +1 @@ +../../Task/Scope-Function-names-and-labels/Go \ No newline at end of file diff --git a/Lang/Go/Set-of-real-numbers b/Lang/Go/Set-of-real-numbers new file mode 120000 index 0000000000..afd6a260ed --- /dev/null +++ b/Lang/Go/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Coloured-text b/Lang/Go/Terminal-control-Coloured-text new file mode 120000 index 0000000000..8a68960b63 --- /dev/null +++ b/Lang/Go/Terminal-control-Coloured-text @@ -0,0 +1 @@ +../../Task/Terminal-control-Coloured-text/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Cursor-movement b/Lang/Go/Terminal-control-Cursor-movement new file mode 120000 index 0000000000..bc2965b91e --- /dev/null +++ b/Lang/Go/Terminal-control-Cursor-movement @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-movement/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Cursor-positioning b/Lang/Go/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..f35438f67a --- /dev/null +++ b/Lang/Go/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Dimensions b/Lang/Go/Terminal-control-Dimensions new file mode 120000 index 0000000000..248cd407a7 --- /dev/null +++ b/Lang/Go/Terminal-control-Dimensions @@ -0,0 +1 @@ +../../Task/Terminal-control-Dimensions/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Hiding-the-cursor b/Lang/Go/Terminal-control-Hiding-the-cursor new file mode 120000 index 0000000000..c21b15aa17 --- /dev/null +++ b/Lang/Go/Terminal-control-Hiding-the-cursor @@ -0,0 +1 @@ +../../Task/Terminal-control-Hiding-the-cursor/Go \ No newline at end of file diff --git a/Lang/Go/Terminal-control-Inverse-video b/Lang/Go/Terminal-control-Inverse-video new file mode 120000 index 0000000000..a31caf57c7 --- /dev/null +++ b/Lang/Go/Terminal-control-Inverse-video @@ -0,0 +1 @@ +../../Task/Terminal-control-Inverse-video/Go \ No newline at end of file diff --git a/Lang/Go/Universal-Turing-machine b/Lang/Go/Universal-Turing-machine new file mode 120000 index 0000000000..4bf8e1e745 --- /dev/null +++ b/Lang/Go/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Go \ No newline at end of file diff --git a/Lang/Go/Zebra-puzzle b/Lang/Go/Zebra-puzzle new file mode 120000 index 0000000000..2b8d8dfa14 --- /dev/null +++ b/Lang/Go/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Go \ No newline at end of file diff --git a/Lang/Groovy/Anagrams-Deranged-anagrams b/Lang/Groovy/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..19238fd938 --- /dev/null +++ b/Lang/Groovy/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Arithmetic-geometric-mean b/Lang/Groovy/Arithmetic-geometric-mean new file mode 120000 index 0000000000..ccbbb800f4 --- /dev/null +++ b/Lang/Groovy/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Delete-a-file b/Lang/Groovy/Delete-a-file new file mode 120000 index 0000000000..9f54a449e3 --- /dev/null +++ b/Lang/Groovy/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Happy-numbers b/Lang/Groovy/Happy-numbers new file mode 120000 index 0000000000..d7b665c830 --- /dev/null +++ b/Lang/Groovy/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Huffman-coding b/Lang/Groovy/Huffman-coding new file mode 120000 index 0000000000..e93f5f7e3a --- /dev/null +++ b/Lang/Groovy/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Least-common-multiple b/Lang/Groovy/Least-common-multiple new file mode 120000 index 0000000000..cf44bcca79 --- /dev/null +++ b/Lang/Groovy/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Optional-parameters b/Lang/Groovy/Optional-parameters new file mode 120000 index 0000000000..4b4b95b0e1 --- /dev/null +++ b/Lang/Groovy/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Parametric-polymorphism b/Lang/Groovy/Parametric-polymorphism new file mode 120000 index 0000000000..c958a596a2 --- /dev/null +++ b/Lang/Groovy/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Polymorphic-copy b/Lang/Groovy/Polymorphic-copy new file mode 120000 index 0000000000..beb6126a65 --- /dev/null +++ b/Lang/Groovy/Polymorphic-copy @@ -0,0 +1 @@ +../../Task/Polymorphic-copy/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Pythagorean-triples b/Lang/Groovy/Pythagorean-triples new file mode 120000 index 0000000000..cc851953f1 --- /dev/null +++ b/Lang/Groovy/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Respond-to-an-unknown-method-call b/Lang/Groovy/Respond-to-an-unknown-method-call new file mode 120000 index 0000000000..fa3a7e42bd --- /dev/null +++ b/Lang/Groovy/Respond-to-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Respond-to-an-unknown-method-call/Groovy \ No newline at end of file diff --git a/Lang/Groovy/Sorting-algorithms-Sleep-sort b/Lang/Groovy/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..e1e94aa1f1 --- /dev/null +++ b/Lang/Groovy/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Groovy \ No newline at end of file diff --git a/Lang/Haskell/Average-loop-length b/Lang/Haskell/Average-loop-length new file mode 120000 index 0000000000..6273bbfa66 --- /dev/null +++ b/Lang/Haskell/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Calendar b/Lang/Haskell/Calendar new file mode 120000 index 0000000000..fac1d87506 --- /dev/null +++ b/Lang/Haskell/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Color-quantization b/Lang/Haskell/Color-quantization new file mode 120000 index 0000000000..9ed5b43c38 --- /dev/null +++ b/Lang/Haskell/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Element-wise-operations b/Lang/Haskell/Element-wise-operations new file mode 120000 index 0000000000..1b3644583c --- /dev/null +++ b/Lang/Haskell/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Honeycombs b/Lang/Haskell/Honeycombs new file mode 120000 index 0000000000..b45565e98f --- /dev/null +++ b/Lang/Haskell/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Hough-transform b/Lang/Haskell/Hough-transform new file mode 120000 index 0000000000..c1a7012c4e --- /dev/null +++ b/Lang/Haskell/Hough-transform @@ -0,0 +1 @@ +../../Task/Hough-transform/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Image-noise b/Lang/Haskell/Image-noise new file mode 120000 index 0000000000..5f0de7444a --- /dev/null +++ b/Lang/Haskell/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Last-Friday-of-each-month b/Lang/Haskell/Last-Friday-of-each-month new file mode 120000 index 0000000000..99ce4b2a74 --- /dev/null +++ b/Lang/Haskell/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Mad-Libs b/Lang/Haskell/Mad-Libs new file mode 120000 index 0000000000..9debd8e854 --- /dev/null +++ b/Lang/Haskell/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Multisplit b/Lang/Haskell/Multisplit new file mode 120000 index 0000000000..1a2fb4aa82 --- /dev/null +++ b/Lang/Haskell/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Narcissist b/Lang/Haskell/Narcissist new file mode 120000 index 0000000000..9b6bbee4aa --- /dev/null +++ b/Lang/Haskell/Narcissist @@ -0,0 +1 @@ +../../Task/Narcissist/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Nautical-bell b/Lang/Haskell/Nautical-bell new file mode 120000 index 0000000000..0bfa811a9d --- /dev/null +++ b/Lang/Haskell/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Optional-parameters b/Lang/Haskell/Optional-parameters new file mode 120000 index 0000000000..db9c4bdff9 --- /dev/null +++ b/Lang/Haskell/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Percentage-difference-between-images b/Lang/Haskell/Percentage-difference-between-images new file mode 120000 index 0000000000..36503515ba --- /dev/null +++ b/Lang/Haskell/Percentage-difference-between-images @@ -0,0 +1 @@ +../../Task/Percentage-difference-between-images/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Rate-counter b/Lang/Haskell/Rate-counter new file mode 120000 index 0000000000..3fc34f2706 --- /dev/null +++ b/Lang/Haskell/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Haskell \ No newline at end of file diff --git a/Lang/Haskell/SHA-1 b/Lang/Haskell/SHA-1 new file mode 120000 index 0000000000..ab2dcabe9e --- /dev/null +++ b/Lang/Haskell/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Sokoban b/Lang/Haskell/Sokoban new file mode 120000 index 0000000000..0cd723dde9 --- /dev/null +++ b/Lang/Haskell/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Haskell \ No newline at end of file diff --git a/Lang/Haskell/String-comparison b/Lang/Haskell/String-comparison new file mode 120000 index 0000000000..e6d2f8114a --- /dev/null +++ b/Lang/Haskell/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Temperature-conversion b/Lang/Haskell/Temperature-conversion new file mode 120000 index 0000000000..2b35a9d612 --- /dev/null +++ b/Lang/Haskell/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Haskell \ No newline at end of file diff --git a/Lang/Haskell/Terminal-control-Clear-the-screen b/Lang/Haskell/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..a01c324736 --- /dev/null +++ b/Lang/Haskell/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Haskell \ No newline at end of file diff --git a/Lang/Haskell/URL-decoding b/Lang/Haskell/URL-decoding new file mode 120000 index 0000000000..cff277ce35 --- /dev/null +++ b/Lang/Haskell/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Haskell \ No newline at end of file diff --git a/Lang/Haskell/URL-encoding b/Lang/Haskell/URL-encoding new file mode 120000 index 0000000000..a2c655a6be --- /dev/null +++ b/Lang/Haskell/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Haskell \ No newline at end of file diff --git a/Lang/Haxe/Execute-HQ9+ b/Lang/Haxe/Execute-HQ9+ new file mode 120000 index 0000000000..a2bbabe549 --- /dev/null +++ b/Lang/Haxe/Execute-HQ9+ @@ -0,0 +1 @@ +../../Task/Execute-HQ9+/Haxe \ No newline at end of file diff --git a/Lang/Haxe/Hello-world-Text b/Lang/Haxe/Hello-world-Text new file mode 120000 index 0000000000..1607027381 --- /dev/null +++ b/Lang/Haxe/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Haxe \ No newline at end of file diff --git a/Lang/Icon/Balanced-ternary b/Lang/Icon/Balanced-ternary new file mode 120000 index 0000000000..b3a5b45706 --- /dev/null +++ b/Lang/Icon/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/Icon \ No newline at end of file diff --git a/Lang/Icon/Carmichael-3-strong-pseudoprimes b/Lang/Icon/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..fd65fe652b --- /dev/null +++ b/Lang/Icon/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Icon \ No newline at end of file diff --git a/Lang/Icon/Create-a-file-on-magnetic-tape b/Lang/Icon/Create-a-file-on-magnetic-tape new file mode 120000 index 0000000000..75b6038832 --- /dev/null +++ b/Lang/Icon/Create-a-file-on-magnetic-tape @@ -0,0 +1 @@ +../../Task/Create-a-file-on-magnetic-tape/Icon \ No newline at end of file diff --git a/Lang/Icon/Fibonacci-n-step-number-sequences b/Lang/Icon/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..8c2e2cb6be --- /dev/null +++ b/Lang/Icon/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Icon \ No newline at end of file diff --git a/Lang/Icon/Hello-world-Line-printer b/Lang/Icon/Hello-world-Line-printer new file mode 120000 index 0000000000..5a817c04f1 --- /dev/null +++ b/Lang/Icon/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Icon \ No newline at end of file diff --git a/Lang/Icon/Keyboard-macros b/Lang/Icon/Keyboard-macros new file mode 120000 index 0000000000..2e8c91c113 --- /dev/null +++ b/Lang/Icon/Keyboard-macros @@ -0,0 +1 @@ +../../Task/Keyboard-macros/Icon \ No newline at end of file diff --git a/Lang/Icon/Permutations-by-swapping b/Lang/Icon/Permutations-by-swapping new file mode 120000 index 0000000000..362a00d701 --- /dev/null +++ b/Lang/Icon/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/Icon \ No newline at end of file diff --git a/Lang/Icon/Reduced-row-echelon-form b/Lang/Icon/Reduced-row-echelon-form new file mode 120000 index 0000000000..66e4dfd5c5 --- /dev/null +++ b/Lang/Icon/Reduced-row-echelon-form @@ -0,0 +1 @@ +../../Task/Reduced-row-echelon-form/Icon \ No newline at end of file diff --git a/Lang/Icon/Roots-of-a-function b/Lang/Icon/Roots-of-a-function new file mode 120000 index 0000000000..812488fa99 --- /dev/null +++ b/Lang/Icon/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Secure-temporary-file b/Lang/Icon/Secure-temporary-file new file mode 120000 index 0000000000..537f9573b1 --- /dev/null +++ b/Lang/Icon/Secure-temporary-file @@ -0,0 +1 @@ +../../Task/Secure-temporary-file/Icon \ No newline at end of file diff --git a/Lang/Icon/Test-a-function b/Lang/Icon/Test-a-function new file mode 120000 index 0000000000..32cadde200 --- /dev/null +++ b/Lang/Icon/Test-a-function @@ -0,0 +1 @@ +../../Task/Test-a-function/Icon \ No newline at end of file diff --git a/Lang/Icon/Video-display-modes b/Lang/Icon/Video-display-modes new file mode 120000 index 0000000000..98b45fabba --- /dev/null +++ b/Lang/Icon/Video-display-modes @@ -0,0 +1 @@ +../../Task/Video-display-modes/Icon \ No newline at end of file diff --git a/Lang/Intercal/Loops-Infinite b/Lang/Intercal/Loops-Infinite new file mode 120000 index 0000000000..663cda358d --- /dev/null +++ b/Lang/Intercal/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Intercal \ No newline at end of file diff --git a/Lang/Io/Man-or-boy-test b/Lang/Io/Man-or-boy-test new file mode 120000 index 0000000000..497c5c3ea6 --- /dev/null +++ b/Lang/Io/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Io \ No newline at end of file diff --git a/Lang/Iptscrae/00DESCRIPTION b/Lang/Iptscrae/00DESCRIPTION index 4d3d27c049..df04a458d5 100644 --- a/Lang/Iptscrae/00DESCRIPTION +++ b/Lang/Iptscrae/00DESCRIPTION @@ -1 +1,6 @@ -{{stub}}{{language}} \ No newline at end of file +{{stub}} +{{language +|exec=interpreted}} +'''Iptscrae''' is the [[Forth]]-like scripting language for the visual chat software [http://www.thepalace.com/ The Palace]. + +[http://www.thepalaceportal.com/downloads/iptscrae.pdf Iptscrae Language Guide] \ No newline at end of file diff --git a/Lang/J/00DESCRIPTION b/Lang/J/00DESCRIPTION index 207d78a850..8d48f2ec70 100644 --- a/Lang/J/00DESCRIPTION +++ b/Lang/J/00DESCRIPTION @@ -31,7 +31,7 @@ The J programming language was designed and developed by [http://en.wikipedia.or == Reading J == -J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. When learning how a J sentence works, you can also try simpler sentences with the same data or perhaps related data. +J is meant to be read with the aid of a computer. J sentences are single lines and trying variations and simplifications of an expression is common practice. The first step in understanding any J sentence is to understand the data you started with and the data which resulted. When learning how a J sentence works, you can also try simpler sentences with the same data or perhaps related data. When trying to understand contexts that use large data structures, it can often be wise to investigate small, representative samples until you understand how the code works. Unless you attend an institution which has made a J interpreter available to you through your web browser (or preinstalled on your machine), if you want to see how J works you should probably [http://www.jsoftware.com/stable.htm install] a copy of J -- or you can try one of the "try me" links, below. If you want to understand how to experiment with alternative expressions you should probably also be studying some of its [[j:Guides/Getting%20Started#Documentation|documentation]]. @@ -57,7 +57,7 @@ To understand how this works, you might try working with simpler sentences and t (+/ % #) 4 5 6 5 -By themselves, these experiments mean nothing, but if you know that +/ was finding the sum of a list and # was finding the length of a list and that % was dividing the two quantities (and looks almost like one of the classical division symbols) then these experiments might help confirm that you have understood things properly. +By themselves, these experiments mean nothing, but if you know that +/ was finding the sum of a list and # was finding the length of a list and that % was dividing the two quantities (and looks almost like one of the old school division symbols) then these experiments might help confirm that you have understood things properly. == Some Perspective == @@ -91,4 +91,6 @@ Want to try one of those cryptic J lines you see peppered through RC? Try pasti If you want to be a bit more interactive, and get some guidance from J gurus, you can join the actual J IRC channel on Freenode, #jsoftware. Buubot and several other J eval bots run there. If you don't have an IRC client you can try [http://webchat.freenode.net/?randomnick=1&channels=jsoftware freenode's web interface] (or just [http://webchat.freenode.net/?channels=jsoftware&randomnick=1 give it a quick spin]). More [[j:Community/IRC|details about the J IRC community]] is available. -If any of that piques your interest, and you want to explore a little more, you can [http://www.jsoftware.com/stable.htm download J] and [http://www.jsoftware.com/forums.htm join the J forums]. \ No newline at end of file +If any of that piques your interest, and you want to explore a little more, you can [http://www.jsoftware.com/stable.htm download J] and [http://www.jsoftware.com/forums.htm join the J forums]. + +If you have problems executing any of the J code here on Rosetta, please make a note of it either on the task page itself, on the talk page, or on the appropriate [http://forums.jsoftware.com J forum], whichever is best. It might be that there's a version dependency that needs to be documented, or you might have found an actual bug. \ No newline at end of file diff --git a/Lang/J/Date-manipulation b/Lang/J/Date-manipulation new file mode 120000 index 0000000000..0d387b4bbd --- /dev/null +++ b/Lang/J/Date-manipulation @@ -0,0 +1 @@ +../../Task/Date-manipulation/J \ No newline at end of file diff --git a/Lang/J/Execute-SNUSP b/Lang/J/Execute-SNUSP new file mode 120000 index 0000000000..59620bb6a3 --- /dev/null +++ b/Lang/J/Execute-SNUSP @@ -0,0 +1 @@ +../../Task/Execute-SNUSP/J \ No newline at end of file diff --git a/Lang/J/Fork b/Lang/J/Fork new file mode 120000 index 0000000000..4fa7ba9e25 --- /dev/null +++ b/Lang/J/Fork @@ -0,0 +1 @@ +../../Task/Fork/J \ No newline at end of file diff --git a/Lang/J/Nautical-bell b/Lang/J/Nautical-bell new file mode 120000 index 0000000000..7640e64234 --- /dev/null +++ b/Lang/J/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/J \ No newline at end of file diff --git a/Lang/J/Send-an-unknown-method-call b/Lang/J/Send-an-unknown-method-call new file mode 120000 index 0000000000..f53ff2399f --- /dev/null +++ b/Lang/J/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/J \ No newline at end of file diff --git a/Lang/J/Sieve-of-Eratosthenes b/Lang/J/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..767e33361e --- /dev/null +++ b/Lang/J/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/J \ No newline at end of file diff --git a/Lang/J/Synchronous-concurrency b/Lang/J/Synchronous-concurrency new file mode 120000 index 0000000000..7e1fcf5aeb --- /dev/null +++ b/Lang/J/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/J \ No newline at end of file diff --git a/Lang/Java/24-game b/Lang/Java/24-game new file mode 120000 index 0000000000..6e249a4a50 --- /dev/null +++ b/Lang/Java/24-game @@ -0,0 +1 @@ +../../Task/24-game/Java \ No newline at end of file diff --git a/Lang/Java/24-game-Solve b/Lang/Java/24-game-Solve new file mode 120000 index 0000000000..560b1debc0 --- /dev/null +++ b/Lang/Java/24-game-Solve @@ -0,0 +1 @@ +../../Task/24-game-Solve/Java \ No newline at end of file diff --git a/Lang/Java/Bitmap-Bresenhams-line-algorithm b/Lang/Java/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..745b792e0d --- /dev/null +++ b/Lang/Java/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Calendar b/Lang/Java/Calendar new file mode 120000 index 0000000000..e599868996 --- /dev/null +++ b/Lang/Java/Calendar @@ -0,0 +1 @@ +../../Task/Calendar/Java \ No newline at end of file diff --git a/Lang/Java/Colour-pinstripe-Display b/Lang/Java/Colour-pinstripe-Display new file mode 120000 index 0000000000..31b93febe5 --- /dev/null +++ b/Lang/Java/Colour-pinstripe-Display @@ -0,0 +1 @@ +../../Task/Colour-pinstripe-Display/Java \ No newline at end of file diff --git a/Lang/Java/Discordian-date b/Lang/Java/Discordian-date new file mode 120000 index 0000000000..7275510c19 --- /dev/null +++ b/Lang/Java/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Java \ No newline at end of file diff --git a/Lang/Java/Draw-a-cuboid b/Lang/Java/Draw-a-cuboid new file mode 120000 index 0000000000..2afd34299a --- /dev/null +++ b/Lang/Java/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Java \ No newline at end of file diff --git a/Lang/Java/Dutch-national-flag-problem b/Lang/Java/Dutch-national-flag-problem new file mode 120000 index 0000000000..1e28861611 --- /dev/null +++ b/Lang/Java/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Java \ No newline at end of file diff --git a/Lang/Java/Execute-a-Markov-algorithm b/Lang/Java/Execute-a-Markov-algorithm new file mode 120000 index 0000000000..8921aaf1ab --- /dev/null +++ b/Lang/Java/Execute-a-Markov-algorithm @@ -0,0 +1 @@ +../../Task/Execute-a-Markov-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/GUI-Maximum-window-dimensions b/Lang/Java/GUI-Maximum-window-dimensions new file mode 120000 index 0000000000..e9d92e024e --- /dev/null +++ b/Lang/Java/GUI-Maximum-window-dimensions @@ -0,0 +1 @@ +../../Task/GUI-Maximum-window-dimensions/Java \ No newline at end of file diff --git a/Lang/Java/Holidays-related-to-Easter b/Lang/Java/Holidays-related-to-Easter new file mode 120000 index 0000000000..43666d728b --- /dev/null +++ b/Lang/Java/Holidays-related-to-Easter @@ -0,0 +1 @@ +../../Task/Holidays-related-to-Easter/Java \ No newline at end of file diff --git a/Lang/Java/Honeycombs b/Lang/Java/Honeycombs new file mode 120000 index 0000000000..dab2140052 --- /dev/null +++ b/Lang/Java/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/Java \ No newline at end of file diff --git a/Lang/Java/Longest-string-challenge b/Lang/Java/Longest-string-challenge new file mode 120000 index 0000000000..1d60bc3f69 --- /dev/null +++ b/Lang/Java/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Java \ No newline at end of file diff --git a/Lang/Java/Multifactorial b/Lang/Java/Multifactorial new file mode 120000 index 0000000000..8d507de263 --- /dev/null +++ b/Lang/Java/Multifactorial @@ -0,0 +1 @@ +../../Task/Multifactorial/Java \ No newline at end of file diff --git a/Lang/Java/Multisplit b/Lang/Java/Multisplit new file mode 120000 index 0000000000..985b3e04a3 --- /dev/null +++ b/Lang/Java/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Java \ No newline at end of file diff --git a/Lang/Java/Nautical-bell b/Lang/Java/Nautical-bell new file mode 120000 index 0000000000..b7cc69a5bf --- /dev/null +++ b/Lang/Java/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Java \ No newline at end of file diff --git a/Lang/Java/Non-continuous-subsequences b/Lang/Java/Non-continuous-subsequences new file mode 120000 index 0000000000..505c46b977 --- /dev/null +++ b/Lang/Java/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Java \ No newline at end of file diff --git a/Lang/Java/Parallel-calculations b/Lang/Java/Parallel-calculations new file mode 120000 index 0000000000..b3890f468c --- /dev/null +++ b/Lang/Java/Parallel-calculations @@ -0,0 +1 @@ +../../Task/Parallel-calculations/Java \ No newline at end of file diff --git a/Lang/Java/Parsing-RPN-to-infix-conversion b/Lang/Java/Parsing-RPN-to-infix-conversion new file mode 120000 index 0000000000..2161559f05 --- /dev/null +++ b/Lang/Java/Parsing-RPN-to-infix-conversion @@ -0,0 +1 @@ +../../Task/Parsing-RPN-to-infix-conversion/Java \ No newline at end of file diff --git a/Lang/Java/Parsing-Shunting-yard-algorithm b/Lang/Java/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..6b77078078 --- /dev/null +++ b/Lang/Java/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/Java \ No newline at end of file diff --git a/Lang/Java/Pinstripe-Display b/Lang/Java/Pinstripe-Display new file mode 120000 index 0000000000..2d04e02613 --- /dev/null +++ b/Lang/Java/Pinstripe-Display @@ -0,0 +1 @@ +../../Task/Pinstripe-Display/Java \ No newline at end of file diff --git a/Lang/Java/Self-referential-sequence b/Lang/Java/Self-referential-sequence new file mode 120000 index 0000000000..856eca7283 --- /dev/null +++ b/Lang/Java/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/Java \ No newline at end of file diff --git a/Lang/Java/Sierpinski-triangle-Graphical b/Lang/Java/Sierpinski-triangle-Graphical new file mode 120000 index 0000000000..0cbc80c17f --- /dev/null +++ b/Lang/Java/Sierpinski-triangle-Graphical @@ -0,0 +1 @@ +../../Task/Sierpinski-triangle-Graphical/Java \ No newline at end of file diff --git a/Lang/Java/Simple-database b/Lang/Java/Simple-database new file mode 120000 index 0000000000..5c51f0e444 --- /dev/null +++ b/Lang/Java/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Java \ No newline at end of file diff --git a/Lang/Java/Solve-a-Hidato-puzzle b/Lang/Java/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..a45118e569 --- /dev/null +++ b/Lang/Java/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Java \ No newline at end of file diff --git a/Lang/Java/String-comparison b/Lang/Java/String-comparison new file mode 120000 index 0000000000..cc9412964f --- /dev/null +++ b/Lang/Java/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Java \ No newline at end of file diff --git a/Lang/Java/Strip-control-codes-and-extended-characters-from-a-string b/Lang/Java/Strip-control-codes-and-extended-characters-from-a-string new file mode 120000 index 0000000000..664542eb28 --- /dev/null +++ b/Lang/Java/Strip-control-codes-and-extended-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-control-codes-and-extended-characters-from-a-string/Java \ No newline at end of file diff --git a/Lang/Java/Sutherland-Hodgman-polygon-clipping b/Lang/Java/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..8140770702 --- /dev/null +++ b/Lang/Java/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Java \ No newline at end of file diff --git a/Lang/Java/Terminal-control-Clear-the-screen b/Lang/Java/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..bfc1e3a4a4 --- /dev/null +++ b/Lang/Java/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Java \ No newline at end of file diff --git a/Lang/Java/Text-processing-1 b/Lang/Java/Text-processing-1 new file mode 120000 index 0000000000..ee81b36d58 --- /dev/null +++ b/Lang/Java/Text-processing-1 @@ -0,0 +1 @@ +../../Task/Text-processing-1/Java \ No newline at end of file diff --git a/Lang/Java/Top-rank-per-group b/Lang/Java/Top-rank-per-group new file mode 120000 index 0000000000..140959a49b --- /dev/null +++ b/Lang/Java/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Java \ No newline at end of file diff --git a/Lang/Java/Update-a-configuration-file b/Lang/Java/Update-a-configuration-file new file mode 120000 index 0000000000..c2fee7ae3b --- /dev/null +++ b/Lang/Java/Update-a-configuration-file @@ -0,0 +1 @@ +../../Task/Update-a-configuration-file/Java \ No newline at end of file diff --git a/Lang/Java/Visualize-a-tree b/Lang/Java/Visualize-a-tree new file mode 120000 index 0000000000..be6868c13f --- /dev/null +++ b/Lang/Java/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Java \ No newline at end of file diff --git a/Lang/Java/Window-management b/Lang/Java/Window-management new file mode 120000 index 0000000000..42b78feb0a --- /dev/null +++ b/Lang/Java/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Java \ No newline at end of file diff --git a/Lang/Java/Zebra-puzzle b/Lang/Java/Zebra-puzzle new file mode 120000 index 0000000000..8a12408004 --- /dev/null +++ b/Lang/Java/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Java \ No newline at end of file diff --git a/Lang/JavaScript/Death-Star b/Lang/JavaScript/Death-Star new file mode 120000 index 0000000000..8f08a85f00 --- /dev/null +++ b/Lang/JavaScript/Death-Star @@ -0,0 +1 @@ +../../Task/Death-Star/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Digital-root b/Lang/JavaScript/Digital-root new file mode 120000 index 0000000000..832a097481 --- /dev/null +++ b/Lang/JavaScript/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Draw-a-sphere b/Lang/JavaScript/Draw-a-sphere new file mode 120000 index 0000000000..32684447fb --- /dev/null +++ b/Lang/JavaScript/Draw-a-sphere @@ -0,0 +1 @@ +../../Task/Draw-a-sphere/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Empty-string b/Lang/JavaScript/Empty-string new file mode 120000 index 0000000000..2298128732 --- /dev/null +++ b/Lang/JavaScript/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Entropy b/Lang/JavaScript/Entropy new file mode 120000 index 0000000000..b2b4bd462a --- /dev/null +++ b/Lang/JavaScript/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Euler-method b/Lang/JavaScript/Euler-method new file mode 120000 index 0000000000..077a07b77d --- /dev/null +++ b/Lang/JavaScript/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Fast-Fourier-transform b/Lang/JavaScript/Fast-Fourier-transform new file mode 120000 index 0000000000..8452dd261c --- /dev/null +++ b/Lang/JavaScript/Fast-Fourier-transform @@ -0,0 +1 @@ +../../Task/Fast-Fourier-transform/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Gamma-function b/Lang/JavaScript/Gamma-function new file mode 120000 index 0000000000..c605e118f3 --- /dev/null +++ b/Lang/JavaScript/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Handle-a-signal b/Lang/JavaScript/Handle-a-signal new file mode 120000 index 0000000000..32380cc6c2 --- /dev/null +++ b/Lang/JavaScript/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Haversine-formula b/Lang/JavaScript/Haversine-formula new file mode 120000 index 0000000000..75a1659275 --- /dev/null +++ b/Lang/JavaScript/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Identity-matrix b/Lang/JavaScript/Identity-matrix new file mode 120000 index 0000000000..be9619120a --- /dev/null +++ b/Lang/JavaScript/Identity-matrix @@ -0,0 +1 @@ +../../Task/Identity-matrix/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Knapsack-problem-0-1 b/Lang/JavaScript/Knapsack-problem-0-1 new file mode 120000 index 0000000000..a543919d4d --- /dev/null +++ b/Lang/JavaScript/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Parsing-Shunting-yard-algorithm b/Lang/JavaScript/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..59545e27fe --- /dev/null +++ b/Lang/JavaScript/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Roots-of-a-function b/Lang/JavaScript/Roots-of-a-function new file mode 120000 index 0000000000..d0f4f2f26b --- /dev/null +++ b/Lang/JavaScript/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Unicode-variable-names b/Lang/JavaScript/Unicode-variable-names new file mode 120000 index 0000000000..563a119ca0 --- /dev/null +++ b/Lang/JavaScript/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/JavaScript \ No newline at end of file diff --git a/Lang/JavaScript/Web-scraping b/Lang/JavaScript/Web-scraping new file mode 120000 index 0000000000..d5364f887e --- /dev/null +++ b/Lang/JavaScript/Web-scraping @@ -0,0 +1 @@ +../../Task/Web-scraping/JavaScript \ No newline at end of file diff --git a/Lang/Jcon/00DESCRIPTION b/Lang/Jcon/00DESCRIPTION index 3323aaf226..e69de29bb2 100644 --- a/Lang/Jcon/00DESCRIPTION +++ b/Lang/Jcon/00DESCRIPTION @@ -1,28 +0,0 @@ -{{Stub}} -{{language|Jcon -|site=http://www.cs.arizona.edu/icon/jcon/ -|exec=bytecode -|parampass=value -|strength=strong -|safety=safe -|express=implicit -|checking=dynamic -|gc=yes -|LCT=yes -}} -{{virtual machine}} -{{language programming paradigm|Procedural}} -{{language programming paradigm|Dynamic}} -{{language programming paradigm|Object-oriented}} -{{language programming paradigm|Logic_Programming}} - -Jcon is a Java-based implementation of the Icon programming language. The Jcon translator, written in Icon, generates Java class files that execute in conjunction with a run-time system written in Java. - -Version 2 of Jcon is an essentially complete implementation of Icon, including graphics and large integers. A few minor features are missing -- mostly things like chdir() that cannot be done in Java. - -Jcon is currently not being developed. - -== Related == -* [[:Icon]] -* [[:ObjectIcon]] -* [[:Unicon]] \ No newline at end of file diff --git a/Lang/Julia/Arithmetic-Integer b/Lang/Julia/Arithmetic-Integer new file mode 120000 index 0000000000..16e0b2de4e --- /dev/null +++ b/Lang/Julia/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Julia \ No newline at end of file diff --git a/Lang/Julia/Associative-array-Creation b/Lang/Julia/Associative-array-Creation new file mode 120000 index 0000000000..a3a42e553c --- /dev/null +++ b/Lang/Julia/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Julia \ No newline at end of file diff --git a/Lang/Julia/Averages-Pythagorean-means b/Lang/Julia/Averages-Pythagorean-means new file mode 120000 index 0000000000..0a2f4e8b0d --- /dev/null +++ b/Lang/Julia/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Julia \ No newline at end of file diff --git a/Lang/Julia/Averages-Simple-moving-average b/Lang/Julia/Averages-Simple-moving-average new file mode 120000 index 0000000000..8f1ed7b153 --- /dev/null +++ b/Lang/Julia/Averages-Simple-moving-average @@ -0,0 +1 @@ +../../Task/Averages-Simple-moving-average/Julia \ No newline at end of file diff --git a/Lang/Julia/Combinations-with-repetitions b/Lang/Julia/Combinations-with-repetitions new file mode 120000 index 0000000000..0d938d4f0c --- /dev/null +++ b/Lang/Julia/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Julia \ No newline at end of file diff --git a/Lang/Julia/Conways-Game-of-Life b/Lang/Julia/Conways-Game-of-Life new file mode 120000 index 0000000000..5b0aa8af55 --- /dev/null +++ b/Lang/Julia/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Julia \ No newline at end of file diff --git a/Lang/Julia/Entropy b/Lang/Julia/Entropy new file mode 120000 index 0000000000..77fd8d4e96 --- /dev/null +++ b/Lang/Julia/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Julia \ No newline at end of file diff --git a/Lang/Julia/Ethiopian-multiplication b/Lang/Julia/Ethiopian-multiplication new file mode 120000 index 0000000000..e2c7939b0a --- /dev/null +++ b/Lang/Julia/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Julia \ No newline at end of file diff --git a/Lang/Julia/Generator-Exponential b/Lang/Julia/Generator-Exponential new file mode 120000 index 0000000000..97f72dbcc8 --- /dev/null +++ b/Lang/Julia/Generator-Exponential @@ -0,0 +1 @@ +../../Task/Generator-Exponential/Julia \ No newline at end of file diff --git a/Lang/Julia/Hamming-numbers b/Lang/Julia/Hamming-numbers new file mode 120000 index 0000000000..4ec4d3b46d --- /dev/null +++ b/Lang/Julia/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Horners-rule-for-polynomial-evaluation b/Lang/Julia/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..340245ebf7 --- /dev/null +++ b/Lang/Julia/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/Julia \ No newline at end of file diff --git a/Lang/Julia/Integer-comparison b/Lang/Julia/Integer-comparison new file mode 120000 index 0000000000..549f01d3ce --- /dev/null +++ b/Lang/Julia/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Julia \ No newline at end of file diff --git a/Lang/Julia/Introspection b/Lang/Julia/Introspection new file mode 120000 index 0000000000..e20f355e1e --- /dev/null +++ b/Lang/Julia/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/Julia \ No newline at end of file diff --git a/Lang/Julia/Kaprekar-numbers b/Lang/Julia/Kaprekar-numbers new file mode 120000 index 0000000000..f91605cd5a --- /dev/null +++ b/Lang/Julia/Kaprekar-numbers @@ -0,0 +1 @@ +../../Task/Kaprekar-numbers/Julia \ No newline at end of file diff --git a/Lang/Julia/Letter-frequency b/Lang/Julia/Letter-frequency new file mode 120000 index 0000000000..a89d6489dd --- /dev/null +++ b/Lang/Julia/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Julia \ No newline at end of file diff --git a/Lang/Julia/Levenshtein-distance b/Lang/Julia/Levenshtein-distance new file mode 120000 index 0000000000..53afa495f8 --- /dev/null +++ b/Lang/Julia/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Julia \ No newline at end of file diff --git a/Lang/Julia/Literals-Integer b/Lang/Julia/Literals-Integer new file mode 120000 index 0000000000..5b0a4f27aa --- /dev/null +++ b/Lang/Julia/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Julia \ No newline at end of file diff --git a/Lang/Julia/Loops-N-plus-one-half b/Lang/Julia/Loops-N-plus-one-half new file mode 120000 index 0000000000..d2860236ec --- /dev/null +++ b/Lang/Julia/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Julia \ No newline at end of file diff --git a/Lang/Julia/Minesweeper-game b/Lang/Julia/Minesweeper-game new file mode 120000 index 0000000000..6a669157c3 --- /dev/null +++ b/Lang/Julia/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/Julia \ No newline at end of file diff --git a/Lang/Julia/Parsing-RPN-calculator-algorithm b/Lang/Julia/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..d1de1bff74 --- /dev/null +++ b/Lang/Julia/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/Julia \ No newline at end of file diff --git a/Lang/Julia/Seven-sided-dice-from-five-sided-dice b/Lang/Julia/Seven-sided-dice-from-five-sided-dice new file mode 120000 index 0000000000..4aaebd23fc --- /dev/null +++ b/Lang/Julia/Seven-sided-dice-from-five-sided-dice @@ -0,0 +1 @@ +../../Task/Seven-sided-dice-from-five-sided-dice/Julia \ No newline at end of file diff --git a/Lang/Julia/Sierpinski-carpet b/Lang/Julia/Sierpinski-carpet new file mode 120000 index 0000000000..22909bb054 --- /dev/null +++ b/Lang/Julia/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Julia \ No newline at end of file diff --git a/Lang/Julia/Special-variables b/Lang/Julia/Special-variables new file mode 120000 index 0000000000..c1d92caa17 --- /dev/null +++ b/Lang/Julia/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Julia \ No newline at end of file diff --git a/Lang/Julia/Truncate-a-file b/Lang/Julia/Truncate-a-file new file mode 120000 index 0000000000..e455e2cc7f --- /dev/null +++ b/Lang/Julia/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Julia \ No newline at end of file diff --git a/Lang/Julia/Y-combinator b/Lang/Julia/Y-combinator new file mode 120000 index 0000000000..c818781cf7 --- /dev/null +++ b/Lang/Julia/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/Julia \ No newline at end of file diff --git a/Lang/Kotlin/00DESCRIPTION b/Lang/Kotlin/00DESCRIPTION index 202a571401..9031d39e4d 100644 --- a/Lang/Kotlin/00DESCRIPTION +++ b/Lang/Kotlin/00DESCRIPTION @@ -1,3 +1,3 @@ {{language |checking=static -|site=http://confluence.jetbrains.net/display/Kotlin/Welcome}}Kotlin is the codename for a statically-typed [[JVM]]-targeted programming language developed by JetBrains and intended for industrial use. \ No newline at end of file +|site=http://kotlinlang.org}}Kotlin is the codename for a statically-typed [[JVM]]-targeted programming language developed by JetBrains and intended for industrial use. \ No newline at end of file diff --git a/Lang/LOLCODE/Loops-Infinite b/Lang/LOLCODE/Loops-Infinite new file mode 120000 index 0000000000..3faeeb018e --- /dev/null +++ b/Lang/LOLCODE/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/LOLCODE \ No newline at end of file diff --git a/Lang/Liberty-BASIC/LZW-compression b/Lang/Liberty-BASIC/LZW-compression new file mode 120000 index 0000000000..126875ba14 --- /dev/null +++ b/Lang/Liberty-BASIC/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/Liberty-BASIC \ No newline at end of file diff --git a/Lang/Logo/Averages-Mean-angle b/Lang/Logo/Averages-Mean-angle new file mode 120000 index 0000000000..0b38fe48f8 --- /dev/null +++ b/Lang/Logo/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Logo \ No newline at end of file diff --git a/Lang/Logo/Langtons-ant b/Lang/Logo/Langtons-ant new file mode 120000 index 0000000000..071b4934a7 --- /dev/null +++ b/Lang/Logo/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Logo \ No newline at end of file diff --git a/Lang/Logo/Sum-digits-of-an-integer b/Lang/Logo/Sum-digits-of-an-integer new file mode 120000 index 0000000000..eb4d8f6f34 --- /dev/null +++ b/Lang/Logo/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Logo \ No newline at end of file diff --git a/Lang/Lua/00DESCRIPTION b/Lang/Lua/00DESCRIPTION index 8b27c1bfda..e9733dd4e8 100644 --- a/Lang/Lua/00DESCRIPTION +++ b/Lang/Lua/00DESCRIPTION @@ -7,11 +7,15 @@ |gc=yes |site=http://www.lua.org |LCT=yes -|bnf=http://www.lua.org/manual/5.1/manual.html}}{{Codepad}}{{language programming paradigm|Object-oriented}}The Lua (pronounced LOO-ah) [[programming language]] is a lightweight, [[reflective programming|reflective]], [[imperative programming|imperative]] and [[procedural programming|procedural]] language, designed as a scripting language with extensible semantics as a primary goal. The name is derived from the Portuguese word for moon. +|bnf=http://www.lua.org/manual/5.1/manual.html}}{{Codepad}}{{CompileOnline}}{{language programming paradigm|Object-oriented}}The Lua (pronounced LOO-ah) [[programming language]] is a lightweight, [[reflective programming|reflective]], [[imperative programming|imperative]] and [[procedural programming|procedural]] language, designed as a scripting language with extensible semantics as a primary goal. +The name is derived from the Portuguese word for moon. -Lua is commonly described as a "multi-[[:Category:Programming Paradigms|paradigm]]" language, providing a small set of general features that can be extended to fit different problem types, rather than providing a more complex and rigid specification to match a single paradigm. Lua, for instance, does not contain explicit support for inheritance, but allows it to be implemented relatively easily with metatables. Similarly, Lua allows programmers to implement namespaces, classes, and other related features using its single table implementation; first class functions allow the employment of many powerful techniques from functional programming; and full lexical scoping allows fine-grained information hiding to enforce the principle of least privilege. +Lua is commonly described as a "multi-[[:Category:Programming Paradigms|paradigm]]" language, providing a small set of general features that can be extended to fit different problem types, rather than providing a more complex and rigid specification to match a single paradigm. +Lua, for instance, does not contain explicit support for inheritance, but allows it to be implemented relatively easily with metatables. +Similarly, Lua allows programmers to implement namespaces, classes, and other related features using its single table implementation; first class functions allow the employment of many powerful techniques from functional programming; and full lexical scoping allows fine-grained information hiding to enforce the principle of least privilege. -In general, Lua strives to provide flexible meta-features that can be extended as needed, rather than supply a feature-set specific to one programming paradigm. As a result, the base language is light—in fact, the full reference interpreter is only about 150KB compiled—and easily adaptable to a broad range of applications. +In general, Lua strives to provide flexible meta-features that can be extended as needed, rather than supply a feature-set specific to one programming paradigm. +As a result, the base language is light—in fact, the full reference interpreter is only about 150KB compiled—and easily adaptable to a broad range of applications. ==Citations== * [[wp:Lua_%28programming_language%29|Wikipedia:Lua (programming language)]] \ No newline at end of file diff --git a/Lang/Lua/Arithmetic-geometric-mean b/Lang/Lua/Arithmetic-geometric-mean new file mode 120000 index 0000000000..296a6979f7 --- /dev/null +++ b/Lang/Lua/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Lua \ No newline at end of file diff --git a/Lang/Lua/Call-a-foreign-language-function b/Lang/Lua/Call-a-foreign-language-function new file mode 120000 index 0000000000..525492bad3 --- /dev/null +++ b/Lang/Lua/Call-a-foreign-language-function @@ -0,0 +1 @@ +../../Task/Call-a-foreign-language-function/Lua \ No newline at end of file diff --git a/Lang/Lua/Combinations-with-repetitions b/Lang/Lua/Combinations-with-repetitions new file mode 120000 index 0000000000..a37f944281 --- /dev/null +++ b/Lang/Lua/Combinations-with-repetitions @@ -0,0 +1 @@ +../../Task/Combinations-with-repetitions/Lua \ No newline at end of file diff --git a/Lang/Lua/Digital-root b/Lang/Lua/Digital-root new file mode 120000 index 0000000000..44bd99e3cb --- /dev/null +++ b/Lang/Lua/Digital-root @@ -0,0 +1 @@ +../../Task/Digital-root/Lua \ No newline at end of file diff --git a/Lang/Lua/Forest-fire b/Lang/Lua/Forest-fire new file mode 120000 index 0000000000..60e6c3f1d4 --- /dev/null +++ b/Lang/Lua/Forest-fire @@ -0,0 +1 @@ +../../Task/Forest-fire/Lua \ No newline at end of file diff --git a/Lang/Lua/JSON b/Lang/Lua/JSON new file mode 120000 index 0000000000..e4555a1ec3 --- /dev/null +++ b/Lang/Lua/JSON @@ -0,0 +1 @@ +../../Task/JSON/Lua \ No newline at end of file diff --git a/Lang/Lua/Langtons-ant b/Lang/Lua/Langtons-ant new file mode 120000 index 0000000000..c8f5f4815c --- /dev/null +++ b/Lang/Lua/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Lua \ No newline at end of file diff --git a/Lang/Lua/Largest-int-from-concatenated-ints b/Lang/Lua/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..c4c2ceb5e9 --- /dev/null +++ b/Lang/Lua/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Lua \ No newline at end of file diff --git a/Lang/Lua/Longest-string-challenge b/Lang/Lua/Longest-string-challenge new file mode 120000 index 0000000000..26c6d3b030 --- /dev/null +++ b/Lang/Lua/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Lua \ No newline at end of file diff --git a/Lang/Lua/Maze-generation b/Lang/Lua/Maze-generation new file mode 120000 index 0000000000..5dd7c62383 --- /dev/null +++ b/Lang/Lua/Maze-generation @@ -0,0 +1 @@ +../../Task/Maze-generation/Lua \ No newline at end of file diff --git a/Lang/Lua/Order-two-numerical-lists b/Lang/Lua/Order-two-numerical-lists new file mode 120000 index 0000000000..a71688ebe3 --- /dev/null +++ b/Lang/Lua/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Lua \ No newline at end of file diff --git a/Lang/Lua/Partial-function-application b/Lang/Lua/Partial-function-application new file mode 120000 index 0000000000..75e619642d --- /dev/null +++ b/Lang/Lua/Partial-function-application @@ -0,0 +1 @@ +../../Task/Partial-function-application/Lua \ No newline at end of file diff --git a/Lang/Lua/Priority-queue b/Lang/Lua/Priority-queue new file mode 120000 index 0000000000..49364499d6 --- /dev/null +++ b/Lang/Lua/Priority-queue @@ -0,0 +1 @@ +../../Task/Priority-queue/Lua \ No newline at end of file diff --git a/Lang/Lua/Range-expansion b/Lang/Lua/Range-expansion new file mode 120000 index 0000000000..b6a4c1129a --- /dev/null +++ b/Lang/Lua/Range-expansion @@ -0,0 +1 @@ +../../Task/Range-expansion/Lua \ No newline at end of file diff --git a/Lang/Lua/Read-a-specific-line-from-a-file b/Lang/Lua/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..85afd13753 --- /dev/null +++ b/Lang/Lua/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Lua \ No newline at end of file diff --git a/Lang/Lua/Sorting-algorithms-Sleep-sort b/Lang/Lua/Sorting-algorithms-Sleep-sort new file mode 120000 index 0000000000..cd569a4210 --- /dev/null +++ b/Lang/Lua/Sorting-algorithms-Sleep-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Sleep-sort/Lua \ No newline at end of file diff --git a/Lang/Lua/Special-variables b/Lang/Lua/Special-variables new file mode 120000 index 0000000000..ffdefa8b6e --- /dev/null +++ b/Lang/Lua/Special-variables @@ -0,0 +1 @@ +../../Task/Special-variables/Lua \ No newline at end of file diff --git a/Lang/Lua/Standard-deviation b/Lang/Lua/Standard-deviation new file mode 120000 index 0000000000..f40b48ac97 --- /dev/null +++ b/Lang/Lua/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Lua \ No newline at end of file diff --git a/Lang/Lua/String-concatenation b/Lang/Lua/String-concatenation new file mode 120000 index 0000000000..88ad441c36 --- /dev/null +++ b/Lang/Lua/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Lua \ No newline at end of file diff --git a/Lang/Lua/Sum-digits-of-an-integer b/Lang/Lua/Sum-digits-of-an-integer new file mode 120000 index 0000000000..5544a3f5ac --- /dev/null +++ b/Lang/Lua/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Lua \ No newline at end of file diff --git a/Lang/Lua/Temperature-conversion b/Lang/Lua/Temperature-conversion new file mode 120000 index 0000000000..d2181303ef --- /dev/null +++ b/Lang/Lua/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Lua \ No newline at end of file diff --git a/Lang/Lua/Van-der-Corput-sequence b/Lang/Lua/Van-der-Corput-sequence new file mode 120000 index 0000000000..051e76971d --- /dev/null +++ b/Lang/Lua/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Lua \ No newline at end of file diff --git a/Lang/Lua/Word-wrap b/Lang/Lua/Word-wrap new file mode 120000 index 0000000000..be6d4f37cc --- /dev/null +++ b/Lang/Lua/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Lua \ No newline at end of file diff --git a/Lang/Lush/Fibonacci-sequence b/Lang/Lush/Fibonacci-sequence new file mode 120000 index 0000000000..c2da700d49 --- /dev/null +++ b/Lang/Lush/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Lush \ No newline at end of file diff --git a/Lang/M4/A+B b/Lang/M4/A+B new file mode 120000 index 0000000000..fd36994d00 --- /dev/null +++ b/Lang/M4/A+B @@ -0,0 +1 @@ +../../Task/A+B/M4 \ No newline at end of file diff --git a/Lang/M4/Even-or-odd b/Lang/M4/Even-or-odd new file mode 120000 index 0000000000..1892364386 --- /dev/null +++ b/Lang/M4/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/M4 \ No newline at end of file diff --git a/Lang/M4/Read-entire-file b/Lang/M4/Read-entire-file new file mode 120000 index 0000000000..f36d6c262d --- /dev/null +++ b/Lang/M4/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/M4 \ No newline at end of file diff --git a/Lang/MATLAB/00DESCRIPTION b/Lang/MATLAB/00DESCRIPTION index 9d74762049..ab092f4c25 100644 --- a/Lang/MATLAB/00DESCRIPTION +++ b/Lang/MATLAB/00DESCRIPTION @@ -2,4 +2,10 @@ |site=http://www.mathworks.com/products/matlab/ |checking=dynamic}} +From [[wp:MATLAB]]: +:MATLAB ('''mat'''rix '''lab'''oratory) is a multi-paradigm +:numerical computing environment and fourth-generation programming language, +:developed by MathWorks. +Not to be confused with MATHLAB. + [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/MATLAB/Bulls-and-cows b/Lang/MATLAB/Bulls-and-cows new file mode 120000 index 0000000000..e426af7e72 --- /dev/null +++ b/Lang/MATLAB/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Bulls-and-cows-Player b/Lang/MATLAB/Bulls-and-cows-Player new file mode 120000 index 0000000000..fda993ec90 --- /dev/null +++ b/Lang/MATLAB/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Element-wise-operations b/Lang/MATLAB/Element-wise-operations new file mode 120000 index 0000000000..72154455a1 --- /dev/null +++ b/Lang/MATLAB/Element-wise-operations @@ -0,0 +1 @@ +../../Task/Element-wise-operations/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Gray-code b/Lang/MATLAB/Gray-code new file mode 120000 index 0000000000..1d5ca0db8e --- /dev/null +++ b/Lang/MATLAB/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Guess-the-number-With-feedback--player- b/Lang/MATLAB/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..fecf0e5bed --- /dev/null +++ b/Lang/MATLAB/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Hamming-numbers b/Lang/MATLAB/Hamming-numbers new file mode 120000 index 0000000000..53c2bda849 --- /dev/null +++ b/Lang/MATLAB/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Handle-a-signal b/Lang/MATLAB/Handle-a-signal new file mode 120000 index 0000000000..96ccd33b45 --- /dev/null +++ b/Lang/MATLAB/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Happy-numbers b/Lang/MATLAB/Happy-numbers new file mode 120000 index 0000000000..22de2bed7c --- /dev/null +++ b/Lang/MATLAB/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Hash-from-two-arrays b/Lang/MATLAB/Hash-from-two-arrays new file mode 120000 index 0000000000..41182f518c --- /dev/null +++ b/Lang/MATLAB/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Honeycombs b/Lang/MATLAB/Honeycombs new file mode 120000 index 0000000000..e5170092ce --- /dev/null +++ b/Lang/MATLAB/Honeycombs @@ -0,0 +1 @@ +../../Task/Honeycombs/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Image-convolution b/Lang/MATLAB/Image-convolution new file mode 120000 index 0000000000..3420fab928 --- /dev/null +++ b/Lang/MATLAB/Image-convolution @@ -0,0 +1 @@ +../../Task/Image-convolution/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Minesweeper-game b/Lang/MATLAB/Minesweeper-game new file mode 120000 index 0000000000..03cc5a1275 --- /dev/null +++ b/Lang/MATLAB/Minesweeper-game @@ -0,0 +1 @@ +../../Task/Minesweeper-game/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Number-reversal-game b/Lang/MATLAB/Number-reversal-game new file mode 120000 index 0000000000..97f81c9b0e --- /dev/null +++ b/Lang/MATLAB/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Perfect-numbers b/Lang/MATLAB/Perfect-numbers new file mode 120000 index 0000000000..bd23b38c9a --- /dev/null +++ b/Lang/MATLAB/Perfect-numbers @@ -0,0 +1 @@ +../../Task/Perfect-numbers/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Probabilistic-choice b/Lang/MATLAB/Probabilistic-choice new file mode 120000 index 0000000000..e0095398a7 --- /dev/null +++ b/Lang/MATLAB/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Runtime-evaluation b/Lang/MATLAB/Runtime-evaluation new file mode 120000 index 0000000000..b70c92a9ba --- /dev/null +++ b/Lang/MATLAB/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Runtime-evaluation-In-an-environment b/Lang/MATLAB/Runtime-evaluation-In-an-environment new file mode 120000 index 0000000000..c3d357e806 --- /dev/null +++ b/Lang/MATLAB/Runtime-evaluation-In-an-environment @@ -0,0 +1 @@ +../../Task/Runtime-evaluation-In-an-environment/MATLAB \ No newline at end of file diff --git a/Lang/MATLAB/Tic-tac-toe b/Lang/MATLAB/Tic-tac-toe new file mode 120000 index 0000000000..102c0d42aa --- /dev/null +++ b/Lang/MATLAB/Tic-tac-toe @@ -0,0 +1 @@ +../../Task/Tic-tac-toe/MATLAB \ No newline at end of file diff --git a/Lang/MAXScript/Animation b/Lang/MAXScript/Animation new file mode 120000 index 0000000000..f39f68e63b --- /dev/null +++ b/Lang/MAXScript/Animation @@ -0,0 +1 @@ +../../Task/Animation/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Averages-Root-mean-square b/Lang/MAXScript/Averages-Root-mean-square new file mode 120000 index 0000000000..5300dc2cff --- /dev/null +++ b/Lang/MAXScript/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Bulls-and-cows b/Lang/MAXScript/Bulls-and-cows new file mode 120000 index 0000000000..c00df09a31 --- /dev/null +++ b/Lang/MAXScript/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Factors-of-an-integer b/Lang/MAXScript/Factors-of-an-integer new file mode 120000 index 0000000000..7851aa3e69 --- /dev/null +++ b/Lang/MAXScript/Factors-of-an-integer @@ -0,0 +1 @@ +../../Task/Factors-of-an-integer/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Greyscale-bars-Display b/Lang/MAXScript/Greyscale-bars-Display new file mode 120000 index 0000000000..e144e3fc30 --- /dev/null +++ b/Lang/MAXScript/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Guess-the-number b/Lang/MAXScript/Guess-the-number new file mode 120000 index 0000000000..eca3638298 --- /dev/null +++ b/Lang/MAXScript/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Guess-the-number-With-feedback b/Lang/MAXScript/Guess-the-number-With-feedback new file mode 120000 index 0000000000..7c1d957793 --- /dev/null +++ b/Lang/MAXScript/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Guess-the-number-With-feedback--player- b/Lang/MAXScript/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..b87421a20a --- /dev/null +++ b/Lang/MAXScript/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Happy-numbers b/Lang/MAXScript/Happy-numbers new file mode 120000 index 0000000000..2457e271ca --- /dev/null +++ b/Lang/MAXScript/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Image-noise b/Lang/MAXScript/Image-noise new file mode 120000 index 0000000000..bbbd8c47fc --- /dev/null +++ b/Lang/MAXScript/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Knapsack-problem-0-1 b/Lang/MAXScript/Knapsack-problem-0-1 new file mode 120000 index 0000000000..535765ef84 --- /dev/null +++ b/Lang/MAXScript/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Loops-Break b/Lang/MAXScript/Loops-Break new file mode 120000 index 0000000000..5d7094f940 --- /dev/null +++ b/Lang/MAXScript/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Loops-For-with-a-specified-step b/Lang/MAXScript/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..b239bfe456 --- /dev/null +++ b/Lang/MAXScript/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Loops-Nested b/Lang/MAXScript/Loops-Nested new file mode 120000 index 0000000000..209e845e5b --- /dev/null +++ b/Lang/MAXScript/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Mouse-position b/Lang/MAXScript/Mouse-position new file mode 120000 index 0000000000..e6decbef36 --- /dev/null +++ b/Lang/MAXScript/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Regular-expressions b/Lang/MAXScript/Regular-expressions new file mode 120000 index 0000000000..986f567f98 --- /dev/null +++ b/Lang/MAXScript/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Comb-sort b/Lang/MAXScript/Sorting-algorithms-Comb-sort new file mode 120000 index 0000000000..5729e80573 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Comb-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Comb-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Counting-sort b/Lang/MAXScript/Sorting-algorithms-Counting-sort new file mode 120000 index 0000000000..aeeeddee9a --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Counting-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Counting-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Gnome-sort b/Lang/MAXScript/Sorting-algorithms-Gnome-sort new file mode 120000 index 0000000000..b06373f451 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Gnome-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Gnome-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Heapsort b/Lang/MAXScript/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..33a72deb01 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Insertion-sort b/Lang/MAXScript/Sorting-algorithms-Insertion-sort new file mode 120000 index 0000000000..62be3c45b1 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Insertion-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Insertion-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Merge-sort b/Lang/MAXScript/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..0e358a8529 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Pancake-sort b/Lang/MAXScript/Sorting-algorithms-Pancake-sort new file mode 120000 index 0000000000..25de9bb56d --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Pancake-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Pancake-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Permutation-sort b/Lang/MAXScript/Sorting-algorithms-Permutation-sort new file mode 120000 index 0000000000..2b527f1dce --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Permutation-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Permutation-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Stooge-sort b/Lang/MAXScript/Sorting-algorithms-Stooge-sort new file mode 120000 index 0000000000..51867189b9 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Stooge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Stooge-sort/MAXScript \ No newline at end of file diff --git a/Lang/MAXScript/Sorting-algorithms-Strand-sort b/Lang/MAXScript/Sorting-algorithms-Strand-sort new file mode 120000 index 0000000000..99da32ade8 --- /dev/null +++ b/Lang/MAXScript/Sorting-algorithms-Strand-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Strand-sort/MAXScript \ No newline at end of file diff --git a/Lang/MS-SQL/00DESCRIPTION b/Lang/MS-SQL/00DESCRIPTION index f66cf163bf..e69de29bb2 100644 --- a/Lang/MS-SQL/00DESCRIPTION +++ b/Lang/MS-SQL/00DESCRIPTION @@ -1 +0,0 @@ -{{language}}{{stub}} \ No newline at end of file diff --git a/Lang/MSSQL/00DESCRIPTION b/Lang/MSSQL/00DESCRIPTION index f66cf163bf..e69de29bb2 100644 --- a/Lang/MSSQL/00DESCRIPTION +++ b/Lang/MSSQL/00DESCRIPTION @@ -1 +0,0 @@ -{{language}}{{stub}} \ No newline at end of file diff --git a/Lang/Make/00DESCRIPTION b/Lang/Make/00DESCRIPTION index e141acd329..ba6324d2da 100644 --- a/Lang/Make/00DESCRIPTION +++ b/Lang/Make/00DESCRIPTION @@ -1 +1,16 @@ -{{language}}One of the mini-languages of [[UNIX]]. It is Turing complete if recursive invocation is allowed. \ No newline at end of file +{{language}} +'''Make''' is one of the mini-languages of [[UNIX]]. + +It is Turing complete if recursive invocation is allowed. + +[[wp:Make (software)|Make]] is normally used to automate +the process of building software-projects,
+i.e. the steps to compile, link, etc. + +;Similar programs: +* [[:Category:Apache Ant]] +* [[:Category:CMake]] +* SCons + + +[[Category:Utility]] \ No newline at end of file diff --git a/Lang/Make/Environment-variables b/Lang/Make/Environment-variables new file mode 120000 index 0000000000..6e00c129da --- /dev/null +++ b/Lang/Make/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Make \ No newline at end of file diff --git a/Lang/Make/Read-entire-file b/Lang/Make/Read-entire-file new file mode 120000 index 0000000000..f1dbce0df1 --- /dev/null +++ b/Lang/Make/Read-entire-file @@ -0,0 +1 @@ +../../Task/Read-entire-file/Make \ No newline at end of file diff --git a/Lang/Maple/Averages-Mode b/Lang/Maple/Averages-Mode new file mode 120000 index 0000000000..569e33caad --- /dev/null +++ b/Lang/Maple/Averages-Mode @@ -0,0 +1 @@ +../../Task/Averages-Mode/Maple \ No newline at end of file diff --git a/Lang/Maple/Averages-Pythagorean-means b/Lang/Maple/Averages-Pythagorean-means new file mode 120000 index 0000000000..28c4f1e23a --- /dev/null +++ b/Lang/Maple/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Maple \ No newline at end of file diff --git a/Lang/Maple/Averages-Root-mean-square b/Lang/Maple/Averages-Root-mean-square new file mode 120000 index 0000000000..432cf2bc05 --- /dev/null +++ b/Lang/Maple/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Maple \ No newline at end of file diff --git a/Lang/Maple/Call-a-function b/Lang/Maple/Call-a-function new file mode 120000 index 0000000000..fee9814272 --- /dev/null +++ b/Lang/Maple/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Maple \ No newline at end of file diff --git a/Lang/Maple/Call-an-object-method b/Lang/Maple/Call-an-object-method new file mode 120000 index 0000000000..01a087b5bc --- /dev/null +++ b/Lang/Maple/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Maple \ No newline at end of file diff --git a/Lang/Maple/Catalan-numbers b/Lang/Maple/Catalan-numbers new file mode 120000 index 0000000000..f0414ec27e --- /dev/null +++ b/Lang/Maple/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Maple \ No newline at end of file diff --git a/Lang/Maple/Collections b/Lang/Maple/Collections new file mode 120000 index 0000000000..d7e5a05a0b --- /dev/null +++ b/Lang/Maple/Collections @@ -0,0 +1 @@ +../../Task/Collections/Maple \ No newline at end of file diff --git a/Lang/Maple/Combinations b/Lang/Maple/Combinations new file mode 120000 index 0000000000..8d39c8f183 --- /dev/null +++ b/Lang/Maple/Combinations @@ -0,0 +1 @@ +../../Task/Combinations/Maple \ No newline at end of file diff --git a/Lang/Maple/Constrained-random-points-on-a-circle b/Lang/Maple/Constrained-random-points-on-a-circle new file mode 120000 index 0000000000..e68af9cc6d --- /dev/null +++ b/Lang/Maple/Constrained-random-points-on-a-circle @@ -0,0 +1 @@ +../../Task/Constrained-random-points-on-a-circle/Maple \ No newline at end of file diff --git a/Lang/Maple/Create-a-file b/Lang/Maple/Create-a-file new file mode 120000 index 0000000000..54eed0fc52 --- /dev/null +++ b/Lang/Maple/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Maple \ No newline at end of file diff --git a/Lang/Maple/Delete-a-file b/Lang/Maple/Delete-a-file new file mode 120000 index 0000000000..e2e52948cc --- /dev/null +++ b/Lang/Maple/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Maple \ No newline at end of file diff --git a/Lang/Maple/Empty-string b/Lang/Maple/Empty-string new file mode 120000 index 0000000000..4d620d5448 --- /dev/null +++ b/Lang/Maple/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Maple \ No newline at end of file diff --git a/Lang/Maple/Even-or-odd b/Lang/Maple/Even-or-odd new file mode 120000 index 0000000000..974d790c65 --- /dev/null +++ b/Lang/Maple/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Maple \ No newline at end of file diff --git a/Lang/Maple/FizzBuzz b/Lang/Maple/FizzBuzz new file mode 120000 index 0000000000..6ada5cf583 --- /dev/null +++ b/Lang/Maple/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Maple \ No newline at end of file diff --git a/Lang/Maple/HTTPS b/Lang/Maple/HTTPS new file mode 120000 index 0000000000..6b15fc73dd --- /dev/null +++ b/Lang/Maple/HTTPS @@ -0,0 +1 @@ +../../Task/HTTPS/Maple \ No newline at end of file diff --git a/Lang/Maple/Hash-from-two-arrays b/Lang/Maple/Hash-from-two-arrays new file mode 120000 index 0000000000..76d753a16a --- /dev/null +++ b/Lang/Maple/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Maple \ No newline at end of file diff --git a/Lang/Maple/Loops-N-plus-one-half b/Lang/Maple/Loops-N-plus-one-half new file mode 120000 index 0000000000..58b85a5dfc --- /dev/null +++ b/Lang/Maple/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Maple \ No newline at end of file diff --git a/Lang/Maple/MD5 b/Lang/Maple/MD5 new file mode 120000 index 0000000000..18f82d3b84 --- /dev/null +++ b/Lang/Maple/MD5 @@ -0,0 +1 @@ +../../Task/MD5/Maple \ No newline at end of file diff --git a/Lang/Maple/Memory-allocation b/Lang/Maple/Memory-allocation new file mode 120000 index 0000000000..36f0b73fbd --- /dev/null +++ b/Lang/Maple/Memory-allocation @@ -0,0 +1 @@ +../../Task/Memory-allocation/Maple \ No newline at end of file diff --git a/Lang/Maple/Multiplicative-order b/Lang/Maple/Multiplicative-order new file mode 120000 index 0000000000..7f79cd4077 --- /dev/null +++ b/Lang/Maple/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Maple \ No newline at end of file diff --git a/Lang/Maple/Optional-parameters b/Lang/Maple/Optional-parameters new file mode 120000 index 0000000000..589f94992f --- /dev/null +++ b/Lang/Maple/Optional-parameters @@ -0,0 +1 @@ +../../Task/Optional-parameters/Maple \ No newline at end of file diff --git a/Lang/Maple/Roman-numerals-Encode b/Lang/Maple/Roman-numerals-Encode new file mode 120000 index 0000000000..885cfdb453 --- /dev/null +++ b/Lang/Maple/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/Maple \ No newline at end of file diff --git a/Lang/Maple/Shell-one-liner b/Lang/Maple/Shell-one-liner new file mode 120000 index 0000000000..2b0f4890c3 --- /dev/null +++ b/Lang/Maple/Shell-one-liner @@ -0,0 +1 @@ +../../Task/Shell-one-liner/Maple \ No newline at end of file diff --git a/Lang/Maple/Stem-and-leaf-plot b/Lang/Maple/Stem-and-leaf-plot new file mode 120000 index 0000000000..a5ef13a4b1 --- /dev/null +++ b/Lang/Maple/Stem-and-leaf-plot @@ -0,0 +1 @@ +../../Task/Stem-and-leaf-plot/Maple \ No newline at end of file diff --git a/Lang/Maple/String-length b/Lang/Maple/String-length new file mode 120000 index 0000000000..7cab7624af --- /dev/null +++ b/Lang/Maple/String-length @@ -0,0 +1 @@ +../../Task/String-length/Maple \ No newline at end of file diff --git a/Lang/Maple/Strip-comments-from-a-string b/Lang/Maple/Strip-comments-from-a-string new file mode 120000 index 0000000000..adbcc455c3 --- /dev/null +++ b/Lang/Maple/Strip-comments-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-comments-from-a-string/Maple \ No newline at end of file diff --git a/Lang/Maple/Substring b/Lang/Maple/Substring new file mode 120000 index 0000000000..fef68965fa --- /dev/null +++ b/Lang/Maple/Substring @@ -0,0 +1 @@ +../../Task/Substring/Maple \ No newline at end of file diff --git a/Lang/Maple/Symmetric-difference b/Lang/Maple/Symmetric-difference new file mode 120000 index 0000000000..37e1e3ace0 --- /dev/null +++ b/Lang/Maple/Symmetric-difference @@ -0,0 +1 @@ +../../Task/Symmetric-difference/Maple \ No newline at end of file diff --git a/Lang/Maple/Ternary-logic b/Lang/Maple/Ternary-logic new file mode 120000 index 0000000000..e04e2f1449 --- /dev/null +++ b/Lang/Maple/Ternary-logic @@ -0,0 +1 @@ +../../Task/Ternary-logic/Maple \ No newline at end of file diff --git a/Lang/Maple/Trigonometric-functions b/Lang/Maple/Trigonometric-functions new file mode 120000 index 0000000000..6c43dd3ce4 --- /dev/null +++ b/Lang/Maple/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Maple \ No newline at end of file diff --git a/Lang/Maple/URL-decoding b/Lang/Maple/URL-decoding new file mode 120000 index 0000000000..41332c6105 --- /dev/null +++ b/Lang/Maple/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/Maple \ No newline at end of file diff --git a/Lang/Maple/URL-encoding b/Lang/Maple/URL-encoding new file mode 120000 index 0000000000..ae1490e758 --- /dev/null +++ b/Lang/Maple/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Maple \ No newline at end of file diff --git a/Lang/Mathematica/00DESCRIPTION b/Lang/Mathematica/00DESCRIPTION index c3b8387364..82337908b1 100644 --- a/Lang/Mathematica/00DESCRIPTION +++ b/Lang/Mathematica/00DESCRIPTION @@ -3,7 +3,7 @@ |strength=strong |checking=dynamic |gc=yes -|LCT=yes}}{{implementation|Mathematica}}{{language programming paradigm|Declarative}}{{language programming paradigm|Functional}} -Mathematica is the name of Wolfram Research's mathematics analysis tool, as well as the name of the principal language used to control it. +|LCT=yes}}{{implementation|Wolfram Language}}{{language programming paradigm|Declarative}}{{language programming paradigm|Functional}} +Mathematica is a computational software program developed by [http://wolfram.com Wolfram Research]. It is used in many scientific, engineering, mathematical and computing fields, and is based on symbolic mathematics. [[Wolfram Language]] is the primary programming language of Mathematica. [[Category:Mathematical programming languages]] \ No newline at end of file diff --git a/Lang/Mathematica/Abstract-type b/Lang/Mathematica/Abstract-type new file mode 120000 index 0000000000..40cfc83c99 --- /dev/null +++ b/Lang/Mathematica/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Globally-replace-text-in-several-files b/Lang/Mathematica/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..416f7078d0 --- /dev/null +++ b/Lang/Mathematica/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Huffman-coding b/Lang/Mathematica/Huffman-coding new file mode 120000 index 0000000000..742060f31d --- /dev/null +++ b/Lang/Mathematica/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/K-means++-clustering b/Lang/Mathematica/K-means++-clustering new file mode 120000 index 0000000000..6dfa618ca9 --- /dev/null +++ b/Lang/Mathematica/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Largest-int-from-concatenated-ints b/Lang/Mathematica/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..4157fdac88 --- /dev/null +++ b/Lang/Mathematica/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Mad-Libs b/Lang/Mathematica/Mad-Libs new file mode 120000 index 0000000000..351f7a8459 --- /dev/null +++ b/Lang/Mathematica/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Metaprogramming b/Lang/Mathematica/Metaprogramming new file mode 120000 index 0000000000..07708201fd --- /dev/null +++ b/Lang/Mathematica/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/One-of-n-lines-in-a-file b/Lang/Mathematica/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..26c7deac62 --- /dev/null +++ b/Lang/Mathematica/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Random-number-generator--device- b/Lang/Mathematica/Random-number-generator--device- new file mode 120000 index 0000000000..d4b294d49a --- /dev/null +++ b/Lang/Mathematica/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rate-counter b/Lang/Mathematica/Rate-counter new file mode 120000 index 0000000000..91db873313 --- /dev/null +++ b/Lang/Mathematica/Rate-counter @@ -0,0 +1 @@ +../../Task/Rate-counter/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Read-a-configuration-file b/Lang/Mathematica/Read-a-configuration-file new file mode 120000 index 0000000000..bbac6c878a --- /dev/null +++ b/Lang/Mathematica/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Remove-lines-from-a-file b/Lang/Mathematica/Remove-lines-from-a-file new file mode 120000 index 0000000000..ce784cd5f7 --- /dev/null +++ b/Lang/Mathematica/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks b/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks new file mode 120000 index 0000000000..5204326bff --- /dev/null +++ b/Lang/Mathematica/Rosetta-Code-Find-unimplemented-tasks @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Send-an-unknown-method-call b/Lang/Mathematica/Send-an-unknown-method-call new file mode 120000 index 0000000000..d76f44d4c1 --- /dev/null +++ b/Lang/Mathematica/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Set-of-real-numbers b/Lang/Mathematica/Set-of-real-numbers new file mode 120000 index 0000000000..37f17c44ff --- /dev/null +++ b/Lang/Mathematica/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Set-puzzle b/Lang/Mathematica/Set-puzzle new file mode 120000 index 0000000000..72e189c7ca --- /dev/null +++ b/Lang/Mathematica/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Sorting-algorithms-Radix-sort b/Lang/Mathematica/Sorting-algorithms-Radix-sort new file mode 120000 index 0000000000..12ece884c9 --- /dev/null +++ b/Lang/Mathematica/Sorting-algorithms-Radix-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Radix-sort/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/String-comparison b/Lang/Mathematica/String-comparison new file mode 120000 index 0000000000..8b75595d16 --- /dev/null +++ b/Lang/Mathematica/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Trabb-Pardo-Knuth-algorithm b/Lang/Mathematica/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..12c308ba12 --- /dev/null +++ b/Lang/Mathematica/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Universal-Turing-machine b/Lang/Mathematica/Universal-Turing-machine new file mode 120000 index 0000000000..af0b676960 --- /dev/null +++ b/Lang/Mathematica/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Vampire-number b/Lang/Mathematica/Vampire-number new file mode 120000 index 0000000000..fc4cfab75b --- /dev/null +++ b/Lang/Mathematica/Vampire-number @@ -0,0 +1 @@ +../../Task/Vampire-number/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Window-management b/Lang/Mathematica/Window-management new file mode 120000 index 0000000000..7569a38fd0 --- /dev/null +++ b/Lang/Mathematica/Window-management @@ -0,0 +1 @@ +../../Task/Window-management/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Word-wrap b/Lang/Mathematica/Word-wrap new file mode 120000 index 0000000000..4622080a76 --- /dev/null +++ b/Lang/Mathematica/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Mathematica \ No newline at end of file diff --git a/Lang/Mathematica/Zebra-puzzle b/Lang/Mathematica/Zebra-puzzle new file mode 120000 index 0000000000..95dba2ac86 --- /dev/null +++ b/Lang/Mathematica/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Mathematica \ No newline at end of file diff --git a/Lang/Maxima/Pick-random-element b/Lang/Maxima/Pick-random-element new file mode 120000 index 0000000000..83b7fcc151 --- /dev/null +++ b/Lang/Maxima/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Maxima \ No newline at end of file diff --git a/Lang/Mercury/Averages-Arithmetic-mean b/Lang/Mercury/Averages-Arithmetic-mean new file mode 120000 index 0000000000..2285590c07 --- /dev/null +++ b/Lang/Mercury/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Factorial b/Lang/Mercury/Factorial new file mode 120000 index 0000000000..ab33f29056 --- /dev/null +++ b/Lang/Mercury/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Flatten-a-list b/Lang/Mercury/Flatten-a-list new file mode 120000 index 0000000000..609d0bce21 --- /dev/null +++ b/Lang/Mercury/Flatten-a-list @@ -0,0 +1 @@ +../../Task/Flatten-a-list/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Greatest-common-divisor b/Lang/Mercury/Greatest-common-divisor new file mode 120000 index 0000000000..06cb1cc2ca --- /dev/null +++ b/Lang/Mercury/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Happy-numbers b/Lang/Mercury/Happy-numbers new file mode 120000 index 0000000000..8639dc8216 --- /dev/null +++ b/Lang/Mercury/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Literals-Integer b/Lang/Mercury/Literals-Integer new file mode 120000 index 0000000000..1bf14cddfe --- /dev/null +++ b/Lang/Mercury/Literals-Integer @@ -0,0 +1 @@ +../../Task/Literals-Integer/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Miller-Rabin-primality-test b/Lang/Mercury/Miller-Rabin-primality-test new file mode 120000 index 0000000000..6022def69b --- /dev/null +++ b/Lang/Mercury/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Program-name b/Lang/Mercury/Program-name new file mode 120000 index 0000000000..0f638f0312 --- /dev/null +++ b/Lang/Mercury/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Mercury \ No newline at end of file diff --git a/Lang/Mercury/String-length b/Lang/Mercury/String-length new file mode 120000 index 0000000000..bb4f55c22b --- /dev/null +++ b/Lang/Mercury/String-length @@ -0,0 +1 @@ +../../Task/String-length/Mercury \ No newline at end of file diff --git a/Lang/Mercury/Synchronous-concurrency b/Lang/Mercury/Synchronous-concurrency new file mode 120000 index 0000000000..687ae3fbd8 --- /dev/null +++ b/Lang/Mercury/Synchronous-concurrency @@ -0,0 +1 @@ +../../Task/Synchronous-concurrency/Mercury \ No newline at end of file diff --git a/Lang/Neko/Increment-a-numerical-string b/Lang/Neko/Increment-a-numerical-string new file mode 120000 index 0000000000..4bf568ddb3 --- /dev/null +++ b/Lang/Neko/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/Neko \ No newline at end of file diff --git a/Lang/NewLISP/Associative-array-Iteration b/Lang/NewLISP/Associative-array-Iteration new file mode 120000 index 0000000000..f6eb81d81c --- /dev/null +++ b/Lang/NewLISP/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Check-that-file-exists b/Lang/NewLISP/Check-that-file-exists new file mode 120000 index 0000000000..7d31c7ba47 --- /dev/null +++ b/Lang/NewLISP/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Delete-a-file b/Lang/NewLISP/Delete-a-file new file mode 120000 index 0000000000..15c26d6f37 --- /dev/null +++ b/Lang/NewLISP/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Even-or-odd b/Lang/NewLISP/Even-or-odd new file mode 120000 index 0000000000..839ec850da --- /dev/null +++ b/Lang/NewLISP/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Execute-a-system-command b/Lang/NewLISP/Execute-a-system-command new file mode 120000 index 0000000000..c57365052e --- /dev/null +++ b/Lang/NewLISP/Execute-a-system-command @@ -0,0 +1 @@ +../../Task/Execute-a-system-command/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/File-modification-time b/Lang/NewLISP/File-modification-time new file mode 120000 index 0000000000..f9d4d86a05 --- /dev/null +++ b/Lang/NewLISP/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/File-size b/Lang/NewLISP/File-size new file mode 120000 index 0000000000..0fc517e12f --- /dev/null +++ b/Lang/NewLISP/File-size @@ -0,0 +1 @@ +../../Task/File-size/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/FizzBuzz b/Lang/NewLISP/FizzBuzz new file mode 120000 index 0000000000..a18aba8c1e --- /dev/null +++ b/Lang/NewLISP/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Fork b/Lang/NewLISP/Fork new file mode 120000 index 0000000000..e2125625bb --- /dev/null +++ b/Lang/NewLISP/Fork @@ -0,0 +1 @@ +../../Task/Fork/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Generic-swap b/Lang/NewLISP/Generic-swap new file mode 120000 index 0000000000..0f3c9f39db --- /dev/null +++ b/Lang/NewLISP/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Handle-a-signal b/Lang/NewLISP/Handle-a-signal new file mode 120000 index 0000000000..44b13a4972 --- /dev/null +++ b/Lang/NewLISP/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Include-a-file b/Lang/NewLISP/Include-a-file new file mode 120000 index 0000000000..fe3e6fe78f --- /dev/null +++ b/Lang/NewLISP/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Increment-a-numerical-string b/Lang/NewLISP/Increment-a-numerical-string new file mode 120000 index 0000000000..0c6698257a --- /dev/null +++ b/Lang/NewLISP/Increment-a-numerical-string @@ -0,0 +1 @@ +../../Task/Increment-a-numerical-string/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Integer-sequence b/Lang/NewLISP/Integer-sequence new file mode 120000 index 0000000000..5163d2d7da --- /dev/null +++ b/Lang/NewLISP/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loop-over-multiple-arrays-simultaneously b/Lang/NewLISP/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..0d7e95eab7 --- /dev/null +++ b/Lang/NewLISP/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Break b/Lang/NewLISP/Loops-Break new file mode 120000 index 0000000000..fc989ac62c --- /dev/null +++ b/Lang/NewLISP/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Continue b/Lang/NewLISP/Loops-Continue new file mode 120000 index 0000000000..bd2e0c3620 --- /dev/null +++ b/Lang/NewLISP/Loops-Continue @@ -0,0 +1 @@ +../../Task/Loops-Continue/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Do-while b/Lang/NewLISP/Loops-Do-while new file mode 120000 index 0000000000..ada2440e46 --- /dev/null +++ b/Lang/NewLISP/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Downward-for b/Lang/NewLISP/Loops-Downward-for new file mode 120000 index 0000000000..17af7588a0 --- /dev/null +++ b/Lang/NewLISP/Loops-Downward-for @@ -0,0 +1 @@ +../../Task/Loops-Downward-for/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-For-with-a-specified-step b/Lang/NewLISP/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..54ca31d250 --- /dev/null +++ b/Lang/NewLISP/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Foreach b/Lang/NewLISP/Loops-Foreach new file mode 120000 index 0000000000..9ec7f6b6f8 --- /dev/null +++ b/Lang/NewLISP/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Infinite b/Lang/NewLISP/Loops-Infinite new file mode 120000 index 0000000000..5e4ecb0b7e --- /dev/null +++ b/Lang/NewLISP/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-N-plus-one-half b/Lang/NewLISP/Loops-N-plus-one-half new file mode 120000 index 0000000000..cde3a720e6 --- /dev/null +++ b/Lang/NewLISP/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-Nested b/Lang/NewLISP/Loops-Nested new file mode 120000 index 0000000000..8d9ec286af --- /dev/null +++ b/Lang/NewLISP/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Loops-While b/Lang/NewLISP/Loops-While new file mode 120000 index 0000000000..7fda9ed025 --- /dev/null +++ b/Lang/NewLISP/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/MD5 b/Lang/NewLISP/MD5 new file mode 120000 index 0000000000..9d54238c7f --- /dev/null +++ b/Lang/NewLISP/MD5 @@ -0,0 +1 @@ +../../Task/MD5/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Nth-root b/Lang/NewLISP/Nth-root new file mode 120000 index 0000000000..91ecf2a81a --- /dev/null +++ b/Lang/NewLISP/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Rot-13 b/Lang/NewLISP/Rot-13 new file mode 120000 index 0000000000..89d086aecb --- /dev/null +++ b/Lang/NewLISP/Rot-13 @@ -0,0 +1 @@ +../../Task/Rot-13/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/SHA-1 b/Lang/NewLISP/SHA-1 new file mode 120000 index 0000000000..b6804f126b --- /dev/null +++ b/Lang/NewLISP/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/SHA-256 b/Lang/NewLISP/SHA-256 new file mode 120000 index 0000000000..5b75019b39 --- /dev/null +++ b/Lang/NewLISP/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Singly-linked-list-Traversal b/Lang/NewLISP/Singly-linked-list-Traversal new file mode 120000 index 0000000000..b4810d2d71 --- /dev/null +++ b/Lang/NewLISP/Singly-linked-list-Traversal @@ -0,0 +1 @@ +../../Task/Singly-linked-list-Traversal/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/String-concatenation b/Lang/NewLISP/String-concatenation new file mode 120000 index 0000000000..b4f6c7c4ca --- /dev/null +++ b/Lang/NewLISP/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Strip-a-set-of-characters-from-a-string b/Lang/NewLISP/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..75ef050d6f --- /dev/null +++ b/Lang/NewLISP/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Strip-whitespace-from-a-string-Top-and-tail b/Lang/NewLISP/Strip-whitespace-from-a-string-Top-and-tail new file mode 120000 index 0000000000..cb3dfb8bac --- /dev/null +++ b/Lang/NewLISP/Strip-whitespace-from-a-string-Top-and-tail @@ -0,0 +1 @@ +../../Task/Strip-whitespace-from-a-string-Top-and-tail/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Substring-Top-and-tail b/Lang/NewLISP/Substring-Top-and-tail new file mode 120000 index 0000000000..d77c55fb09 --- /dev/null +++ b/Lang/NewLISP/Substring-Top-and-tail @@ -0,0 +1 @@ +../../Task/Substring-Top-and-tail/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Sum-and-product-of-an-array b/Lang/NewLISP/Sum-and-product-of-an-array new file mode 120000 index 0000000000..7a725e6659 --- /dev/null +++ b/Lang/NewLISP/Sum-and-product-of-an-array @@ -0,0 +1 @@ +../../Task/Sum-and-product-of-an-array/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Sum-of-a-series b/Lang/NewLISP/Sum-of-a-series new file mode 120000 index 0000000000..a77e94bc05 --- /dev/null +++ b/Lang/NewLISP/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/System-time b/Lang/NewLISP/System-time new file mode 120000 index 0000000000..f1beb6f7bc --- /dev/null +++ b/Lang/NewLISP/System-time @@ -0,0 +1 @@ +../../Task/System-time/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/Tokenize-a-string b/Lang/NewLISP/Tokenize-a-string new file mode 120000 index 0000000000..8f0f3c19b8 --- /dev/null +++ b/Lang/NewLISP/Tokenize-a-string @@ -0,0 +1 @@ +../../Task/Tokenize-a-string/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/URL-decoding b/Lang/NewLISP/URL-decoding new file mode 120000 index 0000000000..1ed09b8c3b --- /dev/null +++ b/Lang/NewLISP/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/NewLISP \ No newline at end of file diff --git a/Lang/NewLISP/URL-encoding b/Lang/NewLISP/URL-encoding new file mode 120000 index 0000000000..d80352a056 --- /dev/null +++ b/Lang/NewLISP/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/NewLISP \ No newline at end of file diff --git a/Lang/Nimrod/00DESCRIPTION b/Lang/Nimrod/00DESCRIPTION index ade96dbd09..a2dbb33327 100644 --- a/Lang/Nimrod/00DESCRIPTION +++ b/Lang/Nimrod/00DESCRIPTION @@ -1,13 +1 @@ -{{language -|exec=machine -|gc=yes -|parampass=both -|express=both -|strength=strong -|LCT=yes -|checking=static -|site=http://nimrod-lang.org}} -{{language programming paradigm|imperative}} -Nimrod is a general purpose, high-level, system programming, statically typed imperative compiled programming language that is developed by Andreas Rumpf. There is a lot of focus on portability and efficiency. The language compiles to C and supports many C compilers. Nimrod is actively being developed although it could use more developers, there is currently only one core developer. The language has excellent [http://nimrod-lang.org/lib.html documentation], and a very good [http://nimrod-lang.org/tut1.html tutorial]. - -You can ask for help on Freenode in the #nimrod channel. \ No newline at end of file +#REDIRECT [[:Category:Nim]] \ No newline at end of file diff --git a/Lang/OCaml/Box-the-compass b/Lang/OCaml/Box-the-compass new file mode 120000 index 0000000000..b88854aab5 --- /dev/null +++ b/Lang/OCaml/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Entropy b/Lang/OCaml/Entropy new file mode 120000 index 0000000000..0df0baf5cf --- /dev/null +++ b/Lang/OCaml/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Pig-the-dice-game b/Lang/OCaml/Pig-the-dice-game new file mode 120000 index 0000000000..f2951f0cee --- /dev/null +++ b/Lang/OCaml/Pig-the-dice-game @@ -0,0 +1 @@ +../../Task/Pig-the-dice-game/OCaml \ No newline at end of file diff --git a/Lang/OCaml/Temperature-conversion b/Lang/OCaml/Temperature-conversion new file mode 120000 index 0000000000..4a0b8b1550 --- /dev/null +++ b/Lang/OCaml/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/OCaml \ No newline at end of file diff --git a/Lang/OOC/99-Bottles-of-Beer b/Lang/OOC/99-Bottles-of-Beer new file mode 120000 index 0000000000..f89e468454 --- /dev/null +++ b/Lang/OOC/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/OOC \ No newline at end of file diff --git a/Lang/OOC/Ackermann-function b/Lang/OOC/Ackermann-function new file mode 120000 index 0000000000..80d8788e9f --- /dev/null +++ b/Lang/OOC/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/OOC \ No newline at end of file diff --git a/Lang/OOC/Arithmetic-geometric-mean b/Lang/OOC/Arithmetic-geometric-mean new file mode 120000 index 0000000000..94087a5d0e --- /dev/null +++ b/Lang/OOC/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/OOC \ No newline at end of file diff --git a/Lang/OOC/Caesar-cipher b/Lang/OOC/Caesar-cipher new file mode 120000 index 0000000000..049e73e32c --- /dev/null +++ b/Lang/OOC/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/OOC \ No newline at end of file diff --git a/Lang/OOC/Empty-program b/Lang/OOC/Empty-program new file mode 120000 index 0000000000..fd2806ad5b --- /dev/null +++ b/Lang/OOC/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/OOC \ No newline at end of file diff --git a/Lang/OOC/Even-or-odd b/Lang/OOC/Even-or-odd new file mode 120000 index 0000000000..adac46b36d --- /dev/null +++ b/Lang/OOC/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/OOC \ No newline at end of file diff --git a/Lang/OOC/Function-definition b/Lang/OOC/Function-definition new file mode 120000 index 0000000000..e6a56d654e --- /dev/null +++ b/Lang/OOC/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/OOC \ No newline at end of file diff --git a/Lang/OOC/Hello-world-Newline-omission b/Lang/OOC/Hello-world-Newline-omission new file mode 120000 index 0000000000..67077a3709 --- /dev/null +++ b/Lang/OOC/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/OOC \ No newline at end of file diff --git a/Lang/OOC/Logical-operations b/Lang/OOC/Logical-operations new file mode 120000 index 0000000000..4f74f4f24f --- /dev/null +++ b/Lang/OOC/Logical-operations @@ -0,0 +1 @@ +../../Task/Logical-operations/OOC \ No newline at end of file diff --git a/Lang/OOC/Loops-While b/Lang/OOC/Loops-While new file mode 120000 index 0000000000..be92ff7557 --- /dev/null +++ b/Lang/OOC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/OOC \ No newline at end of file diff --git a/Lang/OOC/Reverse-a-string b/Lang/OOC/Reverse-a-string new file mode 120000 index 0000000000..5c491c1532 --- /dev/null +++ b/Lang/OOC/Reverse-a-string @@ -0,0 +1 @@ +../../Task/Reverse-a-string/OOC \ No newline at end of file diff --git a/Lang/OOC/String-interpolation--included- b/Lang/OOC/String-interpolation--included- new file mode 120000 index 0000000000..629dc262b0 --- /dev/null +++ b/Lang/OOC/String-interpolation--included- @@ -0,0 +1 @@ +../../Task/String-interpolation--included-/OOC \ No newline at end of file diff --git a/Lang/Oberon-2/Abstract-type b/Lang/Oberon-2/Abstract-type new file mode 120000 index 0000000000..2b02bfc018 --- /dev/null +++ b/Lang/Oberon-2/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Align-columns b/Lang/Oberon-2/Align-columns new file mode 120000 index 0000000000..2a15708e01 --- /dev/null +++ b/Lang/Oberon-2/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Array-concatenation b/Lang/Oberon-2/Array-concatenation new file mode 120000 index 0000000000..55fd9ad881 --- /dev/null +++ b/Lang/Oberon-2/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Arrays b/Lang/Oberon-2/Arrays new file mode 120000 index 0000000000..aa6a0806f5 --- /dev/null +++ b/Lang/Oberon-2/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Associative-array-Creation b/Lang/Oberon-2/Associative-array-Creation new file mode 120000 index 0000000000..4d0ae24907 --- /dev/null +++ b/Lang/Oberon-2/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Associative-array-Iteration b/Lang/Oberon-2/Associative-array-Iteration new file mode 120000 index 0000000000..b1ede5dc83 --- /dev/null +++ b/Lang/Oberon-2/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Binary-digits b/Lang/Oberon-2/Binary-digits new file mode 120000 index 0000000000..0879b8be94 --- /dev/null +++ b/Lang/Oberon-2/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Boolean-values b/Lang/Oberon-2/Boolean-values new file mode 120000 index 0000000000..30e828e798 --- /dev/null +++ b/Lang/Oberon-2/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/CRC-32 b/Lang/Oberon-2/CRC-32 new file mode 120000 index 0000000000..0e9c2dd993 --- /dev/null +++ b/Lang/Oberon-2/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/CSV-to-HTML-translation b/Lang/Oberon-2/CSV-to-HTML-translation new file mode 120000 index 0000000000..8bf5a6e68c --- /dev/null +++ b/Lang/Oberon-2/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Caesar-cipher b/Lang/Oberon-2/Caesar-cipher new file mode 120000 index 0000000000..5027af823e --- /dev/null +++ b/Lang/Oberon-2/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Case-sensitivity-of-identifiers b/Lang/Oberon-2/Case-sensitivity-of-identifiers new file mode 120000 index 0000000000..6ff8c7916a --- /dev/null +++ b/Lang/Oberon-2/Case-sensitivity-of-identifiers @@ -0,0 +1 @@ +../../Task/Case-sensitivity-of-identifiers/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Comments b/Lang/Oberon-2/Comments new file mode 120000 index 0000000000..4fc76f301e --- /dev/null +++ b/Lang/Oberon-2/Comments @@ -0,0 +1 @@ +../../Task/Comments/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Compile-time-calculation b/Lang/Oberon-2/Compile-time-calculation new file mode 120000 index 0000000000..3aaee507e6 --- /dev/null +++ b/Lang/Oberon-2/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Greatest-common-divisor b/Lang/Oberon-2/Greatest-common-divisor new file mode 120000 index 0000000000..9b286b76f0 --- /dev/null +++ b/Lang/Oberon-2/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Greatest-element-of-a-list b/Lang/Oberon-2/Greatest-element-of-a-list new file mode 120000 index 0000000000..a3090d5fc6 --- /dev/null +++ b/Lang/Oberon-2/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Greatest-subsequential-sum b/Lang/Oberon-2/Greatest-subsequential-sum new file mode 120000 index 0000000000..cbbe0acbae --- /dev/null +++ b/Lang/Oberon-2/Greatest-subsequential-sum @@ -0,0 +1 @@ +../../Task/Greatest-subsequential-sum/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Guess-the-number b/Lang/Oberon-2/Guess-the-number new file mode 120000 index 0000000000..b87d2d6f3f --- /dev/null +++ b/Lang/Oberon-2/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Hash-from-two-arrays b/Lang/Oberon-2/Hash-from-two-arrays new file mode 120000 index 0000000000..88238b4b75 --- /dev/null +++ b/Lang/Oberon-2/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Haversine-formula b/Lang/Oberon-2/Haversine-formula new file mode 120000 index 0000000000..e4b84c1490 --- /dev/null +++ b/Lang/Oberon-2/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Hello-world-Newline-omission b/Lang/Oberon-2/Hello-world-Newline-omission new file mode 120000 index 0000000000..86d59439e7 --- /dev/null +++ b/Lang/Oberon-2/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Higher-order-functions b/Lang/Oberon-2/Higher-order-functions new file mode 120000 index 0000000000..910b4a39d3 --- /dev/null +++ b/Lang/Oberon-2/Higher-order-functions @@ -0,0 +1 @@ +../../Task/Higher-order-functions/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Hofstadter-Q-sequence b/Lang/Oberon-2/Hofstadter-Q-sequence new file mode 120000 index 0000000000..c892dfb2cc --- /dev/null +++ b/Lang/Oberon-2/Hofstadter-Q-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Q-sequence/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Hostname b/Lang/Oberon-2/Hostname new file mode 120000 index 0000000000..5dcc67942e --- /dev/null +++ b/Lang/Oberon-2/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Inheritance-Single b/Lang/Oberon-2/Inheritance-Single new file mode 120000 index 0000000000..63b26c7a68 --- /dev/null +++ b/Lang/Oberon-2/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Input-loop b/Lang/Oberon-2/Input-loop new file mode 120000 index 0000000000..8981a7348c --- /dev/null +++ b/Lang/Oberon-2/Input-loop @@ -0,0 +1 @@ +../../Task/Input-loop/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Integer-sequence b/Lang/Oberon-2/Integer-sequence new file mode 120000 index 0000000000..87e1ad4421 --- /dev/null +++ b/Lang/Oberon-2/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loop-over-multiple-arrays-simultaneously b/Lang/Oberon-2/Loop-over-multiple-arrays-simultaneously new file mode 120000 index 0000000000..6dbfef1d91 --- /dev/null +++ b/Lang/Oberon-2/Loop-over-multiple-arrays-simultaneously @@ -0,0 +1 @@ +../../Task/Loop-over-multiple-arrays-simultaneously/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loops-Break b/Lang/Oberon-2/Loops-Break new file mode 120000 index 0000000000..f18ab0c552 --- /dev/null +++ b/Lang/Oberon-2/Loops-Break @@ -0,0 +1 @@ +../../Task/Loops-Break/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loops-Do-while b/Lang/Oberon-2/Loops-Do-while new file mode 120000 index 0000000000..72585ba503 --- /dev/null +++ b/Lang/Oberon-2/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loops-For b/Lang/Oberon-2/Loops-For new file mode 120000 index 0000000000..78d87adbed --- /dev/null +++ b/Lang/Oberon-2/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loops-For-with-a-specified-step b/Lang/Oberon-2/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..08a87dce83 --- /dev/null +++ b/Lang/Oberon-2/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Loops-Infinite b/Lang/Oberon-2/Loops-Infinite new file mode 120000 index 0000000000..883b5afbfd --- /dev/null +++ b/Lang/Oberon-2/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Program-name b/Lang/Oberon-2/Program-name new file mode 120000 index 0000000000..feac2f24e0 --- /dev/null +++ b/Lang/Oberon-2/Program-name @@ -0,0 +1 @@ +../../Task/Program-name/Oberon-2 \ No newline at end of file diff --git a/Lang/Oberon-2/Program-termination b/Lang/Oberon-2/Program-termination new file mode 120000 index 0000000000..8785cd08e9 --- /dev/null +++ b/Lang/Oberon-2/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Oberon-2 \ No newline at end of file diff --git a/Lang/Objeck/00DESCRIPTION b/Lang/Objeck/00DESCRIPTION index 1669baa9f6..b26ec9f064 100644 --- a/Lang/Objeck/00DESCRIPTION +++ b/Lang/Objeck/00DESCRIPTION @@ -1,6 +1,6 @@ {{language|Objeck |exec=bytecode -|site=http://sourceforge.net/projects/objeck-lang +|site=http://www.objeck.org |gc=yes |parampass=value |safety=safe @@ -13,4 +13,4 @@ The '''Objeck Programming Language''' is an [[object-oriented]] computing langua The programming environment consists of an optimizing compiler, virtual machine with associated [[Garbage collection|garbage collector]] and [[JIT]] compiler along with a command-line debugger. The compiler emits binary [[bytecode]] that is executed by the runtime system. The runtime system has the ability to translate the bytecode into AMD64 or IA-32 machine code on the fly. -For more information check out the [http://objeck-lang.sourceforge.net/guide Objeck Programmer's Guide] ([http://sourceforge.net/p/objeck-lang/code/HEAD/tree/main/docs/guide/objeck_lang.pdf?format=raw pdf]) or this YouTube [http://www.youtube.com/watch?v=Mk2Kfb-WESU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file +For more information check out the [http://www.objeck.org/docs/objeck_lang.pdf Programmer's Guide] or this YouTube [https://www.youtube.com/watch?v=IUaQYdw02TU video]. The language can be [http://sourceforge.net/projects/objeck-lang/files/ obtained] from the main project homepage. Also, check out the IRC channel #objeck on freenode.net. \ No newline at end of file diff --git a/Lang/Objeck/Averages-Pythagorean-means b/Lang/Objeck/Averages-Pythagorean-means new file mode 120000 index 0000000000..68937c8523 --- /dev/null +++ b/Lang/Objeck/Averages-Pythagorean-means @@ -0,0 +1 @@ +../../Task/Averages-Pythagorean-means/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Levenshtein-distance b/Lang/Objeck/Levenshtein-distance new file mode 120000 index 0000000000..632a5e45fd --- /dev/null +++ b/Lang/Objeck/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Nth-root b/Lang/Objeck/Nth-root new file mode 120000 index 0000000000..132bbb7ee9 --- /dev/null +++ b/Lang/Objeck/Nth-root @@ -0,0 +1 @@ +../../Task/Nth-root/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Count-examples b/Lang/Objeck/Rosetta-Code-Count-examples new file mode 120000 index 0000000000..2ab7a0001b --- /dev/null +++ b/Lang/Objeck/Rosetta-Code-Count-examples @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Count-examples/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity b/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity new file mode 120000 index 0000000000..da151e30b0 --- /dev/null +++ b/Lang/Objeck/Rosetta-Code-Rank-languages-by-popularity @@ -0,0 +1 @@ +../../Task/Rosetta-Code-Rank-languages-by-popularity/Objeck \ No newline at end of file diff --git a/Lang/Objeck/SQL-based-authentication b/Lang/Objeck/SQL-based-authentication new file mode 120000 index 0000000000..3e614987fa --- /dev/null +++ b/Lang/Objeck/SQL-based-authentication @@ -0,0 +1 @@ +../../Task/SQL-based-authentication/Objeck \ No newline at end of file diff --git a/Lang/Objeck/Sierpinski-carpet b/Lang/Objeck/Sierpinski-carpet new file mode 120000 index 0000000000..391c4d9a9c --- /dev/null +++ b/Lang/Objeck/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/Objeck \ No newline at end of file diff --git a/Lang/Objective-C/00DESCRIPTION b/Lang/Objective-C/00DESCRIPTION index 55349e5be3..f9d5d5e05a 100644 --- a/Lang/Objective-C/00DESCRIPTION +++ b/Lang/Objective-C/00DESCRIPTION @@ -14,4 +14,6 @@ As of October 2011, with the release of [http://developer.apple.com/library/ios/ The release of Xcode 4.4 (4.5 for iOS) added [http://clang.llvm.org/docs/ObjectiveCLiterals.html syntax to specify literals] for NSArray, NSDictionary, NSNumber, and NSString, as well as subscript syntax to access elements of NSArray and NSDictionary. Unless otherwise stated, Objective-C code samples will assume that they are compiled with ARC enabled, and that the compiler supports Objective-C literals and Blocks. + +For details of how to compile and run examples of Rosetta Code tasks written in Objective C under Linux or Windows see [http://www.gnu.org/software/gnustep/ GNUstep]
\ No newline at end of file diff --git a/Lang/Objective-C/100-doors b/Lang/Objective-C/100-doors new file mode 120000 index 0000000000..c571c6c81d --- /dev/null +++ b/Lang/Objective-C/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Enumerations b/Lang/Objective-C/Enumerations new file mode 120000 index 0000000000..5116318584 --- /dev/null +++ b/Lang/Objective-C/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Knuth-shuffle b/Lang/Objective-C/Knuth-shuffle new file mode 120000 index 0000000000..25bd806657 --- /dev/null +++ b/Lang/Objective-C/Knuth-shuffle @@ -0,0 +1 @@ +../../Task/Knuth-shuffle/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Number-names b/Lang/Objective-C/Number-names new file mode 120000 index 0000000000..f4b3509adb --- /dev/null +++ b/Lang/Objective-C/Number-names @@ -0,0 +1 @@ +../../Task/Number-names/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Range-extraction b/Lang/Objective-C/Range-extraction new file mode 120000 index 0000000000..39f9f863fd --- /dev/null +++ b/Lang/Objective-C/Range-extraction @@ -0,0 +1 @@ +../../Task/Range-extraction/Objective-C \ No newline at end of file diff --git a/Lang/Objective-C/Sorting-algorithms-Bubble-sort b/Lang/Objective-C/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..de0fbae717 --- /dev/null +++ b/Lang/Objective-C/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Objective-C \ No newline at end of file diff --git a/Lang/Octave/Resistor-mesh b/Lang/Octave/Resistor-mesh new file mode 120000 index 0000000000..7517e6e4cd --- /dev/null +++ b/Lang/Octave/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Octave \ No newline at end of file diff --git a/Lang/OoRexx/00DESCRIPTION b/Lang/OoRexx/00DESCRIPTION index f97c9111ee..8031f8ae00 100644 --- a/Lang/OoRexx/00DESCRIPTION +++ b/Lang/OoRexx/00DESCRIPTION @@ -5,7 +5,8 @@ {{implementation|REXX}} ooRexx (aka Open Object Rexx) is an object oriented successor of 'Classic' Rexx (another one is NetRexx). Both Open Object Rexx and NetRexx were created by IBM and are now, -open sourced, maintained by the Rexx Language Association. +open sourced, maintained by the [http://www.rexxla.org/ Rexx Language Association]. + ooRexx can be used to run many programs shown here in the [[REXX]] category. See http://rosettacode.org/wiki/Rosetta_Code:Village_Pump/Dialects#REXX.2C_ooRexx.2C_and_others diff --git a/Lang/OoRexx/Box-the-compass b/Lang/OoRexx/Box-the-compass new file mode 120000 index 0000000000..9b8e808eba --- /dev/null +++ b/Lang/OoRexx/Box-the-compass @@ -0,0 +1 @@ +../../Task/Box-the-compass/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Evolutionary-algorithm b/Lang/OoRexx/Evolutionary-algorithm new file mode 120000 index 0000000000..1f1c53519f --- /dev/null +++ b/Lang/OoRexx/Evolutionary-algorithm @@ -0,0 +1 @@ +../../Task/Evolutionary-algorithm/OoRexx \ No newline at end of file diff --git a/Lang/OoRexx/Loops-Nested b/Lang/OoRexx/Loops-Nested new file mode 120000 index 0000000000..a3488e5484 --- /dev/null +++ b/Lang/OoRexx/Loops-Nested @@ -0,0 +1 @@ +../../Task/Loops-Nested/OoRexx \ No newline at end of file diff --git a/Lang/Opa/00DESCRIPTION b/Lang/Opa/00DESCRIPTION index 55eed544fb..b4508579e9 100644 --- a/Lang/Opa/00DESCRIPTION +++ b/Lang/Opa/00DESCRIPTION @@ -1,4 +1,6 @@ {{stub}}{{language|Opa |site=http://opalang.org/ }} -Opa is an open source, simple and unified platform for writing web applications. \ No newline at end of file +Opa is an open source, simple and unified platform +for writing web applications:
+"The Opa Framework for JavaScript", "Rapid & Secure Web Development" \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Loops-Do-while b/Lang/OpenEdge-Progress/Loops-Do-while new file mode 120000 index 0000000000..91697554d7 --- /dev/null +++ b/Lang/OpenEdge-Progress/Loops-Do-while @@ -0,0 +1 @@ +../../Task/Loops-Do-while/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Luhn-test-of-credit-card-numbers b/Lang/OpenEdge-Progress/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..142f2a12bd --- /dev/null +++ b/Lang/OpenEdge-Progress/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/OpenEdge-Progress/Rename-a-file b/Lang/OpenEdge-Progress/Rename-a-file new file mode 120000 index 0000000000..e1e7492fe1 --- /dev/null +++ b/Lang/OpenEdge-Progress/Rename-a-file @@ -0,0 +1 @@ +../../Task/Rename-a-file/OpenEdge-Progress \ No newline at end of file diff --git a/Lang/Oz/Miller-Rabin-primality-test b/Lang/Oz/Miller-Rabin-primality-test new file mode 120000 index 0000000000..e6999d8858 --- /dev/null +++ b/Lang/Oz/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Oz \ No newline at end of file diff --git a/Lang/Oz/Primality-by-trial-division b/Lang/Oz/Primality-by-trial-division new file mode 120000 index 0000000000..f05da667e3 --- /dev/null +++ b/Lang/Oz/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Oz \ No newline at end of file diff --git a/Lang/PARI-GP/00DESCRIPTION b/Lang/PARI-GP/00DESCRIPTION index 8439a2fda6..74f2bf636c 100644 --- a/Lang/PARI-GP/00DESCRIPTION +++ b/Lang/PARI-GP/00DESCRIPTION @@ -32,13 +32,14 @@ Android phones and tablets can use [https://code.google.com/p/paridroid/ paridro 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 invoked with the wrapper function pari. -Finally, gp can be used online through [http://www.compileonline.com/execute_pari_online.php compile online] or the [https://cloud.sagemath.com/ SageMath cloud]. +Finally, gp can be used online through [http://www.compileonline.com/execute_pari_online.php compile online] or the [https://cloud.sagemath.com/ SageMath cloud] (see [http://youtu.be/CzB6T7Nvc-s How to use PARI/GP in the SageMathCloud]). == 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] * [http://go.helms-net.de/sw/paritty/pari_tty_einf_en.html Pari-tty] * [http://www.skalatan.de/pariguide/ pariGUIde] +* [https://github.com/baruchel/vim-notebook vim-notebook] If you want to write a program rather than script a calculator, many languages are supported: * [[C]]: PARI is written in C, so it's very easy to either write your own programs or extend gp using C. @@ -59,14 +60,17 @@ If you want to write a program rather than script a calculator, many languages a === Tutorials === *[http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.5.0/tutorial.pdf Official tutorial] by C. Batut, K. Belabas, D. Bernardi, H. Cohen, M. Olivier (52 pp., 2011) -* Class notes, parts [http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_01.pdf 1][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_02.pdf 2][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_03.pdf 3][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_04.pdf 4][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_05.pdf 5][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_sieve.pdf sieve] by Benjamin L. Levitt (41 pp., 2009) +*[http://www.math.psu.edu/wdb/467/pariinfo.pdf Beginning PARI Programming for CSE/MATH 467] by W. Dale Brownawell (7 pp., 2014) *[http://www.math.uiuc.edu/~r-ash/GPTutorial.pdf Tutorial] by Robert B. Ash (20 pp., 2007) *[http://www.math.umass.edu/~siman/09.791N/tutorial.pdf Tutorial] by Siman Wong (6 pp., 2009) *[http://www.math.uconn.edu/~kconrad/math5230f08/parihandout.pdf Introduction] by Keith Conrad (7 pp., 2008) *[http://www.linuxjournal.com/article/1068 The Pari Package On Linux], by Klaus-Peter Nischke (3 pp., 1995) -*[http://mvngu.wordpress.com/2008/08/01/parigp-programming-for-basic-cryptography/ PARI/GP programming for basic cryptography] by Minh Van Nguyen (appx. 3 pp., 2008) +*[http://mvngu.wordpress.com/2008/08/01/parigp-programming-for-basic-cryptography/ PARI/GP programming for basic cryptography] by Minh Van Nguyen (appx. 3 pp., 2008); also appears in an [https://bbuseruploads.s3.amazonaws.com/mvngu/www/downloads/2008-11-25_numtheory-crypto-gp.pdf?Signature=3c1KatVUdnnTc4lOtzpOgsJg6Fw%3D&Expires=1411628731&AWSAccessKeyId=0EMWEFSGA12Z1HF1TZ82 extended version] lacking a stable URL (9 pp., 2008) *[http://www.exploringbinary.com/exploring-binary-numbers-with-parigp-calculator/ Exploring binary numbers with PARI/GP calculator] by Rick Regan (appx. 4 pp., 2009) -*Video tutorials, parts [http://www.youtube.com/watch?v=0G-9JzlrzBM 1] [http://www.youtube.com/watch?v=d7i0rv59hns 2] [http://http://www.youtube.com/watch?v=wCyU2n-G-pk 3] [http://http://www.youtube.com/watch?v=WOCuBvK8O6Q 4] (appx. 20 minutes, 2011) +*Video tutorials, parts [http://www.youtube.com/watch?v=0G-9JzlrzBM 1] [http://www.youtube.com/watch?v=d7i0rv59hns 2] [http://www.youtube.com/watch?v=wCyU2n-G-pk 3] [http://www.youtube.com/watch?v=WOCuBvK8O6Q 4] (appx. 20 minutes, 2011) +*[http://w3.countnumber.de/fischer/res-ZT2007/PariByExample.pdf Erste Schritte mit PARI/GP] by Lars Fischer (13 pp., 2007; German) +*[http://www.maths.tcd.ie/~vlasenko/MA2316/ Class notes] including PARI/GP tutorial and sample code by Masha Vlasenko (2013) +* Class notes, parts [http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_01.pdf 1][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_02.pdf 2][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_03.pdf 3][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_04.pdf 4][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_05.pdf 5][http://myweb.csuchico.edu/~blevitt/math230/230coursedocs/230notes/230notes_sieve.pdf sieve] by Benjamin L. Levitt (41 pp., 2009; now offline?) === Papers on PARI/GP === * Bill Alombert, [http://www.math.u-bordeaux.fr/~allomber/darkpaper.pdf A new interpretor for PARI/GP], ''Journal de Théorie des Nombres de Bordeaux'' '''20''':3 (2008), pp. 531–541. (English) diff --git a/Lang/PARI-GP/Anonymous-recursion b/Lang/PARI-GP/Anonymous-recursion new file mode 120000 index 0000000000..9e5a3eaa14 --- /dev/null +++ b/Lang/PARI-GP/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Check-Machin-like-formulas b/Lang/PARI-GP/Check-Machin-like-formulas new file mode 120000 index 0000000000..689df3f7be --- /dev/null +++ b/Lang/PARI-GP/Check-Machin-like-formulas @@ -0,0 +1 @@ +../../Task/Check-Machin-like-formulas/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Count-occurrences-of-a-substring b/Lang/PARI-GP/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..3605019b4b --- /dev/null +++ b/Lang/PARI-GP/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Dragon-curve b/Lang/PARI-GP/Dragon-curve new file mode 120000 index 0000000000..ac2ec44ab8 --- /dev/null +++ b/Lang/PARI-GP/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Variable-length-quantity b/Lang/PARI-GP/Variable-length-quantity new file mode 120000 index 0000000000..7f2bde0c00 --- /dev/null +++ b/Lang/PARI-GP/Variable-length-quantity @@ -0,0 +1 @@ +../../Task/Variable-length-quantity/PARI-GP \ No newline at end of file diff --git a/Lang/PARI-GP/Y-combinator b/Lang/PARI-GP/Y-combinator new file mode 120000 index 0000000000..6d13aa645b --- /dev/null +++ b/Lang/PARI-GP/Y-combinator @@ -0,0 +1 @@ +../../Task/Y-combinator/PARI-GP \ No newline at end of file diff --git a/Lang/PHP/Self-describing-numbers b/Lang/PHP/Self-describing-numbers new file mode 120000 index 0000000000..738409a7f9 --- /dev/null +++ b/Lang/PHP/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/PHP \ No newline at end of file diff --git a/Lang/PHP/Terminal-control-Ringing-the-terminal-bell b/Lang/PHP/Terminal-control-Ringing-the-terminal-bell new file mode 120000 index 0000000000..c5cdfd292c --- /dev/null +++ b/Lang/PHP/Terminal-control-Ringing-the-terminal-bell @@ -0,0 +1 @@ +../../Task/Terminal-control-Ringing-the-terminal-bell/PHP \ No newline at end of file diff --git a/Lang/PHP/Tree-traversal b/Lang/PHP/Tree-traversal new file mode 120000 index 0000000000..8d58628a61 --- /dev/null +++ b/Lang/PHP/Tree-traversal @@ -0,0 +1 @@ +../../Task/Tree-traversal/PHP \ No newline at end of file diff --git a/Lang/PHP/Zeckendorf-number-representation b/Lang/PHP/Zeckendorf-number-representation new file mode 120000 index 0000000000..8bf6465832 --- /dev/null +++ b/Lang/PHP/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PHP \ No newline at end of file diff --git a/Lang/PL-I/00DESCRIPTION b/Lang/PL-I/00DESCRIPTION index fcaf6c6859..0d97a07077 100644 --- a/Lang/PL-I/00DESCRIPTION +++ b/Lang/PL-I/00DESCRIPTION @@ -1,6 +1,16 @@ {{stub}} {{language|PL/I +|exec=machine +|strength=strong +|safety=safe +|compat=nominative +|express=explicit +|checking=static +|parampass=both +|gc=no +|LCT=yes |tags=pli}} +{{language programming paradigm|Imperative}} PL/I is a general purpose programming language suitable for commercial, scientific, non-scientific, and system programming. @@ -11,6 +21,7 @@ It provides the following data types: * Binary integer, * Fixed-point decimal (with fractional part), * Fixed-point binary (that is, with fractional part), +* Pointers, * Character strings of two kinds: # fixed-length, and # varying-length. @@ -31,7 +42,7 @@ Multiple precisions are available for floating point: * 64 bits, and * 80 bits. -The language provides for static and dynamic arrays. Of the latter, there are automatic and controlled. +The language provides for static and dynamic arrays. Of the latter, there are automatic, controlled, and based. Controlled can be applied to any data type, including scalar, structure, as well as arrays. With controlled, a push-down and pop-up stack is automatically used. @@ -51,4 +62,6 @@ PL/I has built-in checking for such programmer conditions including Any of those may be enabled or disabled by the user. -When any of those conditions occurs, the user may trap them and recover from them and continue execution. \ No newline at end of file +When any of those conditions occurs, the user may trap them and recover from them and continue execution. + +PL/I has a unique and powerful pre-processor which is a subset of the full PL/I language so it can be used to perform source file inclusion, conditional compilation, and macro expansion. The pre-processor keywords are prefixed with %. \ No newline at end of file diff --git a/Lang/PL-I/Arithmetic-Rational b/Lang/PL-I/Arithmetic-Rational new file mode 120000 index 0000000000..0bbe27b50b --- /dev/null +++ b/Lang/PL-I/Arithmetic-Rational @@ -0,0 +1 @@ +../../Task/Arithmetic-Rational/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Averages-Mean-time-of-day b/Lang/PL-I/Averages-Mean-time-of-day new file mode 120000 index 0000000000..f0c38f4ff0 --- /dev/null +++ b/Lang/PL-I/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Enforced-immutability b/Lang/PL-I/Enforced-immutability new file mode 120000 index 0000000000..ac604e4179 --- /dev/null +++ b/Lang/PL-I/Enforced-immutability @@ -0,0 +1 @@ +../../Task/Enforced-immutability/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Entropy b/Lang/PL-I/Entropy new file mode 120000 index 0000000000..7d4853e5af --- /dev/null +++ b/Lang/PL-I/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Knapsack-problem-Continuous b/Lang/PL-I/Knapsack-problem-Continuous new file mode 120000 index 0000000000..213e01ccfb --- /dev/null +++ b/Lang/PL-I/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Levenshtein-distance b/Lang/PL-I/Levenshtein-distance new file mode 120000 index 0000000000..8fee9d4bf8 --- /dev/null +++ b/Lang/PL-I/Levenshtein-distance @@ -0,0 +1 @@ +../../Task/Levenshtein-distance/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Modular-inverse b/Lang/PL-I/Modular-inverse new file mode 120000 index 0000000000..91c668c6fb --- /dev/null +++ b/Lang/PL-I/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Order-two-numerical-lists b/Lang/PL-I/Order-two-numerical-lists new file mode 120000 index 0000000000..91f02dd968 --- /dev/null +++ b/Lang/PL-I/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sorting-algorithms-Bogosort b/Lang/PL-I/Sorting-algorithms-Bogosort new file mode 120000 index 0000000000..cf8a3bdf56 --- /dev/null +++ b/Lang/PL-I/Sorting-algorithms-Bogosort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bogosort/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Sudoku b/Lang/PL-I/Sudoku new file mode 120000 index 0000000000..f0c65888d5 --- /dev/null +++ b/Lang/PL-I/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/PL-I \ No newline at end of file diff --git a/Lang/PL-I/Take-notes-on-the-command-line b/Lang/PL-I/Take-notes-on-the-command-line new file mode 120000 index 0000000000..59c83dd7a1 --- /dev/null +++ b/Lang/PL-I/Take-notes-on-the-command-line @@ -0,0 +1 @@ +../../Task/Take-notes-on-the-command-line/PL-I \ No newline at end of file diff --git a/Lang/Pascal/Averages-Mean-angle b/Lang/Pascal/Averages-Mean-angle new file mode 120000 index 0000000000..3328f1a655 --- /dev/null +++ b/Lang/Pascal/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Conways-Game-of-Life b/Lang/Pascal/Conways-Game-of-Life new file mode 120000 index 0000000000..3589e94a36 --- /dev/null +++ b/Lang/Pascal/Conways-Game-of-Life @@ -0,0 +1 @@ +../../Task/Conways-Game-of-Life/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Entropy b/Lang/Pascal/Entropy new file mode 120000 index 0000000000..6061826b8b --- /dev/null +++ b/Lang/Pascal/Entropy @@ -0,0 +1 @@ +../../Task/Entropy/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Hailstone-sequence b/Lang/Pascal/Hailstone-sequence new file mode 120000 index 0000000000..839e8333ea --- /dev/null +++ b/Lang/Pascal/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Hamming-numbers b/Lang/Pascal/Hamming-numbers new file mode 120000 index 0000000000..351ec66101 --- /dev/null +++ b/Lang/Pascal/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Harshad-or-Niven-series b/Lang/Pascal/Harshad-or-Niven-series new file mode 120000 index 0000000000..8b2ea14fe7 --- /dev/null +++ b/Lang/Pascal/Harshad-or-Niven-series @@ -0,0 +1 @@ +../../Task/Harshad-or-Niven-series/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Hofstadter-Conway-$10,000-sequence b/Lang/Pascal/Hofstadter-Conway-$10,000-sequence new file mode 120000 index 0000000000..2077953e6e --- /dev/null +++ b/Lang/Pascal/Hofstadter-Conway-$10,000-sequence @@ -0,0 +1 @@ +../../Task/Hofstadter-Conway-$10,000-sequence/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Largest-int-from-concatenated-ints b/Lang/Pascal/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..27e1d54688 --- /dev/null +++ b/Lang/Pascal/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Man-or-boy-test b/Lang/Pascal/Man-or-boy-test new file mode 120000 index 0000000000..ec8d167806 --- /dev/null +++ b/Lang/Pascal/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Mandelbrot-set b/Lang/Pascal/Mandelbrot-set new file mode 120000 index 0000000000..07af9322f5 --- /dev/null +++ b/Lang/Pascal/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Random-numbers b/Lang/Pascal/Random-numbers new file mode 120000 index 0000000000..1b6560c91a --- /dev/null +++ b/Lang/Pascal/Random-numbers @@ -0,0 +1 @@ +../../Task/Random-numbers/Pascal \ No newline at end of file diff --git a/Lang/Pascal/SHA-1 b/Lang/Pascal/SHA-1 new file mode 120000 index 0000000000..7865e8b01c --- /dev/null +++ b/Lang/Pascal/SHA-1 @@ -0,0 +1 @@ +../../Task/SHA-1/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Spiral-matrix b/Lang/Pascal/Spiral-matrix new file mode 120000 index 0000000000..3df09d1d4a --- /dev/null +++ b/Lang/Pascal/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Standard-deviation b/Lang/Pascal/Standard-deviation new file mode 120000 index 0000000000..045fd07fd2 --- /dev/null +++ b/Lang/Pascal/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Sum-digits-of-an-integer b/Lang/Pascal/Sum-digits-of-an-integer new file mode 120000 index 0000000000..381166f705 --- /dev/null +++ b/Lang/Pascal/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Van-der-Corput-sequence b/Lang/Pascal/Van-der-Corput-sequence new file mode 120000 index 0000000000..7a341d0b4f --- /dev/null +++ b/Lang/Pascal/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Window-creation-X11 b/Lang/Pascal/Window-creation-X11 new file mode 120000 index 0000000000..7f4faf7704 --- /dev/null +++ b/Lang/Pascal/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Pascal \ No newline at end of file diff --git a/Lang/Pascal/Xiaolin-Wus-line-algorithm b/Lang/Pascal/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..cba741f83a --- /dev/null +++ b/Lang/Pascal/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Pascal \ No newline at end of file diff --git a/Lang/Perl-6/Cut-a-rectangle b/Lang/Perl-6/Cut-a-rectangle new file mode 120000 index 0000000000..a708ab535a --- /dev/null +++ b/Lang/Perl-6/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Events b/Lang/Perl-6/Events new file mode 120000 index 0000000000..48839047d0 --- /dev/null +++ b/Lang/Perl-6/Events @@ -0,0 +1 @@ +../../Task/Events/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/GUI-enabling-disabling-of-controls b/Lang/Perl-6/GUI-enabling-disabling-of-controls new file mode 120000 index 0000000000..8fa5df5b9d --- /dev/null +++ b/Lang/Perl-6/GUI-enabling-disabling-of-controls @@ -0,0 +1 @@ +../../Task/GUI-enabling-disabling-of-controls/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Handle-a-signal b/Lang/Perl-6/Handle-a-signal new file mode 120000 index 0000000000..32a973a31d --- /dev/null +++ b/Lang/Perl-6/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Image-noise b/Lang/Perl-6/Image-noise new file mode 120000 index 0000000000..9b5909e073 --- /dev/null +++ b/Lang/Perl-6/Image-noise @@ -0,0 +1 @@ +../../Task/Image-noise/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/K-means++-clustering b/Lang/Perl-6/K-means++-clustering new file mode 120000 index 0000000000..b7c2377f2e --- /dev/null +++ b/Lang/Perl-6/K-means++-clustering @@ -0,0 +1 @@ +../../Task/K-means++-clustering/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Simple-windowed-application b/Lang/Perl-6/Simple-windowed-application new file mode 120000 index 0000000000..cc98f56ce2 --- /dev/null +++ b/Lang/Perl-6/Simple-windowed-application @@ -0,0 +1 @@ +../../Task/Simple-windowed-application/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Speech-synthesis b/Lang/Perl-6/Speech-synthesis new file mode 120000 index 0000000000..26b17d630a --- /dev/null +++ b/Lang/Perl-6/Speech-synthesis @@ -0,0 +1 @@ +../../Task/Speech-synthesis/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Stable-marriage-problem b/Lang/Perl-6/Stable-marriage-problem new file mode 120000 index 0000000000..175dd66269 --- /dev/null +++ b/Lang/Perl-6/Stable-marriage-problem @@ -0,0 +1 @@ +../../Task/Stable-marriage-problem/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/User-input-Graphical b/Lang/Perl-6/User-input-Graphical new file mode 120000 index 0000000000..e14b1c806d --- /dev/null +++ b/Lang/Perl-6/User-input-Graphical @@ -0,0 +1 @@ +../../Task/User-input-Graphical/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Window-creation b/Lang/Perl-6/Window-creation new file mode 120000 index 0000000000..a461b138b0 --- /dev/null +++ b/Lang/Perl-6/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Perl-6 \ No newline at end of file diff --git a/Lang/Perl-6/Window-creation-X11 b/Lang/Perl-6/Window-creation-X11 new file mode 120000 index 0000000000..2ff418c059 --- /dev/null +++ b/Lang/Perl-6/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Perl-6 \ No newline at end of file diff --git a/Lang/Perl/Averages-Mean-angle b/Lang/Perl/Averages-Mean-angle new file mode 120000 index 0000000000..b9e93d7ff9 --- /dev/null +++ b/Lang/Perl/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Perl \ No newline at end of file diff --git a/Lang/Perl/Call-a-function b/Lang/Perl/Call-a-function new file mode 120000 index 0000000000..7bdde4b645 --- /dev/null +++ b/Lang/Perl/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Perl \ No newline at end of file diff --git a/Lang/Perl/Carmichael-3-strong-pseudoprimes b/Lang/Perl/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..ac8c5df5f5 --- /dev/null +++ b/Lang/Perl/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/Perl \ No newline at end of file diff --git a/Lang/Perl/Continued-fraction-Arithmetic-Construct-from-rational-number b/Lang/Perl/Continued-fraction-Arithmetic-Construct-from-rational-number new file mode 120000 index 0000000000..8cbe69bcca --- /dev/null +++ b/Lang/Perl/Continued-fraction-Arithmetic-Construct-from-rational-number @@ -0,0 +1 @@ +../../Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Perl \ No newline at end of file diff --git a/Lang/Perl/Cut-a-rectangle b/Lang/Perl/Cut-a-rectangle new file mode 120000 index 0000000000..4bd9d70ccf --- /dev/null +++ b/Lang/Perl/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Perl \ No newline at end of file diff --git a/Lang/Perl/Dinesmans-multiple-dwelling-problem b/Lang/Perl/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..d3ce4a73f7 --- /dev/null +++ b/Lang/Perl/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Perl \ No newline at end of file diff --git a/Lang/Perl/Discordian-date b/Lang/Perl/Discordian-date new file mode 120000 index 0000000000..a758d2be1d --- /dev/null +++ b/Lang/Perl/Discordian-date @@ -0,0 +1 @@ +../../Task/Discordian-date/Perl \ No newline at end of file diff --git a/Lang/Perl/Dragon-curve b/Lang/Perl/Dragon-curve new file mode 120000 index 0000000000..ca1e7dff02 --- /dev/null +++ b/Lang/Perl/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Perl \ No newline at end of file diff --git a/Lang/Perl/Find-largest-left-truncatable-prime-in-a-given-base b/Lang/Perl/Find-largest-left-truncatable-prime-in-a-given-base new file mode 120000 index 0000000000..8fb5f04c4d --- /dev/null +++ b/Lang/Perl/Find-largest-left-truncatable-prime-in-a-given-base @@ -0,0 +1 @@ +../../Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl \ No newline at end of file diff --git a/Lang/Perl/First-class-functions-Use-numbers-analogously b/Lang/Perl/First-class-functions-Use-numbers-analogously new file mode 120000 index 0000000000..9b5c2c3010 --- /dev/null +++ b/Lang/Perl/First-class-functions-Use-numbers-analogously @@ -0,0 +1 @@ +../../Task/First-class-functions-Use-numbers-analogously/Perl \ No newline at end of file diff --git a/Lang/Perl/Four-bit-adder b/Lang/Perl/Four-bit-adder new file mode 120000 index 0000000000..99f7386f3e --- /dev/null +++ b/Lang/Perl/Four-bit-adder @@ -0,0 +1 @@ +../../Task/Four-bit-adder/Perl \ No newline at end of file diff --git a/Lang/Perl/Multiplicative-order b/Lang/Perl/Multiplicative-order new file mode 120000 index 0000000000..1dbe298791 --- /dev/null +++ b/Lang/Perl/Multiplicative-order @@ -0,0 +1 @@ +../../Task/Multiplicative-order/Perl \ No newline at end of file diff --git a/Lang/Perl/RIPEMD-160 b/Lang/Perl/RIPEMD-160 new file mode 120000 index 0000000000..8b354ce170 --- /dev/null +++ b/Lang/Perl/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Perl \ No newline at end of file diff --git a/Lang/Perl/Rock-paper-scissors b/Lang/Perl/Rock-paper-scissors new file mode 120000 index 0000000000..bcbed03e90 --- /dev/null +++ b/Lang/Perl/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Perl \ No newline at end of file diff --git a/Lang/Perl/Terminal-control-Cursor-positioning b/Lang/Perl/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..639f5a0033 --- /dev/null +++ b/Lang/Perl/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Perl \ No newline at end of file diff --git a/Lang/Perl/Write-language-name-in-3D-ASCII b/Lang/Perl/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..2fc6dd3039 --- /dev/null +++ b/Lang/Perl/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/Perl \ No newline at end of file diff --git a/Lang/PicoLisp/00DESCRIPTION b/Lang/PicoLisp/00DESCRIPTION index 58c104f5f9..ee829afafb 100644 --- a/Lang/PicoLisp/00DESCRIPTION +++ b/Lang/PicoLisp/00DESCRIPTION @@ -2,7 +2,9 @@ |exec=interpreted |checking=dynamic |gc=yes -|site=http://home.picolisp.com}}[[Category:Lisp Implementations]] +|site=http://home.picolisp.com}} +{{implementation|Lisp}} +[[Category:Lisp Implementations]] '''PicoLisp''' is a small and fast interpreted [[Lisp]] dialect. It runs on [[Linux]] and other [[POSIX]]-compliant systems, and - in a reduced version - on [[JVM]]. diff --git a/Lang/PicoLisp/Average-loop-length b/Lang/PicoLisp/Average-loop-length new file mode 120000 index 0000000000..5965eda4c4 --- /dev/null +++ b/Lang/PicoLisp/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Balanced-ternary b/Lang/PicoLisp/Balanced-ternary new file mode 120000 index 0000000000..bb286c7010 --- /dev/null +++ b/Lang/PicoLisp/Balanced-ternary @@ -0,0 +1 @@ +../../Task/Balanced-ternary/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Bitcoin-address-validation b/Lang/PicoLisp/Bitcoin-address-validation new file mode 120000 index 0000000000..f27ce9f000 --- /dev/null +++ b/Lang/PicoLisp/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/CRC-32 b/Lang/PicoLisp/CRC-32 new file mode 120000 index 0000000000..7e5073872c --- /dev/null +++ b/Lang/PicoLisp/CRC-32 @@ -0,0 +1 @@ +../../Task/CRC-32/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Carmichael-3-strong-pseudoprimes b/Lang/PicoLisp/Carmichael-3-strong-pseudoprimes new file mode 120000 index 0000000000..51cb522d82 --- /dev/null +++ b/Lang/PicoLisp/Carmichael-3-strong-pseudoprimes @@ -0,0 +1 @@ +../../Task/Carmichael-3-strong-pseudoprimes/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/MD4 b/Lang/PicoLisp/MD4 new file mode 120000 index 0000000000..f245c3f8ca --- /dev/null +++ b/Lang/PicoLisp/MD4 @@ -0,0 +1 @@ +../../Task/MD4/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Main-step-of-GOST-28147-89 b/Lang/PicoLisp/Main-step-of-GOST-28147-89 new file mode 120000 index 0000000000..560d931463 --- /dev/null +++ b/Lang/PicoLisp/Main-step-of-GOST-28147-89 @@ -0,0 +1 @@ +../../Task/Main-step-of-GOST-28147-89/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Modular-inverse b/Lang/PicoLisp/Modular-inverse new file mode 120000 index 0000000000..44607cd28f --- /dev/null +++ b/Lang/PicoLisp/Modular-inverse @@ -0,0 +1 @@ +../../Task/Modular-inverse/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Permutations-by-swapping b/Lang/PicoLisp/Permutations-by-swapping new file mode 120000 index 0000000000..6052f026e6 --- /dev/null +++ b/Lang/PicoLisp/Permutations-by-swapping @@ -0,0 +1 @@ +../../Task/Permutations-by-swapping/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/RIPEMD-160 b/Lang/PicoLisp/RIPEMD-160 new file mode 120000 index 0000000000..f020b4de2f --- /dev/null +++ b/Lang/PicoLisp/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/SHA-256 b/Lang/PicoLisp/SHA-256 new file mode 120000 index 0000000000..5e4c3c909d --- /dev/null +++ b/Lang/PicoLisp/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/String-comparison b/Lang/PicoLisp/String-comparison new file mode 120000 index 0000000000..3ec4d223e6 --- /dev/null +++ b/Lang/PicoLisp/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Universal-Turing-machine b/Lang/PicoLisp/Universal-Turing-machine new file mode 120000 index 0000000000..2635fbef28 --- /dev/null +++ b/Lang/PicoLisp/Universal-Turing-machine @@ -0,0 +1 @@ +../../Task/Universal-Turing-machine/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Write-language-name-in-3D-ASCII b/Lang/PicoLisp/Write-language-name-in-3D-ASCII new file mode 120000 index 0000000000..c3040668f4 --- /dev/null +++ b/Lang/PicoLisp/Write-language-name-in-3D-ASCII @@ -0,0 +1 @@ +../../Task/Write-language-name-in-3D-ASCII/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Zeckendorf-arithmetic b/Lang/PicoLisp/Zeckendorf-arithmetic new file mode 120000 index 0000000000..55fd046ff4 --- /dev/null +++ b/Lang/PicoLisp/Zeckendorf-arithmetic @@ -0,0 +1 @@ +../../Task/Zeckendorf-arithmetic/PicoLisp \ No newline at end of file diff --git a/Lang/PicoLisp/Zeckendorf-number-representation b/Lang/PicoLisp/Zeckendorf-number-representation new file mode 120000 index 0000000000..5a4bd1b70f --- /dev/null +++ b/Lang/PicoLisp/Zeckendorf-number-representation @@ -0,0 +1 @@ +../../Task/Zeckendorf-number-representation/PicoLisp \ No newline at end of file diff --git a/Lang/PlainTeX/Towers-of-Hanoi b/Lang/PlainTeX/Towers-of-Hanoi new file mode 120000 index 0000000000..086cd5b8ce --- /dev/null +++ b/Lang/PlainTeX/Towers-of-Hanoi @@ -0,0 +1 @@ +../../Task/Towers-of-Hanoi/PlainTeX \ No newline at end of file diff --git a/Lang/PowerShell/Caesar-cipher b/Lang/PowerShell/Caesar-cipher new file mode 120000 index 0000000000..cd98fbae02 --- /dev/null +++ b/Lang/PowerShell/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Concurrent-computing b/Lang/PowerShell/Concurrent-computing new file mode 120000 index 0000000000..bc008dade5 --- /dev/null +++ b/Lang/PowerShell/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/Create-an-HTML-table b/Lang/PowerShell/Create-an-HTML-table new file mode 120000 index 0000000000..8a504f608f --- /dev/null +++ b/Lang/PowerShell/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/PowerShell \ No newline at end of file diff --git a/Lang/PowerShell/JSON b/Lang/PowerShell/JSON new file mode 120000 index 0000000000..1dcef3a971 --- /dev/null +++ b/Lang/PowerShell/JSON @@ -0,0 +1 @@ +../../Task/JSON/PowerShell \ No newline at end of file diff --git a/Lang/Prolog/24-game b/Lang/Prolog/24-game new file mode 120000 index 0000000000..e6dafa0cbc --- /dev/null +++ b/Lang/Prolog/24-game @@ -0,0 +1 @@ +../../Task/24-game/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Arbitrary-precision-integers--included- b/Lang/Prolog/Arbitrary-precision-integers--included- new file mode 120000 index 0000000000..c213149e17 --- /dev/null +++ b/Lang/Prolog/Arbitrary-precision-integers--included- @@ -0,0 +1 @@ +../../Task/Arbitrary-precision-integers--included-/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Arithmetic-Integer b/Lang/Prolog/Arithmetic-Integer new file mode 120000 index 0000000000..8cdc1a8392 --- /dev/null +++ b/Lang/Prolog/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Averages-Arithmetic-mean b/Lang/Prolog/Averages-Arithmetic-mean new file mode 120000 index 0000000000..3e5308039d --- /dev/null +++ b/Lang/Prolog/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Binary-search b/Lang/Prolog/Binary-search new file mode 120000 index 0000000000..7697a4314c --- /dev/null +++ b/Lang/Prolog/Binary-search @@ -0,0 +1 @@ +../../Task/Binary-search/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Bitmap-Bresenhams-line-algorithm b/Lang/Prolog/Bitmap-Bresenhams-line-algorithm new file mode 120000 index 0000000000..27713999f7 --- /dev/null +++ b/Lang/Prolog/Bitmap-Bresenhams-line-algorithm @@ -0,0 +1 @@ +../../Task/Bitmap-Bresenhams-line-algorithm/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Check-that-file-exists b/Lang/Prolog/Check-that-file-exists new file mode 120000 index 0000000000..c148a609bb --- /dev/null +++ b/Lang/Prolog/Check-that-file-exists @@ -0,0 +1 @@ +../../Task/Check-that-file-exists/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Concurrent-computing b/Lang/Prolog/Concurrent-computing new file mode 120000 index 0000000000..be0e5565f2 --- /dev/null +++ b/Lang/Prolog/Concurrent-computing @@ -0,0 +1 @@ +../../Task/Concurrent-computing/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Count-occurrences-of-a-substring b/Lang/Prolog/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..1fab2bf7f6 --- /dev/null +++ b/Lang/Prolog/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Date-format b/Lang/Prolog/Date-format new file mode 120000 index 0000000000..8e50f8c104 --- /dev/null +++ b/Lang/Prolog/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Determine-if-a-string-is-numeric b/Lang/Prolog/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..706c5426cf --- /dev/null +++ b/Lang/Prolog/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Empty-string b/Lang/Prolog/Empty-string new file mode 120000 index 0000000000..d5a51707fa --- /dev/null +++ b/Lang/Prolog/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Equilibrium-index b/Lang/Prolog/Equilibrium-index new file mode 120000 index 0000000000..183be67409 --- /dev/null +++ b/Lang/Prolog/Equilibrium-index @@ -0,0 +1 @@ +../../Task/Equilibrium-index/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Ethiopian-multiplication b/Lang/Prolog/Ethiopian-multiplication new file mode 120000 index 0000000000..12f01d746c --- /dev/null +++ b/Lang/Prolog/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Exponentiation-operator b/Lang/Prolog/Exponentiation-operator new file mode 120000 index 0000000000..47edf57369 --- /dev/null +++ b/Lang/Prolog/Exponentiation-operator @@ -0,0 +1 @@ +../../Task/Exponentiation-operator/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Guess-the-number b/Lang/Prolog/Guess-the-number new file mode 120000 index 0000000000..b8edb808e6 --- /dev/null +++ b/Lang/Prolog/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Guess-the-number-With-feedback b/Lang/Prolog/Guess-the-number-With-feedback new file mode 120000 index 0000000000..9ebdf1f089 --- /dev/null +++ b/Lang/Prolog/Guess-the-number-With-feedback @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Guess-the-number-With-feedback--player- b/Lang/Prolog/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..e213f23997 --- /dev/null +++ b/Lang/Prolog/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/Prolog \ No newline at end of file diff --git a/Lang/Prolog/JSON b/Lang/Prolog/JSON new file mode 120000 index 0000000000..dbb7780029 --- /dev/null +++ b/Lang/Prolog/JSON @@ -0,0 +1 @@ +../../Task/JSON/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Loops-Foreach b/Lang/Prolog/Loops-Foreach new file mode 120000 index 0000000000..b0f17b7421 --- /dev/null +++ b/Lang/Prolog/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Menu b/Lang/Prolog/Menu new file mode 120000 index 0000000000..812c010e5a --- /dev/null +++ b/Lang/Prolog/Menu @@ -0,0 +1 @@ +../../Task/Menu/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Middle-three-digits b/Lang/Prolog/Middle-three-digits new file mode 120000 index 0000000000..9316a993bb --- /dev/null +++ b/Lang/Prolog/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Miller-Rabin-primality-test b/Lang/Prolog/Miller-Rabin-primality-test new file mode 120000 index 0000000000..77f0bc56fd --- /dev/null +++ b/Lang/Prolog/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Pick-random-element b/Lang/Prolog/Pick-random-element new file mode 120000 index 0000000000..30d47b6241 --- /dev/null +++ b/Lang/Prolog/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Substring b/Lang/Prolog/Substring new file mode 120000 index 0000000000..87bd69ded6 --- /dev/null +++ b/Lang/Prolog/Substring @@ -0,0 +1 @@ +../../Task/Substring/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Top-rank-per-group b/Lang/Prolog/Top-rank-per-group new file mode 120000 index 0000000000..05b6239154 --- /dev/null +++ b/Lang/Prolog/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Prolog \ No newline at end of file diff --git a/Lang/Prolog/Vector-products b/Lang/Prolog/Vector-products new file mode 120000 index 0000000000..47d2333c05 --- /dev/null +++ b/Lang/Prolog/Vector-products @@ -0,0 +1 @@ +../../Task/Vector-products/Prolog \ No newline at end of file diff --git a/Lang/PureBasic/Create-an-HTML-table b/Lang/PureBasic/Create-an-HTML-table new file mode 120000 index 0000000000..a4044c9b42 --- /dev/null +++ b/Lang/PureBasic/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/PureBasic \ No newline at end of file diff --git a/Lang/Python/GUI-component-interaction b/Lang/Python/GUI-component-interaction new file mode 120000 index 0000000000..5b90ae2d21 --- /dev/null +++ b/Lang/Python/GUI-component-interaction @@ -0,0 +1 @@ +../../Task/GUI-component-interaction/Python \ No newline at end of file diff --git a/Lang/Python/Metaprogramming b/Lang/Python/Metaprogramming new file mode 120000 index 0000000000..8908b7d1a9 --- /dev/null +++ b/Lang/Python/Metaprogramming @@ -0,0 +1 @@ +../../Task/Metaprogramming/Python \ No newline at end of file diff --git a/Lang/Python/Simulate-input-Keyboard b/Lang/Python/Simulate-input-Keyboard new file mode 120000 index 0000000000..068af91bf9 --- /dev/null +++ b/Lang/Python/Simulate-input-Keyboard @@ -0,0 +1 @@ +../../Task/Simulate-input-Keyboard/Python \ No newline at end of file diff --git a/Lang/Python/Topic-variable b/Lang/Python/Topic-variable new file mode 120000 index 0000000000..af83493981 --- /dev/null +++ b/Lang/Python/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Python \ No newline at end of file diff --git a/Lang/Qi/00DESCRIPTION b/Lang/Qi/00DESCRIPTION index bd9db24f5e..269d0b6f44 100644 --- a/Lang/Qi/00DESCRIPTION +++ b/Lang/Qi/00DESCRIPTION @@ -1,5 +1,6 @@ {{stub}}{{language |site=http://www.lambdassociates.org/ |express=explicit}} +{{implementation|Lisp}} * [[wp:Qi (programming language)]] \ No newline at end of file diff --git a/Lang/R/Call-a-function b/Lang/R/Call-a-function new file mode 120000 index 0000000000..05e6ba3d73 --- /dev/null +++ b/Lang/R/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/R \ No newline at end of file diff --git a/Lang/R/Call-a-function-in-a-shared-library b/Lang/R/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..51af006079 --- /dev/null +++ b/Lang/R/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/R \ No newline at end of file diff --git a/Lang/R/DNS-query b/Lang/R/DNS-query new file mode 120000 index 0000000000..6f2115ce75 --- /dev/null +++ b/Lang/R/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/R \ No newline at end of file diff --git a/Lang/R/Dragon-curve b/Lang/R/Dragon-curve new file mode 120000 index 0000000000..fb4f6eb358 --- /dev/null +++ b/Lang/R/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/R \ No newline at end of file diff --git a/Lang/R/Euler-method b/Lang/R/Euler-method new file mode 120000 index 0000000000..0948b8ecb2 --- /dev/null +++ b/Lang/R/Euler-method @@ -0,0 +1 @@ +../../Task/Euler-method/R \ No newline at end of file diff --git a/Lang/R/Gray-code b/Lang/R/Gray-code new file mode 120000 index 0000000000..8ecdda6a9d --- /dev/null +++ b/Lang/R/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/R \ No newline at end of file diff --git a/Lang/R/Integer-sequence b/Lang/R/Integer-sequence new file mode 120000 index 0000000000..0c37a17461 --- /dev/null +++ b/Lang/R/Integer-sequence @@ -0,0 +1 @@ +../../Task/Integer-sequence/R \ No newline at end of file diff --git a/Lang/R/One-of-n-lines-in-a-file b/Lang/R/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..ae2cf65d7b --- /dev/null +++ b/Lang/R/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/R \ No newline at end of file diff --git a/Lang/R/Roman-numerals-Decode b/Lang/R/Roman-numerals-Decode new file mode 120000 index 0000000000..fd0f5817a7 --- /dev/null +++ b/Lang/R/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/R \ No newline at end of file diff --git a/Lang/R/String-comparison b/Lang/R/String-comparison new file mode 120000 index 0000000000..b0658852c0 --- /dev/null +++ b/Lang/R/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/R \ No newline at end of file diff --git a/Lang/R/Sum-digits-of-an-integer b/Lang/R/Sum-digits-of-an-integer new file mode 120000 index 0000000000..248263fc42 --- /dev/null +++ b/Lang/R/Sum-digits-of-an-integer @@ -0,0 +1 @@ +../../Task/Sum-digits-of-an-integer/R \ No newline at end of file diff --git a/Lang/R/URL-decoding b/Lang/R/URL-decoding new file mode 120000 index 0000000000..6aad0771d2 --- /dev/null +++ b/Lang/R/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/R \ No newline at end of file diff --git a/Lang/R/URL-encoding b/Lang/R/URL-encoding new file mode 120000 index 0000000000..5629762e2d --- /dev/null +++ b/Lang/R/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/R \ No newline at end of file diff --git a/Lang/R/Unicode-variable-names b/Lang/R/Unicode-variable-names new file mode 120000 index 0000000000..3f1444f221 --- /dev/null +++ b/Lang/R/Unicode-variable-names @@ -0,0 +1 @@ +../../Task/Unicode-variable-names/R \ No newline at end of file diff --git a/Lang/R/Word-wrap b/Lang/R/Word-wrap new file mode 120000 index 0000000000..bc7b2c3510 --- /dev/null +++ b/Lang/R/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/R \ No newline at end of file diff --git a/Lang/R/Zebra-puzzle b/Lang/R/Zebra-puzzle new file mode 120000 index 0000000000..9bbd5e1eef --- /dev/null +++ b/Lang/R/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/R \ No newline at end of file diff --git a/Lang/REALbasic/Classes b/Lang/REALbasic/Classes new file mode 120000 index 0000000000..55b75de2ed --- /dev/null +++ b/Lang/REALbasic/Classes @@ -0,0 +1 @@ +../../Task/Classes/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Function-definition b/Lang/REALbasic/Function-definition new file mode 120000 index 0000000000..8f0f920f79 --- /dev/null +++ b/Lang/REALbasic/Function-definition @@ -0,0 +1 @@ +../../Task/Function-definition/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Hello-world-Graphical b/Lang/REALbasic/Hello-world-Graphical new file mode 120000 index 0000000000..354a413f22 --- /dev/null +++ b/Lang/REALbasic/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/REALbasic \ No newline at end of file diff --git a/Lang/REALbasic/Variadic-function b/Lang/REALbasic/Variadic-function new file mode 120000 index 0000000000..8e22d752e4 --- /dev/null +++ b/Lang/REALbasic/Variadic-function @@ -0,0 +1 @@ +../../Task/Variadic-function/REALbasic \ No newline at end of file diff --git a/Lang/REBOL/Dot-product b/Lang/REBOL/Dot-product new file mode 120000 index 0000000000..0e405ceca0 --- /dev/null +++ b/Lang/REBOL/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Hello-world-Newline-omission b/Lang/REBOL/Hello-world-Newline-omission new file mode 120000 index 0000000000..a1ab230770 --- /dev/null +++ b/Lang/REBOL/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Horners-rule-for-polynomial-evaluation b/Lang/REBOL/Horners-rule-for-polynomial-evaluation new file mode 120000 index 0000000000..3ed4d272a6 --- /dev/null +++ b/Lang/REBOL/Horners-rule-for-polynomial-evaluation @@ -0,0 +1 @@ +../../Task/Horners-rule-for-polynomial-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Last-Friday-of-each-month b/Lang/REBOL/Last-Friday-of-each-month new file mode 120000 index 0000000000..592b3befd7 --- /dev/null +++ b/Lang/REBOL/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Mad-Libs b/Lang/REBOL/Mad-Libs new file mode 120000 index 0000000000..db4b8d6171 --- /dev/null +++ b/Lang/REBOL/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Number-reversal-game b/Lang/REBOL/Number-reversal-game new file mode 120000 index 0000000000..a23e4203b5 --- /dev/null +++ b/Lang/REBOL/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Runtime-evaluation b/Lang/REBOL/Runtime-evaluation new file mode 120000 index 0000000000..4f29a7904a --- /dev/null +++ b/Lang/REBOL/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/REBOL \ No newline at end of file diff --git a/Lang/REBOL/Simple-database b/Lang/REBOL/Simple-database new file mode 120000 index 0000000000..2171f3e8b2 --- /dev/null +++ b/Lang/REBOL/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/REBOL \ No newline at end of file diff --git a/Lang/REXX/00DESCRIPTION b/Lang/REXX/00DESCRIPTION index 5490849be3..26aa4ce196 100644 --- a/Lang/REXX/00DESCRIPTION +++ b/Lang/REXX/00DESCRIPTION @@ -1,4 +1,12 @@ -{{language|REXX}} +{{language +|strength=strong +|LCT=yes +|gc=allowed +|safety=safe +|express=implicit +|compat=nominative +|checking=dynamic +|parampass=value}} {{Wikipedia|REXX}} REXX (REstructured eXtended eXecutor) is an interpreted programming language which was developed at IBM. It is a structured high-level programming language which was designed to be both easy to learn and easy to read. Both proprietary and open source interpreters for REXX are available on a wide range of computing platforms, and compilers are available for IBM mainframes. @@ -36,11 +44,13 @@ * '''[[ROO oo-REXX]]''' an object-oriented REXX delveloped by Keith Watts of Kilowatt Software, Inc. It can be downloaded freely. '''ROO''' is also known as '''ROO!'''. -* '''[[R4 REXX]]''' a classic REXX developed by Kieth Watts of Kilowatt Software, Inc. It was also known as Portable REXX. It can be downloaded freely. +* '''[[R4 REXX]]''' a classic REXX developed by Keith Watts of Kilowatt Software, Inc. It was also known as Portable REXX. It can be downloaded freely. + +* '''[["T/REXX, a REXX compiler for CMS]]''' is an implementation of classic REXX written by Lundin and Woodruff (according to Wikipedia). * '''[[VM/CMS REXX]]''' is an IBM implementation of classic REXX that was first implemented in the early 1980s. A license is required to use this product as well as the operating system that it runs under. This was the original implementation of REXX written by Mike Cowlishaw of IBM (circa 1979). -* '''[[VM/CMS REXX compiler]]''' is an IBM implementation of classic REXX written by Lundin and Woodruff, a license is required to use this product as well as the operating system it runs under. +* '''[[VM/CMS REXX compiler]]''' is an IBM implementation of classic REXX, a license is required to use this product as well as the operating system it runs under.
[Most of the entries were entered mostly from memory and apologies are offered for not knowing more about what wording should be used; the IBM operating systems or Program Products that run REXX are numerous and varied. Their complete (official) names would fill a pagefull. Some of the REXXes are no longer sold nor available for downloading or purchase, others are no longer maintained. Naming of names is being avoided (especially those licensed products for sale), and it is hoped that this is seen that no products nor vendors are being endorsed, appraised, or critiqued.] -- [[User:Gerard Schildberger|Gerard Schildberger]] 09:28, 1 July 2012 (UTC) diff --git a/Lang/REXX/Averages-Mean-time-of-day b/Lang/REXX/Averages-Mean-time-of-day new file mode 120000 index 0000000000..8a3738671b --- /dev/null +++ b/Lang/REXX/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/REXX \ No newline at end of file diff --git a/Lang/REXX/Bulls-and-cows-Player b/Lang/REXX/Bulls-and-cows-Player new file mode 120000 index 0000000000..51b57115b4 --- /dev/null +++ b/Lang/REXX/Bulls-and-cows-Player @@ -0,0 +1 @@ +../../Task/Bulls-and-cows-Player/REXX \ No newline at end of file diff --git a/Lang/REXX/Colour-bars-Display b/Lang/REXX/Colour-bars-Display new file mode 120000 index 0000000000..6ed14354f2 --- /dev/null +++ b/Lang/REXX/Colour-bars-Display @@ -0,0 +1 @@ +../../Task/Colour-bars-Display/REXX \ No newline at end of file diff --git a/Lang/REXX/Extend-your-language b/Lang/REXX/Extend-your-language new file mode 120000 index 0000000000..bc26628675 --- /dev/null +++ b/Lang/REXX/Extend-your-language @@ -0,0 +1 @@ +../../Task/Extend-your-language/REXX \ No newline at end of file diff --git a/Lang/REXX/Include-a-file b/Lang/REXX/Include-a-file new file mode 120000 index 0000000000..8de16f0510 --- /dev/null +++ b/Lang/REXX/Include-a-file @@ -0,0 +1 @@ +../../Task/Include-a-file/REXX \ No newline at end of file diff --git a/Lang/REXX/LZW-compression b/Lang/REXX/LZW-compression new file mode 120000 index 0000000000..bca8bc2396 --- /dev/null +++ b/Lang/REXX/LZW-compression @@ -0,0 +1 @@ +../../Task/LZW-compression/REXX \ No newline at end of file diff --git a/Lang/REXX/Man-or-boy-test b/Lang/REXX/Man-or-boy-test new file mode 120000 index 0000000000..544a1e804e --- /dev/null +++ b/Lang/REXX/Man-or-boy-test @@ -0,0 +1 @@ +../../Task/Man-or-boy-test/REXX \ No newline at end of file diff --git a/Lang/REXX/Mandelbrot-set b/Lang/REXX/Mandelbrot-set new file mode 120000 index 0000000000..8c39e58c13 --- /dev/null +++ b/Lang/REXX/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/REXX \ No newline at end of file diff --git a/Lang/REXX/Ordered-Partitions b/Lang/REXX/Ordered-Partitions new file mode 120000 index 0000000000..c9d1026b70 --- /dev/null +++ b/Lang/REXX/Ordered-Partitions @@ -0,0 +1 @@ +../../Task/Ordered-Partitions/REXX \ No newline at end of file diff --git a/Lang/REXX/Set-puzzle b/Lang/REXX/Set-puzzle new file mode 120000 index 0000000000..502ea32642 --- /dev/null +++ b/Lang/REXX/Set-puzzle @@ -0,0 +1 @@ +../../Task/Set-puzzle/REXX \ No newline at end of file diff --git a/Lang/REXX/Simple-database b/Lang/REXX/Simple-database new file mode 120000 index 0000000000..168a7bc65d --- /dev/null +++ b/Lang/REXX/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/REXX \ No newline at end of file diff --git a/Lang/REXX/Sort-stability b/Lang/REXX/Sort-stability new file mode 120000 index 0000000000..d368414d61 --- /dev/null +++ b/Lang/REXX/Sort-stability @@ -0,0 +1 @@ +../../Task/Sort-stability/REXX \ No newline at end of file diff --git a/Lang/REXX/Topic-variable b/Lang/REXX/Topic-variable new file mode 120000 index 0000000000..aba10b1a00 --- /dev/null +++ b/Lang/REXX/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/REXX \ No newline at end of file diff --git a/Lang/REXX/Truncate-a-file b/Lang/REXX/Truncate-a-file new file mode 120000 index 0000000000..e707569cbd --- /dev/null +++ b/Lang/REXX/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/REXX \ No newline at end of file diff --git a/Lang/REXX/Visualize-a-tree b/Lang/REXX/Visualize-a-tree new file mode 120000 index 0000000000..a430ad25a7 --- /dev/null +++ b/Lang/REXX/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/REXX \ No newline at end of file diff --git a/Lang/REXX/Wireworld b/Lang/REXX/Wireworld new file mode 120000 index 0000000000..aca281d23c --- /dev/null +++ b/Lang/REXX/Wireworld @@ -0,0 +1 @@ +../../Task/Wireworld/REXX \ No newline at end of file diff --git a/Lang/REXX/XML-XPath b/Lang/REXX/XML-XPath new file mode 120000 index 0000000000..b8910a56d1 --- /dev/null +++ b/Lang/REXX/XML-XPath @@ -0,0 +1 @@ +../../Task/XML-XPath/REXX \ No newline at end of file diff --git a/Lang/RPG/Substring b/Lang/RPG/Substring new file mode 120000 index 0000000000..d5ca9e1270 --- /dev/null +++ b/Lang/RPG/Substring @@ -0,0 +1 @@ +../../Task/Substring/RPG \ No newline at end of file diff --git a/Lang/Racket/00DESCRIPTION b/Lang/Racket/00DESCRIPTION index 004ff32234..3892842bf8 100644 --- a/Lang/Racket/00DESCRIPTION +++ b/Lang/Racket/00DESCRIPTION @@ -1,4 +1,6 @@ {{language}} +{{implementation|Scheme}} + '''Racket''' (renamed from "PLT Scheme" years ago) is a member of the Lisp and Scheme family of languages. Racket draws freely from the various strands of its lineage. * [http://racket-lang.org/ Home page] diff --git a/Lang/Racket/Bitmap-Histogram b/Lang/Racket/Bitmap-Histogram new file mode 120000 index 0000000000..888006d5c0 --- /dev/null +++ b/Lang/Racket/Bitmap-Histogram @@ -0,0 +1 @@ +../../Task/Bitmap-Histogram/Racket \ No newline at end of file diff --git a/Lang/Racket/Constrained-genericity b/Lang/Racket/Constrained-genericity new file mode 120000 index 0000000000..a726d7e531 --- /dev/null +++ b/Lang/Racket/Constrained-genericity @@ -0,0 +1 @@ +../../Task/Constrained-genericity/Racket \ No newline at end of file diff --git a/Lang/Racket/Delegates b/Lang/Racket/Delegates new file mode 120000 index 0000000000..6e9a6d5a47 --- /dev/null +++ b/Lang/Racket/Delegates @@ -0,0 +1 @@ +../../Task/Delegates/Racket \ No newline at end of file diff --git a/Lang/Racket/Object-serialization b/Lang/Racket/Object-serialization new file mode 120000 index 0000000000..4532161245 --- /dev/null +++ b/Lang/Racket/Object-serialization @@ -0,0 +1 @@ +../../Task/Object-serialization/Racket \ No newline at end of file diff --git a/Lang/Racket/Resistor-mesh b/Lang/Racket/Resistor-mesh new file mode 120000 index 0000000000..1f63e864f5 --- /dev/null +++ b/Lang/Racket/Resistor-mesh @@ -0,0 +1 @@ +../../Task/Resistor-mesh/Racket \ No newline at end of file diff --git a/Lang/RapidQ/100-doors b/Lang/RapidQ/100-doors new file mode 120000 index 0000000000..e28ceaaa79 --- /dev/null +++ b/Lang/RapidQ/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/99-Bottles-of-Beer b/Lang/RapidQ/99-Bottles-of-Beer new file mode 120000 index 0000000000..fcde7e00f5 --- /dev/null +++ b/Lang/RapidQ/99-Bottles-of-Beer @@ -0,0 +1 @@ +../../Task/99-Bottles-of-Beer/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Address-of-a-variable b/Lang/RapidQ/Address-of-a-variable new file mode 120000 index 0000000000..1c3f17890a --- /dev/null +++ b/Lang/RapidQ/Address-of-a-variable @@ -0,0 +1 @@ +../../Task/Address-of-a-variable/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Align-columns b/Lang/RapidQ/Align-columns new file mode 120000 index 0000000000..0947fbbdbc --- /dev/null +++ b/Lang/RapidQ/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Anagrams b/Lang/RapidQ/Anagrams new file mode 120000 index 0000000000..f08170293f --- /dev/null +++ b/Lang/RapidQ/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Array-concatenation b/Lang/RapidQ/Array-concatenation new file mode 120000 index 0000000000..40fceb496a --- /dev/null +++ b/Lang/RapidQ/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Find-the-missing-permutation b/Lang/RapidQ/Find-the-missing-permutation new file mode 120000 index 0000000000..365cc971fc --- /dev/null +++ b/Lang/RapidQ/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Greatest-element-of-a-list b/Lang/RapidQ/Greatest-element-of-a-list new file mode 120000 index 0000000000..5695120151 --- /dev/null +++ b/Lang/RapidQ/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Greyscale-bars-Display b/Lang/RapidQ/Greyscale-bars-Display new file mode 120000 index 0000000000..8aa329ec3c --- /dev/null +++ b/Lang/RapidQ/Greyscale-bars-Display @@ -0,0 +1 @@ +../../Task/Greyscale-bars-Display/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Guess-the-number b/Lang/RapidQ/Guess-the-number new file mode 120000 index 0000000000..9475e46519 --- /dev/null +++ b/Lang/RapidQ/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Read-a-configuration-file b/Lang/RapidQ/Read-a-configuration-file new file mode 120000 index 0000000000..0fb4fc7297 --- /dev/null +++ b/Lang/RapidQ/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Read-a-file-line-by-line b/Lang/RapidQ/Read-a-file-line-by-line new file mode 120000 index 0000000000..94ad2b0fd1 --- /dev/null +++ b/Lang/RapidQ/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Repeat-a-string b/Lang/RapidQ/Repeat-a-string new file mode 120000 index 0000000000..3df906948b --- /dev/null +++ b/Lang/RapidQ/Repeat-a-string @@ -0,0 +1 @@ +../../Task/Repeat-a-string/RapidQ \ No newline at end of file diff --git a/Lang/RapidQ/Sleep b/Lang/RapidQ/Sleep new file mode 120000 index 0000000000..70cf57dc1e --- /dev/null +++ b/Lang/RapidQ/Sleep @@ -0,0 +1 @@ +../../Task/Sleep/RapidQ \ No newline at end of file diff --git a/Lang/Ruby/Bitcoin-address-validation b/Lang/Ruby/Bitcoin-address-validation new file mode 120000 index 0000000000..7718f99fa1 --- /dev/null +++ b/Lang/Ruby/Bitcoin-address-validation @@ -0,0 +1 @@ +../../Task/Bitcoin-address-validation/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Color-of-a-screen-pixel b/Lang/Ruby/Color-of-a-screen-pixel new file mode 120000 index 0000000000..379cb5d460 --- /dev/null +++ b/Lang/Ruby/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Cut-a-rectangle b/Lang/Ruby/Cut-a-rectangle new file mode 120000 index 0000000000..381e4c8e87 --- /dev/null +++ b/Lang/Ruby/Cut-a-rectangle @@ -0,0 +1 @@ +../../Task/Cut-a-rectangle/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Draw-a-cuboid b/Lang/Ruby/Draw-a-cuboid new file mode 120000 index 0000000000..490e960afd --- /dev/null +++ b/Lang/Ruby/Draw-a-cuboid @@ -0,0 +1 @@ +../../Task/Draw-a-cuboid/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Knapsack-problem-Continuous b/Lang/Ruby/Knapsack-problem-Continuous new file mode 120000 index 0000000000..879a3ce5c0 --- /dev/null +++ b/Lang/Ruby/Knapsack-problem-Continuous @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Continuous/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Nautical-bell b/Lang/Ruby/Nautical-bell new file mode 120000 index 0000000000..61ad2e31c7 --- /dev/null +++ b/Lang/Ruby/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Permutation-test b/Lang/Ruby/Permutation-test new file mode 120000 index 0000000000..ccb13188ae --- /dev/null +++ b/Lang/Ruby/Permutation-test @@ -0,0 +1 @@ +../../Task/Permutation-test/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Scope-modifiers b/Lang/Ruby/Scope-modifiers new file mode 120000 index 0000000000..44ab75f49e --- /dev/null +++ b/Lang/Ruby/Scope-modifiers @@ -0,0 +1 @@ +../../Task/Scope-modifiers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Set-of-real-numbers b/Lang/Ruby/Set-of-real-numbers new file mode 120000 index 0000000000..a058bccb4c --- /dev/null +++ b/Lang/Ruby/Set-of-real-numbers @@ -0,0 +1 @@ +../../Task/Set-of-real-numbers/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Sokoban b/Lang/Ruby/Sokoban new file mode 120000 index 0000000000..cf350f967a --- /dev/null +++ b/Lang/Ruby/Sokoban @@ -0,0 +1 @@ +../../Task/Sokoban/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Start-from-a-main-routine b/Lang/Ruby/Start-from-a-main-routine new file mode 120000 index 0000000000..3ac3ded8c1 --- /dev/null +++ b/Lang/Ruby/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Topic-variable b/Lang/Ruby/Topic-variable new file mode 120000 index 0000000000..a758e5f38f --- /dev/null +++ b/Lang/Ruby/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Verify-distribution-uniformity-Chi-squared-test b/Lang/Ruby/Verify-distribution-uniformity-Chi-squared-test new file mode 120000 index 0000000000..a8d7fc0038 --- /dev/null +++ b/Lang/Ruby/Verify-distribution-uniformity-Chi-squared-test @@ -0,0 +1 @@ +../../Task/Verify-distribution-uniformity-Chi-squared-test/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Visualize-a-tree b/Lang/Ruby/Visualize-a-tree new file mode 120000 index 0000000000..3f9afc85e8 --- /dev/null +++ b/Lang/Ruby/Visualize-a-tree @@ -0,0 +1 @@ +../../Task/Visualize-a-tree/Ruby \ No newline at end of file diff --git a/Lang/Ruby/Zebra-puzzle b/Lang/Ruby/Zebra-puzzle new file mode 120000 index 0000000000..79baaa34ce --- /dev/null +++ b/Lang/Ruby/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Ruby \ No newline at end of file diff --git a/Lang/Rust/00DESCRIPTION b/Lang/Rust/00DESCRIPTION index 426fc3c260..f983988e48 100644 --- a/Lang/Rust/00DESCRIPTION +++ b/Lang/Rust/00DESCRIPTION @@ -1,9 +1,32 @@ -{{stub}}{{language -|checking=static -|strength=strong -|express=implicit -|compat=structural -|gc=allowed +{{language +|site=http://www.rust-lang.org |exec=machine +|gc=allowed |safety=safe -|site=http://www.rust-lang.org}} \ No newline at end of file +|strength=strong +|compat=structural +|express=implicit +|checking=static +|tags=rust +|hopl id=1558 +}} + +Rust is a work-in-progress general purpose, multi-paradigm, systems programming language sponsored by Mozilla. Its goal is to provide a fast, practical, concurrent language with zero-cost abstractions and strong memory safety. It employs a unique model of ownership to eliminate data races. + +== Features == +From the official website: +* algebraic data types +* apattern matching +* closures +* type inference +* zero-cost abstractions +* guaranteed memory safety +* optional garbage collection +* concurrency without data races +* minimal runtime +* efficient C bindings + +{{language programming paradigm|functional}} +{{language programming paradigm|imperative}} +{{language programming paradigm|Object-oriented}} +{{language programming paradigm|Generic}} \ No newline at end of file diff --git a/Lang/Rust/Accumulator-factory b/Lang/Rust/Accumulator-factory new file mode 120000 index 0000000000..005252fadb --- /dev/null +++ b/Lang/Rust/Accumulator-factory @@ -0,0 +1 @@ +../../Task/Accumulator-factory/Rust \ No newline at end of file diff --git a/Lang/Rust/Align-columns b/Lang/Rust/Align-columns new file mode 120000 index 0000000000..52e607c13d --- /dev/null +++ b/Lang/Rust/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Rust \ No newline at end of file diff --git a/Lang/Rust/Arithmetic-Integer b/Lang/Rust/Arithmetic-Integer new file mode 120000 index 0000000000..6a7e35a2b9 --- /dev/null +++ b/Lang/Rust/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Rust \ No newline at end of file diff --git a/Lang/Rust/Arithmetic-geometric-mean b/Lang/Rust/Arithmetic-geometric-mean new file mode 120000 index 0000000000..683499243d --- /dev/null +++ b/Lang/Rust/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/Rust \ No newline at end of file diff --git a/Lang/Rust/Associative-array-Iteration b/Lang/Rust/Associative-array-Iteration new file mode 120000 index 0000000000..7e81d60a18 --- /dev/null +++ b/Lang/Rust/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Rust \ No newline at end of file diff --git a/Lang/Rust/Averages-Arithmetic-mean b/Lang/Rust/Averages-Arithmetic-mean new file mode 120000 index 0000000000..fd1d919751 --- /dev/null +++ b/Lang/Rust/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Rust \ No newline at end of file diff --git a/Lang/Rust/Binary-digits b/Lang/Rust/Binary-digits new file mode 120000 index 0000000000..516fa0c5c6 --- /dev/null +++ b/Lang/Rust/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Rust \ No newline at end of file diff --git a/Lang/Rust/Call-an-object-method b/Lang/Rust/Call-an-object-method new file mode 120000 index 0000000000..392bb4e08b --- /dev/null +++ b/Lang/Rust/Call-an-object-method @@ -0,0 +1 @@ +../../Task/Call-an-object-method/Rust \ No newline at end of file diff --git a/Lang/Rust/Catalan-numbers b/Lang/Rust/Catalan-numbers new file mode 120000 index 0000000000..90f0bdeb63 --- /dev/null +++ b/Lang/Rust/Catalan-numbers @@ -0,0 +1 @@ +../../Task/Catalan-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Dot-product b/Lang/Rust/Dot-product new file mode 120000 index 0000000000..549e6d10f6 --- /dev/null +++ b/Lang/Rust/Dot-product @@ -0,0 +1 @@ +../../Task/Dot-product/Rust \ No newline at end of file diff --git a/Lang/Rust/Ethiopian-multiplication b/Lang/Rust/Ethiopian-multiplication new file mode 120000 index 0000000000..7141f6ee12 --- /dev/null +++ b/Lang/Rust/Ethiopian-multiplication @@ -0,0 +1 @@ +../../Task/Ethiopian-multiplication/Rust \ No newline at end of file diff --git a/Lang/Rust/Even-or-odd b/Lang/Rust/Even-or-odd new file mode 120000 index 0000000000..7d0e1e757c --- /dev/null +++ b/Lang/Rust/Even-or-odd @@ -0,0 +1 @@ +../../Task/Even-or-odd/Rust \ No newline at end of file diff --git a/Lang/Rust/Filter b/Lang/Rust/Filter new file mode 120000 index 0000000000..0ce11ace5f --- /dev/null +++ b/Lang/Rust/Filter @@ -0,0 +1 @@ +../../Task/Filter/Rust \ No newline at end of file diff --git a/Lang/Rust/Guess-the-number b/Lang/Rust/Guess-the-number new file mode 120000 index 0000000000..941df30226 --- /dev/null +++ b/Lang/Rust/Guess-the-number @@ -0,0 +1 @@ +../../Task/Guess-the-number/Rust \ No newline at end of file diff --git a/Lang/Rust/Hailstone-sequence b/Lang/Rust/Hailstone-sequence new file mode 120000 index 0000000000..e249f6b94a --- /dev/null +++ b/Lang/Rust/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Rust \ No newline at end of file diff --git a/Lang/Rust/Happy-numbers b/Lang/Rust/Happy-numbers new file mode 120000 index 0000000000..6bd02de0b4 --- /dev/null +++ b/Lang/Rust/Happy-numbers @@ -0,0 +1 @@ +../../Task/Happy-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Hello-world-Newline-omission b/Lang/Rust/Hello-world-Newline-omission new file mode 120000 index 0000000000..7940eaeded --- /dev/null +++ b/Lang/Rust/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Rust \ No newline at end of file diff --git a/Lang/Rust/Hello-world-Standard-error b/Lang/Rust/Hello-world-Standard-error new file mode 120000 index 0000000000..1df443310e --- /dev/null +++ b/Lang/Rust/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Rust \ No newline at end of file diff --git a/Lang/Rust/Hello-world-Web-server b/Lang/Rust/Hello-world-Web-server new file mode 120000 index 0000000000..09ddd783f6 --- /dev/null +++ b/Lang/Rust/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/Rust \ No newline at end of file diff --git a/Lang/Rust/Infinity b/Lang/Rust/Infinity new file mode 120000 index 0000000000..dc3a2c3116 --- /dev/null +++ b/Lang/Rust/Infinity @@ -0,0 +1 @@ +../../Task/Infinity/Rust \ No newline at end of file diff --git a/Lang/Rust/Integer-comparison b/Lang/Rust/Integer-comparison new file mode 120000 index 0000000000..bbe5858fb5 --- /dev/null +++ b/Lang/Rust/Integer-comparison @@ -0,0 +1 @@ +../../Task/Integer-comparison/Rust \ No newline at end of file diff --git a/Lang/Rust/JSON b/Lang/Rust/JSON new file mode 120000 index 0000000000..c8bf7b1b11 --- /dev/null +++ b/Lang/Rust/JSON @@ -0,0 +1 @@ +../../Task/JSON/Rust \ No newline at end of file diff --git a/Lang/Rust/Knapsack-problem-0-1 b/Lang/Rust/Knapsack-problem-0-1 new file mode 120000 index 0000000000..5024d37662 --- /dev/null +++ b/Lang/Rust/Knapsack-problem-0-1 @@ -0,0 +1 @@ +../../Task/Knapsack-problem-0-1/Rust \ No newline at end of file diff --git a/Lang/Rust/Langtons-ant b/Lang/Rust/Langtons-ant new file mode 120000 index 0000000000..5d00409af3 --- /dev/null +++ b/Lang/Rust/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Rust \ No newline at end of file diff --git a/Lang/Rust/Letter-frequency b/Lang/Rust/Letter-frequency new file mode 120000 index 0000000000..8e08e0fa70 --- /dev/null +++ b/Lang/Rust/Letter-frequency @@ -0,0 +1 @@ +../../Task/Letter-frequency/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-Infinite b/Lang/Rust/Loops-Infinite new file mode 120000 index 0000000000..c8ee1efb83 --- /dev/null +++ b/Lang/Rust/Loops-Infinite @@ -0,0 +1 @@ +../../Task/Loops-Infinite/Rust \ No newline at end of file diff --git a/Lang/Rust/Loops-While b/Lang/Rust/Loops-While new file mode 120000 index 0000000000..f6fcae469c --- /dev/null +++ b/Lang/Rust/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Rust \ No newline at end of file diff --git a/Lang/Rust/Luhn-test-of-credit-card-numbers b/Lang/Rust/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..fbdcefc90c --- /dev/null +++ b/Lang/Rust/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Parametric-polymorphism b/Lang/Rust/Parametric-polymorphism new file mode 120000 index 0000000000..f00f287cb9 --- /dev/null +++ b/Lang/Rust/Parametric-polymorphism @@ -0,0 +1 @@ +../../Task/Parametric-polymorphism/Rust \ No newline at end of file diff --git a/Lang/Rust/Playing-cards b/Lang/Rust/Playing-cards new file mode 120000 index 0000000000..e0894dbef1 --- /dev/null +++ b/Lang/Rust/Playing-cards @@ -0,0 +1 @@ +../../Task/Playing-cards/Rust \ No newline at end of file diff --git a/Lang/Rust/Price-fraction b/Lang/Rust/Price-fraction new file mode 120000 index 0000000000..55978a740d --- /dev/null +++ b/Lang/Rust/Price-fraction @@ -0,0 +1 @@ +../../Task/Price-fraction/Rust \ No newline at end of file diff --git a/Lang/Rust/Primality-by-trial-division b/Lang/Rust/Primality-by-trial-division new file mode 120000 index 0000000000..d1715122fa --- /dev/null +++ b/Lang/Rust/Primality-by-trial-division @@ -0,0 +1 @@ +../../Task/Primality-by-trial-division/Rust \ No newline at end of file diff --git a/Lang/Rust/Read-a-file-line-by-line b/Lang/Rust/Read-a-file-line-by-line new file mode 120000 index 0000000000..acfbb15ae9 --- /dev/null +++ b/Lang/Rust/Read-a-file-line-by-line @@ -0,0 +1 @@ +../../Task/Read-a-file-line-by-line/Rust \ No newline at end of file diff --git a/Lang/Rust/SHA-256 b/Lang/Rust/SHA-256 new file mode 120000 index 0000000000..a51ed626e2 --- /dev/null +++ b/Lang/Rust/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Rust \ No newline at end of file diff --git a/Lang/Rust/Sort-an-integer-array b/Lang/Rust/Sort-an-integer-array new file mode 120000 index 0000000000..77355a5d3b --- /dev/null +++ b/Lang/Rust/Sort-an-integer-array @@ -0,0 +1 @@ +../../Task/Sort-an-integer-array/Rust \ No newline at end of file diff --git a/Lang/Rust/Sorting-algorithms-Quicksort b/Lang/Rust/Sorting-algorithms-Quicksort new file mode 120000 index 0000000000..baedf35288 --- /dev/null +++ b/Lang/Rust/Sorting-algorithms-Quicksort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Quicksort/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-of-a-series b/Lang/Rust/Sum-of-a-series new file mode 120000 index 0000000000..89a1012af7 --- /dev/null +++ b/Lang/Rust/Sum-of-a-series @@ -0,0 +1 @@ +../../Task/Sum-of-a-series/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-of-squares b/Lang/Rust/Sum-of-squares new file mode 120000 index 0000000000..b221b62ca3 --- /dev/null +++ b/Lang/Rust/Sum-of-squares @@ -0,0 +1 @@ +../../Task/Sum-of-squares/Rust \ No newline at end of file diff --git a/Lang/SAS/Hailstone-sequence b/Lang/SAS/Hailstone-sequence new file mode 120000 index 0000000000..b1ecfeed7e --- /dev/null +++ b/Lang/SAS/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/SAS \ No newline at end of file diff --git a/Lang/SAS/Haversine-formula b/Lang/SAS/Haversine-formula new file mode 120000 index 0000000000..062d8a2282 --- /dev/null +++ b/Lang/SAS/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/SAS \ No newline at end of file diff --git a/Lang/SAS/Power-set b/Lang/SAS/Power-set new file mode 120000 index 0000000000..e7480a2232 --- /dev/null +++ b/Lang/SAS/Power-set @@ -0,0 +1 @@ +../../Task/Power-set/SAS \ No newline at end of file diff --git a/Lang/SAS/Stair-climbing-puzzle b/Lang/SAS/Stair-climbing-puzzle new file mode 120000 index 0000000000..66e8af18e9 --- /dev/null +++ b/Lang/SAS/Stair-climbing-puzzle @@ -0,0 +1 @@ +../../Task/Stair-climbing-puzzle/SAS \ No newline at end of file diff --git a/Lang/SNOBOL4/00DESCRIPTION b/Lang/SNOBOL4/00DESCRIPTION index c905e459d3..8b63ef699f 100644 --- a/Lang/SNOBOL4/00DESCRIPTION +++ b/Lang/SNOBOL4/00DESCRIPTION @@ -9,7 +9,7 @@ A later implementation, developed by Robert B. K. Dewar and called "SPITBOL", ad The use of the code() built-in function (which takes source code as input and returns executable code) combined with user-defined datatypes (implemented using the data() built-in function), provides the ability to rather easily implement many object-oriented techniques, including what are essentially constructors and methods (although this terminology evolved after SNOBOL4 and SPITBOL). -CSnobol4 [ftp://ftp.snobol4.org/snobol sources] and [ftp://ftp.snobol4.org/snobol/win32/1.2/ Win32 binary] +CSnobol4 [ftp://ftp.snobol4.org/snobol sources] and [ftp://ftp.snobol4.org/snobol/win32/ Win32 binary] Above also included in Rafal M. Sulejman's [http://rms.republika.pl/slide.shtml TkS*LIDE SNOBOL4 IDE] [[File:Tkslide.png]] \ No newline at end of file diff --git a/Lang/SPARC-Assembly/Hello-world-Text b/Lang/SPARC-Assembly/Hello-world-Text new file mode 120000 index 0000000000..e60ca45014 --- /dev/null +++ b/Lang/SPARC-Assembly/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/SPARC-Assembly \ No newline at end of file diff --git a/Lang/SQL/100-doors b/Lang/SQL/100-doors new file mode 120000 index 0000000000..43eb4b5c7a --- /dev/null +++ b/Lang/SQL/100-doors @@ -0,0 +1 @@ +../../Task/100-doors/SQL \ No newline at end of file diff --git a/Lang/SQL/Associative-array-Creation b/Lang/SQL/Associative-array-Creation new file mode 120000 index 0000000000..a3c9024c3d --- /dev/null +++ b/Lang/SQL/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/SQL \ No newline at end of file diff --git a/Lang/SQL/Comments b/Lang/SQL/Comments new file mode 120000 index 0000000000..17362b4088 --- /dev/null +++ b/Lang/SQL/Comments @@ -0,0 +1 @@ +../../Task/Comments/SQL \ No newline at end of file diff --git a/Lang/SQL/Fibonacci-sequence b/Lang/SQL/Fibonacci-sequence new file mode 120000 index 0000000000..eea45ca440 --- /dev/null +++ b/Lang/SQL/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/SQL \ No newline at end of file diff --git a/Lang/SQL/Gray-code b/Lang/SQL/Gray-code new file mode 120000 index 0000000000..af1f58f56b --- /dev/null +++ b/Lang/SQL/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/SQL \ No newline at end of file diff --git a/Lang/SQL/Middle-three-digits b/Lang/SQL/Middle-three-digits new file mode 120000 index 0000000000..12a3d19b2a --- /dev/null +++ b/Lang/SQL/Middle-three-digits @@ -0,0 +1 @@ +../../Task/Middle-three-digits/SQL \ No newline at end of file diff --git a/Lang/SQL/N-queens-problem b/Lang/SQL/N-queens-problem new file mode 120000 index 0000000000..e52eed9961 --- /dev/null +++ b/Lang/SQL/N-queens-problem @@ -0,0 +1 @@ +../../Task/N-queens-problem/SQL \ No newline at end of file diff --git a/Lang/Scala/00DESCRIPTION b/Lang/Scala/00DESCRIPTION index ff27b4ec4b..5560f22b58 100644 --- a/Lang/Scala/00DESCRIPTION +++ b/Lang/Scala/00DESCRIPTION @@ -11,6 +11,6 @@ {{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 inter-operate with [[Java]] code. -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 language is most focused on the results of the program, therefor the [http://en.wikipedia.org/wiki/Considered_harmful considered harmful] technical computer oriented concepts like threads, semaphore, pointers, coercion, casting, goto- and break statements to struggle with are not there. For parallel processing (that very simple can archived) these concept are present but not visible to the programmer. Lots of RC tasks addresses technical "features" of goto's, break, continue, side effects, pointers, type-casting, weak-typing and so on and are deliberately not Scala's cup of tea. \ No newline at end of file diff --git a/Lang/Scala/Averages-Mean-angle b/Lang/Scala/Averages-Mean-angle new file mode 120000 index 0000000000..55e2eaa5d5 --- /dev/null +++ b/Lang/Scala/Averages-Mean-angle @@ -0,0 +1 @@ +../../Task/Averages-Mean-angle/Scala \ No newline at end of file diff --git a/Lang/Scala/Averages-Mean-time-of-day b/Lang/Scala/Averages-Mean-time-of-day new file mode 120000 index 0000000000..42f8702934 --- /dev/null +++ b/Lang/Scala/Averages-Mean-time-of-day @@ -0,0 +1 @@ +../../Task/Averages-Mean-time-of-day/Scala \ No newline at end of file diff --git a/Lang/Scala/Bitmap-Flood-fill b/Lang/Scala/Bitmap-Flood-fill new file mode 120000 index 0000000000..51cffc8c22 --- /dev/null +++ b/Lang/Scala/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Scala \ No newline at end of file diff --git a/Lang/Scala/Break-OO-privacy b/Lang/Scala/Break-OO-privacy new file mode 120000 index 0000000000..99a1386656 --- /dev/null +++ b/Lang/Scala/Break-OO-privacy @@ -0,0 +1 @@ +../../Task/Break-OO-privacy/Scala \ No newline at end of file diff --git a/Lang/Scala/Call-a-function b/Lang/Scala/Call-a-function new file mode 120000 index 0000000000..60aa118825 --- /dev/null +++ b/Lang/Scala/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/Scala \ No newline at end of file diff --git a/Lang/Scala/Call-a-function-in-a-shared-library b/Lang/Scala/Call-a-function-in-a-shared-library new file mode 120000 index 0000000000..8879ca9ac4 --- /dev/null +++ b/Lang/Scala/Call-a-function-in-a-shared-library @@ -0,0 +1 @@ +../../Task/Call-a-function-in-a-shared-library/Scala \ No newline at end of file diff --git a/Lang/Scala/Color-of-a-screen-pixel b/Lang/Scala/Color-of-a-screen-pixel new file mode 120000 index 0000000000..e097a5154b --- /dev/null +++ b/Lang/Scala/Color-of-a-screen-pixel @@ -0,0 +1 @@ +../../Task/Color-of-a-screen-pixel/Scala \ No newline at end of file diff --git a/Lang/Scala/Conditional-structures b/Lang/Scala/Conditional-structures new file mode 120000 index 0000000000..7e5917ff97 --- /dev/null +++ b/Lang/Scala/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/Scala \ No newline at end of file diff --git a/Lang/Scala/Create-a-file b/Lang/Scala/Create-a-file new file mode 120000 index 0000000000..2169c15480 --- /dev/null +++ b/Lang/Scala/Create-a-file @@ -0,0 +1 @@ +../../Task/Create-a-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Create-an-HTML-table b/Lang/Scala/Create-an-HTML-table new file mode 120000 index 0000000000..11a68f6b72 --- /dev/null +++ b/Lang/Scala/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/Scala \ No newline at end of file diff --git a/Lang/Scala/DNS-query b/Lang/Scala/DNS-query new file mode 120000 index 0000000000..da5f691e7e --- /dev/null +++ b/Lang/Scala/DNS-query @@ -0,0 +1 @@ +../../Task/DNS-query/Scala \ No newline at end of file diff --git a/Lang/Scala/Define-a-primitive-data-type b/Lang/Scala/Define-a-primitive-data-type new file mode 120000 index 0000000000..3f03b5bdab --- /dev/null +++ b/Lang/Scala/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/Scala \ No newline at end of file diff --git a/Lang/Scala/Dutch-national-flag-problem b/Lang/Scala/Dutch-national-flag-problem new file mode 120000 index 0000000000..c6ea469228 --- /dev/null +++ b/Lang/Scala/Dutch-national-flag-problem @@ -0,0 +1 @@ +../../Task/Dutch-national-flag-problem/Scala \ No newline at end of file diff --git a/Lang/Scala/Exceptions b/Lang/Scala/Exceptions new file mode 120000 index 0000000000..2f75311ab2 --- /dev/null +++ b/Lang/Scala/Exceptions @@ -0,0 +1 @@ +../../Task/Exceptions/Scala \ No newline at end of file diff --git a/Lang/Scala/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Scala/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..8e074c5530 --- /dev/null +++ b/Lang/Scala/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Scala \ No newline at end of file diff --git a/Lang/Scala/Fibonacci-n-step-number-sequences b/Lang/Scala/Fibonacci-n-step-number-sequences new file mode 120000 index 0000000000..52ee65ecf4 --- /dev/null +++ b/Lang/Scala/Fibonacci-n-step-number-sequences @@ -0,0 +1 @@ +../../Task/Fibonacci-n-step-number-sequences/Scala \ No newline at end of file diff --git a/Lang/Scala/File-modification-time b/Lang/Scala/File-modification-time new file mode 120000 index 0000000000..f9c8b404d4 --- /dev/null +++ b/Lang/Scala/File-modification-time @@ -0,0 +1 @@ +../../Task/File-modification-time/Scala \ No newline at end of file diff --git a/Lang/Scala/File-size b/Lang/Scala/File-size new file mode 120000 index 0000000000..5e6f01b9af --- /dev/null +++ b/Lang/Scala/File-size @@ -0,0 +1 @@ +../../Task/File-size/Scala \ No newline at end of file diff --git a/Lang/Scala/Find-common-directory-path b/Lang/Scala/Find-common-directory-path new file mode 120000 index 0000000000..32c38db618 --- /dev/null +++ b/Lang/Scala/Find-common-directory-path @@ -0,0 +1 @@ +../../Task/Find-common-directory-path/Scala \ No newline at end of file diff --git a/Lang/Scala/Flow-control-structures b/Lang/Scala/Flow-control-structures new file mode 120000 index 0000000000..70ca58d53f --- /dev/null +++ b/Lang/Scala/Flow-control-structures @@ -0,0 +1 @@ +../../Task/Flow-control-structures/Scala \ No newline at end of file diff --git a/Lang/Scala/Fork b/Lang/Scala/Fork new file mode 120000 index 0000000000..86df0259ae --- /dev/null +++ b/Lang/Scala/Fork @@ -0,0 +1 @@ +../../Task/Fork/Scala \ No newline at end of file diff --git a/Lang/Scala/Handle-a-signal b/Lang/Scala/Handle-a-signal new file mode 120000 index 0000000000..1e3eb93ff5 --- /dev/null +++ b/Lang/Scala/Handle-a-signal @@ -0,0 +1 @@ +../../Task/Handle-a-signal/Scala \ No newline at end of file diff --git a/Lang/Scala/Here-document b/Lang/Scala/Here-document new file mode 120000 index 0000000000..0ac6a899dd --- /dev/null +++ b/Lang/Scala/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/Scala \ No newline at end of file diff --git a/Lang/Scala/Host-introspection b/Lang/Scala/Host-introspection new file mode 120000 index 0000000000..20eb0d3486 --- /dev/null +++ b/Lang/Scala/Host-introspection @@ -0,0 +1 @@ +../../Task/Host-introspection/Scala \ No newline at end of file diff --git a/Lang/Scala/I-before-E-except-after-C b/Lang/Scala/I-before-E-except-after-C new file mode 120000 index 0000000000..6e3c8d6590 --- /dev/null +++ b/Lang/Scala/I-before-E-except-after-C @@ -0,0 +1 @@ +../../Task/I-before-E-except-after-C/Scala \ No newline at end of file diff --git a/Lang/Scala/Inverted-index b/Lang/Scala/Inverted-index new file mode 120000 index 0000000000..246bfa666c --- /dev/null +++ b/Lang/Scala/Inverted-index @@ -0,0 +1 @@ +../../Task/Inverted-index/Scala \ No newline at end of file diff --git a/Lang/Scala/Last-letter-first-letter b/Lang/Scala/Last-letter-first-letter new file mode 120000 index 0000000000..02c8362450 --- /dev/null +++ b/Lang/Scala/Last-letter-first-letter @@ -0,0 +1 @@ +../../Task/Last-letter-first-letter/Scala \ No newline at end of file diff --git a/Lang/Scala/Longest-string-challenge b/Lang/Scala/Longest-string-challenge new file mode 120000 index 0000000000..691283db1c --- /dev/null +++ b/Lang/Scala/Longest-string-challenge @@ -0,0 +1 @@ +../../Task/Longest-string-challenge/Scala \ No newline at end of file diff --git a/Lang/Scala/Loops-N-plus-one-half b/Lang/Scala/Loops-N-plus-one-half new file mode 120000 index 0000000000..a227223912 --- /dev/null +++ b/Lang/Scala/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Scala \ No newline at end of file diff --git a/Lang/Scala/MD4 b/Lang/Scala/MD4 new file mode 120000 index 0000000000..a6228c5c07 --- /dev/null +++ b/Lang/Scala/MD4 @@ -0,0 +1 @@ +../../Task/MD4/Scala \ No newline at end of file diff --git a/Lang/Scala/Mad-Libs b/Lang/Scala/Mad-Libs new file mode 120000 index 0000000000..353901d190 --- /dev/null +++ b/Lang/Scala/Mad-Libs @@ -0,0 +1 @@ +../../Task/Mad-Libs/Scala \ No newline at end of file diff --git a/Lang/Scala/Miller-Rabin-primality-test b/Lang/Scala/Miller-Rabin-primality-test new file mode 120000 index 0000000000..28de5ef463 --- /dev/null +++ b/Lang/Scala/Miller-Rabin-primality-test @@ -0,0 +1 @@ +../../Task/Miller-Rabin-primality-test/Scala \ No newline at end of file diff --git a/Lang/Scala/Number-reversal-game b/Lang/Scala/Number-reversal-game new file mode 120000 index 0000000000..61bae46e1d --- /dev/null +++ b/Lang/Scala/Number-reversal-game @@ -0,0 +1 @@ +../../Task/Number-reversal-game/Scala \ No newline at end of file diff --git a/Lang/Scala/One-of-n-lines-in-a-file b/Lang/Scala/One-of-n-lines-in-a-file new file mode 120000 index 0000000000..86c6e27523 --- /dev/null +++ b/Lang/Scala/One-of-n-lines-in-a-file @@ -0,0 +1 @@ +../../Task/One-of-n-lines-in-a-file/Scala \ No newline at end of file diff --git a/Lang/Scala/OpenGL b/Lang/Scala/OpenGL new file mode 120000 index 0000000000..3040f24c86 --- /dev/null +++ b/Lang/Scala/OpenGL @@ -0,0 +1 @@ +../../Task/OpenGL/Scala \ No newline at end of file diff --git a/Lang/Scala/Order-two-numerical-lists b/Lang/Scala/Order-two-numerical-lists new file mode 120000 index 0000000000..3e5aa07379 --- /dev/null +++ b/Lang/Scala/Order-two-numerical-lists @@ -0,0 +1 @@ +../../Task/Order-two-numerical-lists/Scala \ No newline at end of file diff --git a/Lang/Scala/Permutations-Derangements b/Lang/Scala/Permutations-Derangements new file mode 120000 index 0000000000..68e958359a --- /dev/null +++ b/Lang/Scala/Permutations-Derangements @@ -0,0 +1 @@ +../../Task/Permutations-Derangements/Scala \ No newline at end of file diff --git a/Lang/Scala/Pick-random-element b/Lang/Scala/Pick-random-element new file mode 120000 index 0000000000..ab238241f5 --- /dev/null +++ b/Lang/Scala/Pick-random-element @@ -0,0 +1 @@ +../../Task/Pick-random-element/Scala \ No newline at end of file diff --git a/Lang/Scala/Probabilistic-choice b/Lang/Scala/Probabilistic-choice new file mode 120000 index 0000000000..c27ddc69d4 --- /dev/null +++ b/Lang/Scala/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Scala \ No newline at end of file diff --git a/Lang/Scala/Program-termination b/Lang/Scala/Program-termination new file mode 120000 index 0000000000..3944357f71 --- /dev/null +++ b/Lang/Scala/Program-termination @@ -0,0 +1 @@ +../../Task/Program-termination/Scala \ No newline at end of file diff --git a/Lang/Scala/RIPEMD-160 b/Lang/Scala/RIPEMD-160 new file mode 120000 index 0000000000..303bc02ee2 --- /dev/null +++ b/Lang/Scala/RIPEMD-160 @@ -0,0 +1 @@ +../../Task/RIPEMD-160/Scala \ No newline at end of file diff --git a/Lang/Scala/Record-sound b/Lang/Scala/Record-sound new file mode 120000 index 0000000000..2474428e56 --- /dev/null +++ b/Lang/Scala/Record-sound @@ -0,0 +1 @@ +../../Task/Record-sound/Scala \ No newline at end of file diff --git a/Lang/Scala/Remove-lines-from-a-file b/Lang/Scala/Remove-lines-from-a-file new file mode 120000 index 0000000000..d639b89f58 --- /dev/null +++ b/Lang/Scala/Remove-lines-from-a-file @@ -0,0 +1 @@ +../../Task/Remove-lines-from-a-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Rock-paper-scissors b/Lang/Scala/Rock-paper-scissors new file mode 120000 index 0000000000..055bfbe9e6 --- /dev/null +++ b/Lang/Scala/Rock-paper-scissors @@ -0,0 +1 @@ +../../Task/Rock-paper-scissors/Scala \ No newline at end of file diff --git a/Lang/Scala/Roots-of-a-function b/Lang/Scala/Roots-of-a-function new file mode 120000 index 0000000000..1b60517cbe --- /dev/null +++ b/Lang/Scala/Roots-of-a-function @@ -0,0 +1 @@ +../../Task/Roots-of-a-function/Scala \ No newline at end of file diff --git a/Lang/Scala/SHA-256 b/Lang/Scala/SHA-256 new file mode 120000 index 0000000000..d74bf1a533 --- /dev/null +++ b/Lang/Scala/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Scala \ No newline at end of file diff --git a/Lang/Scala/Send-an-unknown-method-call b/Lang/Scala/Send-an-unknown-method-call new file mode 120000 index 0000000000..c0c8105813 --- /dev/null +++ b/Lang/Scala/Send-an-unknown-method-call @@ -0,0 +1 @@ +../../Task/Send-an-unknown-method-call/Scala \ No newline at end of file diff --git a/Lang/Scala/Set-consolidation b/Lang/Scala/Set-consolidation new file mode 120000 index 0000000000..c24c1bdb41 --- /dev/null +++ b/Lang/Scala/Set-consolidation @@ -0,0 +1 @@ +../../Task/Set-consolidation/Scala \ No newline at end of file diff --git a/Lang/Scala/Simple-database b/Lang/Scala/Simple-database new file mode 120000 index 0000000000..1dbefec3d4 --- /dev/null +++ b/Lang/Scala/Simple-database @@ -0,0 +1 @@ +../../Task/Simple-database/Scala \ No newline at end of file diff --git a/Lang/Scala/Simulate-input-Mouse b/Lang/Scala/Simulate-input-Mouse new file mode 120000 index 0000000000..0f5325c088 --- /dev/null +++ b/Lang/Scala/Simulate-input-Mouse @@ -0,0 +1 @@ +../../Task/Simulate-input-Mouse/Scala \ No newline at end of file diff --git a/Lang/Scala/Sockets b/Lang/Scala/Sockets new file mode 120000 index 0000000000..248b199568 --- /dev/null +++ b/Lang/Scala/Sockets @@ -0,0 +1 @@ +../../Task/Sockets/Scala \ No newline at end of file diff --git a/Lang/Scala/Sort-disjoint-sublist b/Lang/Scala/Sort-disjoint-sublist new file mode 120000 index 0000000000..a65275b011 --- /dev/null +++ b/Lang/Scala/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Scala \ No newline at end of file diff --git a/Lang/Scala/Special-characters b/Lang/Scala/Special-characters new file mode 120000 index 0000000000..d5a294809c --- /dev/null +++ b/Lang/Scala/Special-characters @@ -0,0 +1 @@ +../../Task/Special-characters/Scala \ No newline at end of file diff --git a/Lang/Scala/Standard-deviation b/Lang/Scala/Standard-deviation new file mode 120000 index 0000000000..f03fff484b --- /dev/null +++ b/Lang/Scala/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Scala \ No newline at end of file diff --git a/Lang/Scala/Start-from-a-main-routine b/Lang/Scala/Start-from-a-main-routine new file mode 120000 index 0000000000..245a3f2334 --- /dev/null +++ b/Lang/Scala/Start-from-a-main-routine @@ -0,0 +1 @@ +../../Task/Start-from-a-main-routine/Scala \ No newline at end of file diff --git a/Lang/Scala/String-comparison b/Lang/Scala/String-comparison new file mode 120000 index 0000000000..7568c62c98 --- /dev/null +++ b/Lang/Scala/String-comparison @@ -0,0 +1 @@ +../../Task/String-comparison/Scala \ No newline at end of file diff --git a/Lang/Scala/Strip-block-comments b/Lang/Scala/Strip-block-comments new file mode 120000 index 0000000000..e865966b0b --- /dev/null +++ b/Lang/Scala/Strip-block-comments @@ -0,0 +1 @@ +../../Task/Strip-block-comments/Scala \ No newline at end of file diff --git a/Lang/Scala/Sutherland-Hodgman-polygon-clipping b/Lang/Scala/Sutherland-Hodgman-polygon-clipping new file mode 120000 index 0000000000..a0d3b06cf3 --- /dev/null +++ b/Lang/Scala/Sutherland-Hodgman-polygon-clipping @@ -0,0 +1 @@ +../../Task/Sutherland-Hodgman-polygon-clipping/Scala \ No newline at end of file diff --git a/Lang/Scala/Temperature-conversion b/Lang/Scala/Temperature-conversion new file mode 120000 index 0000000000..4ba34ef506 --- /dev/null +++ b/Lang/Scala/Temperature-conversion @@ -0,0 +1 @@ +../../Task/Temperature-conversion/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Clear-the-screen b/Lang/Scala/Terminal-control-Clear-the-screen new file mode 120000 index 0000000000..fe11225a95 --- /dev/null +++ b/Lang/Scala/Terminal-control-Clear-the-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Clear-the-screen/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Display-an-extended-character b/Lang/Scala/Terminal-control-Display-an-extended-character new file mode 120000 index 0000000000..e35c818006 --- /dev/null +++ b/Lang/Scala/Terminal-control-Display-an-extended-character @@ -0,0 +1 @@ +../../Task/Terminal-control-Display-an-extended-character/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Preserve-screen b/Lang/Scala/Terminal-control-Preserve-screen new file mode 120000 index 0000000000..7ea005849c --- /dev/null +++ b/Lang/Scala/Terminal-control-Preserve-screen @@ -0,0 +1 @@ +../../Task/Terminal-control-Preserve-screen/Scala \ No newline at end of file diff --git a/Lang/Scala/Terminal-control-Unicode-output b/Lang/Scala/Terminal-control-Unicode-output new file mode 120000 index 0000000000..fbb1fcf824 --- /dev/null +++ b/Lang/Scala/Terminal-control-Unicode-output @@ -0,0 +1 @@ +../../Task/Terminal-control-Unicode-output/Scala \ No newline at end of file diff --git a/Lang/Scala/Topswops b/Lang/Scala/Topswops new file mode 120000 index 0000000000..f9f8cb1dfb --- /dev/null +++ b/Lang/Scala/Topswops @@ -0,0 +1 @@ +../../Task/Topswops/Scala \ No newline at end of file diff --git a/Lang/Scala/Trigonometric-functions b/Lang/Scala/Trigonometric-functions new file mode 120000 index 0000000000..5c60a08e6b --- /dev/null +++ b/Lang/Scala/Trigonometric-functions @@ -0,0 +1 @@ +../../Task/Trigonometric-functions/Scala \ No newline at end of file diff --git a/Lang/Scala/Truncate-a-file b/Lang/Scala/Truncate-a-file new file mode 120000 index 0000000000..5a3c68aeec --- /dev/null +++ b/Lang/Scala/Truncate-a-file @@ -0,0 +1 @@ +../../Task/Truncate-a-file/Scala \ No newline at end of file diff --git a/Lang/Scala/URL-encoding b/Lang/Scala/URL-encoding new file mode 120000 index 0000000000..eb876b0f5c --- /dev/null +++ b/Lang/Scala/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/Scala \ No newline at end of file diff --git a/Lang/Scala/Variable-size-Get b/Lang/Scala/Variable-size-Get new file mode 120000 index 0000000000..c314dd0c4b --- /dev/null +++ b/Lang/Scala/Variable-size-Get @@ -0,0 +1 @@ +../../Task/Variable-size-Get/Scala \ No newline at end of file diff --git a/Lang/Scala/Window-creation-X11 b/Lang/Scala/Window-creation-X11 new file mode 120000 index 0000000000..600cf50995 --- /dev/null +++ b/Lang/Scala/Window-creation-X11 @@ -0,0 +1 @@ +../../Task/Window-creation-X11/Scala \ No newline at end of file diff --git a/Lang/Scala/Word-wrap b/Lang/Scala/Word-wrap new file mode 120000 index 0000000000..118d899383 --- /dev/null +++ b/Lang/Scala/Word-wrap @@ -0,0 +1 @@ +../../Task/Word-wrap/Scala \ No newline at end of file diff --git a/Lang/Scala/Write-float-arrays-to-a-text-file b/Lang/Scala/Write-float-arrays-to-a-text-file new file mode 120000 index 0000000000..4c76d0752a --- /dev/null +++ b/Lang/Scala/Write-float-arrays-to-a-text-file @@ -0,0 +1 @@ +../../Task/Write-float-arrays-to-a-text-file/Scala \ No newline at end of file diff --git a/Lang/Scala/Xiaolin-Wus-line-algorithm b/Lang/Scala/Xiaolin-Wus-line-algorithm new file mode 120000 index 0000000000..23fd5e587d --- /dev/null +++ b/Lang/Scala/Xiaolin-Wus-line-algorithm @@ -0,0 +1 @@ +../../Task/Xiaolin-Wus-line-algorithm/Scala \ No newline at end of file diff --git a/Lang/Scala/Zebra-puzzle b/Lang/Scala/Zebra-puzzle new file mode 120000 index 0000000000..626a246729 --- /dev/null +++ b/Lang/Scala/Zebra-puzzle @@ -0,0 +1 @@ +../../Task/Zebra-puzzle/Scala \ No newline at end of file diff --git a/Lang/Scheme/Associative-array-Iteration b/Lang/Scheme/Associative-array-Iteration new file mode 120000 index 0000000000..294539d486 --- /dev/null +++ b/Lang/Scheme/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Count-occurrences-of-a-substring b/Lang/Scheme/Count-occurrences-of-a-substring new file mode 120000 index 0000000000..9bbba1cc10 --- /dev/null +++ b/Lang/Scheme/Count-occurrences-of-a-substring @@ -0,0 +1 @@ +../../Task/Count-occurrences-of-a-substring/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Formatted-numeric-output b/Lang/Scheme/Formatted-numeric-output new file mode 120000 index 0000000000..466b04f88d --- /dev/null +++ b/Lang/Scheme/Formatted-numeric-output @@ -0,0 +1 @@ +../../Task/Formatted-numeric-output/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Huffman-coding b/Lang/Scheme/Huffman-coding new file mode 120000 index 0000000000..2392e84cbb --- /dev/null +++ b/Lang/Scheme/Huffman-coding @@ -0,0 +1 @@ +../../Task/Huffman-coding/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Knights-tour b/Lang/Scheme/Knights-tour new file mode 120000 index 0000000000..edc22c95fc --- /dev/null +++ b/Lang/Scheme/Knights-tour @@ -0,0 +1 @@ +../../Task/Knights-tour/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Largest-int-from-concatenated-ints b/Lang/Scheme/Largest-int-from-concatenated-ints new file mode 120000 index 0000000000..2c755e94e3 --- /dev/null +++ b/Lang/Scheme/Largest-int-from-concatenated-ints @@ -0,0 +1 @@ +../../Task/Largest-int-from-concatenated-ints/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Multisplit b/Lang/Scheme/Multisplit new file mode 120000 index 0000000000..96f6b2c27e --- /dev/null +++ b/Lang/Scheme/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Probabilistic-choice b/Lang/Scheme/Probabilistic-choice new file mode 120000 index 0000000000..48a7693929 --- /dev/null +++ b/Lang/Scheme/Probabilistic-choice @@ -0,0 +1 @@ +../../Task/Probabilistic-choice/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Pythagorean-triples b/Lang/Scheme/Pythagorean-triples new file mode 120000 index 0000000000..b014c61b55 --- /dev/null +++ b/Lang/Scheme/Pythagorean-triples @@ -0,0 +1 @@ +../../Task/Pythagorean-triples/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Roman-numerals-Decode b/Lang/Scheme/Roman-numerals-Decode new file mode 120000 index 0000000000..6d7e851544 --- /dev/null +++ b/Lang/Scheme/Roman-numerals-Decode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Decode/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Same-Fringe b/Lang/Scheme/Same-Fringe new file mode 120000 index 0000000000..3d889c5eb0 --- /dev/null +++ b/Lang/Scheme/Same-Fringe @@ -0,0 +1 @@ +../../Task/Same-Fringe/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Sort-disjoint-sublist b/Lang/Scheme/Sort-disjoint-sublist new file mode 120000 index 0000000000..78c3d2fac7 --- /dev/null +++ b/Lang/Scheme/Sort-disjoint-sublist @@ -0,0 +1 @@ +../../Task/Sort-disjoint-sublist/Scheme \ No newline at end of file diff --git a/Lang/Scheme/Top-rank-per-group b/Lang/Scheme/Top-rank-per-group new file mode 120000 index 0000000000..9180bb39b0 --- /dev/null +++ b/Lang/Scheme/Top-rank-per-group @@ -0,0 +1 @@ +../../Task/Top-rank-per-group/Scheme \ No newline at end of file diff --git a/Lang/Scilab/Ackermann-function b/Lang/Scilab/Ackermann-function new file mode 120000 index 0000000000..e6318af4c5 --- /dev/null +++ b/Lang/Scilab/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Comments b/Lang/Scilab/Comments new file mode 120000 index 0000000000..464ae2820f --- /dev/null +++ b/Lang/Scilab/Comments @@ -0,0 +1 @@ +../../Task/Comments/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Empty-program b/Lang/Scilab/Empty-program new file mode 120000 index 0000000000..0cb8f21cc3 --- /dev/null +++ b/Lang/Scilab/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Fibonacci-sequence b/Lang/Scilab/Fibonacci-sequence new file mode 120000 index 0000000000..5dfa0e2589 --- /dev/null +++ b/Lang/Scilab/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Gamma-function b/Lang/Scilab/Gamma-function new file mode 120000 index 0000000000..c55af43847 --- /dev/null +++ b/Lang/Scilab/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Hailstone-sequence b/Lang/Scilab/Hailstone-sequence new file mode 120000 index 0000000000..4875a03e35 --- /dev/null +++ b/Lang/Scilab/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Lucas-Lehmer-test b/Lang/Scilab/Lucas-Lehmer-test new file mode 120000 index 0000000000..67321718b4 --- /dev/null +++ b/Lang/Scilab/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Monty-Hall-problem b/Lang/Scilab/Monty-Hall-problem new file mode 120000 index 0000000000..33aa97dcfd --- /dev/null +++ b/Lang/Scilab/Monty-Hall-problem @@ -0,0 +1 @@ +../../Task/Monty-Hall-problem/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Sieve-of-Eratosthenes b/Lang/Scilab/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..0ae44deb7c --- /dev/null +++ b/Lang/Scilab/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Sorting-algorithms-Bubble-sort b/Lang/Scilab/Sorting-algorithms-Bubble-sort new file mode 120000 index 0000000000..1c8930d023 --- /dev/null +++ b/Lang/Scilab/Sorting-algorithms-Bubble-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bubble-sort/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Spiral-matrix b/Lang/Scilab/Spiral-matrix new file mode 120000 index 0000000000..63a4577ec4 --- /dev/null +++ b/Lang/Scilab/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/Scilab \ No newline at end of file diff --git a/Lang/Scilab/Standard-deviation b/Lang/Scilab/Standard-deviation new file mode 120000 index 0000000000..c7e14f9fc7 --- /dev/null +++ b/Lang/Scilab/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Scilab \ No newline at end of file diff --git a/Lang/Scilab/String-concatenation b/Lang/Scilab/String-concatenation new file mode 120000 index 0000000000..f21441e698 --- /dev/null +++ b/Lang/Scilab/String-concatenation @@ -0,0 +1 @@ +../../Task/String-concatenation/Scilab \ No newline at end of file diff --git a/Lang/ScriptBasic/Strip-a-set-of-characters-from-a-string b/Lang/ScriptBasic/Strip-a-set-of-characters-from-a-string new file mode 120000 index 0000000000..5482d8eb94 --- /dev/null +++ b/Lang/ScriptBasic/Strip-a-set-of-characters-from-a-string @@ -0,0 +1 @@ +../../Task/Strip-a-set-of-characters-from-a-string/ScriptBasic \ No newline at end of file diff --git a/Lang/Sed/00DESCRIPTION b/Lang/Sed/00DESCRIPTION index ace8ce1731..23390cea6c 100644 --- a/Lang/Sed/00DESCRIPTION +++ b/Lang/Sed/00DESCRIPTION @@ -1,2 +1,10 @@ -{{stub}}{{language}} -This is the command language used by the line oriented stream editor (a non interactive tool for text manipulation and filtering). \ No newline at end of file +{{stub}} +{{language}} +This is the command language used by [[wp:sed]], +the line oriented "stream editor", +a non interactive tool for text manipulation and filtering. + +One implementation is [[GNU Sed]] + +[[Category:Editor]] +[[Category:Utility]] \ No newline at end of file diff --git a/Lang/Sed/Globally-replace-text-in-several-files b/Lang/Sed/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..f20e20126f --- /dev/null +++ b/Lang/Sed/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/Sed \ No newline at end of file diff --git a/Lang/Seed7/00DESCRIPTION b/Lang/Seed7/00DESCRIPTION index c6767895fa..46674935a0 100644 --- a/Lang/Seed7/00DESCRIPTION +++ b/Lang/Seed7/00DESCRIPTION @@ -1,7 +1,10 @@ {{language|Seed7 |site=http://seed7.sourceforge.net/ |checking=static -|exec=both}} +|strength=strong +|exec=both +|parampass=both +|LCT=yes}} {{language programming paradigm|object-oriented}}'''Seed7''' is a general-purpose programming language designed by Thomas Mertes. It is a higher level language compared to [[Ada]], [[C]] / [[C++]] and [[Java]]. The Seed7 interpreter, and the example programs are [[Open source|open-source]] software. An open-source Seed7 [[compiler]] is also available. In Seed7 new statements and operators can be declared easily. Functions with type results and type parameters are more elegant than the usual template or generics concept. [[Object-oriented_programming|Object orientation]] is used when it brings advantages and not in places when other solutions are more obvious. Although Seed7 contains several concepts of other programming languages it cannot be seen as direct descendant of another programming language. diff --git a/Lang/Seed7/Abstract-type b/Lang/Seed7/Abstract-type new file mode 120000 index 0000000000..0cb4d1a771 --- /dev/null +++ b/Lang/Seed7/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Anonymous-recursion b/Lang/Seed7/Anonymous-recursion new file mode 120000 index 0000000000..6fdada8702 --- /dev/null +++ b/Lang/Seed7/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Average-loop-length b/Lang/Seed7/Average-loop-length new file mode 120000 index 0000000000..095ca2ee8f --- /dev/null +++ b/Lang/Seed7/Average-loop-length @@ -0,0 +1 @@ +../../Task/Average-loop-length/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Bulls-and-cows b/Lang/Seed7/Bulls-and-cows new file mode 120000 index 0000000000..1c83c04116 --- /dev/null +++ b/Lang/Seed7/Bulls-and-cows @@ -0,0 +1 @@ +../../Task/Bulls-and-cows/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Deal-cards-for-FreeCell b/Lang/Seed7/Deal-cards-for-FreeCell new file mode 120000 index 0000000000..c2f20e7c56 --- /dev/null +++ b/Lang/Seed7/Deal-cards-for-FreeCell @@ -0,0 +1 @@ +../../Task/Deal-cards-for-FreeCell/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Delete-a-file b/Lang/Seed7/Delete-a-file new file mode 120000 index 0000000000..74250c1d14 --- /dev/null +++ b/Lang/Seed7/Delete-a-file @@ -0,0 +1 @@ +../../Task/Delete-a-file/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Determine-if-a-string-is-numeric b/Lang/Seed7/Determine-if-a-string-is-numeric new file mode 120000 index 0000000000..afcb5d2e7e --- /dev/null +++ b/Lang/Seed7/Determine-if-a-string-is-numeric @@ -0,0 +1 @@ +../../Task/Determine-if-a-string-is-numeric/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Exceptions-Catch-an-exception-thrown-in-a-nested-call b/Lang/Seed7/Exceptions-Catch-an-exception-thrown-in-a-nested-call new file mode 120000 index 0000000000..3226e19ce9 --- /dev/null +++ b/Lang/Seed7/Exceptions-Catch-an-exception-thrown-in-a-nested-call @@ -0,0 +1 @@ +../../Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Find-the-missing-permutation b/Lang/Seed7/Find-the-missing-permutation new file mode 120000 index 0000000000..46ad48d8f7 --- /dev/null +++ b/Lang/Seed7/Find-the-missing-permutation @@ -0,0 +1 @@ +../../Task/Find-the-missing-permutation/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Gray-code b/Lang/Seed7/Gray-code new file mode 120000 index 0000000000..fb73892c32 --- /dev/null +++ b/Lang/Seed7/Gray-code @@ -0,0 +1 @@ +../../Task/Gray-code/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Hello-world-Line-printer b/Lang/Seed7/Hello-world-Line-printer new file mode 120000 index 0000000000..692c70db76 --- /dev/null +++ b/Lang/Seed7/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Langtons-ant b/Lang/Seed7/Langtons-ant new file mode 120000 index 0000000000..d6d0266978 --- /dev/null +++ b/Lang/Seed7/Langtons-ant @@ -0,0 +1 @@ +../../Task/Langtons-ant/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Nautical-bell b/Lang/Seed7/Nautical-bell new file mode 120000 index 0000000000..e9ca686112 --- /dev/null +++ b/Lang/Seed7/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Non-continuous-subsequences b/Lang/Seed7/Non-continuous-subsequences new file mode 120000 index 0000000000..fa63e749e1 --- /dev/null +++ b/Lang/Seed7/Non-continuous-subsequences @@ -0,0 +1 @@ +../../Task/Non-continuous-subsequences/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Parametrized-SQL-statement b/Lang/Seed7/Parametrized-SQL-statement new file mode 120000 index 0000000000..1952419254 --- /dev/null +++ b/Lang/Seed7/Parametrized-SQL-statement @@ -0,0 +1 @@ +../../Task/Parametrized-SQL-statement/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Solve-a-Hidato-puzzle b/Lang/Seed7/Solve-a-Hidato-puzzle new file mode 120000 index 0000000000..6b3998c2c7 --- /dev/null +++ b/Lang/Seed7/Solve-a-Hidato-puzzle @@ -0,0 +1 @@ +../../Task/Solve-a-Hidato-puzzle/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Sorting-algorithms-Bead-sort b/Lang/Seed7/Sorting-algorithms-Bead-sort new file mode 120000 index 0000000000..abba6bc377 --- /dev/null +++ b/Lang/Seed7/Sorting-algorithms-Bead-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Bead-sort/Seed7 \ No newline at end of file diff --git a/Lang/Seed7/Window-creation b/Lang/Seed7/Window-creation new file mode 120000 index 0000000000..79f8a74c12 --- /dev/null +++ b/Lang/Seed7/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/Seed7 \ No newline at end of file diff --git a/Lang/Simula/Comments b/Lang/Simula/Comments new file mode 120000 index 0000000000..54ff2814be --- /dev/null +++ b/Lang/Simula/Comments @@ -0,0 +1 @@ +../../Task/Comments/Simula \ No newline at end of file diff --git a/Lang/Simula/Empty-program b/Lang/Simula/Empty-program new file mode 120000 index 0000000000..dbbf9f032f --- /dev/null +++ b/Lang/Simula/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Simula \ No newline at end of file diff --git a/Lang/Simula/Hello-world-Line-printer b/Lang/Simula/Hello-world-Line-printer new file mode 120000 index 0000000000..29fd7e12a7 --- /dev/null +++ b/Lang/Simula/Hello-world-Line-printer @@ -0,0 +1 @@ +../../Task/Hello-world-Line-printer/Simula \ No newline at end of file diff --git a/Lang/Simula/Hello-world-Text b/Lang/Simula/Hello-world-Text new file mode 120000 index 0000000000..856380579c --- /dev/null +++ b/Lang/Simula/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Simula \ No newline at end of file diff --git a/Lang/Simula/Loops-For b/Lang/Simula/Loops-For new file mode 120000 index 0000000000..9ffeaf8e7f --- /dev/null +++ b/Lang/Simula/Loops-For @@ -0,0 +1 @@ +../../Task/Loops-For/Simula \ No newline at end of file diff --git a/Lang/Smalltalk/Cholesky-decomposition b/Lang/Smalltalk/Cholesky-decomposition new file mode 120000 index 0000000000..a9ae2833f1 --- /dev/null +++ b/Lang/Smalltalk/Cholesky-decomposition @@ -0,0 +1 @@ +../../Task/Cholesky-decomposition/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Date-format b/Lang/Smalltalk/Date-format new file mode 120000 index 0000000000..57e6970aa4 --- /dev/null +++ b/Lang/Smalltalk/Date-format @@ -0,0 +1 @@ +../../Task/Date-format/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Empty-string b/Lang/Smalltalk/Empty-string new file mode 120000 index 0000000000..70272c1fe7 --- /dev/null +++ b/Lang/Smalltalk/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Environment-variables b/Lang/Smalltalk/Environment-variables new file mode 120000 index 0000000000..401244d890 --- /dev/null +++ b/Lang/Smalltalk/Environment-variables @@ -0,0 +1 @@ +../../Task/Environment-variables/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Hello-world-Newline-omission b/Lang/Smalltalk/Hello-world-Newline-omission new file mode 120000 index 0000000000..2bb985cdd4 --- /dev/null +++ b/Lang/Smalltalk/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/JSON b/Lang/Smalltalk/JSON new file mode 120000 index 0000000000..86ccee1f27 --- /dev/null +++ b/Lang/Smalltalk/JSON @@ -0,0 +1 @@ +../../Task/JSON/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Leap-year b/Lang/Smalltalk/Leap-year new file mode 120000 index 0000000000..eb77f3542f --- /dev/null +++ b/Lang/Smalltalk/Leap-year @@ -0,0 +1 @@ +../../Task/Leap-year/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Least-common-multiple b/Lang/Smalltalk/Least-common-multiple new file mode 120000 index 0000000000..25b6f564e2 --- /dev/null +++ b/Lang/Smalltalk/Least-common-multiple @@ -0,0 +1 @@ +../../Task/Least-common-multiple/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Mouse-position b/Lang/Smalltalk/Mouse-position new file mode 120000 index 0000000000..9241ad948f --- /dev/null +++ b/Lang/Smalltalk/Mouse-position @@ -0,0 +1 @@ +../../Task/Mouse-position/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Read-a-specific-line-from-a-file b/Lang/Smalltalk/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..0fb297b010 --- /dev/null +++ b/Lang/Smalltalk/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/SHA-256 b/Lang/Smalltalk/SHA-256 new file mode 120000 index 0000000000..f3ac5e9f9e --- /dev/null +++ b/Lang/Smalltalk/SHA-256 @@ -0,0 +1 @@ +../../Task/SHA-256/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Singleton b/Lang/Smalltalk/Singleton new file mode 120000 index 0000000000..307dfecbb6 --- /dev/null +++ b/Lang/Smalltalk/Singleton @@ -0,0 +1 @@ +../../Task/Singleton/Smalltalk \ No newline at end of file diff --git a/Lang/Smalltalk/Stack b/Lang/Smalltalk/Stack new file mode 120000 index 0000000000..45cbca8618 --- /dev/null +++ b/Lang/Smalltalk/Stack @@ -0,0 +1 @@ +../../Task/Stack/Smalltalk \ No newline at end of file diff --git a/Lang/Standard-ML/Abstract-type b/Lang/Standard-ML/Abstract-type new file mode 120000 index 0000000000..33923aa60b --- /dev/null +++ b/Lang/Standard-ML/Abstract-type @@ -0,0 +1 @@ +../../Task/Abstract-type/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Anonymous-recursion b/Lang/Standard-ML/Anonymous-recursion new file mode 120000 index 0000000000..46607ae96c --- /dev/null +++ b/Lang/Standard-ML/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Bitmap-Flood-fill b/Lang/Standard-ML/Bitmap-Flood-fill new file mode 120000 index 0000000000..fc8d437f0e --- /dev/null +++ b/Lang/Standard-ML/Bitmap-Flood-fill @@ -0,0 +1 @@ +../../Task/Bitmap-Flood-fill/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Empty-string b/Lang/Standard-ML/Empty-string new file mode 120000 index 0000000000..a72d668f08 --- /dev/null +++ b/Lang/Standard-ML/Empty-string @@ -0,0 +1 @@ +../../Task/Empty-string/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Sorting-algorithms-Heapsort b/Lang/Standard-ML/Sorting-algorithms-Heapsort new file mode 120000 index 0000000000..75f0fa1214 --- /dev/null +++ b/Lang/Standard-ML/Sorting-algorithms-Heapsort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Heapsort/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Soundex b/Lang/Standard-ML/Soundex new file mode 120000 index 0000000000..04b638d1f0 --- /dev/null +++ b/Lang/Standard-ML/Soundex @@ -0,0 +1 @@ +../../Task/Soundex/Standard-ML \ No newline at end of file diff --git a/Lang/Standard-ML/Topic-variable b/Lang/Standard-ML/Topic-variable new file mode 120000 index 0000000000..f84b3a31e4 --- /dev/null +++ b/Lang/Standard-ML/Topic-variable @@ -0,0 +1 @@ +../../Task/Topic-variable/Standard-ML \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Conditional-structures b/Lang/TI-83-BASIC/Conditional-structures new file mode 120000 index 0000000000..ba50a824a4 --- /dev/null +++ b/Lang/TI-83-BASIC/Conditional-structures @@ -0,0 +1 @@ +../../Task/Conditional-structures/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Factorial b/Lang/TI-83-BASIC/Factorial new file mode 120000 index 0000000000..f66af16bfd --- /dev/null +++ b/Lang/TI-83-BASIC/Factorial @@ -0,0 +1 @@ +../../Task/Factorial/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Gamma-function b/Lang/TI-83-BASIC/Gamma-function new file mode 120000 index 0000000000..e15928ce92 --- /dev/null +++ b/Lang/TI-83-BASIC/Gamma-function @@ -0,0 +1 @@ +../../Task/Gamma-function/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Hailstone-sequence b/Lang/TI-83-BASIC/Hailstone-sequence new file mode 120000 index 0000000000..25c76f8826 --- /dev/null +++ b/Lang/TI-83-BASIC/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Loops-While b/Lang/TI-83-BASIC/Loops-While new file mode 120000 index 0000000000..8d23915763 --- /dev/null +++ b/Lang/TI-83-BASIC/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Lucas-Lehmer-test b/Lang/TI-83-BASIC/Lucas-Lehmer-test new file mode 120000 index 0000000000..69d829749e --- /dev/null +++ b/Lang/TI-83-BASIC/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Sieve-of-Eratosthenes b/Lang/TI-83-BASIC/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..d4376dca91 --- /dev/null +++ b/Lang/TI-83-BASIC/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TI-83-BASIC/Spiral-matrix b/Lang/TI-83-BASIC/Spiral-matrix new file mode 120000 index 0000000000..88cd3c55a5 --- /dev/null +++ b/Lang/TI-83-BASIC/Spiral-matrix @@ -0,0 +1 @@ +../../Task/Spiral-matrix/TI-83-BASIC \ No newline at end of file diff --git a/Lang/TXR/Anonymous-recursion b/Lang/TXR/Anonymous-recursion new file mode 120000 index 0000000000..ddedb8e4b8 --- /dev/null +++ b/Lang/TXR/Anonymous-recursion @@ -0,0 +1 @@ +../../Task/Anonymous-recursion/TXR \ No newline at end of file diff --git a/Lang/TXR/First-class-functions b/Lang/TXR/First-class-functions new file mode 120000 index 0000000000..4e56221372 --- /dev/null +++ b/Lang/TXR/First-class-functions @@ -0,0 +1 @@ +../../Task/First-class-functions/TXR \ No newline at end of file diff --git a/Lang/TXR/Self-referential-sequence b/Lang/TXR/Self-referential-sequence new file mode 120000 index 0000000000..3112f0fb8b --- /dev/null +++ b/Lang/TXR/Self-referential-sequence @@ -0,0 +1 @@ +../../Task/Self-referential-sequence/TXR \ No newline at end of file diff --git a/Lang/Tcl/00DESCRIPTION b/Lang/Tcl/00DESCRIPTION index 46405cdc35..5ad88d1a46 100644 --- a/Lang/Tcl/00DESCRIPTION +++ b/Lang/Tcl/00DESCRIPTION @@ -20,20 +20,40 @@ {{language programming paradigm|Reflective}} {{Codepad}} -'''Tcl''' (short for '''T'''ool '''C'''ommand '''L'''anguage) is a scripting language with very simple syntax, dynamic typing, automatic storage allocation and [[garbage collection]] and native Unicode support. '''Tcl''' is often combined with the [[Tk]] library. As a result, it is often referred to as '''Tcl/Tk'''. +'''Tcl''' (short for '''T'''ool '''C'''ommand '''L'''anguage) +is a scripting language with very simple syntax, dynamic typing, +automatic storage allocation and [[garbage collection]] +and native Unicode support.
+'''Tcl''' is often combined with the [[Tk]] library, +which provides support for graphics and GUI.
+As a result, it is often referred to as '''Tcl/Tk'''. -Tcl is known to be supported under a variety of popular operating systems, including [[UNIX]], [[Linux]], [[BSD]], [[Windows]], [[WinCE]], [[PocketPC]], [[Mac OS X]] and [[BeOS]]. Tcl is distributed under the [[wp:BSD licenses|BSD License]]. +Tcl is known to be supported under a variety of popular operating systems, +including [[UNIX]], [[Linux]], [[BSD]], [[Windows]], [[WinCE]], [[PocketPC]], +[[Mac OS X]] and [[BeOS]].
+Tcl is distributed under the [[wp:BSD licenses|BSD License]]. -The Tcl language has been implemented in multiple lower-level languages. The most common one is '''[[libtcl]]''', written in [[C]], which is the engine used to power [[tclsh]] and [[wish]], but others exist. Notably, these include [[Jacl]] and [[Eagle]], which implement Tcl in [[Java]] and [[C sharp|C#]] respectively. +;Current version: Tcl/Tk 8.6.3 (2014-11-12) + +The Tcl language has been implemented in multiple lower-level languages. +The most common one is '''[[libtcl]]''', written in [[C]], which is +the engine used to power [[tclsh]] and [[wish]], but others exist. +Notably, these include [[Jacl]] and [[Eagle]], which implement +Tcl in [[Java]] and [[C sharp|C#]] respectively. Its creator, John Ousterhout, wrote about it: :''“I got the idea for Tcl while on sabbatical leave at DEC's Western Research Laboratory in the fall of 1987. I started actually implementing it when I got back to Berkeley in the spring of 1988; by summer of that year it was in use in some internal applications of ours, but there was no Tk. The first external releases of Tcl were in 1989, I believe. I started implementing Tk in 1989, and the first release of Tk was in 1991.”'' -The principal pre-built distributions of Tcl are all based on [[libtcl]]; the main ones are [[ActiveTcl]] from ActiveState, and [[tclkit]] from Equi4 Software ''et al''. Older versions of the language are distributed as part of Apple's OSX and all Linux distributions. +The principal pre-built distributions of Tcl are all based on [[libtcl]]; +the main ones are [[ActiveTcl]] from ActiveState, +and [[tclkit]] from Equi4 Software ''et al''.
+Older versions of the language are distributed as part of +Apple's OSX and all Linux distributions. ==Language Syntax== ===Grammar=== -Note that this is a simplified language grammar, and it is normal to think of the language at a higher level where these differences don't show. +Note that this is a simplified language grammar, and it is normal +to think of the language at a higher level where these differences don't show.
script '''::=''' command'''? ((''' “''\n''” '''|''' “'';''” ''')''' script ''')''' command '''::=''' “''#''” characters “''\n''” /* comment */ diff --git a/Lang/TorqueScript/Comments b/Lang/TorqueScript/Comments new file mode 120000 index 0000000000..ec4ce7359a --- /dev/null +++ b/Lang/TorqueScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/TorqueScript \ No newline at end of file diff --git a/Lang/TorqueScript/Loops-For-with-a-specified-step b/Lang/TorqueScript/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..17c097b337 --- /dev/null +++ b/Lang/TorqueScript/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/TorqueScript \ No newline at end of file diff --git a/Lang/TorqueScript/Window-creation b/Lang/TorqueScript/Window-creation new file mode 120000 index 0000000000..798773d26c --- /dev/null +++ b/Lang/TorqueScript/Window-creation @@ -0,0 +1 @@ +../../Task/Window-creation/TorqueScript \ No newline at end of file diff --git a/Lang/Transact-SQL/Hello-world-Newline-omission b/Lang/Transact-SQL/Hello-world-Newline-omission new file mode 120000 index 0000000000..5784e38eab --- /dev/null +++ b/Lang/Transact-SQL/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Transact-SQL \ No newline at end of file diff --git a/Lang/Transact-SQL/Hello-world-Standard-error b/Lang/Transact-SQL/Hello-world-Standard-error new file mode 120000 index 0000000000..97e569c7d4 --- /dev/null +++ b/Lang/Transact-SQL/Hello-world-Standard-error @@ -0,0 +1 @@ +../../Task/Hello-world-Standard-error/Transact-SQL \ No newline at end of file diff --git a/Lang/Transact-SQL/SEDOLs b/Lang/Transact-SQL/SEDOLs new file mode 120000 index 0000000000..3e496ef65e --- /dev/null +++ b/Lang/Transact-SQL/SEDOLs @@ -0,0 +1 @@ +../../Task/SEDOLs/Transact-SQL \ No newline at end of file diff --git a/Lang/UBASIC/Haversine-formula b/Lang/UBASIC/Haversine-formula new file mode 120000 index 0000000000..3ee87f1567 --- /dev/null +++ b/Lang/UBASIC/Haversine-formula @@ -0,0 +1 @@ +../../Task/Haversine-formula/UBASIC \ No newline at end of file diff --git a/Lang/UNIX-Shell/24-game b/Lang/UNIX-Shell/24-game new file mode 120000 index 0000000000..2fa8cc235f --- /dev/null +++ b/Lang/UNIX-Shell/24-game @@ -0,0 +1 @@ +../../Task/24-game/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Anagrams b/Lang/UNIX-Shell/Anagrams new file mode 120000 index 0000000000..5e5130dc57 --- /dev/null +++ b/Lang/UNIX-Shell/Anagrams @@ -0,0 +1 @@ +../../Task/Anagrams/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Anagrams-Deranged-anagrams b/Lang/UNIX-Shell/Anagrams-Deranged-anagrams new file mode 120000 index 0000000000..c2f3f63a81 --- /dev/null +++ b/Lang/UNIX-Shell/Anagrams-Deranged-anagrams @@ -0,0 +1 @@ +../../Task/Anagrams-Deranged-anagrams/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Arithmetic-Complex b/Lang/UNIX-Shell/Arithmetic-Complex new file mode 120000 index 0000000000..77bf240d19 --- /dev/null +++ b/Lang/UNIX-Shell/Arithmetic-Complex @@ -0,0 +1 @@ +../../Task/Arithmetic-Complex/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Arithmetic-geometric-mean b/Lang/UNIX-Shell/Arithmetic-geometric-mean new file mode 120000 index 0000000000..89e8137e0d --- /dev/null +++ b/Lang/UNIX-Shell/Arithmetic-geometric-mean @@ -0,0 +1 @@ +../../Task/Arithmetic-geometric-mean/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Assertions b/Lang/UNIX-Shell/Assertions new file mode 120000 index 0000000000..fd468e21b7 --- /dev/null +++ b/Lang/UNIX-Shell/Assertions @@ -0,0 +1 @@ +../../Task/Assertions/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Associative-array-Creation b/Lang/UNIX-Shell/Associative-array-Creation new file mode 120000 index 0000000000..dac1fcf657 --- /dev/null +++ b/Lang/UNIX-Shell/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Balanced-brackets b/Lang/UNIX-Shell/Balanced-brackets new file mode 120000 index 0000000000..9ce611149a --- /dev/null +++ b/Lang/UNIX-Shell/Balanced-brackets @@ -0,0 +1 @@ +../../Task/Balanced-brackets/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Bitmap b/Lang/UNIX-Shell/Bitmap new file mode 120000 index 0000000000..f30df6292d --- /dev/null +++ b/Lang/UNIX-Shell/Bitmap @@ -0,0 +1 @@ +../../Task/Bitmap/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Bitmap-Read-a-PPM-file b/Lang/UNIX-Shell/Bitmap-Read-a-PPM-file new file mode 120000 index 0000000000..48988d2a52 --- /dev/null +++ b/Lang/UNIX-Shell/Bitmap-Read-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Read-a-PPM-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Bitmap-Write-a-PPM-file b/Lang/UNIX-Shell/Bitmap-Write-a-PPM-file new file mode 120000 index 0000000000..94fe4efddd --- /dev/null +++ b/Lang/UNIX-Shell/Bitmap-Write-a-PPM-file @@ -0,0 +1 @@ +../../Task/Bitmap-Write-a-PPM-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/CSV-to-HTML-translation b/Lang/UNIX-Shell/CSV-to-HTML-translation new file mode 120000 index 0000000000..6b7ee4bbb0 --- /dev/null +++ b/Lang/UNIX-Shell/CSV-to-HTML-translation @@ -0,0 +1 @@ +../../Task/CSV-to-HTML-translation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Caesar-cipher b/Lang/UNIX-Shell/Caesar-cipher new file mode 120000 index 0000000000..e7782d6d97 --- /dev/null +++ b/Lang/UNIX-Shell/Caesar-cipher @@ -0,0 +1 @@ +../../Task/Caesar-cipher/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Classes b/Lang/UNIX-Shell/Classes new file mode 120000 index 0000000000..bf2dfe2463 --- /dev/null +++ b/Lang/UNIX-Shell/Classes @@ -0,0 +1 @@ +../../Task/Classes/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Collections b/Lang/UNIX-Shell/Collections new file mode 120000 index 0000000000..fb478a3de8 --- /dev/null +++ b/Lang/UNIX-Shell/Collections @@ -0,0 +1 @@ +../../Task/Collections/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Compound-data-type b/Lang/UNIX-Shell/Compound-data-type new file mode 120000 index 0000000000..c5aee94f0a --- /dev/null +++ b/Lang/UNIX-Shell/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Create-an-HTML-table b/Lang/UNIX-Shell/Create-an-HTML-table new file mode 120000 index 0000000000..293f665858 --- /dev/null +++ b/Lang/UNIX-Shell/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Define-a-primitive-data-type b/Lang/UNIX-Shell/Define-a-primitive-data-type new file mode 120000 index 0000000000..dfe40bd93e --- /dev/null +++ b/Lang/UNIX-Shell/Define-a-primitive-data-type @@ -0,0 +1 @@ +../../Task/Define-a-primitive-data-type/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Five-weekends b/Lang/UNIX-Shell/Five-weekends new file mode 120000 index 0000000000..6ac4c6790e --- /dev/null +++ b/Lang/UNIX-Shell/Five-weekends @@ -0,0 +1 @@ +../../Task/Five-weekends/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Generic-swap b/Lang/UNIX-Shell/Generic-swap new file mode 120000 index 0000000000..cf999051fe --- /dev/null +++ b/Lang/UNIX-Shell/Generic-swap @@ -0,0 +1 @@ +../../Task/Generic-swap/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Globally-replace-text-in-several-files b/Lang/UNIX-Shell/Globally-replace-text-in-several-files new file mode 120000 index 0000000000..9b7f1db192 --- /dev/null +++ b/Lang/UNIX-Shell/Globally-replace-text-in-several-files @@ -0,0 +1 @@ +../../Task/Globally-replace-text-in-several-files/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Guess-the-number-With-feedback--player- b/Lang/UNIX-Shell/Guess-the-number-With-feedback--player- new file mode 120000 index 0000000000..8f27c1a758 --- /dev/null +++ b/Lang/UNIX-Shell/Guess-the-number-With-feedback--player- @@ -0,0 +1 @@ +../../Task/Guess-the-number-With-feedback--player-/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Hamming-numbers b/Lang/UNIX-Shell/Hamming-numbers new file mode 120000 index 0000000000..9da4378e4f --- /dev/null +++ b/Lang/UNIX-Shell/Hamming-numbers @@ -0,0 +1 @@ +../../Task/Hamming-numbers/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Hash-from-two-arrays b/Lang/UNIX-Shell/Hash-from-two-arrays new file mode 120000 index 0000000000..68fb2a57ec --- /dev/null +++ b/Lang/UNIX-Shell/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Hello-world-Web-server b/Lang/UNIX-Shell/Hello-world-Web-server new file mode 120000 index 0000000000..f05d5df320 --- /dev/null +++ b/Lang/UNIX-Shell/Hello-world-Web-server @@ -0,0 +1 @@ +../../Task/Hello-world-Web-server/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Introspection b/Lang/UNIX-Shell/Introspection new file mode 120000 index 0000000000..c6cc32aaed --- /dev/null +++ b/Lang/UNIX-Shell/Introspection @@ -0,0 +1 @@ +../../Task/Introspection/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Linear-congruential-generator b/Lang/UNIX-Shell/Linear-congruential-generator new file mode 120000 index 0000000000..a81447f2e9 --- /dev/null +++ b/Lang/UNIX-Shell/Linear-congruential-generator @@ -0,0 +1 @@ +../../Task/Linear-congruential-generator/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Look-and-say-sequence b/Lang/UNIX-Shell/Look-and-say-sequence new file mode 120000 index 0000000000..4f318cb6bd --- /dev/null +++ b/Lang/UNIX-Shell/Look-and-say-sequence @@ -0,0 +1 @@ +../../Task/Look-and-say-sequence/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Luhn-test-of-credit-card-numbers b/Lang/UNIX-Shell/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..432440167a --- /dev/null +++ b/Lang/UNIX-Shell/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Multisplit b/Lang/UNIX-Shell/Multisplit new file mode 120000 index 0000000000..a423fdb6d1 --- /dev/null +++ b/Lang/UNIX-Shell/Multisplit @@ -0,0 +1 @@ +../../Task/Multisplit/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Queue-Definition b/Lang/UNIX-Shell/Queue-Definition new file mode 120000 index 0000000000..a49b27793d --- /dev/null +++ b/Lang/UNIX-Shell/Queue-Definition @@ -0,0 +1 @@ +../../Task/Queue-Definition/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Queue-Usage b/Lang/UNIX-Shell/Queue-Usage new file mode 120000 index 0000000000..adbac577e2 --- /dev/null +++ b/Lang/UNIX-Shell/Queue-Usage @@ -0,0 +1 @@ +../../Task/Queue-Usage/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Random-number-generator--device- b/Lang/UNIX-Shell/Random-number-generator--device- new file mode 120000 index 0000000000..51568e52e5 --- /dev/null +++ b/Lang/UNIX-Shell/Random-number-generator--device- @@ -0,0 +1 @@ +../../Task/Random-number-generator--device-/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Read-a-configuration-file b/Lang/UNIX-Shell/Read-a-configuration-file new file mode 120000 index 0000000000..be929cf13d --- /dev/null +++ b/Lang/UNIX-Shell/Read-a-configuration-file @@ -0,0 +1 @@ +../../Task/Read-a-configuration-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Read-a-specific-line-from-a-file b/Lang/UNIX-Shell/Read-a-specific-line-from-a-file new file mode 120000 index 0000000000..2237a89d0f --- /dev/null +++ b/Lang/UNIX-Shell/Read-a-specific-line-from-a-file @@ -0,0 +1 @@ +../../Task/Read-a-specific-line-from-a-file/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Real-constants-and-functions b/Lang/UNIX-Shell/Real-constants-and-functions new file mode 120000 index 0000000000..90eaf6a717 --- /dev/null +++ b/Lang/UNIX-Shell/Real-constants-and-functions @@ -0,0 +1 @@ +../../Task/Real-constants-and-functions/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Regular-expressions b/Lang/UNIX-Shell/Regular-expressions new file mode 120000 index 0000000000..454acd77e6 --- /dev/null +++ b/Lang/UNIX-Shell/Regular-expressions @@ -0,0 +1 @@ +../../Task/Regular-expressions/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Roman-numerals-Encode b/Lang/UNIX-Shell/Roman-numerals-Encode new file mode 120000 index 0000000000..791bac31e9 --- /dev/null +++ b/Lang/UNIX-Shell/Roman-numerals-Encode @@ -0,0 +1 @@ +../../Task/Roman-numerals-Encode/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Runtime-evaluation b/Lang/UNIX-Shell/Runtime-evaluation new file mode 120000 index 0000000000..a8c07cbf09 --- /dev/null +++ b/Lang/UNIX-Shell/Runtime-evaluation @@ -0,0 +1 @@ +../../Task/Runtime-evaluation/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Search-a-list b/Lang/UNIX-Shell/Search-a-list new file mode 120000 index 0000000000..79d64c2df4 --- /dev/null +++ b/Lang/UNIX-Shell/Search-a-list @@ -0,0 +1 @@ +../../Task/Search-a-list/UNIX-Shell \ No newline at end of file diff --git a/Lang/UNIX-Shell/Self-describing-numbers b/Lang/UNIX-Shell/Self-describing-numbers new file mode 120000 index 0000000000..0fadeb57d5 --- /dev/null +++ b/Lang/UNIX-Shell/Self-describing-numbers @@ -0,0 +1 @@ +../../Task/Self-describing-numbers/UNIX-Shell \ No newline at end of file diff --git a/Lang/VBA/Comments b/Lang/VBA/Comments new file mode 120000 index 0000000000..1374378fb3 --- /dev/null +++ b/Lang/VBA/Comments @@ -0,0 +1 @@ +../../Task/Comments/VBA \ No newline at end of file diff --git a/Lang/VBA/Parsing-RPN-calculator-algorithm b/Lang/VBA/Parsing-RPN-calculator-algorithm new file mode 120000 index 0000000000..9061aedc91 --- /dev/null +++ b/Lang/VBA/Parsing-RPN-calculator-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-RPN-calculator-algorithm/VBA \ No newline at end of file diff --git a/Lang/VBA/Parsing-Shunting-yard-algorithm b/Lang/VBA/Parsing-Shunting-yard-algorithm new file mode 120000 index 0000000000..73665d094e --- /dev/null +++ b/Lang/VBA/Parsing-Shunting-yard-algorithm @@ -0,0 +1 @@ +../../Task/Parsing-Shunting-yard-algorithm/VBA \ No newline at end of file diff --git a/Lang/VBScript/Comments b/Lang/VBScript/Comments new file mode 120000 index 0000000000..c69310e0c3 --- /dev/null +++ b/Lang/VBScript/Comments @@ -0,0 +1 @@ +../../Task/Comments/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Greatest-common-divisor b/Lang/VBScript/Greatest-common-divisor new file mode 120000 index 0000000000..21744ee391 --- /dev/null +++ b/Lang/VBScript/Greatest-common-divisor @@ -0,0 +1 @@ +../../Task/Greatest-common-divisor/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Hello-world-Graphical b/Lang/VBScript/Hello-world-Graphical new file mode 120000 index 0000000000..2da85a0d7f --- /dev/null +++ b/Lang/VBScript/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Lucas-Lehmer-test b/Lang/VBScript/Lucas-Lehmer-test new file mode 120000 index 0000000000..66d9aca835 --- /dev/null +++ b/Lang/VBScript/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Luhn-test-of-credit-card-numbers b/Lang/VBScript/Luhn-test-of-credit-card-numbers new file mode 120000 index 0000000000..d4c526bfd4 --- /dev/null +++ b/Lang/VBScript/Luhn-test-of-credit-card-numbers @@ -0,0 +1 @@ +../../Task/Luhn-test-of-credit-card-numbers/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sierpinski-carpet b/Lang/VBScript/Sierpinski-carpet new file mode 120000 index 0000000000..89ad7b5cbc --- /dev/null +++ b/Lang/VBScript/Sierpinski-carpet @@ -0,0 +1 @@ +../../Task/Sierpinski-carpet/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sieve-of-Eratosthenes b/Lang/VBScript/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..9a0989d6e2 --- /dev/null +++ b/Lang/VBScript/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Sudoku b/Lang/VBScript/Sudoku new file mode 120000 index 0000000000..874f391e44 --- /dev/null +++ b/Lang/VBScript/Sudoku @@ -0,0 +1 @@ +../../Task/Sudoku/VBScript \ No newline at end of file diff --git a/Lang/VBScript/URL-decoding b/Lang/VBScript/URL-decoding new file mode 120000 index 0000000000..ed7f2f66fa --- /dev/null +++ b/Lang/VBScript/URL-decoding @@ -0,0 +1 @@ +../../Task/URL-decoding/VBScript \ No newline at end of file diff --git a/Lang/VBScript/URL-encoding b/Lang/VBScript/URL-encoding new file mode 120000 index 0000000000..386607071e --- /dev/null +++ b/Lang/VBScript/URL-encoding @@ -0,0 +1 @@ +../../Task/URL-encoding/VBScript \ No newline at end of file diff --git a/Lang/VBScript/Van-der-Corput-sequence b/Lang/VBScript/Van-der-Corput-sequence new file mode 120000 index 0000000000..4bc2ee4d1b --- /dev/null +++ b/Lang/VBScript/Van-der-Corput-sequence @@ -0,0 +1 @@ +../../Task/Van-der-Corput-sequence/VBScript \ No newline at end of file diff --git a/Lang/Vim-Script/00DESCRIPTION b/Lang/Vim-Script/00DESCRIPTION index 28977a85b4..4fb2d89d30 100644 --- a/Lang/Vim-Script/00DESCRIPTION +++ b/Lang/Vim-Script/00DESCRIPTION @@ -1,6 +1,7 @@ {{stub}} {{language}} -Vim Script is the language for editing the popular [http://www.vim.org/ Vim text editor]. It is also sometimes called VimL. +Vim Script is the language for scripting the popular [http://www.vim.org/ Vim text editor] ( a [[Vi|Vi-clone]] ).
+It is also sometimes called VimL. == External Links == * [http://www.vim.org vim.org] - official site diff --git a/Lang/Vim-Script/Apply-a-callback-to-an-array b/Lang/Vim-Script/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..aabab3f374 --- /dev/null +++ b/Lang/Vim-Script/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Arithmetic-Integer b/Lang/Vim-Script/Arithmetic-Integer new file mode 120000 index 0000000000..22617165a6 --- /dev/null +++ b/Lang/Vim-Script/Arithmetic-Integer @@ -0,0 +1 @@ +../../Task/Arithmetic-Integer/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Arrays b/Lang/Vim-Script/Arrays new file mode 120000 index 0000000000..1b7a274323 --- /dev/null +++ b/Lang/Vim-Script/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Associative-array-Creation b/Lang/Vim-Script/Associative-array-Creation new file mode 120000 index 0000000000..05c48e86e0 --- /dev/null +++ b/Lang/Vim-Script/Associative-array-Creation @@ -0,0 +1 @@ +../../Task/Associative-array-Creation/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Associative-array-Iteration b/Lang/Vim-Script/Associative-array-Iteration new file mode 120000 index 0000000000..9700762982 --- /dev/null +++ b/Lang/Vim-Script/Associative-array-Iteration @@ -0,0 +1 @@ +../../Task/Associative-array-Iteration/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Averages-Arithmetic-mean b/Lang/Vim-Script/Averages-Arithmetic-mean new file mode 120000 index 0000000000..4b36f00d75 --- /dev/null +++ b/Lang/Vim-Script/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Binary-digits b/Lang/Vim-Script/Binary-digits new file mode 120000 index 0000000000..5fdacc7a67 --- /dev/null +++ b/Lang/Vim-Script/Binary-digits @@ -0,0 +1 @@ +../../Task/Binary-digits/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Boolean-values b/Lang/Vim-Script/Boolean-values new file mode 120000 index 0000000000..a2e4e6f5b9 --- /dev/null +++ b/Lang/Vim-Script/Boolean-values @@ -0,0 +1 @@ +../../Task/Boolean-values/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Character-codes b/Lang/Vim-Script/Character-codes new file mode 120000 index 0000000000..69b91116bd --- /dev/null +++ b/Lang/Vim-Script/Character-codes @@ -0,0 +1 @@ +../../Task/Character-codes/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Comments b/Lang/Vim-Script/Comments new file mode 120000 index 0000000000..1109d34e2b --- /dev/null +++ b/Lang/Vim-Script/Comments @@ -0,0 +1 @@ +../../Task/Comments/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Compound-data-type b/Lang/Vim-Script/Compound-data-type new file mode 120000 index 0000000000..03fe1527c8 --- /dev/null +++ b/Lang/Vim-Script/Compound-data-type @@ -0,0 +1 @@ +../../Task/Compound-data-type/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Copy-a-string b/Lang/Vim-Script/Copy-a-string new file mode 120000 index 0000000000..203846e385 --- /dev/null +++ b/Lang/Vim-Script/Copy-a-string @@ -0,0 +1 @@ +../../Task/Copy-a-string/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Count-in-octal b/Lang/Vim-Script/Count-in-octal new file mode 120000 index 0000000000..987c2906fe --- /dev/null +++ b/Lang/Vim-Script/Count-in-octal @@ -0,0 +1 @@ +../../Task/Count-in-octal/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Create-a-two-dimensional-array-at-runtime b/Lang/Vim-Script/Create-a-two-dimensional-array-at-runtime new file mode 120000 index 0000000000..6c127d917f --- /dev/null +++ b/Lang/Vim-Script/Create-a-two-dimensional-array-at-runtime @@ -0,0 +1 @@ +../../Task/Create-a-two-dimensional-array-at-runtime/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/FizzBuzz b/Lang/Vim-Script/FizzBuzz new file mode 120000 index 0000000000..87ba6481c0 --- /dev/null +++ b/Lang/Vim-Script/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Greatest-element-of-a-list b/Lang/Vim-Script/Greatest-element-of-a-list new file mode 120000 index 0000000000..e323a9acbe --- /dev/null +++ b/Lang/Vim-Script/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Hello-world-Newline-omission b/Lang/Vim-Script/Hello-world-Newline-omission new file mode 120000 index 0000000000..6f2a784e5c --- /dev/null +++ b/Lang/Vim-Script/Hello-world-Newline-omission @@ -0,0 +1 @@ +../../Task/Hello-world-Newline-omission/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Hello-world-Text b/Lang/Vim-Script/Hello-world-Text new file mode 120000 index 0000000000..69b7776057 --- /dev/null +++ b/Lang/Vim-Script/Hello-world-Text @@ -0,0 +1 @@ +../../Task/Hello-world-Text/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Hostname b/Lang/Vim-Script/Hostname new file mode 120000 index 0000000000..3014afb438 --- /dev/null +++ b/Lang/Vim-Script/Hostname @@ -0,0 +1 @@ +../../Task/Hostname/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-For-with-a-specified-step b/Lang/Vim-Script/Loops-For-with-a-specified-step new file mode 120000 index 0000000000..719704c377 --- /dev/null +++ b/Lang/Vim-Script/Loops-For-with-a-specified-step @@ -0,0 +1 @@ +../../Task/Loops-For-with-a-specified-step/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-Foreach b/Lang/Vim-Script/Loops-Foreach new file mode 120000 index 0000000000..0f23717915 --- /dev/null +++ b/Lang/Vim-Script/Loops-Foreach @@ -0,0 +1 @@ +../../Task/Loops-Foreach/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-N-plus-one-half b/Lang/Vim-Script/Loops-N-plus-one-half new file mode 120000 index 0000000000..09c25640e6 --- /dev/null +++ b/Lang/Vim-Script/Loops-N-plus-one-half @@ -0,0 +1 @@ +../../Task/Loops-N-plus-one-half/Vim-Script \ No newline at end of file diff --git a/Lang/Vim-Script/Loops-While b/Lang/Vim-Script/Loops-While new file mode 120000 index 0000000000..a026615972 --- /dev/null +++ b/Lang/Vim-Script/Loops-While @@ -0,0 +1 @@ +../../Task/Loops-While/Vim-Script \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Align-columns b/Lang/Visual-Basic-.NET/Align-columns new file mode 120000 index 0000000000..f2a5fb8661 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Arrays b/Lang/Visual-Basic-.NET/Arrays new file mode 120000 index 0000000000..5ed7c29a6f --- /dev/null +++ b/Lang/Visual-Basic-.NET/Arrays @@ -0,0 +1 @@ +../../Task/Arrays/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Dragon-curve b/Lang/Visual-Basic-.NET/Dragon-curve new file mode 120000 index 0000000000..6822a6c654 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic-.NET/Lucas-Lehmer-test b/Lang/Visual-Basic-.NET/Lucas-Lehmer-test new file mode 120000 index 0000000000..e605832563 --- /dev/null +++ b/Lang/Visual-Basic-.NET/Lucas-Lehmer-test @@ -0,0 +1 @@ +../../Task/Lucas-Lehmer-test/Visual-Basic-.NET \ No newline at end of file diff --git a/Lang/Visual-Basic/Ackermann-function b/Lang/Visual-Basic/Ackermann-function new file mode 120000 index 0000000000..0d44c47eb6 --- /dev/null +++ b/Lang/Visual-Basic/Ackermann-function @@ -0,0 +1 @@ +../../Task/Ackermann-function/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Align-columns b/Lang/Visual-Basic/Align-columns new file mode 120000 index 0000000000..7a1d76c132 --- /dev/null +++ b/Lang/Visual-Basic/Align-columns @@ -0,0 +1 @@ +../../Task/Align-columns/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Dragon-curve b/Lang/Visual-Basic/Dragon-curve new file mode 120000 index 0000000000..ad32e014ce --- /dev/null +++ b/Lang/Visual-Basic/Dragon-curve @@ -0,0 +1 @@ +../../Task/Dragon-curve/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Empty-program b/Lang/Visual-Basic/Empty-program new file mode 120000 index 0000000000..59b5870d2f --- /dev/null +++ b/Lang/Visual-Basic/Empty-program @@ -0,0 +1 @@ +../../Task/Empty-program/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Fibonacci-sequence b/Lang/Visual-Basic/Fibonacci-sequence new file mode 120000 index 0000000000..bb8eda2774 --- /dev/null +++ b/Lang/Visual-Basic/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Hailstone-sequence b/Lang/Visual-Basic/Hailstone-sequence new file mode 120000 index 0000000000..beb132c89c --- /dev/null +++ b/Lang/Visual-Basic/Hailstone-sequence @@ -0,0 +1 @@ +../../Task/Hailstone-sequence/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Knapsack-problem-Unbounded b/Lang/Visual-Basic/Knapsack-problem-Unbounded new file mode 120000 index 0000000000..de63ded7fa --- /dev/null +++ b/Lang/Visual-Basic/Knapsack-problem-Unbounded @@ -0,0 +1 @@ +../../Task/Knapsack-problem-Unbounded/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Multiplication-tables b/Lang/Visual-Basic/Multiplication-tables new file mode 120000 index 0000000000..63f96583d3 --- /dev/null +++ b/Lang/Visual-Basic/Multiplication-tables @@ -0,0 +1 @@ +../../Task/Multiplication-tables/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Sieve-of-Eratosthenes b/Lang/Visual-Basic/Sieve-of-Eratosthenes new file mode 120000 index 0000000000..dbe585a57d --- /dev/null +++ b/Lang/Visual-Basic/Sieve-of-Eratosthenes @@ -0,0 +1 @@ +../../Task/Sieve-of-Eratosthenes/Visual-Basic \ No newline at end of file diff --git a/Lang/Visual-Basic/Standard-deviation b/Lang/Visual-Basic/Standard-deviation new file mode 120000 index 0000000000..4d4adecb37 --- /dev/null +++ b/Lang/Visual-Basic/Standard-deviation @@ -0,0 +1 @@ +../../Task/Standard-deviation/Visual-Basic \ No newline at end of file diff --git a/Lang/Whitespace/Terminal-control-Cursor-positioning b/Lang/Whitespace/Terminal-control-Cursor-positioning new file mode 120000 index 0000000000..0c865db7ec --- /dev/null +++ b/Lang/Whitespace/Terminal-control-Cursor-positioning @@ -0,0 +1 @@ +../../Task/Terminal-control-Cursor-positioning/Whitespace \ No newline at end of file diff --git a/Lang/XSLT/Averages-Arithmetic-mean b/Lang/XSLT/Averages-Arithmetic-mean new file mode 120000 index 0000000000..41c30aaeaf --- /dev/null +++ b/Lang/XSLT/Averages-Arithmetic-mean @@ -0,0 +1 @@ +../../Task/Averages-Arithmetic-mean/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Call-a-function b/Lang/XSLT/Call-a-function new file mode 120000 index 0000000000..23cc6ff243 --- /dev/null +++ b/Lang/XSLT/Call-a-function @@ -0,0 +1 @@ +../../Task/Call-a-function/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Create-an-HTML-table b/Lang/XSLT/Create-an-HTML-table new file mode 120000 index 0000000000..078408b418 --- /dev/null +++ b/Lang/XSLT/Create-an-HTML-table @@ -0,0 +1 @@ +../../Task/Create-an-HTML-table/XSLT \ No newline at end of file diff --git a/Lang/XSLT/FizzBuzz b/Lang/XSLT/FizzBuzz new file mode 120000 index 0000000000..129ce5a024 --- /dev/null +++ b/Lang/XSLT/FizzBuzz @@ -0,0 +1 @@ +../../Task/FizzBuzz/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Greatest-element-of-a-list b/Lang/XSLT/Greatest-element-of-a-list new file mode 120000 index 0000000000..f5b1942d87 --- /dev/null +++ b/Lang/XSLT/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Hello-world-Graphical b/Lang/XSLT/Hello-world-Graphical new file mode 120000 index 0000000000..f25c0a06ea --- /dev/null +++ b/Lang/XSLT/Hello-world-Graphical @@ -0,0 +1 @@ +../../Task/Hello-world-Graphical/XSLT \ No newline at end of file diff --git a/Lang/XSLT/Here-document b/Lang/XSLT/Here-document new file mode 120000 index 0000000000..6b4a8e5875 --- /dev/null +++ b/Lang/XSLT/Here-document @@ -0,0 +1 @@ +../../Task/Here-document/XSLT \ No newline at end of file diff --git a/Lang/Yacas/Apply-a-callback-to-an-array b/Lang/Yacas/Apply-a-callback-to-an-array new file mode 120000 index 0000000000..75f8f2b3f0 --- /dev/null +++ b/Lang/Yacas/Apply-a-callback-to-an-array @@ -0,0 +1 @@ +../../Task/Apply-a-callback-to-an-array/Yacas \ No newline at end of file diff --git a/Lang/Yacas/Array-concatenation b/Lang/Yacas/Array-concatenation new file mode 120000 index 0000000000..33e162433e --- /dev/null +++ b/Lang/Yacas/Array-concatenation @@ -0,0 +1 @@ +../../Task/Array-concatenation/Yacas \ No newline at end of file diff --git a/Lang/Yacas/Averages-Root-mean-square b/Lang/Yacas/Averages-Root-mean-square new file mode 120000 index 0000000000..d0dff8aa77 --- /dev/null +++ b/Lang/Yacas/Averages-Root-mean-square @@ -0,0 +1 @@ +../../Task/Averages-Root-mean-square/Yacas \ No newline at end of file diff --git a/Lang/Yacas/Greatest-element-of-a-list b/Lang/Yacas/Greatest-element-of-a-list new file mode 120000 index 0000000000..68b5b1476b --- /dev/null +++ b/Lang/Yacas/Greatest-element-of-a-list @@ -0,0 +1 @@ +../../Task/Greatest-element-of-a-list/Yacas \ No newline at end of file diff --git a/Lang/Z80-Assembly/Mandelbrot-set b/Lang/Z80-Assembly/Mandelbrot-set new file mode 120000 index 0000000000..fe9a7f831f --- /dev/null +++ b/Lang/Z80-Assembly/Mandelbrot-set @@ -0,0 +1 @@ +../../Task/Mandelbrot-set/Z80-Assembly \ No newline at end of file diff --git a/Lang/ZED/00DESCRIPTION b/Lang/ZED/00DESCRIPTION index 5ff7e02f03..6627627124 100644 --- a/Lang/ZED/00DESCRIPTION +++ b/Lang/ZED/00DESCRIPTION @@ -2,8 +2,21 @@ == What is ZED? == -ZED is a functional programming language that compiles to Racket/Scheme. +ZED is a self-hosting functional programming language that compiles to Guile Scheme and can be built and run on Ideone. +Development of ZED is happening on GitHub: https://github.com/zelah/tinyZED -Development of ZED is happening on GitHub: https://github.com/zelah/ZED.git -The language page is here: http://zedlan.blogspot.com/ \ No newline at end of file +A version that adds the concept of types also exists to compile ZED into C functions. +Development of ZEDc is also happening on GitHub: https://github.com/zelah/ZEDc + + +My latest programming projects are here: http://zedlan.blogspot.com + + +ZED can be seen compiling itself here: http://ideone.com/UHMQco + + +Language author on RC: [[User:Zelah|Zelah]] ([[User_talk:Zelah|talk]] | [[Special:Contributions/Zelah|contribs]]) + + +. \ No newline at end of file diff --git a/Lang/ZED/Sorting-algorithms-Merge-sort b/Lang/ZED/Sorting-algorithms-Merge-sort new file mode 120000 index 0000000000..7239f1aff9 --- /dev/null +++ b/Lang/ZED/Sorting-algorithms-Merge-sort @@ -0,0 +1 @@ +../../Task/Sorting-algorithms-Merge-sort/ZED \ No newline at end of file diff --git a/Meta/Task.yaml b/Meta/Task.yaml index 2d032f069e..8921d14f75 100644 --- a/Meta/Task.yaml +++ b/Meta/Task.yaml @@ -1472,10 +1472,6 @@ Multisplit: name: Multisplit path: Multisplit url: Multisplit -Mutex: - name: Mutex - path: Mutex - url: Mutex Mutual recursion: name: Mutual recursion path: Mutual-recursion diff --git a/Task/100-doors/00DESCRIPTION b/Task/100-doors/00DESCRIPTION index 8c619b3cb6..930a516fe1 100644 --- a/Task/100-doors/00DESCRIPTION +++ b/Task/100-doors/00DESCRIPTION @@ -1,5 +1,10 @@ -Problem: You have 100 doors in a row that are all initially closed. You make 100 [[task feature::Rosetta Code:multiple passes|passes]] by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. +Problem: You have 100 doors in a row that are all initially closed. +You make 100 [[task feature::Rosetta Code:multiple passes|passes]] by the doors. +The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). +The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. Question: What state are the doors in after the last pass? Which are open, which are closed? [http://www.techinterview.org/Puzzles/fog0000000079.html] -'''[[task feature::Rosetta Code:extra credit|Alternate]]:''' As noted in this page's [[Talk:100 doors|discussion page]], the only doors that remain open are whose numbers are perfect squares of integers. Opening only those doors is an [[task feature::Rosetta Code:optimization|optimization]] that may also be expressed. +'''[[task feature::Rosetta Code:extra credit|Alternate]]:''' +As noted in this page's [[Talk:100 doors|discussion page]], the only doors that remain open are whose numbers are perfect squares of integers. +Opening only those doors is an [[task feature::Rosetta Code:optimization|optimization]] that may also be expressed. diff --git a/Task/100-doors/APL/100-doors-1.apl b/Task/100-doors/APL/100-doors-1.apl index 355458c8f8..8390a1b5b0 100644 --- a/Task/100-doors/APL/100-doors-1.apl +++ b/Task/100-doors/APL/100-doors-1.apl @@ -1,11 +1,11 @@ -out←doors num -⍝ Simulates the 100 doors problem for any number of doors -⍝ Returns a boolean vector with 1 being open +out?doors num +? Simulates the 100 doors problem for any number of doors +? Returns a boolean vector with 1 being open -out←⍳num ⍝ num steps -out←⍳¨out ⍝ Count out the spacing for each step -out←1=out ⍝ Make that into a boolean vector -out←⌽¨out ⍝ Flip each vector around -out←(num∘⍴)¨out ⍝ Copy each out to the right size -out←≠/out ⍝ XOR each vector, toggling each marked door -out←⊃out ⍝ Disclose the results to get a vector +out??num ? num steps +out??¨out ? Count out the spacing for each step +out?1=out ? Make that into a boolean vector +out??¨out ? Flip each vector around +out?(num°?)¨out ? Copy each out to the right size +out??/out ? XOR each vector, toggling each marked door +out??out ? Disclose the results to get a vector diff --git a/Task/100-doors/APL/100-doors-2.apl b/Task/100-doors/APL/100-doors-2.apl index d131e625c1..7d8ad58785 100644 --- a/Task/100-doors/APL/100-doors-2.apl +++ b/Task/100-doors/APL/100-doors-2.apl @@ -1,7 +1,7 @@ -out←doorsOptimized num;marks -⍝ Returns a boolean vector of the doors that would be left open +out?doorsOptimized num;marks +? Returns a boolean vector of the doors that would be left open -marks←⌊num*0.5 ⍝ Take the square root of the size, floored -marks←(⍳marks)*2 ⍝ Get each door to be opened -out←num⍴0 ⍝ Make a vector of 0s -out[marks]←1 ⍝ Set the marked doors to 1 +marks??num*0.5 ? Take the square root of the size, floored +marks?(?marks)*2 ? Get each door to be opened +out?num?0 ? Make a vector of 0s +out[marks]?1 ? Set the marked doors to 1 diff --git a/Task/100-doors/ATS/100-doors.ats b/Task/100-doors/ATS/100-doors.ats new file mode 100644 index 0000000000..138db28eee --- /dev/null +++ b/Task/100-doors/ATS/100-doors.ats @@ -0,0 +1,41 @@ +#include "share/atspre_staload.hats" + +implement +main0((*void*)) = let +// +var A = @[bool][100](false) +val A = $UNSAFE.cast{arrayref(bool,100)}(addr@A) +// +fnx +loop +( + pass: intGte(0) +) : void = + if pass < 100 + then loop2 (pass, pass) + // end of [if] +and +loop2 +( + pass: natLt(100), door: intGte(0) +) : void = + if door < 100 + then (A[door] := ~A[door]; loop2(pass, door+pass+1)) + else loop(pass+1) + // end of [if] +// +fun +loop3 +( + door: intGte(0) +) : void = + if door < 100 + then ( + println!("door #", door+1, " is ", (if A[door] then "open" else "closed"): string, "."); + loop3(door+1) + ) (* end of [then] *) + // end of [if] +// +in + loop(0); loop3 (0) +end // end of [main0] diff --git a/Task/100-doors/C-sharp/100-doors-1.cs b/Task/100-doors/C-sharp/100-doors-1.cs index 941efecc55..d06413f95c 100644 --- a/Task/100-doors/C-sharp/100-doors-1.cs +++ b/Task/100-doors/C-sharp/100-doors-1.cs @@ -1,14 +1,42 @@ -using System; -class Program +namespace ConsoleApplication1 { - static void Main() + using System; + class Program { - //To simplify door numbers, uses indexes 1 to 100 (rather than 0 to 99) - bool[] doors = new bool[101]; - for (int pass = 1; pass <= 100; pass++) - for (int current = pass; current <= 100; current += pass) - doors[current] = !doors[current]; - for (int i = 1; i <= 100; i++) - Console.WriteLine("Door #{0} " + (doors[i] ? "Open" : "Closed"), i); + static void Main(string[] args) + { + bool[] doors = new bool[100]; + + //Close all doors to start. + for (int d = 0; d < 100; d++) doors[d] = false; + + //For each pass... + for (int p = 0; p < 100; p++)//number of passes + { + //For each door to toggle... + for (int d = 0; d < 100; d++)//door number + { + if ((d + 1) % (p + 1) == 0) + { + doors[d] = !doors[d]; + } + } + } + + //Output the results. + Console.WriteLine("Passes Completed!!! Here are the results: \r\n"); + for (int d = 0; d < 100; d++) + { + if (doors[d]) + { + Console.WriteLine(String.Format("Door #{0}: Open", d + 1)); + } + else + { + Console.WriteLine(String.Format("Door #{0}: Closed", d + 1)); + } + } + Console.ReadKey(true); + } } } diff --git a/Task/100-doors/C-sharp/100-doors-2.cs b/Task/100-doors/C-sharp/100-doors-2.cs index 8a7a56123c..eb6c4248a1 100644 --- a/Task/100-doors/C-sharp/100-doors-2.cs +++ b/Task/100-doors/C-sharp/100-doors-2.cs @@ -1,20 +1,30 @@ -using System; -class Program +namespace ConsoleApplication1 { - static void Main() + using System; + class Program { - int door = 1, inrementer = 0; - for (int current = 1; current <= 100; current++) + static void Main() { - Console.Write("Door #{0} ", current); - if (current == door) + //The o variable stores the number of the next OPEN door. + int o = 1; + + //The n variable is used to help calculate the next value of the o variable. + int n = 0; + + //The d variable determines the door to be output next. + for (int d = 1; d <= 100; d++) { - Console.WriteLine("Open"); - inrementer++; - door += 2 * inrementer + 1; + Console.Write("Door #{0}: ", d); + if (d == o) + { + Console.WriteLine("Open"); + n++; + o += 2 * n + 1; + } + else + Console.WriteLine("Closed"); } - else - Console.WriteLine("Closed"); + Console.ReadKey(true); } } } diff --git a/Task/100-doors/C-sharp/100-doors-3.cs b/Task/100-doors/C-sharp/100-doors-3.cs index dda6158dd0..e157701666 100644 --- a/Task/100-doors/C-sharp/100-doors-3.cs +++ b/Task/100-doors/C-sharp/100-doors-3.cs @@ -1,10 +1,21 @@ -using System; -class Program +namespace ConsoleApplication1 { - static void Main() + using System; + class Program { - double n; - for (int t = 1; t <= 100; ++t) - Console.WriteLine(t + ": " + (((n = Math.Sqrt(t)) == (int)n) ? "Open" : "Closed")); + static void Main(string[] args) + { + //Perform the operation. + bool[] doors = new bool[100]; + int n = 0; + int d; + while ((d = (++n * n)) <= 100) + doors[d - 1] = true; + + //Perform the presentation. + for (d = 0; d < doors.Length; d++) + Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed"); + Console.ReadKey(true); + } } } diff --git a/Task/100-doors/C-sharp/100-doors-4.cs b/Task/100-doors/C-sharp/100-doors-4.cs index 69f2f56e35..abd365f161 100644 --- a/Task/100-doors/C-sharp/100-doors-4.cs +++ b/Task/100-doors/C-sharp/100-doors-4.cs @@ -1,41 +1,19 @@ - using System; -class Program +namespace ConsoleApplication1 { - static void Main(string[] args) + using System; + class Program + { + static void Main() { - bool[] Doors = new bool[101]; + bool[] doors = new bool[100]; - - //Close all doors to start - for (int g=1;g<101;g++) Doors[g] = false; - - for (int i = 1; i < 101; i++)//number of passes - { - for (int d = 1; d < 101; d++)//door number - { - if ((d % i) == 0) - { - if (Doors[d]) Doors[d] = false; - else Doors[d] = true; - } - - } - } - - Console.WriteLine("Passes Completed!!! Here are the results: \r\n"); - for (int p = 1; p < 101; p++) - { - if (Doors[p]) - { - string doorStatus = String.Format("Door #{0} is \'OPENED\'.", p.ToString()); - Console.WriteLine(doorStatus); - } - else - { - string doorStatus = String.Format("Door #{0} is \'CLOSED\'.", p.ToString()); - Console.WriteLine(doorStatus); - } - - } + //The number of passes can be 1-based, but the number of doors must be 0-based. + for (int p = 1; p <= 100; p++) + for (int d = p - 1; d < 100; d += p) + doors[d] = !doors[d]; + for (int d = 0; d < 100; d++) + Console.WriteLine("Door #{0}: {1}", d + 1, doors[d] ? "Open" : "Closed"); + Console.ReadKey(true); } + } } diff --git a/Task/100-doors/C-sharp/100-doors-5.cs b/Task/100-doors/C-sharp/100-doors-5.cs index 860050e6aa..9524cdb716 100644 --- a/Task/100-doors/C-sharp/100-doors-5.cs +++ b/Task/100-doors/C-sharp/100-doors-5.cs @@ -1,14 +1,16 @@ +namespace ConsoleApplication1 +{ + using System; class Program { - static void Main(string[] args) + static void Main() { - bool[] doorStates = new bool[100]; - int n = 0; - int d; - while ((d = (++n * n)) <= 100) - doorStates[d - 1] = true; - for (int i = 0; i < doorStates.Length; i++) - Console.WriteLine("Door {0}: {1}", i + 1, doorStates[i] ? "Open" : "Closed"); + double n; + + //If the current door number is the perfect square of an integer, say it is open, else say it is closed. + for (int d = 1; d <= 100; d++) + Console.WriteLine("Door #{0}: {1}", d, (n = Math.Sqrt(d)) == (int)n ? "Open" : "Closed"); Console.ReadKey(true); } } +} diff --git a/Task/100-doors/ColdFusion/100-doors-4.cfm b/Task/100-doors/ColdFusion/100-doors-4.cfm new file mode 100644 index 0000000000..2c24d60b80 --- /dev/null +++ b/Task/100-doors/ColdFusion/100-doors-4.cfm @@ -0,0 +1,14 @@ + + + + + + + + + + + + + +#doorlist# diff --git a/Task/100-doors/Common-Lisp/100-doors-3.lisp b/Task/100-doors/Common-Lisp/100-doors-3.lisp index 3fa15ab328..dfec970db4 100644 --- a/Task/100-doors/Common-Lisp/100-doors-3.lisp +++ b/Task/100-doors/Common-Lisp/100-doors-3.lisp @@ -1,21 +1,23 @@ (defun perfect-square-list (n) - "Generates a list of perfect squares from 0 up to n" - (loop for i from 1 to (sqrt n) collect (expt i 2))) + "Generates a list of perfect squares from 0 up to n" + (loop for i from 1 to (isqrt n) collect (expt i 2))) + +(defun print-doors (doors) + "Pretty prints the doors list" + (format T "~{~A ~A ~A ~A ~A ~A ~A ~A ~A ~A~%~}~%" doors)) (defun open-door (doors num open) - "Sets door at num to open" - (setf (nth (- num 1) doors) open) - doors) + "Sets door at num to open" + (setf (nth (- num 1) doors) open)) (defun visit-all (doors vlist open) - "Visits and opens all the doors indicated in vlist" - (if (null vlist) - doors - (visit-all (open-door doors (car vlist) open) - (cdr vlist) - open))) + "Visits and opens all the doors indicated in vlist" + (dolist (dn vlist doors) + (open-door doors dn open))) (defun start2 (&optional (size 100)) - "Start the program" - (print-doors (visit-all (make-list size :initial-element "#") - (perfect-square-list size) "_"))) + "Start the program" + (print-doors + (visit-all (make-list size :initial-element '\#) + (perfect-square-list size) + '_))) diff --git a/Task/100-doors/Coq/100-doors-1.coq b/Task/100-doors/Coq/100-doors-1.coq index 716e97ea68..a37db1f5d0 100644 --- a/Task/100-doors/Coq/100-doors-1.coq +++ b/Task/100-doors/Coq/100-doors-1.coq @@ -23,4 +23,4 @@ Fixpoint flipwhile l n := | S n' => flipwhile (flipeach l (S n')) n' end. -Definition prison cells := flipwhile (rep false (S cells)) cells. +Definition prison cells := flipwhile (rep false cells) cells. diff --git a/Task/100-doors/Coq/100-doors-2.coq b/Task/100-doors/Coq/100-doors-2.coq index b22b7e0c51..c3f1f1158f 100644 --- a/Task/100-doors/Coq/100-doors-2.coq +++ b/Task/100-doors/Coq/100-doors-2.coq @@ -10,4 +10,4 @@ Fixpoint prisoo' nd n k accu := prisoo' nd' (snd (fst ra)) (snd ra) ((fst (fst ra))::accu) end. -Definition prisoo n := prisoo' (S n) 1 0 nil. +Definition prisoo cells := prisoo' cells 1 0 nil. diff --git a/Task/100-doors/Haskell/100-doors-1.hs b/Task/100-doors/Haskell/100-doors-1.hs index f76307dd9c..b82123a8e8 100644 --- a/Task/100-doors/Haskell/100-doors-1.hs +++ b/Task/100-doors/Haskell/100-doors-1.hs @@ -7,4 +7,4 @@ toggleEvery :: [Door] -> Int -> [Door] toggleEvery xs k = zipWith ($) fs xs where fs = cycle $ (replicate (k-1) id) ++ [toggle] -run n = foldl toggleEvery (replicate n Closed) [0..n] +run n = foldl toggleEvery (replicate n Closed) [1..n] diff --git a/Task/100-doors/Haskell/100-doors-2.hs b/Task/100-doors/Haskell/100-doors-2.hs index 2cea247dfd..e89bb4fea7 100644 --- a/Task/100-doors/Haskell/100-doors-2.hs +++ b/Task/100-doors/Haskell/100-doors-2.hs @@ -1,6 +1,12 @@ -gate :: Eq a => [a] -> [a] -> [Door] -gate (x:xs) (y:ys) | x == y = Open : gate xs ys -gate (x:xs) ys = Closed : gate xs ys -gate [] _ = [] +data Door = Open | Closed deriving Show -run n = gate [1..n] [k*k | k <- [1..]] +toggle Open = Closed +toggle Closed = Open + +toggleEvery :: Int -> [Door] -> [Door] +toggleEvery k = zipWith toggleK [1..] + where + toggleK n door | n `mod` k == 0 = toggle door + | otherwise = door + +run n = foldr toggleEvery (replicate n Closed) [1..n] diff --git a/Task/100-doors/Haskell/100-doors-3.hs b/Task/100-doors/Haskell/100-doors-3.hs index 44f44aa391..2cea247dfd 100644 --- a/Task/100-doors/Haskell/100-doors-3.hs +++ b/Task/100-doors/Haskell/100-doors-3.hs @@ -1 +1,6 @@ -run n = takeWhile (< n) [k*k | k <- [1..]] +gate :: Eq a => [a] -> [a] -> [Door] +gate (x:xs) (y:ys) | x == y = Open : gate xs ys +gate (x:xs) ys = Closed : gate xs ys +gate [] _ = [] + +run n = gate [1..n] [k*k | k <- [1..]] diff --git a/Task/100-doors/Haskell/100-doors-4.hs b/Task/100-doors/Haskell/100-doors-4.hs new file mode 100644 index 0000000000..44f44aa391 --- /dev/null +++ b/Task/100-doors/Haskell/100-doors-4.hs @@ -0,0 +1 @@ +run n = takeWhile (< n) [k*k | k <- [1..]] diff --git a/Task/100-doors/J/100-doors-3.j b/Task/100-doors/J/100-doors-3.j index 3a185875e1..42485fe2b4 100644 --- a/Task/100-doors/J/100-doors-3.j +++ b/Task/100-doors/J/100-doors-3.j @@ -1,4 +1,4 @@ 'these doors are open' ; >: I. (>:i.100) e. *: i.11 -┌────────────────────┬───────────────────────────┐ -│these doors are open│1 4 9 16 25 36 49 64 81 100│ -└────────────────────┴───────────────────────────┘ ++------------------------------------------------+ +¦these doors are open¦1 4 9 16 25 36 49 64 81 100¦ ++------------------------------------------------+ diff --git a/Task/100-doors/JavaScript/100-doors-1.js b/Task/100-doors/JavaScript/100-doors-1.js index 0aee8648bb..61cc824915 100644 --- a/Task/100-doors/JavaScript/100-doors-1.js +++ b/Task/100-doors/JavaScript/100-doors-1.js @@ -1,6 +1,8 @@ -for (var door = 1; door <= 100; i++) { - var sqrt = Math.sqrt(door); - if (sqrt === (sqrt | 0)) { - console.log("Door %d is open", door); - } -} +var doors=[]; +for(var i=0;i<100;i++) + doors[i]=false; //create doors +for(var i=1;i<=100;i++) + for(var i2=i-1,g;i2<100;i2+=i) + doors[i2]=!doors[i2]; //toggle doors +for(var i=1;i<=100;i++) //read doors + console.log("Door %d is %s",i,doors[i-1]?"open":"closed") diff --git a/Task/100-doors/JavaScript/100-doors-2.js b/Task/100-doors/JavaScript/100-doors-2.js index 7a4f61260e..085eb9a2d9 100644 --- a/Task/100-doors/JavaScript/100-doors-2.js +++ b/Task/100-doors/JavaScript/100-doors-2.js @@ -1,9 +1,6 @@ -Array.apply(null, { length: 100 }) - .map(function(v, i) { return i + 1; }) - .forEach(function(door) { - var sqrt = Math.sqrt(door); - - if (sqrt === (sqrt | 0)) { - console.log("Door %d is open", door); - } - }); +for (var door = 1; door <= 100; door++) { + var sqrt = Math.sqrt(door); + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } +} diff --git a/Task/100-doors/JavaScript/100-doors-3.js b/Task/100-doors/JavaScript/100-doors-3.js index 2e3d824574..7a4f61260e 100644 --- a/Task/100-doors/JavaScript/100-doors-3.js +++ b/Task/100-doors/JavaScript/100-doors-3.js @@ -1,6 +1,6 @@ Array.apply(null, { length: 100 }) - .map((v, i) => i + 1) - .forEach(door => { + .map(function(v, i) { return i + 1; }) + .forEach(function(door) { var sqrt = Math.sqrt(door); if (sqrt === (sqrt | 0)) { diff --git a/Task/100-doors/JavaScript/100-doors-4.js b/Task/100-doors/JavaScript/100-doors-4.js index 7378d4bae5..5c4fcdcf84 100644 --- a/Task/100-doors/JavaScript/100-doors-4.js +++ b/Task/100-doors/JavaScript/100-doors-4.js @@ -1,9 +1,3 @@ -// Array comprehension style -[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { - var door = i + 1 - var sqrt = Math.sqrt(door); - - if (sqrt === (sqrt | 0)) { - console.log("Door %d is open", door); - } -}); +for(var door=1;i<10/*Math.sqrt(100)*/;i++){ + console.log("Door %d is open",i*i); +} diff --git a/Task/100-doors/JavaScript/100-doors-5.js b/Task/100-doors/JavaScript/100-doors-5.js new file mode 100644 index 0000000000..2e3d824574 --- /dev/null +++ b/Task/100-doors/JavaScript/100-doors-5.js @@ -0,0 +1,9 @@ +Array.apply(null, { length: 100 }) + .map((v, i) => i + 1) + .forEach(door => { + var sqrt = Math.sqrt(door); + + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } + }); diff --git a/Task/100-doors/JavaScript/100-doors-6.js b/Task/100-doors/JavaScript/100-doors-6.js new file mode 100644 index 0000000000..7378d4bae5 --- /dev/null +++ b/Task/100-doors/JavaScript/100-doors-6.js @@ -0,0 +1,9 @@ +// Array comprehension style +[ for (i of Array.apply(null, { length: 100 })) i ].forEach((_, i) => { + var door = i + 1 + var sqrt = Math.sqrt(door); + + if (sqrt === (sqrt | 0)) { + console.log("Door %d is open", door); + } +}); diff --git a/Task/100-doors/Julia/100-doors-1.julia b/Task/100-doors/Julia/100-doors-1.julia index b239ca730e..35148bded1 100644 --- a/Task/100-doors/Julia/100-doors-1.julia +++ b/Task/100-doors/Julia/100-doors-1.julia @@ -1,5 +1,7 @@ doors = falses(100) for a = 1:100, b in a:a:100 - doors[b] = !doors[b] + doors[b] = !doors[b] +end +for a = 1:100 + println("Door $a is " * (doors[a] ? "open" : "close")) end -for a = 1:100 println("Door $a is " * (doors[a] ? "open" : "close") ) end diff --git a/Task/100-doors/Maple/100-doors-1.maple b/Task/100-doors/Maple/100-doors-1.maple index af1eb31b4f..5e8354464a 100644 --- a/Task/100-doors/Maple/100-doors-1.maple +++ b/Task/100-doors/Maple/100-doors-1.maple @@ -1,9 +1,9 @@ NDoors := proc( N :: posint ) # Initialise, using 0 to represent "closed" - local doors := Array( 1 .. N, 'datatype' = 'integer'[ 1 ] ); + local pass, door, doors := Array( 1 .. N, 'datatype' = 'integer'[ 1 ] ); # Now do N passes - for local pass from 1 to N do - for local door from pass by pass while door <= N do + for pass from 1 to N do + for door from pass by pass while door <= N do doors[ door ] := 1 - doors[ door ] end do end do; diff --git a/Task/100-doors/Mathematica/100-doors-3.math b/Task/100-doors/Mathematica/100-doors-3.math index b867d8da88..8e15efde66 100644 --- a/Task/100-doors/Mathematica/100-doors-3.math +++ b/Task/100-doors/Mathematica/100-doors-3.math @@ -1 +1,5 @@ -Do[Print["door ",i," is ",If[IntegerQ[Sqrt[i]],"open","closed"]],{i,100}] +Fold[ + ReplacePart[#1, (i_ /; Mod[i, #2] == 0) :> (-#1[[i]])] &, + ConstantArray[-1, {100}], + Range[100] +] /. {1 -> "Open", -1 -> "Closed"} diff --git a/Task/100-doors/Mathematica/100-doors-4.math b/Task/100-doors/Mathematica/100-doors-4.math index 272215487f..b867d8da88 100644 --- a/Task/100-doors/Mathematica/100-doors-4.math +++ b/Task/100-doors/Mathematica/100-doors-4.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-5.math b/Task/100-doors/Mathematica/100-doors-5.math index 5c83a1f2b3..272215487f 100644 --- a/Task/100-doors/Mathematica/100-doors-5.math +++ b/Task/100-doors/Mathematica/100-doors-5.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-6.math b/Task/100-doors/Mathematica/100-doors-6.math index 8dab41125d..5c83a1f2b3 100644 --- a/Task/100-doors/Mathematica/100-doors-6.math +++ b/Task/100-doors/Mathematica/100-doors-6.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-7.math b/Task/100-doors/Mathematica/100-doors-7.math index 11e842986e..8dab41125d 100644 --- a/Task/100-doors/Mathematica/100-doors-7.math +++ b/Task/100-doors/Mathematica/100-doors-7.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-8.math b/Task/100-doors/Mathematica/100-doors-8.math new file mode 100644 index 0000000000..11e842986e --- /dev/null +++ b/Task/100-doors/Mathematica/100-doors-8.math @@ -0,0 +1 @@ +Range[Sqrt[100]]^2 diff --git a/Task/100-doors/Mercury/100-doors.mercury b/Task/100-doors/Mercury/100-doors.mercury index 9d1bdb769e..5987a0b6b6 100644 --- a/Task/100-doors/Mercury/100-doors.mercury +++ b/Task/100-doors/Mercury/100-doors.mercury @@ -21,7 +21,7 @@ walk(N, !D) :- walk(N, N, !D). :- pred walk(int::in, int::in, doors::in, doors::out) is semidet. walk(At, By, !D) :- semidet_lookup(!.D, At - 1, Door), - slow_set(!.D, At - 1, toggle(Door), !:D), + slow_set(At - 1, toggle(Door), !D), ( walk(At + By, By, !D) -> true ; true ). walks(N, End, !D) :- diff --git a/Task/100-doors/Objective-C/100-doors-1.m b/Task/100-doors/Objective-C/100-doors-1.m new file mode 100644 index 0000000000..675efb04e0 --- /dev/null +++ b/Task/100-doors/Objective-C/100-doors-1.m @@ -0,0 +1,28 @@ +@import Foundation; + +int main(int argc, const char * argv[]) { + @autoreleasepool { + + // Create a mutable array + NSMutableArray *doorArray = [@[] mutableCopy]; + + // Fill the doorArray with 100 closed doors + for (NSInteger i = 0; i < 100; ++i) { + doorArray[i] = @NO; + } + + // Do the 100 passes + for (NSInteger pass = 0; pass < 100; ++pass) { + for (NSInteger door = pass; door < 100; door += pass+1) { + doorArray[door] = [doorArray[door] isEqual: @YES] ? @NO : @YES; + } + } + + // Print the results + [doorArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if ([obj isEqual: @YES]) { + NSLog(@"Door number %lu is open", idx + 1); + } + }]; + } +} diff --git a/Task/100-doors/Objective-C/100-doors-2.m b/Task/100-doors/Objective-C/100-doors-2.m new file mode 100644 index 0000000000..10f042faf7 --- /dev/null +++ b/Task/100-doors/Objective-C/100-doors-2.m @@ -0,0 +1,68 @@ +@import Foundation; + +#pragma mark - Classes +//////////////////////////////////////////////////// +// Model class header - A we are using a category to add a method to MSMutableArray +@interface NSMutableArray (DoorModelExtension) + +- (void)setNumberOfDoors:(NSUInteger)doors; + +@end + +// Model class implementation +@implementation NSMutableArray (DoorModelExtension) + +- (void)setNumberOfDoors:(NSUInteger)doors { + // Fill the doorArray with 100 closed doors + for (NSInteger i = 0; i < doors; ++i) { + self[i] = @NO; + } +} +@end +//////////////////////////////////////////////////// + +// View class header - A simple class to handle printing our values +@interface DoorViewClass : NSObject + +- (void)printResultsOfDoorTask:(NSMutableArray *)doors; + +@end + +// View class implementation +@implementation DoorViewClass + +- (void)printResultsOfDoorTask:(NSMutableArray *)doors { + + // Print the results, using an enumeration block for easy index tracking + [doors enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if ([obj isEqual: @YES]) { + NSLog(@"Door number %lu is open", idx + 1); + } + }]; +} + +@end +//////////////////////////////////////////////////// + +#pragma mark - main +// With our classes set we can use them from our controller, in this case main +int main(int argc, const char * argv[]) { + + // Init our classes + NSMutableArray *doorArray = [NSMutableArray array]; + DoorViewClass *doorView = [DoorViewClass new]; + + // Use our class category to add the doors + [doorArray setNumberOfDoors:100]; + + // Do the 100 passes + for (NSUInteger pass = 0; pass < 100; ++pass) { + for (NSUInteger door = pass; door < 100; door += pass+1) { + doorArray[door] = [doorArray[door] isEqual: @YES] ? @NO : @YES; + } + } + + // Print the results + [doorView printResultsOfDoorTask:doorArray]; + +} diff --git a/Task/100-doors/Perl/100-doors-2.pl b/Task/100-doors/Perl/100-doors-2.pl index 27827647b5..36694fcc14 100644 --- a/Task/100-doors/Perl/100-doors-2.pl +++ b/Task/100-doors/Perl/100-doors-2.pl @@ -1 +1,10 @@ -print "Door $_ is open\n" for map $_**2, 1 .. 10; +#!/usr/bin/perl +use strict; +use warnings; + +my @doors = (1) x 100; +for my $N (1 .. 100) { + $doors[$_]=1-$doors[$_] for map { $_*$N - 1 } 1 .. int(100/$N); +} +print join("\n", map { "Door $_ is Open" } grep { ! $doors[$_-1] } 1 .. 100), "\n"; +print "The rest are closed\n"; diff --git a/Task/100-doors/Perl/100-doors-3.pl b/Task/100-doors/Perl/100-doors-3.pl index 934096bc3e..27827647b5 100644 --- a/Task/100-doors/Perl/100-doors-3.pl +++ b/Task/100-doors/Perl/100-doors-3.pl @@ -1 +1 @@ -print "Door $_ is ", qw"closed open"[int sqrt == sqrt], "\n" for 1..100; +print "Door $_ is open\n" for map $_**2, 1 .. 10; diff --git a/Task/100-doors/Perl/100-doors-4.pl b/Task/100-doors/Perl/100-doors-4.pl index 8925cc9e0e..934096bc3e 100644 --- a/Task/100-doors/Perl/100-doors-4.pl +++ b/Task/100-doors/Perl/100-doors-4.pl @@ -1,12 +1 @@ -while( ++$i <= 100 ) -{ - $root = sqrt($i); - if ( int( $root ) == $root ) - { - print "Door $i is open\n"; - } - else - { - print "Door $i is closed\n"; - } -} +print "Door $_ is ", qw"closed open"[int sqrt == sqrt], "\n" for 1..100; diff --git a/Task/100-doors/Perl/100-doors-5.pl b/Task/100-doors/Perl/100-doors-5.pl new file mode 100644 index 0000000000..8925cc9e0e --- /dev/null +++ b/Task/100-doors/Perl/100-doors-5.pl @@ -0,0 +1,12 @@ +while( ++$i <= 100 ) +{ + $root = sqrt($i); + if ( int( $root ) == $root ) + { + print "Door $i is open\n"; + } + else + { + print "Door $i is closed\n"; + } +} diff --git a/Task/100-doors/PowerShell/100-doors-6.psh b/Task/100-doors/PowerShell/100-doors-6.psh new file mode 100644 index 0000000000..fc185f3853 --- /dev/null +++ b/Task/100-doors/PowerShell/100-doors-6.psh @@ -0,0 +1,6 @@ +Workflow Calc-Doors { + Foreach –parallel ($number in 1..100) { + "Door " + $number.ToString("0000") + ": " + @{$true="Closed";$false="Open"}[([Math]::pow($number, 0.5)%1) -ne 0] + } +} +Calc-Doors | sort diff --git a/Task/100-doors/PowerShell/100-doors-7.psh b/Task/100-doors/PowerShell/100-doors-7.psh new file mode 100644 index 0000000000..1714f382c9 --- /dev/null +++ b/Task/100-doors/PowerShell/100-doors-7.psh @@ -0,0 +1 @@ +1..10|%{"Door "+ $_*$_ + " is open"} diff --git a/Task/100-doors/Prolog/100-doors-2.pro b/Task/100-doors/Prolog/100-doors-2.pro index 04252bdc72..ec41cb4af2 100644 --- a/Task/100-doors/Prolog/100-doors-2.pro +++ b/Task/100-doors/Prolog/100-doors-2.pro @@ -1,4 +1,31 @@ -doors_optimized(N) :- - Max is floor(sqrt(N)), - forall(between(1, Max, I), - ( J is I*I,format('Door ~w is open.~n',[J]))). +doors(Num, Passes) :- + forall(( everyNth(1,Passes,1,Pass) + , forall((everyNth(Pass,Num,Pass,Door), toggle(Door))) + )) + , show(Num) + . + + +toggle(Door) :- + Opened = opened(Door) + , ( clause(Opened,_) -> retract(Opened) + ; asserta(Opened) + ). + + +show(Num) :- + forall(( between(1,Num,Door) + , (opened(Door) -> State = opened ; State = closed) + , write(Door), write(' '), write(State), nl + )). + + +% utils +forall(X) :- findall(_, X, _). + +everyNth(From,To,Step,X) :- + From =< To + , ( X = From ; From1 is From + Step, everyNth(From1,To,Step,X) ) + . + +main :- doors(100,100), halt. diff --git a/Task/100-doors/Prolog/100-doors-3.pro b/Task/100-doors/Prolog/100-doors-3.pro new file mode 100644 index 0000000000..04252bdc72 --- /dev/null +++ b/Task/100-doors/Prolog/100-doors-3.pro @@ -0,0 +1,4 @@ +doors_optimized(N) :- + Max is floor(sqrt(N)), + forall(between(1, Max, I), + ( J is I*I,format('Door ~w is open.~n',[J]))). diff --git a/Task/100-doors/Python/100-doors-6.py b/Task/100-doors/Python/100-doors-6.py new file mode 100644 index 0000000000..7524fc9970 --- /dev/null +++ b/Task/100-doors/Python/100-doors-6.py @@ -0,0 +1 @@ +for i in range(1,11): print("Door %s is open" % i**2) diff --git a/Task/100-doors/RapidQ/100-doors.rapidq b/Task/100-doors/RapidQ/100-doors.rapidq new file mode 100644 index 0000000000..4c147a99ae --- /dev/null +++ b/Task/100-doors/RapidQ/100-doors.rapidq @@ -0,0 +1,20 @@ +dim x as integer, y as integer +dim door(1 to 100) as byte + +'initialize array +for x = 1 to 100 : door(x) = 0 : next + +'set door values +for y = 1 to 100 + for x = y to 100 step y + door(x) = not door(x) + next x +next y + +'print result +for x = 1 to 100 + if door(x) then print "Door " + str$(x) + " = open" +next + +while inkey$="":wend +end diff --git a/Task/100-doors/Rust/100-doors-1.rust b/Task/100-doors/Rust/100-doors-1.rust index 68683bbd4e..5f84be178f 100644 --- a/Task/100-doors/Rust/100-doors-1.rust +++ b/Task/100-doors/Rust/100-doors-1.rust @@ -1,17 +1,14 @@ -// rust 0.8 - +// rust 1.0.0-alpha +#![feature(core)] +use std::iter::{range_step_inclusive}; fn main() { - let mut door_open = [false, ..100]; - - 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]; - } - } - } - for (i, state) in door_open.iter().enumerate() { - println!("Door {} is {}.", i + 1, - if *state {"open"} else {"closed"}); + let mut door_open = [false; 100]; + for pass in (1us..101) { + for door in range_step_inclusive(pass, 100, pass) { + door_open[door - 1] = !door_open[door - 1]; } + } + for (i, state) in door_open.iter().enumerate() { + println!("Door {} is {}.", i + 1, if *state {"open"} else {"closed"}); + } } diff --git a/Task/100-doors/SQL/100-doors.sql b/Task/100-doors/SQL/100-doors.sql new file mode 100644 index 0000000000..3b1a12d21b --- /dev/null +++ b/Task/100-doors/SQL/100-doors.sql @@ -0,0 +1,23 @@ +DECLARE @sqr int, + @i int, + @door int; + +SELECT @sqr =1, + @i = 3, + @door = 1; + +WHILE(@door <=100) +BEGIN + IF(@door = @sqr) + BEGIN + PRINT 'Door ' + RTRIM(CAST(@door as char)) + ' is open.'; + SET @sqr= @sqr+@i; + SET @i=@i+2; + END + ELSE + BEGIN + PRINT 'Door ' + RTRIM(CONVERT(char,@door)) + ' is closed.'; + END +SET @door = @door + 1 +END + diff --git a/Task/100-doors/Scheme/100-doors-3.ss b/Task/100-doors/Scheme/100-doors-3.ss new file mode 100644 index 0000000000..38019f9407 --- /dev/null +++ b/Task/100-doors/Scheme/100-doors-3.ss @@ -0,0 +1,17 @@ +(define (N_doors N) + (define (init) + (define (str n) + (if (> n N) '() (cons 0 (str (+ 1 n))))) + (str 1)) + (define (toggle x str) + (define (s n lis) + (define (revert x) + (if (eq? x 0) 1 0)) + (cond ((null? lis) '()) + ((zero? (remainder n x)) (cons (revert (car lis)) (s (+ n 1) (cdr lis)))) + (else (cons (car lis) (s (+ n 1) (cdr lis)))))) + (s 1 str)) + (define (iterate x lis) + (if (> x N) lis (iterate (+ x 1) (toggle x lis)))) + (iterate 1 (init))) +(N_doors 100) diff --git a/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 b/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 index 6baddcf0be..9fb8669fce 100644 --- a/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 +++ b/Task/100-doors/TI-83-BASIC/100-doors-1.ti-83 @@ -3,14 +3,14 @@ PROGRAM:DOORS100 :Disp "SETTING UP LIST" :Disp "PLEASE WAIT..." :For(I,1,100,1) -:0→L1(I) +:0?L1(I) :End :ClrHome :Disp "Pass" :For(I,1,100,1) :For(J,I,100,I) :Output(2,1,I) -:not(L1(J))→L1(J) +:not(L1(J))?L1(J) :End :End :ClrHome diff --git a/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 b/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 index 9de3419c64..18f28256a3 100644 --- a/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 +++ b/Task/100-doors/TI-83-BASIC/100-doors-2.ti-83 @@ -1,4 +1,4 @@ PROGRAM:DOORSOPT :For(I,1,100,1) -:not(fPart(√(I)))→L1(I) +:not(fPart(v(I)))?L1(I) :End diff --git a/Task/100-doors/TI-89-BASIC/100-doors.ti-89 b/Task/100-doors/TI-89-BASIC/100-doors.ti-89 index 2198b934fa..c2d3256259 100644 --- a/Task/100-doors/TI-89-BASIC/100-doors.ti-89 +++ b/Task/100-doors/TI-89-BASIC/100-doors.ti-89 @@ -1,14 +1,14 @@ Define doors(fast) = Func Local doors,i,j - seq(false,x,1,100) → doors + seq(false,x,1,100) ? doors If fast Then For i,1,10,1 - true → doors[i^2] + true ? doors[i^2] EndFor Else For i,1,100,1 For j,i,100,i - not doors[j] → doors[j] + not doors[j] ? doors[j] EndFor EndFor EndIf diff --git a/Task/100-doors/TXR/100-doors.txr b/Task/100-doors/TXR/100-doors.txr index b0717473b0..507a5de2bc 100644 --- a/Task/100-doors/TXR/100-doors.txr +++ b/Task/100-doors/TXR/100-doors.txr @@ -1,9 +1,9 @@ -@(do (defun hyaku-mai-to () +@(do (defun hyaku-mai-tobira () (let ((doors (vector 100))) (each ((i (range 0 99))) (each ((j (range i 99 (+ i 1)))) (flip [doors j]))) doors)) (each ((counter (range 1)) - (door (list-vector (hyaku-mai-to)))) - (format t "door ~a is ~a\n" counter (if door "open" "closed")))) + (door (hyaku-mai-tobira))) + (put-line `door @counter is @(if door "open" "closed")`))) diff --git a/Task/24-game-Solve/00DESCRIPTION b/Task/24-game-Solve/00DESCRIPTION index b198118587..3828d70f94 100644 --- a/Task/24-game-Solve/00DESCRIPTION +++ b/Task/24-game-Solve/00DESCRIPTION @@ -1,6 +1,5 @@ -Write a function that given four digits subject to the rules of the [[24 game]], computes an expression to solve the game if possible. - -Show examples of solutions generated by the function +Write a program that takes four digits, either from user input or by random generation, and computes arithmetic expressions following the rules of the [[24 game]]. +Show examples of solutions generated by the program. C.F: [[Arithmetic Evaluator]] diff --git a/Task/24-game-Solve/C++/24-game-solve.cpp b/Task/24-game-Solve/C++/24-game-solve.cpp new file mode 100644 index 0000000000..653cf0ba8e --- /dev/null +++ b/Task/24-game-Solve/C++/24-game-solve.cpp @@ -0,0 +1,90 @@ +#include +#include +#include +#include +#include + +typedef short int Digit; // Typedef for the digits data type. + +constexpr Digit nDigits{4}; // Amount of digits that are taken into the game. +constexpr Digit maximumDigit{9}; // Maximum digit that may be taken into the game. +constexpr short int gameGoal{24}; // Desired result. + +typedef std::array digitSet; // Typedef for the set of digits in the game. +digitSet d; + +void printTrivialOperation(std::string operation) { // Prints a commutative operation taking all the digits. + bool printOperation(false); + for(const Digit& number : d) { + if(printOperation) + std::cout << operation; + else + printOperation = true; + std::cout << number; + } + std::cout << std::endl; +} + +void printOperation(std::string prefix, std::string operation1, std::string operation2, std::string operation3, std::string suffix = "") { + std::cout << prefix << d[0] << operation1 << d[1] << operation2 << d[2] << operation3 << d[3] << suffix << std::endl; +} + +int main() { + std::mt19937_64 randomGenerator; + std::uniform_int_distribution digitDistro{1, maximumDigit}; + // Let us set up a number of trials: + for(int trial{10}; trial; --trial) { + for(Digit& digit : d) { + digit = digitDistro(randomGenerator); + std::cout << digit << " "; + } + std::cout << std::endl; + std::sort(d.begin(), d.end()); + // We start with the most trivial, commutative operations: + if(std::accumulate(d.cbegin(), d.cend(), 0) == gameGoal) + printTrivialOperation(" + "); + if(std::accumulate(d.cbegin(), d.cend(), 1, std::multiplies{}) == gameGoal) + printTrivialOperation(" * "); + // Now let's start working on every permutation of the digits. + do { + // Operations with 2 symbols + and one symbol -: + if(d[0] + d[1] + d[2] - d[3] == gameGoal) printOperation("", " + ", " + ", " - "); // If gameGoal is ever changed to a smaller value, consider adding more operations in this category. + // Operations with 2 symbols + and one symbol *: + if(d[0] * d[1] + d[2] + d[3] == gameGoal) printOperation("", " * ", " + ", " + "); + if(d[0] * (d[1] + d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) + "); + if(d[0] * (d[1] + d[2] + d[3]) == gameGoal) printOperation("", " * ( ", " + ", " + ", " )"); + // Operations with one symbol + and 2 symbols *: + if((d[0] * d[1] * d[2]) + d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) + "); + if(d[0] * d[1] * (d[2] + d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " + ", " )"); + if((d[0] * d[1]) + (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) + ( ", " * ", " )"); + // Operations with one symbol - and 2 symbols *: + if((d[0] * d[1] * d[2]) - d[3] == gameGoal) printOperation("( ", " * ", " * ", " ) - "); + if(d[0] * d[1] * (d[2] - d[3]) == gameGoal) printOperation("( ", " * ", " * ( ", " - ", " )"); + if((d[0] * d[1]) - (d[2] * d[3]) == gameGoal) printOperation("( ", " * ", " ) - ( ", " * ", " )"); + // Operations with one symbol +, one symbol *, and one symbol -: + if(d[0] * d[1] + d[2] - d[3] == gameGoal) printOperation("", " * ", " + ", " - "); + if(d[0] * (d[1] + d[2]) - d[3] == gameGoal) printOperation("", " * ( ", " + ", " ) - "); + if(d[0] * (d[1] - d[2]) + d[3] == gameGoal) printOperation("", " * ( ", " - ", " ) + "); + if(d[0] * (d[1] + d[2] - d[3]) == gameGoal) printOperation("", " * ( ", " + ", " - ", " )"); + if(d[0] * d[1] - (d[2] + d[3]) == gameGoal) printOperation("", " * ", " - ( ", " + ", " )"); + // Operations with one symbol *, one symbol /, one symbol +: + if(d[0] * d[1] == (gameGoal - d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) + "); + if(((d[0] * d[1]) + d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) + ", " ) / "); + if((d[0] + d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " + ", " ) * ", " ) / "); + if(d[0] * d[1] == gameGoal * (d[2] + d[3])) printOperation("( ", " * ", " ) / ( ", " + ", " )"); + // Operations with one symbol *, one symbol /, one symbol -: + if(d[0] * d[1] == (gameGoal + d[3]) * d[2]) printOperation("( ", " * ", " / ", " ) - "); + if(((d[0] * d[1]) - d[2]) == gameGoal * d[3]) printOperation("(( ", " * ", " ) - ", " ) / "); + if((d[0] - d[1]) * d[2] == gameGoal * d[3]) printOperation("(( ", " - ", " ) * ", " ) / "); + if(d[0] * d[1] == gameGoal * (d[2] - d[3])) printOperation("( ", " * ", " ) / ( ", " - ", " )"); + // Operations with 2 symbols *, one symbol /: + if(d[0] * d[1] * d[2] == gameGoal * d[3]) printOperation("", " * ", " * ", " / "); + if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("", " * ", " / ( ", " * ", " )"); + // Operations with 2 symbols /, one symbol -: + if(d[0] * d[3] == gameGoal * (d[1] * d[3] - d[2])) printOperation("", " / ( ", " - ", " / ", " )"); + // Operations with 2 symbols /, one symbol *: + if(d[0] * d[1] == gameGoal * d[2] * d[3]) printOperation("( ", " * ", " / ", " ) / ", ""); + } while(std::next_permutation(d.begin(), d.end())); // All operations are repeated for all possible permutations of the numbers. + } + return 0; +} diff --git a/Task/24-game-Solve/Clojure/24-game-solve.clj b/Task/24-game-Solve/Clojure/24-game-solve.clj index f30b5c5987..52796cf385 100644 --- a/Task/24-game-Solve/Clojure/24-game-solve.clj +++ b/Task/24-game-Solve/Clojure/24-game-solve.clj @@ -1,30 +1,25 @@ -(use 'clojure.contrib.combinatorics) +(ns rosettacode.24game.solve + (:require [clojure.math.combinatorics :as c] + [clojure.walk :as w])) -(defn nested-replace [l m] -(cond -(= l '()) '() -(m (first l)) (concat (list (m (first l))) (nested-replace (rest l) m)) -(seq? (first l)) (concat (list (nested-replace (first l) m)) (nested-replace (rest l) m)) -true (concat (list (first l)) (nested-replace (rest l) m)))) +(def ^:private op-maps + (map #(zipmap [:o1 :o2 :o3] %) (c/selections '(* + - /) 3))) -(defn format-solution [sol] -(cond -(number? sol) sol -(seq? sol) - (list (format-solution (second sol)) (first sol) (format-solution (nth sol 2))))) +(def ^:private patterns '( + (:o1 (:o2 :n1 :n2) (:o3 :n3 :n4)) + (:o1 :n1 (:o2 :n2 (:o3 :n3 :n4))) + (:o1 (:o2 (:o3 :n1 :n2) :n3) :n4))) -(defn play24 [& digits] (count (map #(-> % format-solution println) -(let [operator-map-list (map (fn [a] {:op1 (nth a 0) :op2 (nth a 1) :op3 (nth a 2)}) - (selections '(* + - /) 3)) - digits-map-list - (map (fn [a] {:num1 (nth a 0) :num2 (nth a 1) :num3 (nth a 2) :num4 (nth a 3)}) - (permutations digits)) - patterns-list (list - '(:op1 (:op2 :num1 :num2) (:op3 :num3 :num4)) - '(:op1 :num1 (:op2 :num2 (:op3 :num3 :num4)))) - ;other patterns can be added here, e.g. '(:op1 (:op2 (:op3 :num1 :num2) :num3) :num4) - op-subbed (reduce concat '() - (map (fn [a] (map #(nested-replace a % ) operator-map-list)) patterns-list)) - full-subbed (reduce concat '() - (map (fn [a] (map #(nested-replace % a) op-subbed)) digits-map-list))] - (filter #(= (try (eval %) (catch Exception e nil)) 24) full-subbed))))) +(defn play24 [& digits] + {:pre (and (every? #(not= 0 %) digits) + (= (count digits) 4))} + (->> (for [:let [digit-maps + (->> digits sort c/permutations + (map #(zipmap [:n1 :n2 :n3 :n4] %)))] + om op-maps, dm digit-maps] + (w/prewalk-replace dm + (w/prewalk-replace om patterns))) + (filter #(= (eval %) 24)) + (map println) + doall + count)) diff --git a/Task/24-game-Solve/CoffeeScript/24-game-solve.coffee b/Task/24-game-Solve/CoffeeScript/24-game-solve.coffee new file mode 100644 index 0000000000..ca775d9813 --- /dev/null +++ b/Task/24-game-Solve/CoffeeScript/24-game-solve.coffee @@ -0,0 +1,87 @@ +# This program tries to find some way to turn four digits into an arithmetic +# expression that adds up to 24. +# +# Example solution for 5, 7, 8, 8: +# (((8 + 7) * 8) / 5) + + +solve_24_game = (digits...) -> + # Create an array of objects for our helper functions + arr = for digit in digits + { + val: digit + expr: digit + } + combo4 arr... + +combo4 = (a, b, c, d) -> + arr = [a, b, c, d] + # Reduce this to a three-node problem by combining two + # nodes from the array. + permutations = [ + [0, 1, 2, 3] + [0, 2, 1, 3] + [0, 3, 1, 2] + [1, 2, 0, 3] + [1, 3, 0, 2] + [2, 3, 0, 1] + ] + for permutation in permutations + [i, j, k, m] = permutation + for combo in combos arr[i], arr[j] + answer = combo3 combo, arr[k], arr[m] + return answer if answer + null + +combo3 = (a, b, c) -> + arr = [a, b, c] + permutations = [ + [0, 1, 2] + [0, 2, 1] + [1, 2, 0] + ] + for permutation in permutations + [i, j, k] = permutation + for combo in combos arr[i], arr[j] + answer = combo2 combo, arr[k] + return answer if answer + null + +combo2 = (a, b) -> + for combo in combos a, b + return combo.expr if combo.val == 24 + null + +combos = (a, b) -> + [ + val: a.val + b.val + expr: "(#{a.expr} + #{b.expr})" + , + val: a.val * b.val + expr: "(#{a.expr} * #{b.expr})" + , + val: a.val - b.val + expr: "(#{a.expr} - #{b.expr})" + , + val: b.val - a.val + expr: "(#{b.expr} - #{a.expr})" + , + val: a.val / b.val + expr: "(#{a.expr} / #{b.expr})" + , + val: b.val / a.val + expr: "(#{b.expr} / #{a.expr})" + , + ] + +# test +do -> + rand_digit = -> 1 + Math.floor (9 * Math.random()) + + for i in [1..15] + a = rand_digit() + b = rand_digit() + c = rand_digit() + d = rand_digit() + solution = solve_24_game a, b, c, d + console.log "Solution for #{[a,b,c,d]}: #{solution ? 'no solution'}" diff --git a/Task/24-game-Solve/D/24-game-solve.d b/Task/24-game-Solve/D/24-game-solve.d index 690bf17863..aa1bf28f7b 100644 --- a/Task/24-game-Solve/D/24-game-solve.d +++ b/Task/24-game-Solve/D/24-game-solve.d @@ -1,47 +1,36 @@ -import std.stdio, std.algorithm, std.range, std.typecons, std.conv, - std.string, permutations2, arithmetic_rational; +import std.stdio, std.algorithm, std.range, std.conv, std.string, + std.concurrency, permutations2, arithmetic_rational; string solve(in int target, in int[] problem) { - static struct ComputeAllOperations { - //static struct T { Rational r; string e; } - alias T = Tuple!(Rational,"r", string,"e"); - Rational[] L; + static struct T { Rational r; string e; } - int opApply(in int delegate(ref T) dg) { - int result; - - if (!L.empty) { - auto x = L[0]; - auto xs = L[1 .. $]; - if (L.length == 1) { - T aux = T(x, text(x)); - result = dg(aux); - } else { - OUTER: foreach (o; ComputeAllOperations(xs)) { - auto y = o.r; - auto sub = [T(x * y, "*"), T(x + y, "+"), T(x - y, "-")]; - if (y) sub ~= [T(x/y, "/")]; - foreach (e; sub) { - auto aux = T(e.r, format("(%s%s%s)", x, e.e, o.e)); - result = dg(aux); if (result) break OUTER; + Generator!T computeAllOperations(in Rational[] L) { + return new typeof(return)({ + if (!L.empty) { + immutable x = L[0]; + if (L.length == 1) { + yield(T(x, x.text)); + } else { + foreach (const o; computeAllOperations(L.dropOne)) { + immutable y = o.r; + auto sub = [T(x * y, "*"), T(x + y, "+"), T(x - y, "-")]; + if (y) sub ~= [T(x / y, "/")]; + foreach (const e; sub) + yield(T(e.r, format("(%s%s%s)", x, e.e, o.e))); + } + } } - } - } - } - - return result; + }); } - } - - foreach (p; problem.map!Rational.array.permutations) - foreach (sol; ComputeAllOperations(p)) - if (sol.r == target) - return sol.e; - return "No solution"; + foreach (const p; problem.map!Rational.array.permutations!false) + foreach (const sol; computeAllOperations(p)) + if (sol.r == target) + return sol.e; + return "No solution"; } void main() { - foreach (prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]]) - writeln(prob, ": ", solve(24, prob)); + foreach (const prob; [[6, 7, 9, 5], [3, 3, 8, 8], [1, 1, 1, 1]]) + writeln(prob, ": ", solve(24, prob)); } diff --git a/Task/24-game-Solve/Go/24-game-solve.go b/Task/24-game-Solve/Go/24-game-solve.go index c19b9116f3..ae6c7815c4 100644 --- a/Task/24-game-Solve/Go/24-game-solve.go +++ b/Task/24-game-Solve/Go/24-game-solve.go @@ -73,23 +73,23 @@ func expr_eval(x *Expr) (f frac) { l, r := expr_eval(x.left), expr_eval(x.right) - switch { - case x.op == op_add: + switch x.op { + case op_add: f.num = l.num*r.denom + l.denom*r.num f.denom = l.denom * r.denom return - case x.op == op_sub: + case op_sub: f.num = l.num*r.denom - l.denom*r.num f.denom = l.denom * r.denom return - case x.op == op_mul: + case op_mul: f.num = l.num * r.num f.denom = l.denom * r.denom return - case x.op == op_div: + case op_div: f.num = l.num * r.denom f.denom = l.denom * r.num return diff --git a/Task/24-game-Solve/Haskell/24-game-solve-2.hs b/Task/24-game-Solve/Haskell/24-game-solve-2.hs index 2d42d88fdc..09069d19c7 100644 --- a/Task/24-game-Solve/Haskell/24-game-solve-2.hs +++ b/Task/24-game-Solve/Haskell/24-game-solve-2.hs @@ -1,76 +1,42 @@ -invocable all -link strings # for csort, deletec, permutes +import Control.Applicative +import Data.List +import Text.PrettyPrint -procedure main() -static eL -initial { - eoP := [] # set-up expression and operator permutation patterns - every ( e := !["a@b#c$d", "a@(b#c)$d", "a@b#(c$d)", "a@(b#c$d)", "a@(b#(c$d))"] ) & - ( o := !(opers := "+-*/") || !opers || !opers ) do - put( eoP, map(e,"@#$",o) ) # expr+oper perms - eL := [] # all cases - every ( e := !eoP ) & ( p := permutes("wxyz") ) do - put(eL, map(e,"abcd",p)) +data Expr = C Int | Op String Expr Expr - } +toDoc (C x ) = int x +toDoc (Op op x y) = parens $ toDoc x <+> text op <+> toDoc y -write("This will attempt to find solutions to 24 for sets of numbers by\n", - "combining 4 single digits between 1 and 9 to make 24 using only + - * / and ( ).\n", - "All operations have equal precedence and are evaluated left to right.\n", - "Enter 'use n1 n2 n3 n4' or just hit enter (to use a random set),", - "'first'/'all' shows the first or all solutions, 'quit' to end.\n\n") +ops :: [(String, Int -> Int -> Int)] +ops = [("+",(+)), ("-",(-)), ("*",(*)), ("/",div)] -repeat { - e := trim(read()) | fail - e ? case tab(find(" ")|0) of { - "q"|"quit" : break - "u"|"use" : e := tab(0) - "f"|"first": first := 1 & next - "a"|"all" : first := &null & next - "" : e := " " ||(1+?8) || " " || (1+?8) ||" " || (1+?8) || " " || (1+?8) - } - writes("Attempting to solve 24 for",e) +solve :: Int -> [Int] -> [Expr] +solve res = filter ((Just res ==) . eval) . genAst + where + genAst [x] = [C x] + genAst xs = do + (ys,zs) <- split xs + let f (Op op _ _) = op `notElem` ["+","*"] || ys <= zs + filter f $ Op <$> map fst ops <*> genAst ys <*> genAst zs - e := deletec(e,' \t') # no whitespace - if e ? ( tab(many('123456789')), pos(5), pos(0) ) then - write(":") - else write(" - invalid, only the digits '1..9' are allowed.") & next + eval (C x ) = Just x + eval (Op "/" _ y) | Just 0 <- eval y = Nothing + eval (Op op x y) = lookup op ops <*> eval x <*> eval y - eS := set() - every ex := map(!eL,"wxyz",e) do { - if member(eS,ex) then next # skip duplicates of final expression - insert(eS,ex) - if ex ? (ans := eval(E()), pos(0)) then # parse and evaluate - if ans = 24 then { - write("Success ",image(ex)," evaluates to 24.") - if \first then break - } - } - } -write("Quiting.") -end -procedure eval(X) #: return the evaluated AST - if type(X) == "list" then { - x := eval(get(X)) - while o := get(X) do - if y := get(X) then - x := o( real(x), (o ~== "/" | fail, eval(y) )) - else write("Malformed expression.") & fail - } - return \x | X -end +select :: Int -> [Int] -> [[Int]] +select 0 _ = [[]] +select n xs = [x:zs | k <- [0..length xs - n] + , let (x:ys) = drop k xs + , zs <- select (n - 1) ys + ] -procedure E() #: expression - put(lex := [],T()) - while put(lex,tab(any('+-*/'))) do - put(lex,T()) - suspend if *lex = 1 then lex[1] else lex # strip useless [] -end +split :: [Int] -> [([Int],[Int])] +split xs = [(ys, xs \\ ys) | n <- [1..length xs - 1] + , ys <- nub . sort $ select n xs + ] -procedure T() #: Term - suspend 2(="(", E(), =")") | # parenthesized subexpression, or ... - tab(any(&digits)) # just a value -end + +main = mapM_ (putStrLn . render . toDoc) $ solve 24 [2,3,8,9] diff --git a/Task/24-game-Solve/Haskell/24-game-solve-3.hs b/Task/24-game-Solve/Haskell/24-game-solve-3.hs new file mode 100644 index 0000000000..2d42d88fdc --- /dev/null +++ b/Task/24-game-Solve/Haskell/24-game-solve-3.hs @@ -0,0 +1,76 @@ +invocable all +link strings # for csort, deletec, permutes + +procedure main() +static eL +initial { + eoP := [] # set-up expression and operator permutation patterns + every ( e := !["a@b#c$d", "a@(b#c)$d", "a@b#(c$d)", "a@(b#c$d)", "a@(b#(c$d))"] ) & + ( o := !(opers := "+-*/") || !opers || !opers ) do + put( eoP, map(e,"@#$",o) ) # expr+oper perms + + eL := [] # all cases + every ( e := !eoP ) & ( p := permutes("wxyz") ) do + put(eL, map(e,"abcd",p)) + + } + +write("This will attempt to find solutions to 24 for sets of numbers by\n", + "combining 4 single digits between 1 and 9 to make 24 using only + - * / and ( ).\n", + "All operations have equal precedence and are evaluated left to right.\n", + "Enter 'use n1 n2 n3 n4' or just hit enter (to use a random set),", + "'first'/'all' shows the first or all solutions, 'quit' to end.\n\n") + +repeat { + e := trim(read()) | fail + e ? case tab(find(" ")|0) of { + "q"|"quit" : break + "u"|"use" : e := tab(0) + "f"|"first": first := 1 & next + "a"|"all" : first := &null & next + "" : e := " " ||(1+?8) || " " || (1+?8) ||" " || (1+?8) || " " || (1+?8) + } + + writes("Attempting to solve 24 for",e) + + e := deletec(e,' \t') # no whitespace + if e ? ( tab(many('123456789')), pos(5), pos(0) ) then + write(":") + else write(" - invalid, only the digits '1..9' are allowed.") & next + + eS := set() + every ex := map(!eL,"wxyz",e) do { + if member(eS,ex) then next # skip duplicates of final expression + insert(eS,ex) + if ex ? (ans := eval(E()), pos(0)) then # parse and evaluate + if ans = 24 then { + write("Success ",image(ex)," evaluates to 24.") + if \first then break + } + } + } +write("Quiting.") +end + +procedure eval(X) #: return the evaluated AST + if type(X) == "list" then { + x := eval(get(X)) + while o := get(X) do + if y := get(X) then + x := o( real(x), (o ~== "/" | fail, eval(y) )) + else write("Malformed expression.") & fail + } + return \x | X +end + +procedure E() #: expression + put(lex := [],T()) + while put(lex,tab(any('+-*/'))) do + put(lex,T()) + suspend if *lex = 1 then lex[1] else lex # strip useless [] +end + +procedure T() #: Term + suspend 2(="(", E(), =")") | # parenthesized subexpression, or ... + tab(any(&digits)) # just a value +end diff --git a/Task/24-game-Solve/Java/24-game-solve.java b/Task/24-game-Solve/Java/24-game-solve.java new file mode 100644 index 0000000000..c912a0836e --- /dev/null +++ b/Task/24-game-Solve/Java/24-game-solve.java @@ -0,0 +1,264 @@ +import java.util.*; + +public class Game24Player { + final String[] patterns = {"nnonnoo", "nnonono", "nnnoono", "nnnonoo", + "nnnnooo"}; + final String ops = "+-*/^"; + + String solution; + List digits; + + public static void main(String[] args) { + new Game24Player().play(); + } + + void play() { + digits = getSolvableDigits(); + + Scanner in = new Scanner(System.in); + while (true) { + System.out.print("Make 24 using these digits: "); + System.out.println(digits); + System.out.println("(Enter 'q' to quit, 's' for a solution)"); + System.out.print("> "); + + String line = in.nextLine(); + if (line.equalsIgnoreCase("q")) { + System.out.println("\nThanks for playing"); + return; + } + + if (line.equalsIgnoreCase("s")) { + System.out.println(solution); + digits = getSolvableDigits(); + continue; + } + + char[] entry = line.replaceAll("[^*+-/)(\\d]", "").toCharArray(); + + try { + validate(entry); + + if (evaluate(infixToPostfix(entry))) { + System.out.println("\nCorrect! Want to try another? "); + digits = getSolvableDigits(); + } else { + System.out.println("\nNot correct."); + } + + } catch (Exception e) { + System.out.printf("%n%s Try again.%n", e.getMessage()); + } + } + } + + void validate(char[] input) throws Exception { + int total1 = 0, parens = 0, opsCount = 0; + + for (char c : input) { + if (Character.isDigit(c)) + total1 += 1 << (c - '0') * 4; + else if (c == '(') + parens++; + else if (c == ')') + parens--; + else if (ops.indexOf(c) != -1) + opsCount++; + if (parens < 0) + throw new Exception("Parentheses mismatch."); + } + + if (parens != 0) + throw new Exception("Parentheses mismatch."); + + if (opsCount != 3) + throw new Exception("Wrong number of operators."); + + int total2 = 0; + for (int d : digits) + total2 += 1 << d * 4; + + if (total1 != total2) + throw new Exception("Not the same digits."); + } + + boolean evaluate(char[] line) throws Exception { + Stack s = new Stack<>(); + try { + for (char c : line) { + if ('0' <= c && c <= '9') + s.push((float) c - '0'); + else + s.push(applyOperator(s.pop(), s.pop(), c)); + } + } catch (EmptyStackException e) { + throw new Exception("Invalid entry."); + } + return (Math.abs(24 - s.peek()) < 0.001F); + } + + float applyOperator(float a, float b, char c) { + switch (c) { + case '+': + return a + b; + case '-': + return b - a; + case '*': + return a * b; + case '/': + return b / a; + default: + return Float.NaN; + } + } + + List randomDigits() { + Random r = new Random(); + List result = new ArrayList<>(4); + for (int i = 0; i < 4; i++) + result.add(r.nextInt(9) + 1); + return result; + } + + List getSolvableDigits() { + List result; + do { + result = randomDigits(); + } while (!isSolvable(result)); + return result; + } + + boolean isSolvable(List digits) { + Set> dPerms = new HashSet<>(4 * 3 * 2); + permute(digits, dPerms, 0); + + int total = 4 * 4 * 4; + List> oPerms = new ArrayList<>(total); + permuteOperators(oPerms, 4, total); + + StringBuilder sb = new StringBuilder(4 + 3); + + for (String pattern : patterns) { + char[] patternChars = pattern.toCharArray(); + + for (List dig : dPerms) { + for (List opr : oPerms) { + + int i = 0, j = 0; + for (char c : patternChars) { + if (c == 'n') + sb.append(dig.get(i++)); + else + sb.append(ops.charAt(opr.get(j++))); + } + + String candidate = sb.toString(); + try { + if (evaluate(candidate.toCharArray())) { + solution = postfixToInfix(candidate); + return true; + } + } catch (Exception ignored) { + } + sb.setLength(0); + } + } + } + return false; + } + + String postfixToInfix(String postfix) { + class Expression { + String op, ex; + int prec = 3; + + Expression(String e) { + ex = e; + } + + Expression(String e1, String e2, String o) { + ex = String.format("%s %s %s", e1, o, e2); + op = o; + prec = ops.indexOf(o) / 2; + } + } + + Stack expr = new Stack<>(); + + for (char c : postfix.toCharArray()) { + int idx = ops.indexOf(c); + if (idx != -1) { + + Expression r = expr.pop(); + Expression l = expr.pop(); + + int opPrec = idx / 2; + + if (l.prec < opPrec) + l.ex = '(' + l.ex + ')'; + + if (r.prec <= opPrec) + r.ex = '(' + r.ex + ')'; + + expr.push(new Expression(l.ex, r.ex, "" + c)); + } else { + expr.push(new Expression("" + c)); + } + } + return expr.peek().ex; + } + + char[] infixToPostfix(char[] infix) throws Exception { + StringBuilder sb = new StringBuilder(); + Stack s = new Stack<>(); + try { + for (char c : infix) { + int idx = ops.indexOf(c); + if (idx != -1) { + if (s.isEmpty()) + s.push(idx); + else { + while (!s.isEmpty()) { + int prec2 = s.peek() / 2; + int prec1 = idx / 2; + if (prec2 >= prec1) + sb.append(ops.charAt(s.pop())); + else + break; + } + s.push(idx); + } + } else if (c == '(') { + s.push(-2); + } else if (c == ')') { + while (s.peek() != -2) + sb.append(ops.charAt(s.pop())); + s.pop(); + } else { + sb.append(c); + } + } + while (!s.isEmpty()) + sb.append(ops.charAt(s.pop())); + + } catch (EmptyStackException e) { + throw new Exception("Invalid entry."); + } + return sb.toString().toCharArray(); + } + + void permute(List lst, Set> res, int k) { + for (int i = k; i < lst.size(); i++) { + Collections.swap(lst, i, k); + permute(lst, res, k + 1); + Collections.swap(lst, k, i); + } + if (k == lst.size()) + res.add(new ArrayList<>(lst)); + } + + void permuteOperators(List> res, int n, int total) { + for (int i = 0, npow = n * n; i < total; i++) + res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); + } +} diff --git a/Task/24-game-Solve/ProDOS/24-game-solve.dos b/Task/24-game-Solve/ProDOS/24-game-solve.dos new file mode 100644 index 0000000000..4da948715f --- /dev/null +++ b/Task/24-game-Solve/ProDOS/24-game-solve.dos @@ -0,0 +1,35 @@ +editvar /modify -random- = <10 +:a +editvar /newvar /withothervar /value=-random- /title=1 +editvar /newvar /withothervar /value=-random- /title=2 +editvar /newvar /withothervar /value=-random- /title=3 +editvar /newvar /withothervar /value=-random- /title=4 +printline These are your four digits: -1- -2- -3- -4- +printline Use an algorithm to make the number 24. +editvar /newvar /value=a /userinput=1 /title=Algorithm: +do -a- +if -a- /hasvalue 24 printline Your algorithm worked! & goto :b ( +) else printline Your algorithm did not work. +editvar /newvar /value=b /userinput=1 /title=Do you want to see how you could have done it? +if -b- /hasvalue y goto :c else goto :b +:b +editvar /newvar /value=c /userinput=1 /title=Do you want to play again? +if -c- /hasvalue y goto :a else exitcurrentprogram +:c +editvar /newvar /value=do -1- + -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- - -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- / -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- * -2- + -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- - -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- / -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- * -3- + -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- + -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- + -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- + -2- + -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- - -2- - -3- - -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- / -2- / -3- / -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +editvar /newvar /value=do -1- * -2- * -3- * -4- /title=c & do -c- >d & if -d- /hasvalue 24 goto :solve +:solve +printline you could have done it by doing -c- +stoptask +goto :b diff --git a/Task/24-game-Solve/Prolog/24-game-solve.pro b/Task/24-game-Solve/Prolog/24-game-solve-1.pro similarity index 100% rename from Task/24-game-Solve/Prolog/24-game-solve.pro rename to Task/24-game-Solve/Prolog/24-game-solve-1.pro diff --git a/Task/24-game-Solve/Prolog/24-game-solve-2.pro b/Task/24-game-Solve/Prolog/24-game-solve-2.pro new file mode 100644 index 0000000000..597be97327 --- /dev/null +++ b/Task/24-game-Solve/Prolog/24-game-solve-2.pro @@ -0,0 +1,22 @@ +:- initialization(main). + +solve(N,Xs,Ast) :- + Err = evaluation_error(zero_divisor) + , gen_ast(Xs,Ast), catch(Ast =:= N, error(Err,_), fail) + . + +gen_ast([N],N) :- between(1,9,N). +gen_ast(Xs,Ast) :- + Ys = [_|_], Zs = [_|_], split(Xs,Ys,Zs) + , ( member(Op, [(+),(*)]), Ys @=< Zs ; member(Op, [(-),(//)]) ) + , gen_ast(Ys,A), gen_ast(Zs,B), Ast =.. [Op,A,B] + . + +split(Xs,Ys,Zs) :- sublist(Ys,Xs), select_all(Ys,Xs,Zs). + % where + select_all([],Xs,Xs). + select_all([Y|Ys],Xs,Zs) :- select(Y,Xs,X1), !, select_all(Ys,X1,Zs). + + +test(T) :- solve(24, [2,3,8,9], T). +main :- forall(test(T), (write(T), nl)), halt. diff --git a/Task/24-game-Solve/REXX/24-game-solve.rexx b/Task/24-game-Solve/REXX/24-game-solve.rexx index 4c57515328..9c70bc0157 100644 --- a/Task/24-game-Solve/REXX/24-game-solve.rexx +++ b/Task/24-game-Solve/REXX/24-game-solve.rexx @@ -3,7 +3,7 @@ │ Argument is either of two forms: ssss ==or== ssss-ffff │ │ │ │ where one or both strings must be exactly four numerals (digits) │ - │ comprised soley of the numerals (digits) 1 ──> 9 (no zeroes). │ + │ comprised soley of the numerals (digits) 1 ──► 9 (no zeroes). │ │ │ │ In SSSS-FFFF SSSS is the start, │ │ FFFF is the start. │ @@ -17,8 +17,8 @@ digs=123456789 /*numerals (digits) that can be used. */ call validate start call validate finish opers='+-*/' /*define the legal arithmetic operators*/ -ops=length(opers) /* ... and the count of them (length). */ - do j=1 for ops /*define a version for fast execution. */ +ops=length(opers) /* ··· and the count of them (length). */ + do j=1 for ops /*define a version for fast execution. */ o.j=substr(opers,j,1) end /*j*/ finds=0 /*number of found solutions (so far). */ @@ -28,22 +28,22 @@ indent=left('',30) /*used to indent display of solutions. */ Lpar='(' /*a string to make REXX code prettier. */ Rpar=')' /*ditto. */ - do g=start to finish /*process a (possible) range of values.*/ - if pos(0,g)\==0 then iterate /*ignore values with zero in them. */ + do g=start to finish /*process a (possible) range of values.*/ + if pos(0,g)\==0 then iterate /*ignore values with zero in them. */ - do _=1 for 4 /*define versions for faster execution.*/ + do _=1 for 4 /*define versions for faster execution.*/ g._=substr(g,_,1) end /*_*/ do i=1 for ops /*insert an operator after 1st number. */ do j=1 for ops /*insert an operator after 2nd number. */ do k=1 for ops /*insert an operator after 2nd number. */ - do m=0 to 3; L.= /*assume no left parenthesis so far. */ - do n=m+1 to 4 /*match left paren with a right paren. */ + do m=0 for 4; L.= /*assume no left parenthesis so far. */ + do n=m+1 to 4 /*match left paren with a right paren. */ L.m=Lpar /*define a left paren, m=0 means ignore*/ - R.="" /*un-define all right parenthesis. */ - if m==1 & n==2 then L.="" /*special case: (n)+ ... */ - else if m\==0 then R.n=Rpar /*no (, no )*/ + R.= /*un-define all right parenthesis. */ + if m==1 & n==2 then L.= /*special case: (n)+ ··· */ + else if m\==0 then R.n=Rpar /*no (, no )*/ e= L.1 g.1 o.i L.2 g.2 o.j L.3 g.3 R.3 o.k g.4 R.4 e=space(e,0) /*remove all blanks from the expression*/ @@ -51,7 +51,7 @@ Rpar=')' /*ditto. */ /* /(yyy) ===> /div(yyy) */ /*Enables to check for division by zero*/ origE=e /*keep old version for the display. */ - if pos('/(',e)\==0 then e=changestr('/(',e,"/div(") + if pos('/(',e)\==0 then e=changestr('/(', e, "/div(") /*The above could be replaced by: */ /* e=changestr('/(',e,"/div(") */ @@ -60,12 +60,12 @@ Rpar=')' /*ditto. */ if x.e then iterate /*was the expression already used? */ x.e=1 /*mark this expression as unique. */ /*have REXX do the heavy lifting (ugh).*/ - interpret 'x=' e /*... strain... */ + interpret 'x=' e /*··· strain··· */ x=x/1 /*remove trailing decimal points(maybe)*/ - if x\==24 then iterate /*Not correct? Try again. */ + if x\==24 then iterate /*Not correct? Try again. */ finds=finds+1 /*bump number of found solutions. */ _=translate(origE, '][', ")(") /*show [], not (). */ - say indent 'a solution:' _ /*display a solution. */ + say indent 'a solution:' _ /*display a solution. */ end /*n*/ end /*m*/ end /*k*/ @@ -79,15 +79,15 @@ say; say sols 'unique solution's(finds) "found for" orig /*pluralize.*/ exit /*───────────────────────────DIV subroutine─────────────────────────────*/ div: procedure; parse arg q /*tests if dividing by 0 (zero). */ -if q=0 then q=1e9 /*if dividing by zero, change divisor. */ +if q=0 then q=1e9 /*if dividing by zero, change divisor. */ return q /*changing Q invalidates the expression*/ /*───────────────────────────GER subroutine─────────────────────────────*/ -ger: say; say '*** error! ***'; if _\=='' then say 'guess=' _ -say arg(1); say; exit 13 +ger: say; say '*** error! ***'; if _\=='' then say 'guess=' _ +say arg(1); say; exit 13 /*───────────────────────────S subroutine───────────────────────────────*/ -s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ +s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ /*───────────────────────────validate subroutine────────────────────────*/ -validate: parse arg y; errCode=0; _v=verify(y,digs) +validate: parse arg y; errCode=0; _v=verify(y,digs) select when y=='' then call ger 'no digits entered.' when length(y)<4 then call ger 'not enough digits entered, must be 4' diff --git a/Task/24-game-Solve/Tcl/24-game-solve.tcl b/Task/24-game-Solve/Tcl/24-game-solve.tcl index 0099b6a4c3..ec1896c421 100644 --- a/Task/24-game-Solve/Tcl/24-game-solve.tcl +++ b/Task/24-game-Solve/Tcl/24-game-solve.tcl @@ -2,10 +2,10 @@ package require struct::list # Encoding the various expression trees that are possible set patterns { {((A x B) y C) z D} - {(A x (B y C)) z D} - {(A x B) y (C z D)} - {A x ((B y C) z D)} - {A x (B y (C z D))} + {(A x (B y C)) z D} + {(A x B) y (C z D)} + {A x ((B y C) z D)} + {A x (B y (C z D))} } # Encoding the various permutations of digits set permutations [struct::list map [struct::list permutations {a b c d}] \ @@ -13,8 +13,8 @@ set permutations [struct::list map [struct::list permutations {a b c d}] \ # The permitted operations set operations {+ - * /} -# Given a list of four integers (precondition not checked!) return a list of -# solutions to the 24 game using those four integers. +# Given a list of four integers (precondition not checked!) +# return a list of solutions to the 24 game using those four integers. proc find24GameSolutions {values} { global operations patterns permutations set found {} diff --git a/Task/24-game/00DESCRIPTION b/Task/24-game/00DESCRIPTION index 5cb3d944e2..8e28595bf2 100644 --- a/Task/24-game/00DESCRIPTION +++ b/Task/24-game/00DESCRIPTION @@ -1,6 +1,7 @@ The [[wp:24 Game|24 Game]] tests one's mental arithmetic. -Write a program that [[task feature::Rosetta Code:randomness|randomly]] chooses and [[task feature::Rosetta Code:user output|displays]] four digits, each from one to nine, with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits. The program should ''check'' then [[task feature::Rosetta Code:parsing|evaluate the expression]]. The goal is for the player to [[task feature::Rosetta Code:user input|enter]] an expression that evaluates to '''24'''. +Write a program that [[task feature::Rosetta Code:randomness|randomly]] chooses and [[task feature::Rosetta Code:user output|displays]] four digits, each from one to nine, with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using ''just'' those, and ''all'' of those four digits, used exactly ''once'' each. The program should ''check'' then [[task feature::Rosetta Code:parsing|evaluate the expression]]. +The goal is for the player to [[task feature::Rosetta Code:user input|enter]] an expression that evaluates to '''24'''. * Only multiplication, division, addition, and subtraction operators/functions are allowed. * Division should use floating point or rational arithmetic, etc, to preserve remainders. * Brackets are allowed, if using an infix expression evaluator. diff --git a/Task/24-game/Batch-File/24-game.bat b/Task/24-game/Batch-File/24-game.bat new file mode 100644 index 0000000000..d3ff85cd53 --- /dev/null +++ b/Task/24-game/Batch-File/24-game.bat @@ -0,0 +1,83 @@ +@echo off +::24.bat +:: +::Batch file implemetnation of the 24 Game where a player is given four random +::digits n, where 1 <= n <= 9, and needs to provide a simple arithmetic +::operation that does evaluate to 24. +:: +::Note: [1]This implementation does not evaluate brackets +:: [2]This implementation does not keep remainders since batch language +:: has no support for floating point calculations +cls +echo The 24 Game +echo. +echo Given four digits, provide a simple arithmetic expression +echo that evaluates to 24 using +,-,*,/. +echo. +echo Enter 'SHOW' to show the digits or 'EXIT' to end the game. +echo. + +set TRY=0 + +::Get four random digits +set /a "DIGIT_1=%RANDOM% %%9 + 1" +set /a "DIGIT_2=%RANDOM% %%9 + 1" +set /a "DIGIT_3=%RANDOM% %%9 + 1" +set /a "DIGIT_4=%RANDOM% %%9 + 1" + +goto SHOW + +::Main Program Loop +:MAIN +set /a TRY+=1 +set "TMP_DIGIT_1=%DIGIT_1%" +set "TMP_DIGIT_2=%DIGIT_2%" +set "TMP_DIGIT_3=%DIGIT_3%" +set "TMP_DIGIT_4=%DIGIT_4%" + +::Promt for an answer and trim answer string +set /p ANSWER="Try %TRY%: " +set "ANSWER=%ANSWER: =%" + + +if /i "%ANSWER%"=="SHOW" goto SHOW +if /i "%ANSWER%"=="EXIT" goto ABORT +if "%ANSWER:~6,1%"=="" goto ERROR_MISSING_CHARS: + +::Determine if each digits has ben used once in the input equation +set DIGITS_USED=0 +set COUNTER=0 +:LOOP +call set CURR_DIGIT=%%ANSWER:~%COUNTER%,1%% +if %CURR_DIGIT%==%TMP_DIGIT_1% (set "TMP_DIGIT_1=" & set /a "DIGITS_USED+=1") +if %CURR_DIGIT%==%TMP_DIGIT_2% (set "TMP_DIGIT_2=" & set /a "DIGITS_USED+=2") +if %CURR_DIGIT%==%TMP_DIGIT_3% (set "TMP_DIGIT_3=" & set /a "DIGITS_USED+=4") +if %CURR_DIGIT%==%TMP_DIGIT_4% (set "TMP_DIGIT_4=" & set /a "DIGITS_USED+=8") +set /a "COUNTER+=2" +if not "%COUNTER%"=="8" goto LOOP +if not "%DIGITS_USED%"=="15" goto ERROR_INCORRECT_INPUT + +::Calculate and evaluate result +set /a "RESULT=%ANSWER%" +if "%RESULT%"=="24" goto END + +echo Invalid input [Bad result: Expected 24, Received %RESULT%] +goto MAIN + +:ERROR_MISSING_CHARS +echo Invalid input [insufficient number of characters] +goto MAIN + +:ERROR_INCORRECT_INPUT +echo Invalid input [incorrect digits] +goto MAIN + +:SHOW +echo Given digits: %DIGIT_1% %DIGIT_2% %DIGIT_3% %DIGIT_4% +goto MAIN + +:END +echo Correct input [Congratulations!] + +:ABORT +echo. diff --git a/Task/24-game/Common-Lisp/24-game-1.lisp b/Task/24-game/Common-Lisp/24-game-1.lisp index 89aacc0051..ddfc3fdc29 100644 --- a/Task/24-game/Common-Lisp/24-game-1.lisp +++ b/Task/24-game/Common-Lisp/24-game-1.lisp @@ -9,7 +9,7 @@ chosen-digits) (read)) (lose () (error 'bad-equation)) - (choose () (setf chosen-digits (loop repeat 4 collecting (random 10)))) + (choose () (setf chosen-digits (loop repeat 4 collecting (1+ (random 9))))) (check (e) (typecase e ((eql bye) (return-from 24-game)) diff --git a/Task/24-game/Java/24-game.java b/Task/24-game/Java/24-game.java new file mode 100644 index 0000000000..f944644954 --- /dev/null +++ b/Task/24-game/Java/24-game.java @@ -0,0 +1,62 @@ +import java.util.*; + +public class Game24 { + + public static void main(String[] args) { + + int[] digits = randomDigits(); + Scanner in = new Scanner(System.in); + + System.out.print("Make 24 using these digits: "); + System.out.println(Arrays.toString(digits)); + System.out.print("> "); + + Stack s = new Stack<>(); + long total = 0; + for (char c : in.nextLine().toCharArray()) { + if ('0' <= c && c <= '9') { + int d = c - '0'; + total += (1 << (d * 5)); + s.push((float) d); + } else if ("+/-*".indexOf(c) != -1) { + s.push(applyOperator(s.pop(), s.pop(), c)); + } + } + if (tallyDigits(digits) != total) + System.out.print("Not the same digits. "); + else if (Math.abs(24 - s.peek()) < 0.001F) + System.out.println("Correct!"); + else + System.out.print("Not correct."); + } + + static float applyOperator(float a, float b, char c) { + switch (c) { + case '+': + return a + b; + case '-': + return b - a; + case '*': + return a * b; + case '/': + return b / a; + default: + return Float.NaN; + } + } + + static long tallyDigits(int[] a) { + long total = 0; + for (int i = 0; i < 4; i++) + total += (1 << (a[i] * 5)); + return total; + } + + static int[] randomDigits() { + Random r = new Random(); + int[] result = new int[4]; + for (int i = 0; i < 4; i++) + result[i] = r.nextInt(9) + 1; + return result; + } +} diff --git a/Task/24-game/JavaScript/24-game.js b/Task/24-game/JavaScript/24-game.js index 06fb37c3ff..7a870eb0e3 100644 --- a/Task/24-game/JavaScript/24-game.js +++ b/Task/24-game/JavaScript/24-game.js @@ -1,48 +1,51 @@ -String.prototype.replaceAll = function(patt,repl) { var that = this; - that = that.replace(patt,repl); - if (that.search(patt) != -1) { - that = that.replaceAll(patt,repl); - } - return that; - }; +function twentyfour(numbers, input) { + var invalidChars = /[^\d\+\*\/\s-\(\)]/; -function validChars(input) { var regInvalidChar = /[^\d\+\*\/\s-\(\)]/; - return input.search(regInvalidChar) == -1; - } + var validNums = function(str) { + // Create a duplicate of our input numbers, so that + // both lists will be sorted. + var mnums = numbers.slice(); + mnums.sort(); -function validNums(str, nums) { - var arr, l; - arr = str.replaceAll(/[^\d\s]/," ").replaceAll(" "," ").trim().split(" ").sort(); - l = arr.length; + // Sort after mapping to numbers, to make comparisons valid. + return str.replace(/[^\d\s]/g, " ") + .trim() + .split(/\s+/) + .map(function(n) { return parseInt(n, 10); }) + .sort() + .every(function(v, i) { return v === mnums[i]; }); + }; - while(l--) { arr[l] = Number(arr[l]); } + var validEval = function(input) { + try { + return eval(input); + } catch (e) { + return {error: e.toString()}; + } + }; - return _.isEqual(arr,nums.sort()); + if (input.trim() === "") return "You must enter a value."; + if (input.match(invalidChars)) return "Invalid chars used, try again. Use only:\n + - * / ( )"; + if (!validNums(input)) return "Wrong numbers used, try again."; + var calc = validEval(input); + if (typeof calc !== 'number') return "That is not a valid input; please try again."; + if (calc !== 24) return "Wrong answer: " + String(calc) + "; please try again."; + return input + " == 24. Congratulations!"; +}; + +// I/O below. + +while (true) { + var numbers = [1, 2, 3, 4].map(function() { + return Math.floor(Math.random() * 8 + 1); + }); + + var input = prompt( + "Your numbers are:\n" + numbers.join(" ") + + "\nEnter expression. (use only + - * / and parens).\n", +"'x' to exit.", ""); + + if (input === 'x') { + break; + } + alert(twentyfour(numbers, input)); } - -function validEval(input) { try { eval(input); } catch (e) { return false; }; - return true; - } - -var input; - -while(true){ var numbers = []; - var i = 4; - while(i--) { numbers.push(Math.floor(Math.random()*8+1)); - } - - input = prompt("Your numbers are:\n" - + numbers.join(" ") - + "\nEnter expression. (use only + - * / and parens).\n" - + "'x' to exit." - ); - - if (input === 'x') break; - - !validChars(input) ? alert("Invalid chars used, try again. Use only:\n + - * / ( )") - : !validNums(input,numbers) ? alert("Wrong numbers used, try again.") - : !validEval(input) ? alert("Could not evaluate input, try again.") - : eval(input) != 24 ? alert("Wrong answer:" + eval(input) + "\nTry again.") - : alert(input + "== 24. Congrats!!") - ; - } diff --git a/Task/24-game/Julia/24-game.julia b/Task/24-game/Julia/24-game.julia index 8176012812..72ca7bc598 100644 --- a/Task/24-game/Julia/24-game.julia +++ b/Task/24-game/Julia/24-game.julia @@ -1,63 +1,28 @@ +validexpr(ex::Expr) = ex.head == :call && ex.args[1] in [:*,:/,:+,:-] && all(validexpr, ex.args[2:end]) +validexpr(ex::Int) = true +validexpr(ex::Any) = false +findnumbers(ex::Number) = Int[ex] +findnumbers(ex::Expr) = vcat(map(findnumbers, ex.args)...) +findnumbers(ex::Any) = Int[] function twentyfour() - function check(input) - d = ref(Int) - for i in input.args - if typeof(i) == Expr - c = check(i) - typeof(c) == String || append!(d,c) - elseif contains([:*,:/,:-,:+],i) - continue - elseif contains([1:9],i) - push!(d,i) - continue - elseif i > 9 || i < 1 - d = "Sorry, $i is not allowed, please use only numbers between 1 and 9" - else - d = "Sorry, $i isn't allowed" - end - end - return d - end - new_digits() = [rand(1:9),rand(1:9),rand(1:9),rand(1:9)] - answer = new_digits() - 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' 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 - input = chomp(readline(STDIN)) - input == "q" && break - if input == "n" - answer = new_digits() - print("\nLet's try again, go ahead and guess\n Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n>") - continue - end - input = try - parse(input) - catch - print("I couldn't calculate your answer, please try again\n>"); - continue - end - c = check(input) - cc = all([sum(i .== answer) == sum(i .== c) for i in answer]) - !cc && (print("Sorry, valid digits are \n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n are allowed and all four must be used. Please try again\n>"); continue) - if eval(input) == 24 - answer = new_digits() - print("\nYou did it!\nLet's do another round, or enter 'q' to quit\n - Here's your 4 digits\n$(answer[1]) $(answer[2]) $(answer[3]) $(answer[4])\n - >") - continue - else - print("\nSorry your answer calculates to $(eval(input))\nTry again\n>") - end - end + digits = sort!(rand(1:9, 4)) + while true + print("enter expression using $digits => ") + ex = parse(readline()) + try + validexpr(ex) || error("only *, /, +, - of integers is allowed") + nums = sort!(findnumbers(ex)) + nums == digits || error("expression $ex used numbers $nums != $digits") + val = eval(ex) + val == 24 || error("expression $ex evaluated to $val, not 24") + println("you won!") + return + catch e + if isa(e, ErrorException) + println("incorrect: ", e.msg) + else + rethrow() + end + end + end end diff --git a/Task/24-game/Perl-6/24-game.pl6 b/Task/24-game/Perl-6/24-game.pl6 index 60ecc4cd8c..bef0c6aa5f 100644 --- a/Task/24-game/Perl-6/24-game.pl6 +++ b/Task/24-game/Perl-6/24-game.pl6 @@ -1,38 +1,23 @@ +say "Here are your digits: ", +constant @digits = (1..9).roll(4)».Str; + grammar Exp24 { - token TOP { ^ $ } - token exp { [ ]* } - token term { '(' ')' | \d } - token op { '+' | '-' | '*' | '/' } + token TOP { ^ $ { fail unless EVAL($/) == 24 } } + rule exp { + % } + rule term { '(' ')' | <@digits> } + token op { < + - * / > } } -my @digits = roll 4, 1..9; # to a gamer, that's a "4d9" roll -say "Here's your digits: {@digits}"; - -while my $exp = prompt "\n24-Exp? " { - unless is-valid($exp, @digits) { - say "Sorry, your expression is not valid!"; - next; +while my $exp = prompt "\n24? " { + if Exp24.parse: $exp { + say "You win :)"; + last; + } else { + say pick 1, + 'Sorry. Try again.' xx 20, + 'Try harder.' xx 5, + 'Nope. Not even close.' xx 2, + 'Are you five or something?', + 'Come on, you can do better than that.'; } - - my $value = eval $exp; - say "$exp = $value"; - if $value == 24 { - say "You win!"; - last; - } - say "Sorry, your expression doesn't evaluate to 24!"; -} - -sub is-valid($exp, @digits) { - unless ?Exp24.parse($exp) { - say "Expression doesn't match rules!"; - return False; - } - - unless $exp.comb(/\d/).sort.join == @digits.sort.join { - say "Expression must contain digits {@digits} only!"; - return False; - } - - return True; } diff --git a/Task/24-game/Perl/24-game.pl b/Task/24-game/Perl/24-game.pl index 6358ff67ac..071bb8e2b8 100644 --- a/Task/24-game/Perl/24-game.pl +++ b/Task/24-game/Perl/24-game.pl @@ -1,122 +1,46 @@ -#!/usr/bin/perl - -use strict; +#!/usr/bin/env perl use warnings; +use strict; +use feature 'say'; print <<'EOF'; The 24 Game Given any four digits in the range 1 to 9, which may have repetitions, Using just the +, -, *, and / operators; and the possible use of -brackets, (), show how to make an answer of 24. +parentheses, (), show how to make an answer of 24. -An answer of "q" will quit the game. -An answer of "!" will generate a new set of four digits. -Otherwise you are repeatedly asked for an expression until it evaluates to 24 +An answer of "q" or EOF will quit the game. +A blank answer will generate a new set of four digits. +Otherwise you are repeatedly asked for an expression until it evaluates to 24. Note: you cannot form multiple digit numbers from the supplied digits, so an answer of 12+12 when given 1, 2, 2, and 1 would not be allowed. EOF -while(1) -{ - my $iteration_num = 0; +my $try = 1; +while (1) { + my @digits = map { 1+int(rand(9)) } 1..4; + say "\nYour four digits: ", join(" ", @digits); + print "Expression (try ", $try++, "): "; - my $numbers = make_numbers(); + my $entry = <>; + if (!defined $entry || $entry eq 'q') + { say "Goodbye. Sorry you couldn't win."; last; } + $entry =~ s/\s+//g; # remove all white space + next if $entry eq ''; - TRY_SOLVING: - while(1) - { - $iteration_num++; - print "Expression ${iteration_num}: "; + my $given_digits = join "", sort @digits; + my $entry_digits = join "", sort grep { /\d/ } split(//, $entry); + if ($given_digits ne $entry_digits || # not correct digits + $entry =~ /\d\d/ || # combined digits + $entry =~ m|[-+*/]{2}| || # combined operators + $entry =~ tr|-0-9()+*/||c) # Invalid characters + { say "That's not valid"; next; } - my $entry = <>; - chomp($entry); + my $n = eval $entry; - last TRY_SOLVING if $entry eq '!'; - - exit if $entry eq 'q'; - - my $result = play($numbers, $entry); - - if (!defined $result) - { - print "That's not valid\n"; - next TRY_SOLVING; - } - elsif ($result != 24) - { - print "Sorry, that's $result\n"; - next TRY_SOLVING; - } - else - { - print "That's right! 24!!\n"; - exit; - } - } -} - -sub make_numbers -{ - my %numbers = (); - - print "Your four digits:"; - - for(1..4) - { - my $i = 1 + int(rand(9)); - $numbers{$i}++; - print "$i "; - } - - print "\n"; - - return \%numbers; -} - -sub play -{ - my ($numbers, $expression) = @_; - - my %running_numbers = %$numbers; - - my @chars = split //, $expression; - - my $operator = 1; - - CHARS: - foreach (@chars) - { - next CHARS if $_ =~ /[()]/; - - $operator = !$operator; - - if (! $operator) - { - if (defined $running_numbers{$_} && $running_numbers{$_} > 0) - { - $running_numbers{$_}--; - next CHARS; - } - else - { - return; - } - } - else - { - return if $_ !~ m{[-+*/]}; - } - } - - foreach my $remaining (values(%running_numbers)) - { - if ($remaining > 0) - { - return; - } - } - - return eval($expression); + if (!defined $n) { say "Invalid expression"; } + elsif ($n == 24) { say "You win!"; last; } + else { say "Sorry, your expression is $n, not 24"; } } diff --git a/Task/24-game/Prolog/24-game.pro b/Task/24-game/Prolog/24-game.pro new file mode 100644 index 0000000000..f65261d413 --- /dev/null +++ b/Task/24-game/Prolog/24-game.pro @@ -0,0 +1,30 @@ +:- initialization(main). + + +answer(24). +play :- round, play ; true. + +round :- + prompt(Ns), get_line(Input), Input \= "stop" + , ( phrase(parse(Ns,[]), Input) -> Result = 'correct' + ; Result = 'wrong' + ), write(Result), nl, nl + . % where + prompt(Ns) :- length(Ns,4), maplist(random(1,10), Ns) + , write('Digits: '), write(Ns), nl + . + +parse([],[X]) --> { answer(X) }. +parse(Ns,[Y,X|S]) --> "+", { Z is X + Y }, parse(Ns,[Z|S]). +parse(Ns,[Y,X|S]) --> "-", { Z is X - Y }, parse(Ns,[Z|S]). +parse(Ns,[Y,X|S]) --> "*", { Z is X * Y }, parse(Ns,[Z|S]). +parse(Ns,[Y,X|S]) --> "/", { Z is X div Y }, parse(Ns,[Z|S]). +parse(Ns,Stack) --> " ", parse(Ns,Stack). +parse(Ns,Stack) --> { select(N,Ns,Ns1), number_codes(N,[Code]) } + , [Code], parse(Ns1,[N|Stack]) + . + +get_line(Xs) :- get_code(X) + , ( X == 10 -> Xs = [] ; Xs = [X|Ys], get_line(Ys) ) + . +main :- randomize, play, halt. diff --git a/Task/24-game/REXX/24-game-1.rexx b/Task/24-game/REXX/24-game-1.rexx index 1e72c6f878..4b3a3c51fb 100644 --- a/Task/24-game/REXX/24-game-1.rexx +++ b/Task/24-game/REXX/24-game-1.rexx @@ -1,204 +1,22 @@ -/*REXX program which allows a user to play the game of 24 (twenty-four).*/ -/* - ╔══════════════════════════════════════════════════════════════════╗ - ║ Argument is either of three forms: (blank) ║ - ║ ssss ║ - ║ ssss-ffff ║ - ║ ║ - ║ where one or both strings must be exactly four numerals (digits) ║ - ║ comprised soley of the numerals (digits) 1 ──> 9 (no zeroes). ║ - ║ ║ - ║ SSSS is the start, ║ - ║ FFFF is the start. ║ - ║ ║ - ║ If no argument is specified, this program finds a four digit ║ - ║ number (no zeroes) which has at least one solution, and shows ║ - ║ the number to the user, requesting that they enter a solution ║ - ║ in the form of: w operator x operator y operator z ║ - ║ where w x y and z are single digit numbers (no zeroes), ║ - ║ and operator can be any one of: + - * / ║ - ║ Parentheses () may be used in the normal manner for grouping, ║ - ║ as well as brackets [] or braces {}. ║ - ╚══════════════════════════════════════════════════════════════════╝ */ -parse arg orig /*get the guess from the argument. */ -orig=space(orig,0) /*remove extraneous blanks from ORIG. */ -parse var orig start '-' finish /*get the start and finish (maybe). */ -finish=word(finish start,1) /*if no FINISH specified, use START.*/ -opers='+-*/' /*define the legal arithmetic operators*/ -ops=length(opers) /* ... and the count of them (length). */ -groupsymbols='()[]{}' /*legal grouping symbols. */ -indent=left('',30) /*used to indent display of solutions. */ -Lpar='(' /*a string to make REXX code prettier. */ -Rpar=')' /*ditto. */ -show=1 /*flag used show solutions (0 = not). */ -digs=123456789 /*numerals (digits) that can be used. */ - - do j=1 for ops /*define a version for fast execution. */ - o.j=substr(opers,j,1) - end /*j*/ - -if orig\=='' then do - sols=solve(start,finish) - if sols<0 then exit 13 - if sols==0 then sols='No' /*un-geek the SOLS var.*/ - say; say sols 'unique solution's(finds) "found for" orig - exit /* [↑] "S" pluralizes.*/ - end -show=0 /*stop SOLVE from blabbing solutions. */ - do forever - rrrr=random(1111,9999) - if pos(0,rrrr)\==0 then iterate - if solve(rrrr)\==0 then leave - end /*forever*/ -show=1 /*enable SOLVE to show solutions. */ -rrrr=sort(rrrr) /*sort four elements. */ -rd.=0 - do j=1 for 9 /*digit count # for each digit in RRRR.*/ - _=substr(rrrr,j,1) - rd._=countdigs(rrrr,_) - end /*j*/ - - do guesses=1; say - say 'Using the digits' rrrr", enter an expression that equals 24 (or QUIT):" - pull y; y=space(y,0) /*get Y from CL, then remove all blanks*/ - if y=='QUIT' then exit /*Does user want to quit? If so, exit.*/ - _v=verify(y, digs || opers || groupsymbols); __=substr(y, _v, 1) - if _v\==0 then do; call ger 'invalid character:' __; iterate; end - if pos('**',y) then do; call ger 'invalid ** operator'; iterate; end - if pos('//',y) then do; call ger 'invalid // operator'; iterate; end - yL=length(y) - if y=='' then do; call validate y; iterate; end - - do j=1 for yL-1; if \datatype(substr(y, j , 1), 'W') then iterate - if \datatype(substr(y, j+1, 1), 'W') then iterate - call ger 'invalid use of digit abuttal' - iterate guesses - end /*j*/ - - yd=countdigs(y,digs) /*count of digits 123456789.*/ - if yd<4 then do - call ger 'not enough digits entered.' - iterate guesses - end - if yd>4 then do - call ger 'too many digits entered.' - iterate guesses - end - - do j=1 for 9; if rd.j==0 then iterate - _d=countdigs(y,j) - if _d==rd.j then iterate - if _d /div(yyy) */ - /*Enables to check for division by zero*/ - origE=e /*keep old version for the display. */ - if pos('/(',e)\==0 then e=changestr('/(',e,"/div(") - /*The above could be replaced by: */ - /* e=changestr('/(',e,"/div(") */ - - /*INTERPRET stresses REXX's groin, */ - /*so try to avoid repeated lifting. */ - if x.e then iterate /*was the expression already used? */ - x.e=1 /*mark this expression as unique. */ - /*have REXX do the heavy lifting. */ - interpret 'x=' e - x=x/1 /*remove trailing decimal points. */ - if x\==24 then iterate /*Not correct? Try again.*/ - finds=finds+1 /*bump number of found solutions. */ - _=translate(origE, '][', ")(") /*show [], not ().*/ - if show then say indent 'a solution:' _ /*show solution.*/ - end /*n*/ - end /*m*/ - end /*k*/ - end /*j*/ - end /*i*/ - end /*g*/ - -return finds -/*───────────────────────────CHANGESTR subroutine───────────────────────*/ -changestr: procedure; parse arg o,h,n,,r; w=length(o); if w==0 then return n||h -do forever; parse var h y (o) _ +(w) h; if _=='' then return r||y; r=r||y||n; end -/*───────────────────────────COUNTDIGS subroutine───────────────────────*/ -countdigs: arg field,numerals /*count of digits NUMERALS.*/ -return length(field)-length(space(translate(field,,numerals),0)) -/*───────────────────────────DIV subroutine─────────────────────────────*/ -div: procedure; parse arg q /*tests if dividing by 0 (zero). */ -if q=0 then q=1e9 /*if dividing by zero, change divisor. */ -return q /*changing Q invalidates the expression*/ -/*───────────────────────────GER subroutine─────────────────────────────*/ -ger: say; say '*** error! *** for argument:' y; say arg(1); say; errCode=1; return 0 -/*───────────────────────────S subroutine───────────────────────────────*/ -s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ -/*───────────────────────────SORT subroutine────────────────────────────*/ -sort: procedure; arg nnnn; L=length(nnnn) - - do i=1 for L /*build an array of digits from NNNN.*/ - a.i=substr(nnnn,i,1) /*this enables SORT to sort an array. */ - end /*i*/ - - do j=1 for L; _=a.j - do k=j+1 to L - if a.k<_ then parse value a.j a.k with a.k a.j - end /*k*/ - end /*j*/ -return a.1 || a.2 || a.3 || a.4 -/*───────────────────────────SYNTAX subroutin───────────────────────────*/ -syntax: call ger 'illegal syntax in' y; exit -/*───────────────────────────validate subroutine────────────────────────*/ -validate: parse arg y; errCode=0; _v=verify(y,digs) - select - when y=='' then call ger 'no digits entered.' - when length(y)<4 then call ger 'not enough digits entered, must be 4' - when length(y)>4 then call ger 'too many digits entered, must be 4' - when pos(0,y)\==0 then call ger "can't use the digit 0 (zero)" - when _v\==0 then call ger 'illegal character:' substr(y,_v,1) - otherwise nop - end /*select*/ -return \errCode +╔══════════════════════════════════════════════════════════════════════════╗ +║ Argument for the "24" program is either of three forms: (blank) ║ +║ ssss ║ +║ ssss-ffff ║ +║ ║ +║ where one or both strings must be exactly four numerals (digits) ║ +║ comprised soley of the numerals (digits) 1 ──► 9 (with no zeroes). ║ +║ ║ +║ SSSS is the start, ║ +║ FFFF is the finish. ║ +║ ║ +║ If no argument is specified, this program finds a four digit number with ║ +║ no zeroes) which has at least one solution, and shows the number to ║ +║ the user, requesting that they enter a solution in the form of: ║ +║ ║ +║ w operator x operator y operator z ║ +║ ║ +║ where w x y and z are single digit numbers (no zeroes). ║ +║ and operator can be any one of: + - * / ║ +║ Parentheses ( ), brackets [ ], and/or braces { } may be used in the║ +║ normal manner for grouping expressions. Leading signs are permitted. ║ +╚══════════════════════════════════════════════════════════════════════════╝ diff --git a/Task/24-game/REXX/24-game-2.rexx b/Task/24-game/REXX/24-game-2.rexx index 79165ca303..fbc6c51304 100644 --- a/Task/24-game/REXX/24-game-2.rexx +++ b/Task/24-game/REXX/24-game-2.rexx @@ -1,25 +1,158 @@ -changestr: Procedure -/* change needle to newneedle in haystack (as often as specified */ -/* or all of them if count is omitted */ - Parse Arg needle,haystack,newneedle,count - If count>'' Then Do - If count=0 Then Do - Say 'chstr count must be > 0' - Signal Syntax - End - End - res="" - changes=0 - px=1 - do Until py=0 - py=pos(needle,haystack,px) - if py>0 then Do - res=res||substr(haystack,px,py-px)||newneedle - px=py+length(needle) - changes=changes+1 - If count>'' Then - If changes=count Then Leave - End - end - res=res||substr(haystack,px) - Return res +/*REXX program which allows a user to play the game of 24 (twenty-four). */ +numeric digits 15 /*allow more leeway when computing #s. */ +parse arg yyy /*get the optional arguments from C.L. */ + yyy = space(yyy,0) /*remove extraneous blanks from YYY. */ +parse var yyy start '-' fin /*get the START and FINish (maybe). */ + fin = word(fin start,1) /*if no FINish specified, use START.*/ + opers = '+-*/' /*define the legal arithmetic operators*/ + ops = length(opers) /* ··· and the count of them (length). */ +groupSymbols = '()[]{}' /*legal grouping symbols for this game.*/ + indent = left('',30) /*used to indent display of solutions. */ + Lpar = '(' /*a string to make the output prettier.*/ + Rpar = ')' /*Ditto. [You can say that again.] */ + digs = 123456789 /*numerals (digits) that can be used. */ + show = 1 /*flag used show solutions (0 = not). */ + do j=1 for ops /*define a version for fast execution. */ + @.j=substr(opers,j,1) /*assign each operation to an array. */ + end /*j*/ +signal on syntax /*enable program to trap syntax errors.*/ +if yyy\=='' then do /*if START (or FINish), then solve 'em.*/ + sols=solve(start,fin) /*solve START ───► FINish. */ + if sols <0 then exit 13 /*Was there a problem with input? */ + if sols==0 then sols='No' /*Englishize the SOLS variable.*/ + say; say sols 'unique solution's(sols) "found for" yyy + exit /*S [↑] does pluralizations. */ + end +show=0 /*stop SOLVE from blabbing solutions.*/ + do forever; rrrr=random(1111, 9999) + if pos(0, rrrr)\==0 then iterate /*if contains a zero, ignore it*/ + if solve(rrrr)\==0 then leave /*if solved, then stop looking.*/ + end /*forever*/ +show=1 /*enable SOLVE to display solutions. */ +rrrr=sort(rrrr) /*sort four digits (for consistancy). */ +$.=0 + do j=1 for length(rrrr) /*digit count for each digit in RRRR. */ + _=substr(rrrr, j, 1) /*pick off one of the digits in RRRR. */ + $._=countDigs(rrrr, _) /*define the count for this digit. */ + end /*j*/ /* [↑] counts duplicates twice, no harm*/ + +prompt= 'Using the digits' rrrr", enter an expression that equals 24 (or QUIT):" + /* [↓] ITERATE needs a variable name.*/ + do prompter=0; say; say prompt /*display blank line and the prompt (P)*/ + pull y; y=space(y,0) /*get Y from CL, then remove all blanks*/ + if abbrev('QUIT',y,1) then exit /*Does the user want to quit this game?*/ + _v=verify(y, digs || opers || groupSymbols); a=substr(y, max(1,_v), 1) + if _v\==0 then do; call ger 'invalid character:' a; iterate; end + if pos('**',y) then do; call ger 'invalid ** operator'; iterate; end + if pos('//',y) then do; call ger 'invalid // operator'; iterate; end + yL=length(y) + if y=='' then do; call validate y; iterate; end + + do j=1 for yL-1; if \datatype(substr(y, j ,1), 'W') then iterate + if \datatype(substr(y, j+1,1), 'W') then iterate + call ger 'invalid use of "digit abuttal".' + iterate prompter + end /*j*/ + + yd=countDigs(y, digs) /*count of the digits 1──►9 (123456789)*/ + if yd<4 then do; call ger 'not enough digits entered.'; iterate prompter; end + if yd>4 then do; call ger 'too many digits entered.' ; iterate prompter; end + + do j=1 for 9; if $.j==0 then iterate + _d=countDigs(y, j); if $.j==_d then iterate + if _d<$.j then call ger 'not enough' j "digits, must be" $.j + else call ger 'too many' j "digits, must be" $.j + iterate prompter + end /*j*/ + + y=translate(y, '()()', "[]{}") + interpret 'ans=' y; ans=ans/1; if ans==24 then leave prompter + say 'incorrect, ' y'='ans + end /*prompter*/ + +say; say center('┌─────────────────────┐', 79) + say center('│ │', 79) + say center('│ congratulations ! │', 79) + say center('│ │', 79) + say center('└─────────────────────┘', 79) +exit /*stick a fork in it, we're all done. */ +/*──────────────────────────────────one─liner subroutines─────────────────────*/ +countDigs: arg ?; return length(?) - length(space(translate(?, , arg(2)), 0)) +div: if arg(1)=0 then return 7e9; return arg(1) /*if ÷ by 0, fudge result*/ +ger: say; say '***error!*** for argument:' y; say arg(1); say;errCode=1;return 0 +s: if arg(1)==1 then return ''; return 's' /*simple pluralizer.*/ +syntax: call ger 'illegal syntax in' y; exit +/*──────────────────────────────────SOLVE subroutine──────────────────────────*/ +solve: parse arg ssss, ffff /*parse the argument passed to SOLVE. */ +if ffff=='' then ffff=ssss /*create a FFFF if necessary. */ +if \validate(ssss) then return -1 /*validate the SSSS field. */ +if \validate(ffff) then return -1 /* " " FFFF " */ +#=0 /*number of found solutions (so far). */ +!.=0 /*a method to hold unique expressions. */ + /*alternative: indent=copies(' ',30) */ + + do g=ssss to ffff /*process a (possible) range of values.*/ + if pos(0, g)\==0 then iterate /*ignore values with zero in them. */ + + do j=1 for 4 /*define a version for fast execution. */ + g.j=substr(g, j, 1) /*extract each digit of G into array.*/ + end /*j*/ + + do i =1 for ops /*insert an operator after 1st number. */ + do j =1 for ops /*insert an operator after 2nd number. */ + do k =1 for ops /*insert an operator after 2nd number. */ + do m=0 to 3; L.= /*assume no left parenthesis so far. */ + do n=m+1 to 4 /*match left paren with a right paren. */ + L.m=Lpar /*define a left paren, m=0 means ignore*/ + R.= /*un-define all right parenthesis. */ + if m==1 & n==2 then L.= /*special case of : (n) + ··· */ + else if m\==0 then R.n=Rpar /*no (, no )*/ + e = L.1 g.1 @.i L.2 g.2 @.j L.3 g.3 R.3 @.k g.4 R.4 + e=space(e, 0) /*remove all blanks from the expression*/ + /* [↓] change expression: */ + /* /(yyy) ═══► /div(yyy) */ + /*Enables to check for division by zero*/ + yyyE=e /*keep old the version for the display.*/ + if pos('/(', e)\==0 then e=changestr( '/(', e, "/div(" ) + /* [↓] INTERPRET stresses REXX's groin,*/ + /* so try to avoid repeated lifting.*/ + if !.e then iterate /*was this expression already used? */ + !.e=1 /*mark this expression as being used. */ + interpret 'x=' e /*have REXX do all the heavy lifting */ + x=x/1 /*remove any trailing decimal point. */ + if x\==24 then iterate /*Is the result incorrect? Try again. */ + #=#+1 /*bump number of found solutions. */ + _=translate(yyyE, '][', ")(") /*display [], not (). */ + if show then say indent 'a solution:' _ + end /*n*/ /* [↑] show a solution.*/ + end /*m*/ + end /*k*/ + end /*j*/ + end /*i*/ + end /*g*/ + +return # +/*──────────────────────────────────SORT subroutine───────────────────────────*/ +sort: procedure; arg nnnn; L=length(nnnn) + + do i=1 for L /*build an array of digits from NNNN. */ + s.i=substr(nnnn, i, 1) /*this enables SORT to sort an array. */ + end /*i*/ + + do j=1 for L; _=s.j + do k=j+1 to L + if s.k<_ then parse value s.j s.k with s.k s.j + end /*k*/ + end /*j*/ +return s.1 || s.2 || s.3 || s.4 +/*──────────────────────────────────VALIDATE subroutine───────────────────────*/ +validate: parse arg y; errCode=0; _v=verify(y,digs) + select + when y=='' then call ger 'no digits entered.' + when length(y)<4 then call ger 'not enough digits entered, must be four.' + when length(y)>4 then call ger 'too many digits entered, must be four.' + when pos(0,y)\==0 then call ger "can't use the digit 0 (zero)." + when _v\==0 then call ger 'illegal character: ' substr(y,_v,1) + otherwise nop + end /*select*/ +return \errCode diff --git a/Task/24-game/REXX/24-game-3.rexx b/Task/24-game/REXX/24-game-3.rexx new file mode 100644 index 0000000000..79165ca303 --- /dev/null +++ b/Task/24-game/REXX/24-game-3.rexx @@ -0,0 +1,25 @@ +changestr: Procedure +/* change needle to newneedle in haystack (as often as specified */ +/* or all of them if count is omitted */ + Parse Arg needle,haystack,newneedle,count + If count>'' Then Do + If count=0 Then Do + Say 'chstr count must be > 0' + Signal Syntax + End + End + res="" + changes=0 + px=1 + do Until py=0 + py=pos(needle,haystack,px) + if py>0 then Do + res=res||substr(haystack,px,py-px)||newneedle + px=py+length(needle) + changes=changes+1 + If count>'' Then + If changes=count Then Leave + End + end + res=res||substr(haystack,px) + Return res diff --git a/Task/24-game/Ruby/24-game.rb b/Task/24-game/Ruby/24-game.rb index 4372355ad9..290d04e9c6 100644 --- a/Task/24-game/Ruby/24-game.rb +++ b/Task/24-game/Ruby/24-game.rb @@ -1,4 +1,4 @@ -require "rational" +require "rational" # for Ruby versions before 2.0 def play digits = Array.new(4){rand(1..9)} diff --git a/Task/24-game/UNIX-Shell/24-game.sh b/Task/24-game/UNIX-Shell/24-game.sh new file mode 100644 index 0000000000..2b1883fca3 --- /dev/null +++ b/Task/24-game/UNIX-Shell/24-game.sh @@ -0,0 +1,30 @@ +gen_digits() { + awk 'BEGIN { srand() + for(i = 1; i <= 4; i++) print 1 + int(9 * rand()) + }' | sort +} + +same_digits() { + [ "$(tr -dc 0-9 | sed 's/./&\n/g' | grep . | sort)" = "$*" ] +} + +guessed() { + [ "$(echo "$1" | tr -dc '\n0-9()*/+-' | bc 2>/dev/null)" = 24 ] +} + + +while : +do + digits=$(gen_digits) + echo + echo Digits: $digits + read -r expr + + echo " $expr" | same_digits "$digits" || \ + { echo digits should be: $digits; continue; } + + guessed "$expr" && message=correct \ + || message=wrong + + echo $message +done diff --git a/Task/99-Bottles-of-Beer/00DESCRIPTION b/Task/99-Bottles-of-Beer/00DESCRIPTION index a30be4d290..b80cf19829 100644 --- a/Task/99-Bottles-of-Beer/00DESCRIPTION +++ b/Task/99-Bottles-of-Beer/00DESCRIPTION @@ -1,4 +1,8 @@ -In this puzzle, write code to print out the entire "99 bottles of beer on the wall" song. For those who do not know the song, the lyrics follow this form: +'''The beersong'''
+In this puzzle, write code to print out +the entire "99 bottles of beer on the wall" song. + +For those who do not know the song, the lyrics follow this form: X bottles of beer on the wall X bottles of beer Take one down, pass it around @@ -8,6 +12,14 @@ In this puzzle, write code to print out the entire "99 bottles of beer on the wa ... Take one down, pass it around 0 bottles of beer on the wall -Where X and X-1 are replaced by numbers of course. Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too). +Where X and X-1 are replaced by numbers of course. +Grammatical support for "1 bottle of beer" is optional. +As with any puzzle, try to do it in as creative/concise/comical a way +as possible (simple, obvious solutions allowed, too). -See also: http://99-bottles-of-beer.net/ +;See also: +* http://99-bottles-of-beer.net/ +* [[:Category:99_Bottles_of_Beer]] +* [[:Category:Programming language families]] + +
diff --git a/Task/99-Bottles-of-Beer/ATS/99-bottles-of-beer.ats b/Task/99-Bottles-of-Beer/ATS/99-bottles-of-beer.ats index 03a0cd9943..cad41f30eb 100644 --- a/Task/99-Bottles-of-Beer/ATS/99-bottles-of-beer.ats +++ b/Task/99-Bottles-of-Beer/ATS/99-bottles-of-beer.ats @@ -1,13 +1,29 @@ -/* .. is a termination metric to prove that the function terminates. It can be omitted. */ -fun bottles {n:nat} .. (n: int n): void = - if n = 0 then - () - else begin - printf ("%d bottles of beer on the wall\n", @(n)); - printf ("%d bottles of beer\n", @(n)); - printf ("Take one down, pass it around\n", @()); - printf ("%d bottles of beer on the wall\n", @(n-1)); - bottles (n - 1) - end +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) -implement main () = bottles (99) +fun bottles + (n0: int): void = let +// +fun loop (n: int): void = +( + if n > 0 then + ( + if n0 > n then println! (); + println! (n, " bottles of beer on the wall"); + println! (n, " bottles of beer"); + println! ("Take one down, pass it around"); + println! (n-1, " bottles of beer on the wall"); + loop (n - 1) + ) (* end of [if] *) +) +// +in + loop (n0) +end // end of [bottles] + +(* ****** ****** *) + +implement main0 () = bottles (99) diff --git a/Task/99-Bottles-of-Beer/AWK/99-bottles-of-beer.awk b/Task/99-Bottles-of-Beer/AWK/99-bottles-of-beer.awk index 07b781bb05..b0fc6db4b7 100644 --- a/Task/99-Bottles-of-Beer/AWK/99-bottles-of-beer.awk +++ b/Task/99-Bottles-of-Beer/AWK/99-bottles-of-beer.awk @@ -1,7 +1,21 @@ -{ i = 99 -while (i > 0) - {print i, " bottles of beer on the wall," - print i, " bottles of beer." - print "Take one down, pass it around," - i-- - print i, " bottles of beer on the wall\n"}} +# usage: gawk -v i=6 -f beersong.awk + +function bb(n) { + b = " bottles of beer" + if( n==1 ) { sub("s","",b) } + if( n==0 ) { n="No more" } + return n b +} + +BEGIN { + if( !i ) { i = 99 } + ow = "on the wall" + td = "Take one down, pass it around." + print "The beersong:\n" + while (i > 0) { + printf( "%s %s,\n%s.\n%s\n%s %s.\n\n", + bb(i), ow, bb(i), td, bb(--i), ow ) + if( i==1 ) sub( "one","it", td ) + } + print "Go to the store and buy some more!" +} 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-1.clj similarity index 64% rename from Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj rename to Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-1.clj index ce14d9cf09..a0f52a6878 100644 --- a/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer.clj +++ b/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-1.clj @@ -1,16 +1,12 @@ -(defn verse - [n] - (printf "%d bottles of beer on the wall, +(defn sing + [start] + (doseq [n (range start 0 -1)] + (printf "%d bottles of beer on the wall, %d bottles of beer, Take one down, pass it around, %d bottles of beer on the wall.\n\n" n n - (dec n))) - -(defn sing - [start] - (doseq [n (range start 0 -1)] - (verse n))) + (dec n)))) (sing 99) diff --git a/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-2.clj b/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-2.clj new file mode 100644 index 0000000000..bf7e4c165e --- /dev/null +++ b/Task/99-Bottles-of-Beer/Clojure/99-bottles-of-beer-2.clj @@ -0,0 +1,5 @@ +(clojure.pprint/cl-format + true + "~{~[~^~]~:*~D bottle~:P of beer on the wall~%~:*~D bottle~:P of beer +Take one down, pass it around,~%~D bottle~:P~:* of beer on the wall.~2%~}" + (range 99 0 -1)) diff --git a/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl b/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl index f0d54e3fd2..50fbca6461 100644 --- a/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl +++ b/Task/99-Bottles-of-Beer/Fexl/99-bottles-of-beer.fexl @@ -1,36 +1,16 @@ -\bottles_of_beer = - (\n - print (< n 1 "No more" n); - print " bottle"; print (== n 1 "" "s"); - print " of beer"; +\suffix=(\n eq n 1 "" "s") +\sing_count=(\n put n put " " put "bottle" put (suffix n) put " of beer") +\sing_line1=(\n sing_count n put " on the wall" nl) +\sing_line2=(\n sing_count n nl) +\sing= + (@\loop\n + le n 0 (); + sing_line1 n + sing_line2 n + say "Take one down, pass it around" + \n=(- n 1) + sing_line1 n + nl + loop n ) - -\bottles_of_beer_on_the_wall = - (\n - bottles_of_beer n; print " on the wall"; - ) - -\sing_bottles_of_beer = - (\max - do (range max 0) \qty - bottles_of_beer_on_the_wall qty; nl; - bottles_of_beer qty; nl; - - \qty = - ( - > qty 0 - ( - print "Take one down, pass it around";nl; - - qty 1 - ) - ( - print "Go to the store and buy some more";nl; - max - ) - ) - - bottles_of_beer_on_the_wall qty; nl; - nl; - ) - -sing_bottles_of_beer 99; +sing 3 diff --git a/Task/99-Bottles-of-Beer/Frege/99-bottles-of-beer.frege b/Task/99-Bottles-of-Beer/Frege/99-bottles-of-beer.frege index b9995a8fe7..3776689c4f 100644 --- a/Task/99-Bottles-of-Beer/Frege/99-bottles-of-beer.frege +++ b/Task/99-Bottles-of-Beer/Frege/99-bottles-of-beer.frege @@ -1,10 +1,9 @@ module Beer where +main = mapM_ (putStrLn . beer) [99, 98 .. 0] beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around" beer 0 = "better go to the store and buy some more." beer v = show v ++ " bottles of beer on the wall\n" ++ show v - ++" bottles of beer\nTake one down, pass it around\n" + ++ " bottles of beer\nTake one down, pass it around\n" ++ head (lines $ beer $ v-1) ++ "\n" - -main _ = mapM_ (printStrLn . beer) (reverse (0..99)) diff --git a/Task/99-Bottles-of-Beer/Go/99-bottles-of-beer.go b/Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-1.go similarity index 100% rename from Task/99-Bottles-of-Beer/Go/99-bottles-of-beer.go rename to Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-1.go diff --git a/Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-2.go b/Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-2.go new file mode 100644 index 0000000000..81006e5c32 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Go/99-bottles-of-beer-2.go @@ -0,0 +1,80 @@ +package main + +import ( + "fmt" + "math/rand" + "strings" + "time" +) + +func main() { + rand.Seed(time.Now().UnixNano()) + for i := 99; i > 0; i-- { + fmt.Printf("%s %s %s\n", + slur(numberName(i), i), + pluralizeFirst(slur("bottle of", i), i), + slur("beer on the wall", i)) + fmt.Printf("%s %s %s\n", + slur(numberName(i), i), + pluralizeFirst(slur("bottle of", i), i), + slur("beer", i)) + fmt.Printf("%s %s %s\n", + slur("take one", i), + slur("down", i), + slur("pass it around", i)) + fmt.Printf("%s %s %s\n", + slur(numberName(i-1), i), + pluralizeFirst(slur("bottle of", i), i-1), + slur("beer on the wall", i)) + } +} + +// adapted from Number names task +func numberName(n int) string { + switch { + case n < 0: + case n < 20: + return small[n] + case n < 100: + t := tens[n/10] + s := n % 10 + if s > 0 { + t += " " + small[s] + } + return t + } + return "" +} + +var small = []string{"no", "one", "two", "three", "four", "five", "six", + "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", + "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"} +var tens = []string{"ones", "ten", "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"} + +// pluralize first word of s by adding an s, but only if n is not 1. +func pluralizeFirst(s string, n int) string { + if n == 1 { + return s + } + w := strings.Fields(s) + w[0] += "s" + return strings.Join(w, " ") +} + +// p is string to slur, d is drunkenness, from 0 to 99 +func slur(p string, d int) string { + // shuffle only interior letters + a := []byte(p[1 : len(p)-1]) + // adapted from Knuth shuffle task. + // shuffle letters with probability d/100. + for i := len(a) - 1; i >= 1; i-- { + if rand.Intn(100) >= d { + j := rand.Intn(i + 1) + a[i], a[j] = a[j], a[i] + } + } + // condense spaces + w := strings.Fields(p[:1] + string(a) + p[len(p)-1:]) + return strings.Join(w, " ") +} diff --git a/Task/99-Bottles-of-Beer/J/99-bottles-of-beer.j b/Task/99-Bottles-of-Beer/J/99-bottles-of-beer.j new file mode 100644 index 0000000000..09f09cd83e --- /dev/null +++ b/Task/99-Bottles-of-Beer/J/99-bottles-of-beer.j @@ -0,0 +1,4 @@ +bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_ +bobw=: bob , ' on the wall'"_ +beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<: +beer"0 >:i.-99 diff --git a/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer.lua b/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-1.lua similarity index 100% rename from Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer.lua rename to Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-1.lua diff --git a/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-2.lua b/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-2.lua new file mode 100644 index 0000000000..d35305a948 --- /dev/null +++ b/Task/99-Bottles-of-Beer/Lua/99-bottles-of-beer-2.lua @@ -0,0 +1,10 @@ +verse = [[%i bottle%s of beer on the wall +%i bottle%s of beer +Take one down, pass it around +%i bottle%s of beer on the wall +]] +function suffix(i) return i ~= 1 and 's' or '' end + +for i = 99, 1, -1 do + print(verse:format(i, suffix(i), i, suffix(i), i-1, suffix(i-1))) +end diff --git a/Task/99-Bottles-of-Beer/OOC/99-bottles-of-beer.ooc b/Task/99-Bottles-of-Beer/OOC/99-bottles-of-beer.ooc new file mode 100644 index 0000000000..babef32107 --- /dev/null +++ b/Task/99-Bottles-of-Beer/OOC/99-bottles-of-beer.ooc @@ -0,0 +1,24 @@ +sing_line: func (b: Int, suffix: Bool) { + "#{b > 0 ? "#{b}" : "No more"} bottle#{b == 1 ? "" : "s"}" print() + " of beer#{suffix ? " on the wall" : ""}" println() +} + +sing_verse: func (b: Int) { + println() + sing_line(b, true) + sing_line(b, false) + if (b > 0) { + "Take one down, pass it around" println() + } else { + "Go to the store and buy some more" println() + b += 100 + } + sing_line(b-1, true) +} + +main: func { + b := 100 + while (b > 0) { + sing_verse(--b) + } +} diff --git a/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer.rebol b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol similarity index 100% rename from Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer.rebol rename to Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-1.rebol diff --git a/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-2.rebol b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-2.rebol new file mode 100644 index 0000000000..c18e5da9e0 --- /dev/null +++ b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-2.rebol @@ -0,0 +1,9 @@ +for i 99 1 -1 [ + x: rejoin [ + i b: " bottles of beer" o: " on the wall. " i b + ". Take one down, pass it around. " (i - 1) b o "^/" + ] + r: :replace j: "bottles" k: "bottle" + switch i [1 [r x j k r at x 10 j k r x "0" "No"] 2 [r at x 40 j k]] + print x +] halt diff --git a/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-3.rebol b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-3.rebol new file mode 100644 index 0000000000..700b665832 --- /dev/null +++ b/Task/99-Bottles-of-Beer/REBOL/99-bottles-of-beer-3.rebol @@ -0,0 +1 @@ +for i 99 1 -1[print rejoin[i b:" bottles of beer"o:" on the wall. "i b". Take one down, pass it around. "(i - 1)b o"^/"]] diff --git a/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx b/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx index eb77bd2cd5..62a56cb038 100644 --- a/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx +++ b/Task/99-Bottles-of-Beer/REXX/99-bottles-of-beer.rexx @@ -1,19 +1,20 @@ -/*REXX pgm displays words to the song "99 Bottles of Beer on the Wall". */ +/*REXX pgm displays lyrics to the song "99 Bottles of Beer on the Wall".*/ +parse arg N .; if N=='' then N=99 /*let # bottles be specified*/ - do j=99 by -1 to 1 /*start countdown | singdown*/ + do j=N by -1 to 1 /*start countdown & singdown*/ say j 'bottle's(j) "of beer on the wall," /*sing the #bottles of beer.*/ - say j 'bottle's(j) "of beer." /* ... and the refrain. */ + say j 'bottle's(j) "of beer." /* ··· and the refrain.*/ say 'Take one down, pass it around,' /*get a bottle and share it.*/ - n=j-1 /*N is #bottles we have now.*/ - if n==0 then n='no' /*use "no" instead of 0. */ - say n 'bottle's(n) "of beer on the wall." /*sing beer bottle inventory*/ + m=j-1 /*M: # bottles we have now.*/ + if m==0 then m='no' /*use "no" instead of 0. */ + say m 'bottle's(m) "of beer on the wall." /*sing beer bottle inventory*/ say /*blank line between verses.*/ end /*j*/ - + /*Not tanked? Then sing it.*/ say 'No more bottles of beer on the wall,' /*Finally! The last verse.*/ -say 'no more bottles of beer.' /*so sad ... */ +say 'no more bottles of beer.' /*this is so forlorn ··· */ say 'Go to the store and buy some more,' /*replenishment of the beer.*/ -say '99 bottles of beer on the wall.' /*All is well in the tavern.*/ +say N 'bottles of beer on the wall.' /*all is well in the tavern.*/ exit /*we're done & also sloshed.*/ /*───────────────────────────────────S subroutine───────────────────────*/ -s: if arg(1)=1 then return ''; return 's' /*a simple pluralizer funct.*/ +s: if arg(1)=1 then return ''; return 's' /*simple pluralizer function*/ diff --git a/Task/99-Bottles-of-Beer/RapidQ/99-bottles-of-beer.rapidq b/Task/99-Bottles-of-Beer/RapidQ/99-bottles-of-beer.rapidq new file mode 100644 index 0000000000..599dd9cd4b --- /dev/null +++ b/Task/99-Bottles-of-Beer/RapidQ/99-bottles-of-beer.rapidq @@ -0,0 +1,13 @@ +dim nBott as integer + nBott = 99 + +While nBott > 0 + Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer on the wall") + Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer") + Print("Take one down, pass it around") + nBott-- + Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer on the wall" + chr$(10)) +Wend + +while inkey$="":wend +end diff --git a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust index 8126b2a723..189f945b3e 100644 --- a/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust +++ b/Task/99-Bottles-of-Beer/Rust/99-bottles-of-beer.rust @@ -1,24 +1,32 @@ use std::iter::range_step_inclusive; +trait Bottles { + fn bottles_of_beer(&self) -> Self; + fn on_the_wall(&self); +} + +impl Bottles for isize { + + fn bottles_of_beer(&self) -> isize { + match *self { + 1 => print!("{} bottle of beer", self), + 0 => print!("No bottles of beer"), + _ => print!("{} bottles of beer", self) + } + *self // return a number for chaining + } + + fn on_the_wall(&self) { + println!(" on the wall!"); + } +} + fn main() { - for num_bottles in range_step_inclusive(99, 1, -1) { - sing_bottles_line(num_bottles, true); - sing_bottles_line(num_bottles, false); - println("Take one down, pass it around..."); - sing_bottles_line(num_bottles - 1, true); - println("-----------------------------------"); - } -} - -fn sing_bottles_line(num_bottles: int, on_the_wall: bool) { - - // the print! macro uses a built in internationalization formatting language - // check out the docs for std::fmt - print!("{0, plural, =0{No bottles} =1{One bottle} other{# bottles}} of beer", num_bottles as uint); - - if on_the_wall { - println(" on the wall!"); - } else { - println(""); - } + for i in range_step_inclusive(99is, 1, -1) { + i.bottles_of_beer().on_the_wall(); + i.bottles_of_beer(); + println!("\nTake one down, pass it around..."); + (i - 1).bottles_of_beer().on_the_wall(); + println!("-----------------------------------"); + } } 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 index f191022cf4..538c9a4edd 100644 --- 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 @@ -1,29 +1,9 @@ -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; +select + ( 100 - level ) || ' bottle' || case 100 - level when 1 then '' else 's' end || ' of beer on the wall' + || chr(10) + || ( 100 - level ) || ' bottle' || case 100 - level when 1 then '' else 's' end || ' of beer' + || chr(10) + || 'Take one down, pass it around' + || chr(10) + || ( 99 - level ) || ' bottle' || case 99 - level when 1 then '' else 's' end || ' of beer on the wall' + from dual connect by level <= 99; 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 index 393ec50ba2..f191022cf4 100644 --- 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 @@ -1,46 +1,29 @@ -CREATE PROCEDURE bottles - @bottle_count int, - @song varchar(MAX) - -AS +DELIMITER $$ +DROP PROCEDURE IF EXISTS bottles_$$ +CREATE pROCEDURE `bottles_`(inout bottle_count int, inout song text) BEGIN - -declare @bottles_text VARCHAR(MAX); +declare bottles_text varchar(30); -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 +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; - SET @song = @song + CAST(@bottle_count AS VARCHAR) + @bottles_text + '\n'; + 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 @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, ''; +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-3.sql b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-3.sql new file mode 100644 index 0000000000..393ec50ba2 --- /dev/null +++ b/Task/99-Bottles-of-Beer/SQL/99-bottles-of-beer-3.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/A+B/00META.yaml b/Task/A+B/00META.yaml new file mode 100644 index 0000000000..df58a6932c --- /dev/null +++ b/Task/A+B/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Simple diff --git a/Task/A+B/Aime/a+b.aime b/Task/A+B/Aime/a+b.aime index 71b98988e9..066858d2c2 100644 --- a/Task/A+B/Aime/a+b.aime +++ b/Task/A+B/Aime/a+b.aime @@ -3,5 +3,5 @@ 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_integer(atoi(l[0]) + atoi(l[1])); o_newline(); diff --git a/Task/A+B/BASIC/a+b.basic b/Task/A+B/BASIC/a+b-1.basic similarity index 100% rename from Task/A+B/BASIC/a+b.basic rename to Task/A+B/BASIC/a+b-1.basic diff --git a/Task/A+B/BASIC/a+b-2.basic b/Task/A+B/BASIC/a+b-2.basic new file mode 100644 index 0000000000..da0b189ed4 --- /dev/null +++ b/Task/A+B/BASIC/a+b-2.basic @@ -0,0 +1,11 @@ +10 BH = PEEK(37) +20 INPUT ""; A$ : I$ = A$ : VTAB BH : A = PEEK(40) + PEEK(41) * 256 : FOR S = 0 TO 39 : IF PEEK(A + S) = 160 THEN NEXT S : S = 0 +40 IF LEN(I$) THEN IF MID$(I$, LEN(I$), 1) = " " THEN I$ = MID$(I$, 1, LEN(I$) - 1) : GOTO 40RTRIM +50 IF LEN(I$) < 3 THEN 10"TRY AGAIN +60 FOR WHERE = 1 TO LEN(I$) : IF MID$(I$, WHERE, 1) <> " " THEN NEXT WHERE : GOTO 10"TRY AGAIN +70 A% = VAL(LEFT$(I$, WHERE - 1)) +80 B% = VAL(MID$(I$, WHERE + 1, LEN(I$))) +90 C% = A% + B% +100 VTAB BH +110 HTAB LEN(A$) + 2 + S +120 PRINT C% diff --git a/Task/A+B/C/a+b-3.c b/Task/A+B/C/a+b-3.c new file mode 100644 index 0000000000..ce3ae45f03 --- /dev/null +++ b/Task/A+B/C/a+b-3.c @@ -0,0 +1,7 @@ +#include +#include +int main(int argc, char **argv) //not sure if argv counts as input stream... certainly it is brought here via input stream. +{ + printf("%d\n", atoi(*(argv+1)) + atoi(*(argv+2))); + return 0; +} diff --git a/Task/A+B/Fortran/a+b.f b/Task/A+B/Fortran/a+b.f index d4cf0c2c61..2044e00764 100644 --- a/Task/A+B/Fortran/a+b.f +++ b/Task/A+B/Fortran/a+b.f @@ -1,10 +1,6 @@ program a_plus_b - implicit none - integer :: a - integer :: b - + integer :: a,b read (*, *) a, b write (*, '(i0)') a + b - end program a_plus_b diff --git a/Task/A+B/Gema/a+b.gema b/Task/A+B/Gema/a+b.gema new file mode 100644 index 0000000000..3b18df8462 --- /dev/null +++ b/Task/A+B/Gema/a+b.gema @@ -0,0 +1 @@ + =@add{$1;$2} diff --git a/Task/A+B/Kite/a+b.kite b/Task/A+B/Kite/a+b.kite new file mode 100644 index 0000000000..a3a3e3d14d --- /dev/null +++ b/Task/A+B/Kite/a+b.kite @@ -0,0 +1,13 @@ +#!/usr/bin/kite + +import "System.file"; + +in = System.file.stdin; +line = in|readline; +while(not (line is null)) [ + arry = line|split(" "); + result = (arry[0])|int + (arry[1])|int; + result|print; + + line = in|readline; +]; diff --git a/Task/A+B/M4/a+b.m4 b/Task/A+B/M4/a+b.m4 new file mode 100644 index 0000000000..2e10c887b6 --- /dev/null +++ b/Task/A+B/M4/a+b.m4 @@ -0,0 +1,4 @@ + define(`sumstr', `eval(patsubst(`$1',` ',`+'))') + +sumstr(1 2) +3 diff --git a/Task/A+B/Maple/a+b.maple b/Task/A+B/Maple/a+b.maple index f4471f7a31..2f38e7bc47 100644 --- a/Task/A+B/Maple/a+b.maple +++ b/Task/A+B/Maple/a+b.maple @@ -1,3 +1,3 @@ -> convert( scanf( "%d %d" ), '`+`' ); + convert( scanf( "%d %d" ), '`+`' ); 23 34 57 diff --git a/Task/A+B/Perl/a+b.pl b/Task/A+B/Perl/a+b.pl index 86f4e16943..bbca152247 100644 --- a/Task/A+B/Perl/a+b.pl +++ b/Task/A+B/Perl/a+b.pl @@ -1,2 +1,2 @@ -my ($a,$b) = split(/\D+/,); +my ($a,$b) = split(' ', scalar()); print "$a $b " . ($a + $b) . "\n"; diff --git a/Task/A+B/Python/a+b-2.py b/Task/A+B/Python/a+b-2.py index b30c99664a..71e8a4ff5c 100644 --- a/Task/A+B/Python/a+b-2.py +++ b/Task/A+B/Python/a+b-2.py @@ -1,4 +1,4 @@ -a = int(raw_input("Enter integer 1: ")) -b = int(raw_input("Enter integer 2: ")) +import sys -print a + b +for line in sys.stdin: + print(sum(int(i) for i in line.split())) diff --git a/Task/A+B/Scheme/a+b.ss b/Task/A+B/Scheme/a+b.ss index 3c80727a5a..d2cb4178a3 100644 --- a/Task/A+B/Scheme/a+b.ss +++ b/Task/A+B/Scheme/a+b.ss @@ -1,3 +1 @@ -(let* ((x (read)) - (y (read))) - (write (+ x y))) +(display (+ (read) (read))) diff --git a/Task/A+B/ZED/a+b.zed b/Task/A+B/ZED/a+b.zed index 51a65c1711..6c28d79b86 100644 --- a/Task/A+B/ZED/a+b.zed +++ b/Task/A+B/ZED/a+b.zed @@ -1,5 +1,14 @@ (A+B) -comment: returns the sum of two values taken from standard input -(always) -(+) (read) (default-input-port) - (read) (default-input-port) +comment: +#true +(+) (read) (read) + +(+) one two +comment: +#true +(003) "+" one two + +(read) +comment: +#true +(001) "read" diff --git a/Task/Abstract-type/Mathematica/abstract-type.math b/Task/Abstract-type/Mathematica/abstract-type.math new file mode 100644 index 0000000000..91712dd295 --- /dev/null +++ b/Task/Abstract-type/Mathematica/abstract-type.math @@ -0,0 +1,26 @@ +(* Define an interface, Foo, which requires that the functions Foo, Bar, and Baz be defined *) +InterfaceFooQ[obj_] := ValueQ[Foo[obj]] && ValueQ[Bar[obj]] && ValueQ[Baz[obj]]; +PrintFoo[obj_] := Print["Object ", obj, " does not implement interface Foo."]; +PrintFoo[obj_?InterfaceFooQ] := Print[ + "Foo: ", Foo[obj], "\n", + "Bar: ", Bar[obj], "\n", + "Baz: ", Baz[obj], "\n"]; + +(* Extend all integers with Interface Foo *) +Foo[x_Integer] := Mod[x, 2]; +Bar[x_Integer] := Mod[x, 3]; +Baz[x_Integer] := Mod[x, 5]; + +(* Extend a particular string with Interface Foo *) +Foo["Qux"] = "foo"; +Bar["Qux"] = "bar"; +Baz["Qux"] = "baz"; + +(* Print a non-interface object *) +PrintFoo[{"Some", "List"}]; +(* And for an integer *) +PrintFoo[8]; +(* And for the specific string *) +PrintFoo["Qux"]; +(* And finally a non-specific string *) +PrintFoo["foobarbaz"] diff --git a/Task/Abstract-type/Oberon-2/abstract-type.oberon-2 b/Task/Abstract-type/Oberon-2/abstract-type.oberon-2 new file mode 100644 index 0000000000..1972a1f63a --- /dev/null +++ b/Task/Abstract-type/Oberon-2/abstract-type.oberon-2 @@ -0,0 +1,7 @@ +TYPE + Animal = POINTER TO AnimalDesc; + AnimalDec = RECORD [ABSTRACT] END; + + (* Cat inherits from Animal *) + Cat = POINTER TO CatDesc; + CatDesc = RECORD (AnimalDesc) END; diff --git a/Task/Abstract-type/Seed7/abstract-type.seed7 b/Task/Abstract-type/Seed7/abstract-type.seed7 new file mode 100644 index 0000000000..4e740e32eb --- /dev/null +++ b/Task/Abstract-type/Seed7/abstract-type.seed7 @@ -0,0 +1,5 @@ +const type: myInterf is sub object interface; + +const func integer: method1 (in myInterf: interf, in float: aFloat) is DYNAMIC; +const func integer: method2 (in myInterf: interf, in string: name) is DYNAMIC; +const func integer: add (in myInterf: interf, in integer: a, in integer: b) is DYNAMIC; diff --git a/Task/Abstract-type/Standard-ML/abstract-type-1.ml b/Task/Abstract-type/Standard-ML/abstract-type-1.ml new file mode 100644 index 0000000000..6666202c95 --- /dev/null +++ b/Task/Abstract-type/Standard-ML/abstract-type-1.ml @@ -0,0 +1,6 @@ +signature QUEUE = sig + type 'a queue + val empty : 'a queue + val enqueue : 'a -> 'a queue -> 'a queue + val dequeue : 'a queue -> ('a * 'a queue) option +end diff --git a/Task/Abstract-type/Standard-ML/abstract-type-2.ml b/Task/Abstract-type/Standard-ML/abstract-type-2.ml new file mode 100644 index 0000000000..21f67df958 --- /dev/null +++ b/Task/Abstract-type/Standard-ML/abstract-type-2.ml @@ -0,0 +1,6 @@ +signature LIST_QUEUE = sig + type 'a queue = 'a list + val empty : 'a queue + val enqueue : 'a -> 'a queue -> 'a queue + val dequeue : 'a queue -> ('a * 'a queue) option +end diff --git a/Task/Accumulator-factory/AppleScript/accumulator-factory.applescript b/Task/Accumulator-factory/AppleScript/accumulator-factory.applescript new file mode 100644 index 0000000000..3d07aeeab9 --- /dev/null +++ b/Task/Accumulator-factory/AppleScript/accumulator-factory.applescript @@ -0,0 +1,16 @@ +on accumulator(n) + -- Returns a new script object + -- containing a handler. + script + on call(i) + set n to n + i -- Returns n. + end call + end script +end accumulator + +set x to accumulator(10) +log x's call(1) +set y to accumulator(5) +log y's call(2) +log x's call(3.5) +-- Event Log: (*11*) (*7*) (*14.5*) diff --git a/Task/Accumulator-factory/Elena/accumulator-factory.elena b/Task/Accumulator-factory/Elena/accumulator-factory.elena index bfe4530345..b843af4afd 100644 --- a/Task/Accumulator-factory/Elena/accumulator-factory.elena +++ b/Task/Accumulator-factory/Elena/accumulator-factory.elena @@ -5,7 +5,7 @@ (:x) [ self append:x ]. #symbol Accumulator = (:anInitialValue) - [ Wrap(Function, Variable new:anInitialValue) ]. + [ Extension(Function, Variable new:anInitialValue) ]. #symbol Program = [ diff --git a/Task/Accumulator-factory/Java/accumulator-factory-3.java b/Task/Accumulator-factory/Java/accumulator-factory-3.java index 99c7f67e49..614eb8cd68 100644 --- a/Task/Accumulator-factory/Java/accumulator-factory-3.java +++ b/Task/Accumulator-factory/Java/accumulator-factory-3.java @@ -1,30 +1,15 @@ -public class Accumulator { - private Long sumA; // non-null if we're working in the integer domain - private double sumB; - public Accumulator(Number sum0) { - if (sum0 instanceof Double) { - sumB = sum0.doubleValue(); - } else { - sumA = sum0.longValue(); - } - } - public Number call(Number n) { - if (sumA != null) { - if (n instanceof Double) { - sumB = n.doubleValue() + sumA; - sumA = null; - return sumB; - } - return sumA += n.longValue(); - } - return sumB += n.doubleValue(); - } +import java.util.function.DoubleUnaryOperator; - public static void main(String[] args) { - Accumulator x = new Accumulator(1); - x.call(5); - Accumulator y = new Accumulator(3); - System.out.println(y+" has value "+y.call(0)); - System.out.println(x.call(2.3)); - } +public interface AccumulatorFactory { + public static DoubleUnaryOperator accumulator(double element) { + double[] sum = new double[] { element }; + return value -> sum[0] += value; + } + + public static void main(String... arguments) { + DoubleUnaryOperator x = accumulator(1d); + x.applyAsDouble(5d); + System.out.println(accumulator(3d)); + System.out.println(x.applyAsDouble(2.3)); + } } diff --git a/Task/Accumulator-factory/Java/accumulator-factory-4.java b/Task/Accumulator-factory/Java/accumulator-factory-4.java new file mode 100644 index 0000000000..99c7f67e49 --- /dev/null +++ b/Task/Accumulator-factory/Java/accumulator-factory-4.java @@ -0,0 +1,30 @@ +public class Accumulator { + private Long sumA; // non-null if we're working in the integer domain + private double sumB; + public Accumulator(Number sum0) { + if (sum0 instanceof Double) { + sumB = sum0.doubleValue(); + } else { + sumA = sum0.longValue(); + } + } + public Number call(Number n) { + if (sumA != null) { + if (n instanceof Double) { + sumB = n.doubleValue() + sumA; + sumA = null; + return sumB; + } + return sumA += n.longValue(); + } + return sumB += n.doubleValue(); + } + + public static void main(String[] args) { + Accumulator x = new Accumulator(1); + x.call(5); + Accumulator y = new Accumulator(3); + System.out.println(y+" has value "+y.call(0)); + System.out.println(x.call(2.3)); + } +} diff --git a/Task/Accumulator-factory/Rust/accumulator-factory.rust b/Task/Accumulator-factory/Rust/accumulator-factory.rust new file mode 100644 index 0000000000..651e5f3188 --- /dev/null +++ b/Task/Accumulator-factory/Rust/accumulator-factory.rust @@ -0,0 +1,19 @@ +#![feature(unboxed_closures)] + +use std::ops::Add; +use std::ops::FnMut; + +fn accumulator_factory<'a, T>(n: T) -> Box T + 'a> + where T: Add + Copy + 'a { + let mut acc = n; + Box::new (move |&mut: i: T| { + acc = acc + i; + acc + }) +} + +fn main() { + let mut acc = accumulator_factory(10f64); + println!("{}", acc(12f64)); + println!("{}", acc(12f64)); +} diff --git a/Task/Accumulator-factory/TXR/accumulator-factory.txr b/Task/Accumulator-factory/TXR/accumulator-factory-1.txr similarity index 100% rename from Task/Accumulator-factory/TXR/accumulator-factory.txr rename to Task/Accumulator-factory/TXR/accumulator-factory-1.txr diff --git a/Task/Accumulator-factory/TXR/accumulator-factory-2.txr b/Task/Accumulator-factory/TXR/accumulator-factory-2.txr new file mode 100644 index 0000000000..2c16137ba5 --- /dev/null +++ b/Task/Accumulator-factory/TXR/accumulator-factory-2.txr @@ -0,0 +1,2 @@ +@(do (let ((f (let ((sum 0)) (do inc sum @1)))) + (mapdo (op format t "~s -> ~s\n" @1 [f @1]) (gun (read))))) diff --git a/Task/Ackermann-function/00DESCRIPTION b/Task/Ackermann-function/00DESCRIPTION index c270cadb62..a0c1132e36 100644 --- a/Task/Ackermann-function/00DESCRIPTION +++ b/Task/Ackermann-function/00DESCRIPTION @@ -1,4 +1,6 @@ -The '''[[wp:Ackermann function|Ackermann function]]''' is a classic recursive example in computer science. It is a function that grows very quickly (in its value and in the size of its call tree). It is defined as follows: +The '''[[wp:Ackermann function|Ackermann function]]''' is a classic recursive example in computer science. +It is a function that grows very quickly (in its value and in the size of its call tree). +It is defined as follows: : A(m, n) = \begin{cases} @@ -10,3 +12,8 @@ The '''[[wp:Ackermann function|Ackermann function]]''' is a classic recursive ex Its arguments are never negative and it always terminates. Write a function which returns the value of A(m, n). Arbitrary precision is preferred (since the function grows so quickly), but not required. + +Interestingly enough, the Ackermann function is one of the very few known examples of function that can ''only'' be implemented recursively. It is impossible to implement it with just for loops and other control flow commands. See this [http://youtube.com/watch?v=i7sm9dzFtEI computerphile episode] for more information. + +;See also: +* [[wp:Conway_chained_arrow_notation#Ackermann_function|Conway chained arrow notation]] for the Ackermann function. diff --git a/Task/Ackermann-function/Babel/ackermann-function.pb b/Task/Ackermann-function/Babel/ackermann-function.pb index 4b841dfa87..62c8dbd385 100644 --- a/Task/Ackermann-function/Babel/ackermann-function.pb +++ b/Task/Ackermann-function/Babel/ackermann-function.pb @@ -30,24 +30,3 @@ ack!: if } zero?!: { 0 = } - -Output: - -A(0 0 ) = 1 -A(0 1 ) = 2 -A(0 2 ) = 3 -A(0 3 ) = 4 -A(0 4 ) = 5 -A(1 0 ) = 2 -A(1 1 ) = 3 -A(1 2 ) = 4 -A(1 3 ) = 5 -A(1 4 ) = 6 -A(2 0 ) = 3 -A(2 1 ) = 5 -A(2 2 ) = 7 -A(2 3 ) = 9 -A(3 0 ) = 5 -A(3 1 ) = 13 -A(3 2 ) = 29 -A(4 0 ) = 13 diff --git a/Task/Ackermann-function/C++/ackermann-function-1.cpp b/Task/Ackermann-function/C++/ackermann-function-1.cpp new file mode 100644 index 0000000000..e29f7bcf4a --- /dev/null +++ b/Task/Ackermann-function/C++/ackermann-function-1.cpp @@ -0,0 +1,19 @@ +#include + +unsigned int ackermann(unsigned int m, unsigned int n) { + if (m == 0) { + return n + 1; + } + if (n == 0) { + return ackermann(m - 1, 1); + } + return ackermann(m - 1, ackermann(m, n - 1)); +} + +int main() { + for (unsigned int m = 0; m < 4; ++m) { + for (unsigned int n = 0; n < 10; ++n) { + std::cout << "A(" << m << ", " << n << ") = " << ackermann(m, n) << "\n"; + } + } +} diff --git a/Task/Ackermann-function/C++/ackermann-function-2.cpp b/Task/Ackermann-function/C++/ackermann-function-2.cpp new file mode 100644 index 0000000000..417ddda23d --- /dev/null +++ b/Task/Ackermann-function/C++/ackermann-function-2.cpp @@ -0,0 +1,54 @@ +#include +#include +#include +#include + +using big_int = boost::multiprecision::cpp_int; + +big_int ipow(big_int base, big_int exp) { + big_int result(1); + while (exp) { + if (exp & 1) { + result *= base; + } + exp >>= 1; + base *= base; + } + return result; +} + +big_int ackermann(unsigned m, unsigned n) { + static big_int (*ack)(unsigned, big_int) = + [](unsigned m, big_int n)->big_int { + switch (m) { + case 0: + return n + 1; + case 1: + return n + 2; + case 2: + return 3 + 2 * n; + case 3: + return 5 + 8 * (ipow(big_int(2), n) - 1); + default: + return n == 0 ? ack(m - 1, big_int(1)) : ack(m - 1, ack(m, n - 1)); + } + }; + return ack(m, big_int(n)); +} + +int main() { + for (unsigned m = 0; m < 4; ++m) { + for (unsigned n = 0; n < 10; ++n) { + std::cout << "A(" << m << ", " << n << ") = " << ackermann(m, n) << "\n"; + } + } + + std::cout << "A(4, 1) = " << ackermann(4, 1) << "\n"; + + std::stringstream ss; + ss << ackermann(4, 2); + auto text = ss.str(); + std::cout << "A(4, 2) = (" << text.length() << " digits)\n" + << text.substr(0, 80) << "\n...\n" + << text.substr(text.length() - 80) << "\n"; +} diff --git a/Task/Ackermann-function/C++/ackermann-function.cpp b/Task/Ackermann-function/C++/ackermann-function.cpp deleted file mode 100644 index 297e06dcd2..0000000000 --- a/Task/Ackermann-function/C++/ackermann-function.cpp +++ /dev/null @@ -1,18 +0,0 @@ -#include -using namespace std; -long ackermann(long x, long y) -{ - if (x == 0) return y+1; - else if (y == 0) return ackermann(x-1, 1); - else return ackermann(x-1, ackermann(x, y-1)); -} - -int main() -{ - long x,y; - cout << "x ve y..:"; - cin>>x; - cin>>y; - cout<= 0 && n >= 0); -} out(result) { +BigInt ackermann(in uint m, in uint n) pure nothrow +out(result) { assert(result >= 0); } body { - static BigInt ack(in int m, in BigInt n) pure /*nothrow*/ { + static BigInt ack(in uint m, in BigInt n) pure nothrow { switch (m) { case 0: return n + 1; case 1: return n + 2; case 2: return 3 + 2 * n; //case 3: return 5 + 8 * (2 ^^ n - 1); case 3: return 5 + 8 * (ipow(2.BigInt, n) - 1); - default: if (n == 0) - return ack(m - 1, 1.BigInt); - else - return ack(m - 1, ack(m, n - 1)); + default: return (n == 0) ? + ack(m - 1, 1.BigInt) : + ack(m - 1, ack(m, n - 1)); } } diff --git a/Task/Ackermann-function/Elena/ackermann-function.elena b/Task/Ackermann-function/Elena/ackermann-function.elena index 4c51a26a8c..34ccffe5c9 100644 --- a/Task/Ackermann-function/Elena/ackermann-function.elena +++ b/Task/Ackermann-function/Elena/ackermann-function.elena @@ -1,4 +1,5 @@ #define system. +#define extensions. // --- Ackermann function --- @@ -14,13 +15,11 @@ #symbol program = [ - control from:0 &to:3 &do: i + control forrange &int:0 &int:3 &do: (&int:i) [ - control from:0 &to:5 &do: j + control forrange &int:0 &int:5 &do: (&int:j) [ - console << "A(" << i << "," << j << ")=" << (ackermann:i:j). - - console writeLine. + consoleEx writeLine:"A(":i:",":j:")=":(ackermann:i:j). ]. ]. diff --git a/Task/Ackermann-function/Elixir/ackermann-function.elixir b/Task/Ackermann-function/Elixir/ackermann-function.elixir new file mode 100644 index 0000000000..1590e96bd5 --- /dev/null +++ b/Task/Ackermann-function/Elixir/ackermann-function.elixir @@ -0,0 +1,5 @@ +defmodule Ackermann do + def ack(0, n), do: n + 1 + def ack(m, 0), do: ack(m - 1, 1) + def ack(m, n), do: ack(m - 1, ack(m, n - 1)) +end diff --git a/Task/Ackermann-function/GML/ackermann-function.gml b/Task/Ackermann-function/GML/ackermann-function.gml index 770d4deed2..d753da09ac 100644 --- a/Task/Ackermann-function/GML/ackermann-function.gml +++ b/Task/Ackermann-function/GML/ackermann-function.gml @@ -1,8 +1,16 @@ -m=argument0 -n=argument1 +///ackermann(m,n) +var m, n; +m = argument0; +n = argument1; if(m=0) + { return (n+1) -else if(n=0) + } +else if(n == 0) + { return (ackermann(m-1,1,1)) + } else + { return (ackermann(m-1,ackermann(m,n-1,2),1)) + } diff --git a/Task/Ackermann-function/JavaScript/ackermann-function.js b/Task/Ackermann-function/JavaScript/ackermann-function.js index 8b07754850..641d25510f 100644 --- a/Task/Ackermann-function/JavaScript/ackermann-function.js +++ b/Task/Ackermann-function/JavaScript/ackermann-function.js @@ -1,4 +1,3 @@ -function ack(m, n) -{ +function ack(m, n) { return m === 0 ? n + 1 : ack(m - 1, n === 0 ? 1 : ack(m, n - 1)); } diff --git a/Task/Ackermann-function/Julia/ackermann-function-3.julia b/Task/Ackermann-function/Julia/ackermann-function-3.julia new file mode 100644 index 0000000000..34d9313690 --- /dev/null +++ b/Task/Ackermann-function/Julia/ackermann-function-3.julia @@ -0,0 +1,5 @@ +using Memoize +@memoize ack3(m, n) = + m == 0 ? n + 1 : + n == 0 ? ack3(m-1, 1) : + ack3(m-1, ack3(m, n-1)) diff --git a/Task/Ackermann-function/OOC/ackermann-function.ooc b/Task/Ackermann-function/OOC/ackermann-function.ooc new file mode 100644 index 0000000000..5da6c01a94 --- /dev/null +++ b/Task/Ackermann-function/OOC/ackermann-function.ooc @@ -0,0 +1,17 @@ +ack: func (m: Int, n: Int) -> Int { + if (m == 0) { + n + 1 + } else if (n == 0) { + ack(m - 1, 1) + } else { + ack(m - 1, ack(m, n - 1)) + } +} + +main: func { + for (m in 0..4) { + for (n in 0..10) { + "ack(#{m}, #{n}) = #{ack(m, n)}" println() + } + } +} diff --git a/Task/Ackermann-function/Perl/ackermann-function-4.pl b/Task/Ackermann-function/Perl/ackermann-function-4.pl new file mode 100644 index 0000000000..04ca00fdfe --- /dev/null +++ b/Task/Ackermann-function/Perl/ackermann-function-4.pl @@ -0,0 +1,15 @@ +use Memoize; memoize('ack2'); +use bigint try=>"GMP"; + +sub ack2 { + my ($m, $n) = @_; + $m == 0 ? $n + 1 : + $m == 1 ? $n + 2 : + $m == 2 ? 2*$n + 3 : + $m == 3 ? 8 * (2**$n - 1) + 5 : + $n == 0 ? ack2($m-1, 1) + : ack2($m-1, ack2($m, $n-1)); +} +print "ack2(3,4) is ", ack2(3,4), "\n"; +print "ack2(4,1) is ", ack2(4,1), "\n"; +print "ack2(4,2) has ", length(ack2(4,2)), " digits\n"; diff --git a/Task/Ackermann-function/Python/ackermann-function-2.py b/Task/Ackermann-function/Python/ackermann-function-2.py index 0245d4e659..1e1658ebab 100644 --- a/Task/Ackermann-function/Python/ackermann-function-2.py +++ b/Task/Ackermann-function/Python/ackermann-function-2.py @@ -2,6 +2,6 @@ def ack2(M, N): if M == 0: return N + 1 elif N == 0: - return ack1(M - 1, 1) + return ack2(M - 1, 1) else: - return ack1(M - 1, ack1(M, N - 1)) + return ack2(M - 1, ack2(M, N - 1)) diff --git a/Task/Ackermann-function/Rust/ackermann-function.rust b/Task/Ackermann-function/Rust/ackermann-function-1.rust similarity index 100% rename from Task/Ackermann-function/Rust/ackermann-function.rust rename to Task/Ackermann-function/Rust/ackermann-function-1.rust diff --git a/Task/Ackermann-function/Rust/ackermann-function-2.rust b/Task/Ackermann-function/Rust/ackermann-function-2.rust new file mode 100644 index 0000000000..762a9169b4 --- /dev/null +++ b/Task/Ackermann-function/Rust/ackermann-function-2.rust @@ -0,0 +1,7 @@ +fn ack(m: u64, n: u64) -> u64 { + match (m, n) { + (0, n) => n + 1, + (m, 0) => ack(m - 1, 1), + (m, n) => ack(m - 1, ack(m, n - 1)), + } +} diff --git a/Task/Ackermann-function/Scilab/ackermann-function.scilab b/Task/Ackermann-function/Scilab/ackermann-function.scilab new file mode 100644 index 0000000000..8872143e4e --- /dev/null +++ b/Task/Ackermann-function/Scilab/ackermann-function.scilab @@ -0,0 +1,23 @@ +clear +function acker=ackermann(m,n) + global calls + calls=calls+1 + if m==0 then acker=n+1 + else + if n==0 then acker=ackermann(m-1,1) + else acker=ackermann(m-1,ackermann(m,n-1)) + end + end +endfunction +function printacker(m,n) + global calls + calls=0 + printf('ackermann(%d,%d)=',m,n) + printf('%d calls=%d\n',ackermann(m,n),calls) +endfunction +maxi=3; maxj=6 +for i=0:maxi + for j=0:maxj + printacker(i,j) + end +end diff --git a/Task/Ackermann-function/Visual-Basic/ackermann-function.vb b/Task/Ackermann-function/Visual-Basic/ackermann-function.vb new file mode 100644 index 0000000000..e9dce52dd6 --- /dev/null +++ b/Task/Ackermann-function/Visual-Basic/ackermann-function.vb @@ -0,0 +1,29 @@ +Option Explicit +Dim calls As Long +Sub main() + Const maxi = 4 + Const maxj = 9 + Dim i As Long, j As Long + For i = 0 To maxi + For j = 0 To maxj + Call print_acker(i, j) + Next j + Next i +End Sub 'main +Sub print_acker(m As Long, n As Long) + calls = 0 + Debug.Print "ackermann("; m; ","; n; ")="; + Debug.Print ackermann(m, n), "calls="; calls +End Sub 'print_acker +Function ackermann(m As Long, n As Long) As Long + calls = calls + 1 + If m = 0 Then + ackermann = n + 1 + Else + If n = 0 Then + ackermann = ackermann(m - 1, 1) + Else + ackermann = ackermann(m - 1, ackermann(m, n - 1)) + End If + End If +End Function 'ackermann diff --git a/Task/Ackermann-function/ZED/ackermann-function.zed b/Task/Ackermann-function/ZED/ackermann-function.zed index 98337d2325..a16fe385ad 100644 --- a/Task/Ackermann-function/ZED/ackermann-function.zed +++ b/Task/Ackermann-function/ZED/ackermann-function.zed @@ -1,14 +1,29 @@ -(ackermann) integer1 integer2 -comment: takes two integers -> returns the result -(zero?) integer1 -(add1) integer2 +(A) m n +comment: +(=) m 0 +(add1) n -(ackermann) integer1 integer2 -comment: takes two integers -> returns the result -(and) (positive?) integer1 (zero?) integer2 -(ackermann) (sub1) integer1 1 +(A) m n +comment: +(=) n 0 +(A) (sub1) m 1 -(ackermann) integer1 integer2 -comment: takes two integers -> returns the result -(and) (positive?) integer1 (positive?) integer2 -(ackermann) (sub1) integer1 (ackermann) integer1 (sub1) integer2 +(A) m n +comment: +#true +(A) (sub1) m (A) m (sub1) n + +(add1) n +comment: +#true +(003) "+" n 1 + +(sub1) n +comment: +#true +(003) "-" n 1 + +(=) n1 n2 +comment: +#true +(003) "=" n1 n2 diff --git a/Task/Active-Directory-Connect/ColdFusion/active-directory-connect.cfm b/Task/Active-Directory-Connect/ColdFusion/active-directory-connect.cfm new file mode 100644 index 0000000000..e59e36dc96 --- /dev/null +++ b/Task/Active-Directory-Connect/ColdFusion/active-directory-connect.cfm @@ -0,0 +1,10 @@ + diff --git a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m index 1ab166b5b6..68fbbf7235 100644 --- a/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m +++ b/Task/Add-a-variable-to-a-class-instance-at-runtime/Objective-C/add-a-variable-to-a-class-instance-at-runtime-1.m @@ -1,7 +1,7 @@ #import #import -static char fooKey; +static void *fooKey = &fooKey; // one way to define a unique key is a pointer variable that points to itself int main (int argc, const char *argv[]) { @autoreleasepool { @@ -9,10 +9,10 @@ int main (int argc, const char *argv[]) { id e = [[NSObject alloc] init]; // set - objc_setAssociatedObject(e, &fooKey, @1, OBJC_ASSOCIATION_RETAIN); + objc_setAssociatedObject(e, fooKey, @1, OBJC_ASSOCIATION_RETAIN); // get - NSNumber *associatedObject = objc_getAssociatedObject(e, &fooKey); + NSNumber *associatedObject = objc_getAssociatedObject(e, fooKey); NSLog(@"associatedObject: %@", associatedObject); } diff --git a/Task/Address-of-a-variable/00DESCRIPTION b/Task/Address-of-a-variable/00DESCRIPTION index 4007bb7aca..a6bdb20480 100644 --- a/Task/Address-of-a-variable/00DESCRIPTION +++ b/Task/Address-of-a-variable/00DESCRIPTION @@ -1 +1,4 @@ -{{basic data operation}}Demonstrate how to get the address of a variable and how to set the address of a variable. +{{basic data operation}} + +Demonstrate how to get the address of a variable +and how to set the address of a variable. diff --git a/Task/Address-of-a-variable/Go/address-of-a-variable-1.go b/Task/Address-of-a-variable/Go/address-of-a-variable-1.go index 37c46c441b..e8a07f664b 100644 --- a/Task/Address-of-a-variable/Go/address-of-a-variable-1.go +++ b/Task/Address-of-a-variable/Go/address-of-a-variable-1.go @@ -1,16 +1,32 @@ package main import ( - "fmt" - "unsafe" + "fmt" + "unsafe" ) func main() { - myVar := 3.14 - myPointer := &myVar - fmt.Println(myPointer) - fmt.Printf("%p\n", myPointer) + myVar := 3.14 + myPointer := &myVar + fmt.Println("Address:", myPointer, &myVar) + fmt.Printf("Address: %p %p\n", myPointer, &myVar) - addr := int64(uintptr(unsafe.Pointer(myPointer))) - fmt.Printf("0x%x\n", addr) + var addr64 int64 + var addr32 int32 + ptr := unsafe.Pointer(myPointer) + if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr64) { + addr64 = int64(uintptr(ptr)) + fmt.Printf("Pointer stored in int64: %#016x\n", addr64) + } + if unsafe.Sizeof(ptr) <= unsafe.Sizeof(addr32) { + // Only runs on architectures where a pointer is <= 32 bits + addr32 = int32(uintptr(ptr)) + fmt.Printf("Pointer stored in int32: %#08x\n", addr32) + } + addr := uintptr(ptr) + fmt.Printf("Pointer stored in uintptr: %#08x\n", addr) + + fmt.Println("value as float:", myVar) + i := (*int32)(unsafe.Pointer(&myVar)) + fmt.Printf("value as int32: %#08x\n", *i) } diff --git a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx index 334ae4d6db..21c8179c31 100644 --- a/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx +++ b/Task/Address-of-a-variable/REXX/address-of-a-variable.rexx @@ -1 +1 @@ -zzz=storage(xxx) +zzz = storage(xxx) diff --git a/Task/Address-of-a-variable/RapidQ/address-of-a-variable.rapidq b/Task/Address-of-a-variable/RapidQ/address-of-a-variable.rapidq new file mode 100644 index 0000000000..f4278e1e50 --- /dev/null +++ b/Task/Address-of-a-variable/RapidQ/address-of-a-variable.rapidq @@ -0,0 +1,19 @@ +Dim TheAddress as long +Dim SecVar as byte +Dim MyVar as byte + MyVar = 10 + +'Get the address of MyVar +TheAddress = varptr(MyVar) + +'Set a new value on the address +MEMSET(TheAddress, 102, SizeOf(byte)) + +'Myvar is now = 102 +showmessage "MyVar = " + str$(MyVar) + +'...or copy from one address to another using: +MEMCPY(VarPtr(SecVar), TheAddress, SizeOf(byte)) + +'SecVar is now also = 102 +showmessage "SecVar = " + str$(SecVar) diff --git a/Task/Align-columns/D/align-columns.d b/Task/Align-columns/D/align-columns.d index 82e75d80c4..9c507bf7be 100644 --- a/Task/Align-columns/D/align-columns.d +++ b/Task/Align-columns/D/align-columns.d @@ -1,22 +1,22 @@ -import std.stdio, std.string, std.algorithm, std.range, std.typetuple; - void main() { - auto data = + import std.stdio, std.string, std.algorithm, std.range, std.typetuple; + + immutable data = "Given$a$txt$file$of$many$lines,$where$fields$within$a$line$ are$delineated$by$a$single$'dollar'$character,$write$a$program that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ column$are$separated$by$at$least$one$space. Further,$allow$for$each$word$in$a$column$to$be$either$left$ justified,$right$justified,$or$center$justified$within$its$column." - .split.map!(r => r.chomp("$").split("$")); + .split.map!(r => r.chomp("$").split("$")).array; - int[int] maxWidths; + size_t[size_t] maxWidths; foreach (const line; data) foreach (immutable i, const word; line) maxWidths[i] = max(maxWidths.get(i, 0), word.length); - foreach (const just; TypeTuple!(leftJustify, center, rightJustify)) - foreach (const line; data) + foreach (immutable just; TypeTuple!(leftJustify, center, rightJustify)) + foreach (immutable line; data) writefln("%-(%s %)", line.length.iota .map!(i => just(line[i], maxWidths[i], ' '))); } diff --git a/Task/Align-columns/JavaScript/align-columns.js b/Task/Align-columns/JavaScript/align-columns-1.js similarity index 100% rename from Task/Align-columns/JavaScript/align-columns.js rename to Task/Align-columns/JavaScript/align-columns-1.js diff --git a/Task/Align-columns/JavaScript/align-columns-2.js b/Task/Align-columns/JavaScript/align-columns-2.js new file mode 100644 index 0000000000..b7a48bcab7 --- /dev/null +++ b/Task/Align-columns/JavaScript/align-columns-2.js @@ -0,0 +1,48 @@ +//break up each string by '$'. The assumption is that the user wants the trailing $. +var data = [ + "Given$a$text$file$of$many$lines,$where$fields$within$a$line$", + "are$delineated$by$a$single$'dollar'$character,$write$a$program", + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", + "column$are$separated$by$at$least$one$space.", + "Further,$allow$for$each$word$in$a$column$to$be$either$left$", + "justified,$right$justified,$or$center$justified$within$its$column." +].map(function (str) { return str.split('$'); }) + +//boilerplate: get longest array or string in array +var getLongest = function (arr) { + return arr.reduce(function (acc, item) { return acc.length > item.length ? acc : item; }, 0); +}; + +//boilerplate: this function would normally be in a library like underscore, lodash, or ramda +var zip = function (items, toInsert) { + toInsert = (toInsert === undefined) ? null : toInsert; + var longestItem = getLongest(items); + return longestItem.map(function (_unused, index) { + return items.map(function (item) { + return item[index] === undefined ? toInsert : item[index]; + }); + }); +}; + +//here's the part that's not boilerplate +var makeColumns = function (formatting, data) { + var zipData = zip(data, ''); + var makeSpaces = function (num) { return new Array(num + 1).join(' '); }; + var formattedCols = zipData.map(function (column) { + var maxLen = getLongest(column).length;//find the maximum word length + if (formatting === 'left') { + return column.map(function (word) { return word + makeSpaces(maxLen - word.length); }); + } else if (formatting === 'right') { + return column.map(function (word) { return makeSpaces(maxLen - word.length) + word; }); + } else { + return column.map(function (word) { + var spaces = maxLen - word.length, + first = ~~(spaces / 2), + last = spaces - first; + return makeSpaces(first) + word + makeSpaces(last); + }); + } + }); + + return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n'); +}; diff --git a/Task/Align-columns/Oberon-2/align-columns.oberon-2 b/Task/Align-columns/Oberon-2/align-columns.oberon-2 new file mode 100644 index 0000000000..458e970eb2 --- /dev/null +++ b/Task/Align-columns/Oberon-2/align-columns.oberon-2 @@ -0,0 +1,107 @@ +MODULE Columns; +IMPORT + NPCT:Tools, + Object, + Out; + +TYPE + Parts = ARRAY 32 OF STRING; + Formatter = PROCEDURE (s: STRING; len: LONGINT): STRING; +VAR + lines: ARRAY 6 OF STRING; + words: ARRAY 6 OF Parts; + columnWidth: ARRAY 128 OF INTEGER; + lineIdx: INTEGER; + + (* + * Size: returns de number of words in a line + *) + PROCEDURE Size(p: Parts): INTEGER; + VAR + i: INTEGER; + BEGIN + i := 0; + WHILE (i < LEN(p)) & (p[i] # NIL) DO + INC(i); + END; + RETURN i + END Size; + (* + * Max: returns maximum number of words in the lines + *) + PROCEDURE Max(w: ARRAY OF Parts): INTEGER; + VAR + i, max, resp: INTEGER; + BEGIN + i := 0;resp := 0; + WHILE (i < LEN(w)) DO + max := Size(w[i]); + IF (max > resp) THEN resp := max END; + INC(i) + END; + RETURN resp; + END Max; + + (* + * MaxColumnWidth: returns the maximum width of a column + *) + PROCEDURE MaxColumnWidth(w: ARRAY OF Parts;column: INTEGER): INTEGER; + VAR + line,max: LONGINT; + BEGIN + line := 0; + max := MIN(INTEGER); + WHILE (line < LEN(w)) DO; + IF (w[line,column] # NIL) & (w[line,column](Object.String8).length > max) THEN max := w[line,column](Object.String8).length END; + INC(line) + END; + RETURN SHORT(max) + END MaxColumnWidth; + + (* + * PrintWords: prints the words in 'w' using the formatter passed in 'format' + *) + PROCEDURE PrintWords(w: ARRAY OF Parts; format: Formatter); + VAR + i,j: INTEGER; + BEGIN + i := 0; + WHILE (i < LEN(words)) DO + j := 0; + WHILE (j < Max(words)) & (words[i,j] # NIL) DO + Out.Object(format(words[i,j],columnWidth[j] + 1)); + INC(j) + END; + Out.Ln; + INC(i) + END; + Out.Ln + END PrintWords; + +BEGIN +lines[0] := "Given$a$text$file$of$many$lines,$where$fields$within$a$line$"; +lines[1] := "are$delineated$by$a$single$'dollar'$character,$write$a$program"; +lines[2] := "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$"; +lines[3] := "column$are$separated$by$at$least$one$space."; +lines[4] := "Further,$allow$for$each$word$in$a$column$to$be$either$left$"; +lines[5] := "justified,$right$justified,$or$center$justified$within$its$column."; + +(* Split line in words *) +lineIdx := 0; +WHILE lineIdx < LEN(lines) DO + Tools.Split(lines[lineIdx],"$",words[lineIdx]); + INC(lineIdx) +END; + +(* Calculate width of the column *) +lineIdx := 0; +WHILE (lineIdx < Max(words)) DO + columnWidth[lineIdx] := MaxColumnWidth(words,lineIdx); + INC(lineIdx) +END; + +(* Print Results *) +PrintWords(words,Tools.AdjustLeft); +PrintWords(words,Tools.AdjustCenter); +PrintWords(words,Tools.AdjustRight); +END Columns. diff --git a/Task/Align-columns/REXX/align-columns-2.rexx b/Task/Align-columns/REXX/align-columns-2.rexx index 4f32eaa738..2acf00cc06 100644 --- a/Task/Align-columns/REXX/align-columns-2.rexx +++ b/Task/Align-columns/REXX/align-columns-2.rexx @@ -1,35 +1,34 @@ -/*REXX program to display various alignments. */ -cols=0; size=0; wid.=0; t.=; @.= - +/*REXX program displays various alignments for words in a text string.*/ +cols=0; size=0; wid.=0; t.=; @.= /*zero|nullify some variables*/ + /* [↓] some "text" lines. */ t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program" t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" t.4 = "column$are$separated$by$at$least$one$space." t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$" t.6 = "justified,$right$justified,$or$center$justified$within$its$column." - - do r=1 while t.r\=='' - _=strip(t.r,,'$') - do c=1 until _=='' - parse var _ @.r.c '$' _ - wid.c=max(wid.c,length(@.r.c)) - end /*c*/ - cols=max(cols,c) + /* [↑] a null line is the end*/ + do r=1 while t.r\=='' /* [↓] process all text lines*/ + _=strip(t.r,,'$') /*strip leading & trailing $.*/ + do c=1 until _=='' /* [↓] process each word. */ + parse var _ @.r.c '$' _ + wid.c=max(wid.c, length(@.r.c)) /*max word width.*/ + end /*c*/ + cols=max(cols,c) /*use the maximum COLS found.*/ end /*r*/ -rows=r-1 /*adjust ROWS, it's 1 too big*/ - do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ + do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ +rows=r-1 /*adjust ROWS because of DO.*/ + do j=1 for 3; say; say /*show 2 blank lines for sep.*/ + say center(word('left right center', j) "aligned", size+cols-1, "═") - do j=1 for 3; say - say center(word('left right center',j) "aligned",size+cols-1,"=") - - do r=1 for rows; _= - do c=1 for cols; x=@.r.c - if j==1 then _=_ left(x,wid.c) - if j==2 then _=_ right(x,wid.c) - if j==3 then _=_ centre(x,wid.c) - end /*c*/ - say substr(_,2) - end /*r*/ - say + do r=1 for rows; _= /*build row by row*/ + do c=1 for cols; x=@.r.c /* " col " col*/ + if j==1 then _=_ left(x, wid.c) /*justified left.*/ + if j==2 then _=_ right(x, wid.c) /* " right.*/ + if j==3 then _=_ centre(x, wid.c) /* " center.*/ + end /*c*/ + say substr(_,2) /*ignore the leading extra blank.*/ + end /*r*/ end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Align-columns/REXX/align-columns-3.rexx b/Task/Align-columns/REXX/align-columns-3.rexx index 5d9ca65f6d..4069842473 100644 --- a/Task/Align-columns/REXX/align-columns-3.rexx +++ b/Task/Align-columns/REXX/align-columns-3.rexx @@ -1,43 +1,40 @@ -/*REXX program to display various alignments. */ -cols=0; parse var cols size 1 wid. t. /*initializations.*/ - +/*REXX program displays various alignments for words in a text string.*/ +cols=0; size=0; wid.=0; t.=; @.= /*zero|nullify some variables*/ + /* [↓] some "text" lines. */ t.1 = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" t.2 = "are$delineated$by$a$single$'dollar'$character,$write$a$program" t.3 = "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" t.4 = "column$are$separated$by$at$least$one$space." t.5 = "Further,$allow$for$each$word$in$a$column$to$be$either$left$" t.6 = "justified,$right$justified,$or$center$justified$within$its$column." + /* [↑] a null line is the end*/ + do r=1 while t.r\=='' /* [↓] process all text lines*/ + _=strip(t.r,,'$') /*strip leading & trailing $.*/ + do c=1 until _=='' /* [↓] process each word. */ + parse var _ @.r.c '$' _ + wid.c=max(wid.c, length(@.r.c)) /*max word width.*/ + end /*c*/ + cols=max(cols,c) /*use the maximum COLS found.*/ + end /*r*/ - do r=1 while t.r\=='' - t.r=translate(t.r,,'$') - do c=1 until word(t.r,c)=='' - wid.c=max(wid.c,length(word(t.r,c))) - end /*c*/ - cols=max(cols,c) - end /*r*/ + do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ +rows=r-1 /*adjust ROWS because of DO.*/ + do j=1 for 3; say; say /*show 2 blank lines for sep.*/ + say center(word('left right center', j) "aligned", size+cols+1, "═") -rows=r-1 /*adjust ROWS, it's 1 too big*/ - - do k=1 for cols; size=size+wid.k; end /*find width of biggest line.*/ - - do j=1 for 3; say - say center(word('left right center',j) "aligned",size+cols,"="); say - - do r=0 to rows; _=; !='│'; if r==0 then !='┬' - - do c=1 for cols; x=word(t.r,c) - if r==0 then x=copies("─",wid.c+1) - else x=word(t.r,c) - if j==1 then _=_ || ! || left(x,wid.c) - if j==2 then _=_ || ! || right(x,wid.c) - if j==3 then _=_ || ! || centre(x,wid.c) + do r=0 to rows; _=; !='│'; if r==0 then !='┬' + do c=1 for cols; x=@.r.c + if r==0 then x=copies("─",wid.c+1) + if j==1 then _=_ || ! || left(x,wid.c) + if j==2 then _=_ || ! || right(x,wid.c) + if j==3 then _=_ || ! || centre(x,wid.c) end /*c*/ - - if r==0 then do; _='┌'substr(_,2,length(_)-2)"┐" - bot='└'substr(_,2,length(_)-2)"┘" + if r==0 then do; _= '┌'substr(_,2,length(_)-1)"┐" + bot= '└'substr(_,2,length(_)-2)"┘" end + else _=_ || ! say _ end /*r*/ - - say translate(bot,'┴',"┬"); say; say + /* [↑] shows words in boxes.*/ + say translate(bot,'┴',"┬") end /*j*/ diff --git a/Task/Align-columns/RapidQ/align-columns.rapidq b/Task/Align-columns/RapidQ/align-columns.rapidq new file mode 100644 index 0000000000..bdcad11ade --- /dev/null +++ b/Task/Align-columns/RapidQ/align-columns.rapidq @@ -0,0 +1,41 @@ +Dim MText as QMemorystream + MText.WriteLine "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" + MText.WriteLine "are$delineated$by$a$single$'dollar'$character,$write$a$program" + MText.WriteLine "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" + MText.WriteLine "column$are$separated$by$at$least$one$space." + MText.WriteLine "Further,$allow$for$each$word$in$a$column$to$be$either$left$" + MText.WriteLine "justified,$right$justified,$or$center$justified$within$its$column." + +DefStr TextLeft, TextRight, TextCenter +DefStr MLine, LWord, Newline = chr$(13)+chr$(10) +DefInt ColWidth(100), ColCount +DefSng NrSpaces + +'Find column widths +MText.position = 0 +for x = 0 to MText.linecount -1 + MLine = MText.ReadLine + for y = 0 to Tally(MLine, "$") + LWord = Field$(MLine, "$", y+1) + ColWidth(y) = iif (ColWidth(y) < len(LWord), len(LWord), ColWidth(y)) + next +next + +'Create aligned wordlists +MText.position = 0 +for x = 0 to MText.linecount -1 + MLine = MText.ReadLine + for y = 0 to Tally(MLine, "$") + LWord = Field$(MLine, "$", y+1) + NrSpaces = ColWidth(y) - len(LWord) + 'left align + TextLeft = TextLeft + LWord + Space$(NrSpaces+1) + 'Right align + TextRight = TextRight + Space$(NrSpaces+1) + LWord + 'Center + TextCenter = TextCenter + Space$(floor((NrSpaces)/2)+1) + LWord + Space$(Ceil((NrSpaces)/2)) + next + TextLeft = TextLeft + Newline + TextRight = TextRight + Newline + TextCenter = TextCenter + Newline +next diff --git a/Task/Align-columns/Ruby/align-columns.rb b/Task/Align-columns/Ruby/align-columns.rb index ae42acdf65..cf0a0b8845 100644 --- a/Task/Align-columns/Ruby/align-columns.rb +++ b/Task/Align-columns/Ruby/align-columns.rb @@ -1,3 +1,32 @@ +J2justifier = {'L' => :ljust, + 'R' => :rjust, + 'C' => :center} + +=begin +Justify columns of textual tabular input where the record separator is the newline +and the field separator is a 'dollar' character. +justification can be L, R, or C; (Left, Right, or Centered). + +Return the justified output as a string +=end +def aligner(infile, justification = 'L') + fieldsbyrow = infile.map {|line| line.strip.split('$')} + # pad to same number of fields per record + maxfields = fieldsbyrow.map(&:length).max + fieldsbyrow.map! {|row| row + ['']*(maxfields - row.length)} + # calculate max fieldwidth per column + colwidths = fieldsbyrow.transpose.map {|column| + column.map(&:length).max + } + # pad fields in columns to colwidth with spaces + justifier = J2justifier[justification] + fieldsbyrow.map {|row| + row.zip(colwidths).map {|field, width| + field.send(justifier, width) + }.join(" ") + }.join("\n") +end + require 'stringio' textinfile = < String.instance_method(:ljust), - 'R' => String.instance_method(:rjust), - 'C' => String.instance_method(:center)} - -=begin -Justify columns of textual tabular input where the record separator is the newline -and the field separator is a 'dollar' character. -justification can be L, R, or C; (Left, Right, or Centered). - -Return the justified output as a string -=end -def aligner(infile, justification = 'L') - justifier = J2justifier[justification] - - fieldsbyrow = infile.map {|line| line.strip.split('$')} - # pad to same number of fields per record - maxfields = fieldsbyrow.map {|row| row.length}.max - fieldsbyrow.map! {|row| - row + ['']*(maxfields - row.length) - } - # calculate max fieldwidth per column - colwidths = fieldsbyrow.transpose.map {|column| - column.map {|field| field.length}.max - } - # pad fields in columns to colwidth with spaces - fieldsbyrow.map! {|row| - row.zip(colwidths).map {|field, width| - justifier.bind(field)[width] - } - } - - fieldsbyrow.map {|row| row.join(" ")}.join("\n") -end - for align in %w{Left Right Center} infile = StringIO.new(textinfile) puts "\n# %s Column-aligned output:" % align diff --git a/Task/Align-columns/Rust/align-columns.rust b/Task/Align-columns/Rust/align-columns.rust new file mode 100644 index 0000000000..b8e58fc179 --- /dev/null +++ b/Task/Align-columns/Rust/align-columns.rust @@ -0,0 +1,62 @@ +#![feature(core)] +extern crate core; + +use core::iter::repeat; +use core::str::StrExt; +use std::iter::Extend; + +enum AlignmentType { Left, Center, Right } + +fn get_column_widths(text: &str) -> Vec { + let mut widths = Vec::new(); + for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { + let mut lens = line.split('$').map(|s| s.char_len()); + let mut idx = 0; + for len in lens { + if idx < widths.len() { + widths[idx] = std::cmp::max(widths[idx], len); + } + else { + widths.push(len); + } + idx += 1; + } + } + widths +} + +fn align_columns(text: &str, alignment: AlignmentType) -> String { + let widths = get_column_widths(text); + let mut result = String::new(); + for line in text.lines().map(|s| s.trim_matches(' ').trim_right_matches('$')) { + for (s, w) in line.split('$').zip(widths.iter()) { + let blank_count = w - s.char_len(); + let (pre, post) = match alignment { + AlignmentType::Left => (0, blank_count), + AlignmentType::Center => (blank_count / 2, (blank_count + 1) / 2), + AlignmentType::Right => (blank_count, 0), + }; + result.extend(repeat(' ').take(pre)); + result.push_str(s); + result.extend(repeat(' ').take(post)); + result.push(' '); + } + result.push_str("\n"); + } + result +} + +fn main() { + let text = r#"Given$a$text$file$of$many$lines,$where$fields$within$a$line$ +are$delineated$by$a$single$'dollar'$character,$write$a$program +that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$ +column$are$separated$by$at$least$one$space. +Further,$allow$for$each$word$in$a$column$to$be$either$left$ +justified,$right$justified,$or$center$justified$within$its$column."#; + + println!("{}", align_columns(text, AlignmentType::Left)); + println!("{}", repeat('-').take(110).collect::()); + println!("{}", align_columns(text, AlignmentType::Center)); + println!("{}", repeat('-').take(110).collect::()); + println!("{}", align_columns(text, AlignmentType::Right)); +} diff --git a/Task/Align-columns/Visual-Basic-.NET/align-columns.visual b/Task/Align-columns/Visual-Basic-.NET/align-columns.visual new file mode 100644 index 0000000000..c1a59fa525 --- /dev/null +++ b/Task/Align-columns/Visual-Basic-.NET/align-columns.visual @@ -0,0 +1,67 @@ +Module Module1 + + + Private Delegate Function Justification(s As String, width As Integer) As String + + Private Function AlignColumns(lines As String(), justification As Justification) As String() + Const Separator As Char = "$"c + ' build input container table and calculate columns count + Dim containerTbl As String()() = New String(lines.Length - 1)() {} + Dim columns As Integer = 0 + For i As Integer = 0 To lines.Length - 1 + Dim row As String() = lines(i).TrimEnd(Separator).Split(Separator) + If columns < row.Length Then + columns = row.Length + End If + containerTbl(i) = row + Next + ' create formatted container table + Dim formattedTable As String()() = New String(containerTbl.Length - 1)() {} + For i As Integer = 0 To formattedTable.Length - 1 + formattedTable(i) = New String(columns - 1) {} + Next + For j As Integer = 0 To columns - 1 + ' get max column width + Dim columnWidth As Integer = 0 + For i As Integer = 0 To containerTbl.Length - 1 + If j < containerTbl(i).Length AndAlso columnWidth < containerTbl(i)(j).Length Then + columnWidth = containerTbl(i)(j).Length + End If + Next + ' justify column cells + For i As Integer = 0 To formattedTable.Length - 1 + If j < containerTbl(i).Length Then + formattedTable(i)(j) = justification(containerTbl(i)(j), columnWidth) + Else + formattedTable(i)(j) = New [String](" "c, columnWidth) + End If + Next + Next + ' create result + Dim result As String() = New String(formattedTable.Length - 1) {} + For i As Integer = 0 To result.Length - 1 + result(i) = [String].Join(" ", formattedTable(i)) + Next + Return result + End Function + + Private Function JustifyLeft(s As String, width As Integer) As String + Return s.PadRight(width) + End Function + Private Function JustifyRight(s As String, width As Integer) As String + Return s.PadLeft(width) + End Function + Private Function JustifyCenter(s As String, width As Integer) As String + Return s.PadLeft((width + s.Length) / 2).PadRight(width) + End Function + + Sub Main() + Dim input As String() = {"Given$a$text$file$of$many$lines,$where$fields$within$a$line$", "are$delineated$by$a$single$'dollar'$character,$write$a$program", "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$", "column$are$separated$by$at$least$one$space.", "Further,$allow$for$each$word$in$a$column$to$be$either$left$", "justified,$right$justified,$or$center$justified$within$its$column."} + + For Each line As String In AlignColumns(input, AddressOf JustifyLeft) + Console.WriteLine(line) + Next + Console.ReadLine() + End Sub + +End Module diff --git a/Task/Align-columns/Visual-Basic/align-columns-1.vb b/Task/Align-columns/Visual-Basic/align-columns-1.vb new file mode 100644 index 0000000000..3002d96085 --- /dev/null +++ b/Task/Align-columns/Visual-Basic/align-columns-1.vb @@ -0,0 +1,16 @@ +Sub AlignCols(Lines, Optional Align As AlignmentConstants, Optional Sep$ = "$", Optional Sp% = 1) +Dim i&, j&, D&, L&, R&: ReDim W(UBound(Lines)): ReDim C&(0) + + For j = 0 To UBound(W) + W(j) = Split(Lines(j), Sep) + If UBound(W(j)) > UBound(C) Then ReDim Preserve C(UBound(W(j))) + For i = 0 To UBound(W(j)): If Len(W(j)(i)) > C(i) Then C(i) = Len(W(j)(i)) + Next i, j + + For j = 0 To UBound(W): For i = 0 To UBound(W(j)) + D = C(i) - Len(W(j)(i)) + L = Choose(Align + 1, 0, D, D \ 2) + R = Choose(Align + 1, D, 0, D - L) + Sp + Debug.Print Space(L); W(j)(i); Space(R); IIf(i < UBound(W(j)), "", vbLf); + Next i, j +End Sub diff --git a/Task/Align-columns/Visual-Basic/align-columns-2.vb b/Task/Align-columns/Visual-Basic/align-columns-2.vb new file mode 100644 index 0000000000..1275588e97 --- /dev/null +++ b/Task/Align-columns/Visual-Basic/align-columns-2.vb @@ -0,0 +1,12 @@ +Sub Main() 'usage of the above +Const Text$ = "Given$a$text$file$of$many$lines,$where$fields$within$a$line$" & vbLf & _ + "are$delineated$by$a$single$'dollar'$character,$write$a$program" & vbLf & _ + "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$" & vbLf & _ + "column$are$separated$by$at$least$one$space." & vbLf & _ + "Further,$allow$for$each$word$in$a$column$to$be$either$left$" & vbLf & _ + "justified,$right$justified,$or$center$justified$within$its$column." + + Debug.Print vbLf; "-- Left:": AlignCols Split(Text, vbLf), vbLeftJustify + Debug.Print vbLf; "-- Center:": AlignCols Split(Text, vbLf), vbCenter + Debug.Print vbLf; "-- Right:": AlignCols Split(Text, vbLf), vbRightJustify +End Sub diff --git a/Task/Anagrams-Deranged-anagrams/AWK/anagrams-deranged-anagrams.awk b/Task/Anagrams-Deranged-anagrams/AWK/anagrams-deranged-anagrams.awk new file mode 100644 index 0000000000..7208db492d --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/AWK/anagrams-deranged-anagrams.awk @@ -0,0 +1,59 @@ +#!/bin/gawk -f +BEGIN{ +FS="" +wordcount = 0 +maxlength = 0 + +} +# hash generates the sorted sequence of characters in a word, +# so that the hashes for a pair of anagrams will be the same. +# Example: hash meat = aemt and hash team = aemt +function hash(myword, i,letters,myhash){ + split(myword,letters,"") + asort(letters) + for (i=1;i<=length(myword);i++) myhash=myhash letters[i] + return myhash +} +# deranged checks two anagrems for derangement +function deranged(worda, wordb, a,b,i,n,len){ + n=0 + len=split(worda,a,"") + split(wordb,b,"") + for (i=len; i>=1; i--){ + if (a[i] == b[i]) n = n+1 + } + return n==0 +} + +# field separator null makes gawk split input record character by character. +# the split function works the same way +{ + wordcount = wordcount + 1 + fullword[wordcount]=$0 + bylength[length($0)]=bylength[length($0)] wordcount "|" + if (length($0) > maxlength) maxlength = length($0) +} + +END{ + for (len=maxlength; len>1; len--){ + numwords=split(bylength[len],words,"|") + split("",hashed) + split("",anagrams) + for (i=1;i<=numwords;i++){ +# make lists of anagrams in hashed + myword = fullword[words[i]] + myhash = hash(myword) + hashed[myhash] = hashed[myhash] myword " " + } +# check anagrams for derangement + for (myhash in hashed){ + n = split(hashed[myhash],anagrams," ") + for (i=1; i< n; i++) + for (j=i+1; j<=n; j++){ + if(deranged(anagrams[i],anagrams[j])) found = found anagrams[i] " " anagrams[j] " " + } + } + if (length(found) > 0 ) print "deranged: " found + if (length(found) > 0) exit + } +} diff --git a/Task/Anagrams-Deranged-anagrams/Clojure/anagrams-deranged-anagrams.clj b/Task/Anagrams-Deranged-anagrams/Clojure/anagrams-deranged-anagrams.clj index 6b01637d5d..c18a3bee23 100644 --- a/Task/Anagrams-Deranged-anagrams/Clojure/anagrams-deranged-anagrams.clj +++ b/Task/Anagrams-Deranged-anagrams/Clojure/anagrams-deranged-anagrams.clj @@ -1,5 +1,9 @@ -(let - [words (re-seq #"\w+" (slurp "unixdict.txt")) - anagrams (filter second (vals (group-by sort words))) - deranged (remove #(some true? (apply map = %)) anagrams)] - (prn (last (sort-by #(count (first %)) deranged)))) +(->> (slurp "unixdict.txt") ; words + (re-seq #"\w+") ; | + (group-by sort) ; anagrams + vals ; | + (filter second) ; | + (remove #(some true? (apply map = %))) ; deranged + (sort-by #(count (first %))) + last + prn) diff --git a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d index 34eed5b85d..220781f947 100644 --- a/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d +++ b/Task/Anagrams-Deranged-anagrams/D/anagrams-deranged-anagrams-3.d @@ -1,17 +1,20 @@ import std.stdio, std.file, std.algorithm, std.string, std.array, std.functional, std.exception; -string[2][] findDeranged(in string[] words) pure nothrow { - // return words.pairwise.filter!(ww => ww[].equal!q{ a != b }); +string[2][] findDeranged(in string[] words) pure nothrow /*@safe*/ { + // return words + // .map!representation + // .pairwise + // .filter!(ww => ww[].equal!q{ a != b }); typeof(return) result; - foreach (immutable i, w1; words) - foreach (w2; words[i + 1 .. $]) + foreach (immutable i, immutable w1; words) + foreach (immutable w2; words[i + 1 .. $]) if (w1.representation.equal!q{ a != b }(w2.representation)) result ~= [w1, w2]; return result; } -void main() { +void main() /*@safe*/ { Appender!(string[])[30] wClasses; foreach (const w; "unixdict.txt".readText.splitter) wClasses[$ - w.length] ~= w; @@ -19,7 +22,7 @@ void main() { foreach (const ws; wClasses[].map!q{ a.data }.filter!(not!empty)) { string[][const ubyte[]] anags; // Assume ASCII input. foreach (immutable w; ws) - anags[w.dup.representation.sort().release.assumeUnique]~= w; + anags[w.dup.representation.sort().release.assumeUnique] ~= w; auto pairs = anags.byValue.map!findDeranged.joiner; if (!pairs.empty) return writefln("Longest deranged: %-(%s %)", pairs.front); diff --git a/Task/Anagrams-Deranged-anagrams/Groovy/anagrams-deranged-anagrams.groovy b/Task/Anagrams-Deranged-anagrams/Groovy/anagrams-deranged-anagrams.groovy new file mode 100644 index 0000000000..1d2558404e --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/Groovy/anagrams-deranged-anagrams.groovy @@ -0,0 +1,29 @@ +def map = new TreeMap>>() + +new URL('http://www.puzzlers.org/pub/wordlists/unixdict.txt').eachLine { word -> + def size = - word.size() + map[size] = map[size] ?: new TreeMap>() + def norm = word.toList().sort().sum() + map[size][norm] = map[size][norm] ?: [] + map[size][norm] << word +} + +def result = map.findResult { negasize, normMap -> + def size = - negasize + normMap.findResults { x, anagrams -> + def n = anagrams.size() + (0..<(n-1)).findResults { i -> + ((i+1).. + (0.. anagrams[i][k] != anagrams[j][k] } \ + ? anagrams[i,j] + : null + } + }?.flatten() ?: null + }?.flatten() ?: null +} + +if (result) { + println "Longest deranged anagram pair: ${result}" +} else { + println 'Deranged anagrams are a MYTH!' +} diff --git a/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb b/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb index d256ecc19d..9de29cf66d 100644 --- a/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb +++ b/Task/Anagrams-Deranged-anagrams/Ruby/anagrams-deranged-anagrams.rb @@ -1,27 +1,22 @@ -require 'open-uri' -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 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.combination(2) {|a,b| return a,b if deranged?(a,b)} nil end +require 'open-uri' +anagram = open('http://www.puzzlers.org/pub/wordlists/unixdict.txt') do |f| + f.read.split.group_by {|s| s.each_char.sort} +end + anagram = anagram.select{|k,list| list.size>1}.sort_by{|k,list| -k.size} anagram.each do |k,list| - derangements = find_derangements(list) - if derangements - puts "derangement with longest word size: #{derangements}" + if derangements = find_derangements(list) + puts "Longest derangement anagram: #{derangements}" break end end diff --git a/Task/Anagrams-Deranged-anagrams/UNIX-Shell/anagrams-deranged-anagrams.sh b/Task/Anagrams-Deranged-anagrams/UNIX-Shell/anagrams-deranged-anagrams.sh new file mode 100644 index 0000000000..e02c799752 --- /dev/null +++ b/Task/Anagrams-Deranged-anagrams/UNIX-Shell/anagrams-deranged-anagrams.sh @@ -0,0 +1,47 @@ +function get_words { + typeset host=www.puzzlers.org + typeset page=/pub/wordlists/unixdict.txt + exec 7<>/dev/tcp/$host/80 + print -e -u7 "GET $page HTTP/1.1\r\nhost: $host\r\nConnection: close\r\n\r\n" + # remove the http header and save the word list + sed 's/\r$//; 1,/^$/d' <&7 >"$1" + exec 7<&- +} + +function is_deranged { + typeset -i i + for ((i=0; i<${#1}; i++)); do + [[ ${1:i:1} == ${2:i:1} ]] && return 1 + done + return 0 +} + +function word2key { + typeset -a chars=( $( + for ((i=0; i<${#word}; i++)); do + echo "${word:i:1}" + done | sort + ) ) + typeset IFS="" + echo "${chars[*]}" +} + +[[ -f word.list ]] || get_words word.list + +typeset -A words +typeset -i max=0 + +while IFS= read -r word; do + key=$(word2key $word) + if [[ -z "${words["$key"]}" ]]; then + words["$key"]=$word + else + if (( ${#word} > max )); then + if is_deranged "${words["$key"]}" "$word"; then + max_deranged=("${words["$key"]}" "$word") + max=${#word} + fi + fi + fi +done ws.length == m)); + writefln("%(%-(%s %)\n%)", anags.byValue.filter!(ws => ws.length == m)); } diff --git a/Task/Anagrams/JavaScript/anagrams-1.js b/Task/Anagrams/JavaScript/anagrams-1.js new file mode 100644 index 0000000000..3a368ef1d2 --- /dev/null +++ b/Task/Anagrams/JavaScript/anagrams-1.js @@ -0,0 +1,23 @@ +var fs = require('fs'); +var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n'); + +var i, item, max = 0, + anagrams = {}; + +for (i = 0; i < words.length; i += 1) { + var key = words[i].split('').sort().join(''); + if (!anagrams.hasOwnProperty(key)) {//check if property exists on current obj only + anagrams[key] = []; + } + var count = anagrams[key].push(words[i]); //push returns new array length + max = Math.max(count, max); +} + +//note, this returns all arrays that match the maximum length +for (item in anagrams) { + if (anagrams.hasOwnProperty(item)) {//check if property exists on current obj only + if (anagrams[item].length === max) { + console.log(anagrams[item].join(' ')); + } + } +} diff --git a/Task/Anagrams/JavaScript/anagrams-2.js b/Task/Anagrams/JavaScript/anagrams-2.js new file mode 100644 index 0000000000..81974ecdff --- /dev/null +++ b/Task/Anagrams/JavaScript/anagrams-2.js @@ -0,0 +1,22 @@ +var fs = require('fs'); +var dictionary = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n'); + +//group anagrams +var sortedDict = dictionary.reduce(function (acc, word) { + var sortedLetters = word.split('').sort().join(''); + if (acc[sortedLetters] === undefined) { acc[sortedLetters] = []; } + acc[sortedLetters].push(word); + return acc; +}, {}); + +//sort list by frequency +var keysSortedByFrequency = Object.keys(sortedDict).sort(function (keyA, keyB) { + if (sortedDict[keyA].length < sortedDict[keyB].length) { return 1; } + if (sortedDict[keyA].length > sortedDict[keyB].length) { return -1; } + return 0; +}); + +//print first 10 anagrams by frequency +keysSortedByFrequency.slice(0, 10).forEach(function (key) { + console.log(sortedDict[key].join(' ')); +}); diff --git a/Task/Anagrams/JavaScript/anagrams.js b/Task/Anagrams/JavaScript/anagrams.js deleted file mode 100644 index 25f2b6ed2b..0000000000 --- a/Task/Anagrams/JavaScript/anagrams.js +++ /dev/null @@ -1,20 +0,0 @@ -var fs = require('fs'); - -var anas = {}; -var words = fs.readFileSync('unixdict.txt', 'UTF-8').split('\n'); -var max = 0; - -for (var w in words) { - var key = words[w].split('').sort().join(''); - if (!(key in anas)) { - anas[key] = []; - } - var count = anas[key].push(words[w]); - max = Math.max(count, max); -} - -for (var a in anas) { - if (anas[a].length === max) { - console.log(anas[a]); - } -} diff --git a/Task/Anagrams/Objeck/anagrams.objeck b/Task/Anagrams/Objeck/anagrams.objeck index bea692b02c..e6c8c84a18 100644 --- a/Task/Anagrams/Objeck/anagrams.objeck +++ b/Task/Anagrams/Objeck/anagrams.objeck @@ -4,11 +4,11 @@ use Collection; class Anagrams { function : Main(args : String[]) ~ Nil { lines := HttpClient->New()->Get("http://www.puzzlers.org/pub/wordlists/unixdict.txt"); + anagrams := StringMap->New(); + count := 0; 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()); @@ -18,12 +18,13 @@ class Anagrams { anagrams->Insert(key, list); }; list->AddBack(word); + count := count->Max(list->Size()); }; lists := anagrams->GetValues(); each(i : lists) { list := lists->Get(i)->As(Vector); - if(list->Size() > 1) { + if(list->Size() >= count) { '['->Print(); each(j : list) { list->Get(j)->As(String)->Print(); diff --git a/Task/Anagrams/Python/anagrams-2.py b/Task/Anagrams/Python/anagrams-2.py index ce3e8422c7..0a7705f4f0 100644 --- a/Task/Anagrams/Python/anagrams-2.py +++ b/Task/Anagrams/Python/anagrams-2.py @@ -1,14 +1,25 @@ -import urllib.request, itertools -import time -words = urllib.request.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() -print('Words ready') -t0 = time.clock() -anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)] -anagrams.sort(key=len, reverse=True) -count = len(anagrams[0]) -for ana in anagrams: - if len(ana) < count: - break - print(ana) -t0 -= time.clock() -print('Finished in %f s' % -t0) +>>> import urllib +>>> from collections import defaultdict +>>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() +>>> len(words) +25104 +>>> anagram = defaultdict(list) # map sorted chars to anagrams +>>> for word in words: + anagram[tuple(sorted(word))].append( word ) + + +>>> count = max(len(ana) for ana in anagram.itervalues()) +>>> for ana in anagram.itervalues(): + if len(ana) >= count: + print ana + + +['angel', 'angle', 'galen', 'glean', 'lange'] +['alger', 'glare', 'lager', 'large', 'regal'] +['caret', 'carte', 'cater', 'crate', 'trace'] +['evil', 'levi', 'live', 'veil', 'vile'] +['elan', 'lane', 'lean', 'lena', 'neal'] +['abel', 'able', 'bale', 'bela', 'elba'] +>>> count +5 +>>> diff --git a/Task/Anagrams/Python/anagrams-3.py b/Task/Anagrams/Python/anagrams-3.py index 0a7705f4f0..fc284a8617 100644 --- a/Task/Anagrams/Python/anagrams-3.py +++ b/Task/Anagrams/Python/anagrams-3.py @@ -1,25 +1,22 @@ ->>> import urllib ->>> from collections import defaultdict +>>> import urllib, itertools >>> words = urllib.urlopen('http://www.puzzlers.org/pub/wordlists/unixdict.txt').read().split() >>> len(words) 25104 ->>> anagram = defaultdict(list) # map sorted chars to anagrams ->>> for word in words: - anagram[tuple(sorted(word))].append( word ) +>>> anagrams = [list(g) for k,g in itertools.groupby(sorted(words, key=sorted), key=sorted)] - ->>> count = max(len(ana) for ana in anagram.itervalues()) ->>> for ana in anagram.itervalues(): + +>>> count = max(len(ana) for ana in anagrams) +>>> for ana in anagrams: if len(ana) >= count: print ana +['abel', 'able', 'bale', 'bela', 'elba'] +['caret', 'carte', 'cater', 'crate', 'trace'] ['angel', 'angle', 'galen', 'glean', 'lange'] ['alger', 'glare', 'lager', 'large', 'regal'] -['caret', 'carte', 'cater', 'crate', 'trace'] -['evil', 'levi', 'live', 'veil', 'vile'] ['elan', 'lane', 'lean', 'lena', 'neal'] -['abel', 'able', 'bale', 'bela', 'elba'] +['evil', 'levi', 'live', 'veil', 'vile'] >>> count 5 >>> diff --git a/Task/Anagrams/RapidQ/anagrams.rapidq b/Task/Anagrams/RapidQ/anagrams.rapidq new file mode 100644 index 0000000000..942e190b52 --- /dev/null +++ b/Task/Anagrams/RapidQ/anagrams.rapidq @@ -0,0 +1,63 @@ +dim x as integer, y as integer +dim SortX as integer +dim StrOutPut as string +dim Count as integer +dim MaxCount as integer + +dim AnaList as QStringlist +dim wordlist as QStringlist +dim Templist as QStringlist +dim Charlist as Qstringlist + + +function sortChars(expr as string) as string + Charlist.clear + for SortX = 1 to len(expr) + Charlist.AddItems expr[SortX] + next + charlist.sort + result = Charlist.text - chr$(10) - chr$(13) +end function + +'--- Start main code + wordlist.loadfromfile ("unixdict.txt") + + 'create anagram list + for x = 0 to wordlist.itemcount-1 + AnaList.AddItems sortChars(wordlist.item(x)) + next + + 'Filter largest anagram lists + analist.sort + MaxCount = 0 + + for x = 0 to AnaList.Itemcount-1 + Count = 0 + for y = x+1 to AnaList.Itemcount-1 + if AnaList.item(y) = AnaList.item(x) then + inc(count) + else + if count > MaxCount then + Templist.clear + MaxCount = Count + Templist.AddItems AnaList.item(x) + elseif count = MaxCount then + Templist.AddItems AnaList.item(x) + end if + exit for + end if + next + next + + 'Now get the words + for x = 0 to Templist.Itemcount-1 + for y = 0 to wordlist.Itemcount-1 + if Templist.item(x) = sortChars(wordlist.item(y)) then + StrOutPut = StrOutPut + wordlist.item(y) + " " + end if + next + StrOutPut = StrOutPut + chr$(13) + chr$(10) + next + +ShowMessage StrOutPut +End diff --git a/Task/Anagrams/Rust/anagrams.rust b/Task/Anagrams/Rust/anagrams.rust index a14b29d754..e323f34020 100644 --- a/Task/Anagrams/Rust/anagrams.rust +++ b/Task/Anagrams/Rust/anagrams.rust @@ -1,39 +1,27 @@ -extern crate collections; - -use std::str; -use collections::HashMap; +use std::collections::hashmap::{HashMap, Occupied, Vacant}; use std::io::File; use std::io::BufferedReader; use std::cmp; -fn sort_string(string: &str) -> ~str { - let mut chars = string.chars().to_owned_vec(); +fn sort_string(string: &str) -> String { + let mut chars = string.chars().collect::>(); chars.sort(); - str::from_chars(chars) + String::from_chars(chars.as_slice()) } fn main () { let path = Path::new("unixdict.txt"); let mut file = BufferedReader::new(File::open(&path)); - - let mut map: HashMap<~str, ~[~str]> = HashMap::new(); - - for line in file.lines() { - let s = line.trim().to_owned(); - map.mangle(sort_string(s.clone()), s, - |_k, v| ~[v], - |_k, v, string| v.push(string) - ); - } - - let max_length = map.iter().fold(0, |s, (_k, v)| cmp::max(s, v.len())); - - for (_k, v) in map.iter() { - if v.len() == max_length { - for s in v.iter() { - print!("{} ", *s) - } - println!("") + let mut map = HashMap::new(); + for line in file.lines().map(|s| s.unwrap()) { + let s = line.as_slice().trim(); + match map.entry(sort_string(s)) { + Vacant(entry) => { entry.set(vec![s.into_string()]); }, + Occupied(mut entry) => { entry.get_mut().push(s.into_string()); } } } + let max_length = map.values().fold(0, |s, v| cmp::max(s, v.len())); + for v in map.values().filter(|&v| v.len() == max_length) { + println!("{}", v.connect(" ")) + } } diff --git a/Task/Anagrams/UNIX-Shell/anagrams.sh b/Task/Anagrams/UNIX-Shell/anagrams.sh new file mode 100644 index 0000000000..d9a0f67802 --- /dev/null +++ b/Task/Anagrams/UNIX-Shell/anagrams.sh @@ -0,0 +1,36 @@ +http_get_body() { + local host=$1 + local uri=$2 + exec 5<> /dev/tcp/$host/80 + printf >&5 "%s\r\n" "GET $uri HTTP/1.1" "Host: $host" "Connection: close" "" + mapfile -t -u5 + local lines=( "${MAPFILE[@]//$'\r'}" ) + local i=0 found=0 + for (( ; found == 0; i++ )); do + [[ -z ${lines[i]} ]] && (( found++ )) + done + printf "%s\n" "${lines[@]:i}" + exec 5>&- +} + +declare -A wordlist + +while read -r word; do + uniq_letters=( $(for ((i=0; i<${#word}; i++)); do echo "${word:i:1}"; done | sort) ) + wordlist["${uniq_letters[*]}"]+="$word " +done < <( http_get_body www.puzzlers.org /pub/wordlists/unixdict.txt ) + +maxlen=0 +maxwords=() + +for key in "${!wordlist[@]}"; do + words=( ${wordlist[$key]} ) + if (( ${#words[@]} > maxlen )); then + maxlen=${#words[@]} + maxwords=( "${wordlist["$key"]}" ) + elif (( ${#words[@]} == maxlen )); then + maxwords+=( "${wordlist[$key]}" ) + fi +done + +printf "%s\n" "${maxwords[@]}" diff --git a/Task/Animate-a-pendulum/00DESCRIPTION b/Task/Animate-a-pendulum/00DESCRIPTION index 75f411c684..611e094421 100644 --- a/Task/Animate-a-pendulum/00DESCRIPTION +++ b/Task/Animate-a-pendulum/00DESCRIPTION @@ -1,3 +1,4 @@ -One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. The classic such physical system is a [[wp:Pendulum|simple gravity pendulum]]. +One good way of making an animation is by simulating a physical system and illustrating the variables in that system using a dynamically changing graphical display. +The classic such physical system is a [[wp:Pendulum|simple gravity pendulum]]. For this task, create a simple physical model of a pendulum and animate it. diff --git a/Task/Animate-a-pendulum/Common-Lisp/animate-a-pendulum.lisp b/Task/Animate-a-pendulum/Common-Lisp/animate-a-pendulum.lisp new file mode 100644 index 0000000000..aa0ba29b41 --- /dev/null +++ b/Task/Animate-a-pendulum/Common-Lisp/animate-a-pendulum.lisp @@ -0,0 +1,45 @@ +(defvar *frame-rate* 30) +(defvar *damping* 0.99 "Deceleration factor.") + +(defun make-pendulum (length theta0 x) + "Returns an anonymous function with enclosed state representing a pendulum." + (let* ((theta (* (/ theta0 180) pi)) + (acceleration 0)) + (if (< length 40) (setf length 40)) ;;avoid a divide-by-zero + (lambda () + ;;Draws the pendulum, updating its location and speed. + (sdl:draw-line (sdl:point :x x :y 1) + (sdl:point :x (+ (* (sin theta) length) x) + :y (* (cos theta) length))) + (sdl:draw-filled-circle (sdl:point :x (+ (* (sin theta) length) x) + :y (* (cos theta) length)) + 20 + :color sdl:*yellow* + :stroke-color sdl:*white*) + ;;The magic constant approximates the speed we want for a given frame-rate. + (incf acceleration (* (sin theta) (* *frame-rate* -0.001))) + (incf theta acceleration) + (setf acceleration (* acceleration *damping*))))) + + +(defun main (&optional (w 640) (h 480)) + (sdl:with-init () + (sdl:window w h :title-caption "Pendulums" + :fps (make-instance 'sdl:fps-fixed)) + (setf (sdl:frame-rate) *frame-rate*) + (let ((pendulums nil)) + (sdl:with-events () + (:quit-event () t) + (:idle () + (sdl:clear-display sdl:*black*) + (mapcar #'funcall pendulums) ;;Draw all the pendulums + + (sdl:update-display)) + (:key-down-event (:key key) + (cond ((sdl:key= key :sdl-key-escape) + (sdl:push-quit-event)) + ((sdl:key= key :sdl-key-space) + (push (make-pendulum (random (- h 100)) + (random 90) + (round w 2)) + pendulums)))))))) diff --git a/Task/Animate-a-pendulum/Fortran/animate-a-pendulum.f b/Task/Animate-a-pendulum/Fortran/animate-a-pendulum.f new file mode 100644 index 0000000000..035fabcff2 --- /dev/null +++ b/Task/Animate-a-pendulum/Fortran/animate-a-pendulum.f @@ -0,0 +1,74 @@ +!Implemented by Anant Dixit (October, 2014) +program animated_pendulum +implicit none +double precision, parameter :: pi = 4.0D0*atan(1.0D0), l = 1.0D-1, dt = 1.0D-2, g = 9.8D0 +integer :: io +double precision :: s_ang, c_ang, p_ang, n_ang + +write(*,*) 'Enter starting angle (in degrees):' +do + read(*,*,iostat=io) s_ang + if(io.ne.0 .or. s_ang.lt.-90.0D0 .or. s_ang.gt.90.0D0) then + write(*,*) 'Please enter an angle between 90 and -90 degrees:' + else + exit + end if +end do +call system('clear') + +c_ang = s_ang*pi/180.0D0 +p_ang = c_ang + +call display(c_ang) +do + call next_time_step(c_ang,p_ang,g,l,dt,n_ang) + if(abs(c_ang-p_ang).ge.0.05D0) then + call system('clear') + call display(c_ang) + end if +end do +end program + +subroutine next_time_step(c_ang,p_ang,g,l,dt,n_ang) +double precision :: c_ang, p_ang, g, l, dt, n_ang +n_ang = (-g*sin(c_ang)/l)*2.0D0*dt**2 + 2.0D0*c_ang - p_ang +p_ang = c_ang +c_ang = n_ang +end subroutine + +subroutine display(c_ang) +double precision :: c_ang +character (len=*), parameter :: cfmt = '(A1)' +double precision :: rx, ry +integer :: x, y, i, j +rx = 45.0D0*sin(c_ang) +ry = 22.5D0*cos(c_ang) +x = int(rx)+51 +y = int(ry)+2 +do i = 1,32 + do j = 1,100 + if(i.eq.y .and. j.eq.x) then + write(*,cfmt,advance='no') 'O' + else if(i.eq.y .and. (j.eq.(x-1).or.j.eq.(x+1))) then + write(*,cfmt,advance='no') 'G' + else if(j.eq.x .and. (i.eq.(y-1).or.i.eq.(y+1))) then + write(*,cfmt,advance='no') 'G' + else if(i.eq.y .and. (j.eq.(x-2).or.j.eq.(x+2))) then + write(*,cfmt,advance='no') '#' + else if(j.eq.x .and. (i.eq.(y-2).or.i.eq.(y+2))) then + write(*,cfmt,advance='no') 'G' + else if((i.eq.(y+1).and.j.eq.(x+1)) .or. (i.eq.(y-1).and.j.eq.(x-1))) then + write(*,cfmt,advance='no') '#' + else if((i.eq.(y+1).and.j.eq.(x-1)) .or. (i.eq.(y-1).and.j.eq.(x+1))) then + write(*,cfmt,advance='no') '#' + else if(j.eq.50) then + write(*,cfmt,advance='no') '|' + else if(i.eq.2) then + write(*,cfmt,advance='no') '-' + else + write(*,cfmt,advance='no') ' ' + end if + end do + write(*,*) +end do +end subroutine diff --git a/Task/Animate-a-pendulum/J/animate-a-pendulum.j b/Task/Animate-a-pendulum/J/animate-a-pendulum-1.j similarity index 94% rename from Task/Animate-a-pendulum/J/animate-a-pendulum.j rename to Task/Animate-a-pendulum/J/animate-a-pendulum-1.j index 6d87485676..a9924abb88 100644 --- a/Task/Animate-a-pendulum/J/animate-a-pendulum.j +++ b/Task/Animate-a-pendulum/J/animate-a-pendulum-1.j @@ -2,7 +2,7 @@ require 'gl2 trig' coinsert 'jgl2' DT =: %30 NB. seconds -ANGLE=: 0.25p1 NB. radians +ANGLE=: 0.45p1 NB. radians L =: 1 NB. metres G =: 9.80665 NB. ms_2 VEL =: 0 NB. ms_1 @@ -33,8 +33,7 @@ drawPendulum=: verb define width=. {. glqwh'' ps=. (-: width) , 40 pe=. ps + 280 <.@* (cos , sin) 0.5p1 + y NB. adjust orientation - glrgb 91 91 91 - glbrush'' + glbrush glrgb 91 91 91 gllines ps , pe glellipse (,~ ps - -:) 40 15 glellipse (,~ pe - -:) 20 20 diff --git a/Task/Animate-a-pendulum/J/animate-a-pendulum-2.j b/Task/Animate-a-pendulum/J/animate-a-pendulum-2.j new file mode 100644 index 0000000000..574502bc96 --- /dev/null +++ b/Task/Animate-a-pendulum/J/animate-a-pendulum-2.j @@ -0,0 +1,52 @@ +require 'gl2 trig' +coinsert 'jgl2' + +DT =: %30 NB. seconds +ANGLE=: 0.45p1 NB. radians +L =: 1 NB. metres +G =: 9.80665 NB. ms_2 +VEL =: 0 NB. ms_1 + +PEND=: noun define +pc pend;pn "Pendulum"; +minwh 320 200; cc isi isigraph type flush; +) + +pend_run=: verb define + wd PEND,'pshow' + wd 'timer ',":DT * 1000 +) + +pend_close=: verb define + wd 'timer 0; pclose' +) + +sys_timer_z_=: verb define + recalcAngle_base_ '' + wd 'psel pend; set isi invalid' +) + +pend_isi_paint=: verb define + drawPendulum ANGLE +) + +recalcAngle=: verb define + accel=. - (G % L) * sin ANGLE + VEL =: VEL + accel * DT + ANGLE=: ANGLE + VEL * DT +) + +drawPendulum=: verb define + width=. {. glqwh'' + ps=. (-: width) , 20 + pe=. ps + 150 <.@* (cos , sin) 0.5p1 + y NB. adjust orientation + glclear'' + glbrush glrgb 91 91 91 NB. gray + gllines ps , pe + glellipse (,~ ps - -:) 40 15 + glrect 0 0, width, 20 + glbrush glrgb 255 255 0 NB. yellow + glellipse (,~ pe - -:) 15 15 NB. orb +) + +pend_run'' diff --git a/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala b/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala index 292f77aa72..1d4bd3ba7c 100644 --- a/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala +++ b/Task/Animate-a-pendulum/Scala/animate-a-pendulum.scala @@ -1,33 +1,26 @@ -import scala.swing._ -import scala.swing.Swing._ -import scala.actors._ -import scala.actors.Actor._ - -import java.awt.{Color, Graphics} +import java.awt.Color +import scala.actors.Actor +import scala.swing.{ Graphics2D, MainFrame, Panel, SimpleSwingApplication } +import scala.swing.Swing.pair2Dimension object Pendulum extends SimpleSwingApplication { - - val length = 100 - - val prefSizeX = 2*length+50 - val prefSizeY = length/2*3 + val length = 100 lazy val ui = new Panel { - import math._ + import scala.math.{ cos, Pi, sin } background = Color.white - preferredSize = (prefSizeX, prefSizeY) + preferredSize = (2 * length + 50, length / 2 * 3) peer.setDoubleBuffered(true) - var angle: Double = Pi/2; + var angle: Double = Pi / 2 def pendular = new Actor { - var angleAccel, angleVelocity = 0.0; - var dt = 0.1 + var angleVelocity = 0.0 + val dt = 0.1 def act() { while (true) { - angleAccel = -9.81 / length * sin(angle) - angleVelocity += angleAccel * dt + angleVelocity += (-9.81 / length * sin(angle)) * dt angle += angleVelocity * dt repaint() Thread.sleep(15) @@ -38,14 +31,11 @@ object Pendulum extends SimpleSwingApplication { override def paintComponent(g: Graphics2D) = { super.paintComponent(g) - g.setColor(Color.white); - g.fillRect(0, 0, size.width, size.height); - val anchorX = size.width / 2 - val anchorY = size.height / 4 - val ballX = anchorX + (sin(angle) * length).toInt - val ballY = anchorY + (cos(angle) * length).toInt + val (anchorX, anchorY) = (size.width / 2, size.height / 4) + val (ballX, ballY) = + (anchorX + (sin(angle) * length).toInt, anchorY + (cos(angle) * length).toInt) g.setColor(Color.lightGray) - g.drawLine(anchorX-2*length, anchorY, anchorX+2*length, anchorY) + g.drawLine(anchorX - 2 * length, anchorY, anchorX + 2 * length, anchorY) g.setColor(Color.black) g.drawLine(anchorX, anchorY, ballX, ballY) g.fillOval(anchorX - 3, anchorY - 4, 7, 7) @@ -58,7 +48,7 @@ object Pendulum extends SimpleSwingApplication { def top = new MainFrame { title = "Rosetta Code >>> Task: Animate a pendulum | Language: Scala" contents = ui + centerOnScreen ui.pendular.start } - } diff --git a/Task/Animation/00DESCRIPTION b/Task/Animation/00DESCRIPTION index 732d4e8cea..ae07b2fd12 100644 --- a/Task/Animation/00DESCRIPTION +++ b/Task/Animation/00DESCRIPTION @@ -1,3 +1,3 @@ -Animation is the foundation of a great many parts of graphical user interfaces, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this. +'''Animation''' is integral to many parts of [[GUI]]s, including both the fancy effects when things change used in window managers, and of course games. The core of any animation system is a scheme for periodically changing the display while still remaining responsive to the user. This task demonstrates this. Create a window containing the string "Hello World! " (the trailing space is significant). Make the text appear to be rotating right by periodically removing one letter from the end of the string and attaching it to the front. When the user clicks on the text, it should reverse its direction. diff --git a/Task/Animation/MAXScript/animation.max b/Task/Animation/MAXScript/animation.max new file mode 100644 index 0000000000..b4a5957446 --- /dev/null +++ b/Task/Animation/MAXScript/animation.max @@ -0,0 +1,47 @@ +try destroydialog animGUI catch () + +global userDirection = "right" + +fn reverseStr str: direction: = +( + local lastChar = str[str.count] + local firstChar = str[1] + local newStr = "" + local dir + + if direction == unsupplied then dir = "left" else dir = direction + + case dir of + ( + "right": (newstr = lastChar + (substring str 1 (str.count-1))) + "left": (newstr = (substring str 2 (str.count))+firstChar) + ) + + return newstr +) + +rollout animGUI "Hello World" width:200 +( + button switchToLeft "<--" pos:[40,0] height:15 + label HelloWorldLabel "Hello World! " pos:[80,0] + button switchToRight "-->" pos:[150,0] height:15 + + timer activeTimer interval:70 active:true + + on activeTimer tick do + ( + HelloWorldLabel.text = reverseStr str:(HelloWorldLabel.text) direction:userDirection + ) + + on switchToLeft pressed do + ( + userDirection = "left" + ) + + on switchToRight pressed do + ( + userDirection = "right" + ) +) + +createdialog animGUI diff --git a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp index 390f5351d1..e324d05129 100644 --- a/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp +++ b/Task/Anonymous-recursion/Common-Lisp/anonymous-recursion-3.lisp @@ -2,8 +2,8 @@ "Fibonacci sequence function." (if (< number 0) (error "Error. The number entered: ~A is negative" number) - (labels ((fib1 (n a b) + (labels ((fib (n a b) (if (= n 0) a - (fib1 (- n 1) b (+ a b))))) - (fib1 number 0 1)))) + (fib (- n 1) b (+ a b))))) + (fib number 0 1)))) diff --git a/Task/Anonymous-recursion/D/anonymous-recursion-1.d b/Task/Anonymous-recursion/D/anonymous-recursion-1.d index 544c0926b6..c82ec2c5ff 100644 --- a/Task/Anonymous-recursion/D/anonymous-recursion-1.d +++ b/Task/Anonymous-recursion/D/anonymous-recursion-1.d @@ -1,14 +1,14 @@ -import std.stdio, std.exception; +int fib(in uint arg) pure nothrow @safe @nogc { + assert(arg >= 0); -int fib(int arg) pure { - enforce(arg >= 0); - - return function int (int n) pure nothrow { - auto self = __traits(parent, {}); + return function uint(in uint n) pure nothrow @safe @nogc { + static immutable self = &__traits(parent, {}); return (n < 2) ? n : self(n - 1) + self(n - 2); }(arg); } void main() { + import std.stdio; + 39.fib.writeln; } diff --git a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena index cb67970619..d662a8511a 100644 --- a/Task/Anonymous-recursion/Elena/anonymous-recursion.elena +++ b/Task/Anonymous-recursion/Elena/anonymous-recursion.elena @@ -10,11 +10,11 @@ #symbol program = [ - control from:-1 &to:10 &do: i + control forrange &int:-1 &int:10 &do: (&int:i) [ console << "fib(" << i << ")=". - console writeLine:(fibo:i) | onInvalidArgumentError: e + console writeLine:(fibo:i) | if &InvalidArgumentError: e [ console writeLine:"invalid". ]. diff --git a/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-1.pari b/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-1.pari new file mode 100644 index 0000000000..9eaa1db4f3 --- /dev/null +++ b/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-1.pari @@ -0,0 +1,4 @@ +Fib(n)={ + my(F=(k,f)->if(k<2,k,f(k-1,f)+f(k-2,f))); + if(n<0,(-1)^(n+1),1)*F(abs(n),F) +}; diff --git a/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-2.pari b/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-2.pari new file mode 100644 index 0000000000..cc32639b0f --- /dev/null +++ b/Task/Anonymous-recursion/PARI-GP/anonymous-recursion-2.pari @@ -0,0 +1,4 @@ +Fib(n)={ + my(F=k->my(f=self());if(k<2,k,f(k-1)+f(k-2))); + if(n<0,(-1)^(n+1),1)*F(abs(n)) +}; diff --git a/Task/Anonymous-recursion/PHP/anonymous-recursion-1.php b/Task/Anonymous-recursion/PHP/anonymous-recursion-1.php index 43246dc489..af1af2ccbd 100644 --- a/Task/Anonymous-recursion/PHP/anonymous-recursion-1.php +++ b/Task/Anonymous-recursion/PHP/anonymous-recursion-1.php @@ -2,12 +2,15 @@ function fib($n) { if ($n < 0) throw new Exception('Negative numbers not allowed'); - else if ($n < 2) - return 1; - else { - $f = __FUNCTION__; - return $f($n-1) + $f($n-2); - } + $f = function($n) { // This function must be called using call_user_func() only + if ($n < 2) + return 1; + else { + $g = debug_backtrace()[1]['args'][0]; + return call_user_func($g, $n-1) + call_user_func($g, $n-2); + } + }; + return call_user_func($f, $n); } echo fib(8), "\n"; ?> diff --git a/Task/Anonymous-recursion/Seed7/anonymous-recursion.seed7 b/Task/Anonymous-recursion/Seed7/anonymous-recursion.seed7 new file mode 100644 index 0000000000..b81b659abe --- /dev/null +++ b/Task/Anonymous-recursion/Seed7/anonymous-recursion.seed7 @@ -0,0 +1,32 @@ +$ include "seed7_05.s7i"; + +const func integer: fib (in integer: x) is func + result + var integer: fib is 0; + local + const func integer: fib1 (in integer: n) is func + result + var integer: fib1 is 0; + begin + if n < 2 then + fib1 := n; + else + fib1 := fib1(n-2) + fib1(n-1); + end if; + end func; + begin + if x < 0 then + raise RANGE_ERROR; + else + fib := fib1(x); + end if; + end func; + +const proc: main is func + local + var integer: i is 0; + begin + for i range 0 to 4 do + writeln(fib(i)); + end for; + end func; diff --git a/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-1.ml b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-1.ml new file mode 100644 index 0000000000..3ad8629c96 --- /dev/null +++ b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-1.ml @@ -0,0 +1,9 @@ +fun fix f x = f (fix f) x + +fun fib n = + if n < 0 then raise Fail "Negative" + else + fix (fn fib => + (fn 0 => 0 + | 1 => 1 + | n => fib (n-1) + fib (n-2))) n diff --git a/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-2.ml b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-2.ml new file mode 100644 index 0000000000..59691e5b39 --- /dev/null +++ b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-2.ml @@ -0,0 +1,11 @@ +fun fib n = + let + fun fib 0 = 0 + | fib 1 = 1 + | fib n = fib (n-1) + fib (n-2) + in + if n < 0 then + raise Fail "Negative" + else + fib n + end diff --git a/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-3.ml b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-3.ml new file mode 100644 index 0000000000..f86c55d31b --- /dev/null +++ b/Task/Anonymous-recursion/Standard-ML/anonymous-recursion-3.ml @@ -0,0 +1,6 @@ +fun fib 0 = 0 + | fib 1 = 1 + | fib n = fib (n-1) + fib (n-2) + +val fib = fn n => if n < 0 then raise Fail "Negative" + else fib n diff --git a/Task/Anonymous-recursion/TXR/anonymous-recursion.txr b/Task/Anonymous-recursion/TXR/anonymous-recursion.txr new file mode 100644 index 0000000000..32235b9fd7 --- /dev/null +++ b/Task/Anonymous-recursion/TXR/anonymous-recursion.txr @@ -0,0 +1,17 @@ +@(do + (defmacro recursive ((. parm-init-pairs) . body) + (let ((hidden-name (gensym "RECURSIVE-"))) + ^(macrolet ((recurse (. args) ^(,',hidden-name ,*args))) + (labels ((,hidden-name (,*[mapcar first parm-init-pairs]) ,*body)) + (,hidden-name ,*[mapcar second parm-init-pairs]))))) + + (defun fib (number) + (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)))))) + + (put-line `fib(10) = @(fib 10)`) + (put-line `fib(-1) = @(fib -1)`)) diff --git a/Task/Apply-a-callback-to-an-array/00DESCRIPTION b/Task/Apply-a-callback-to-an-array/00DESCRIPTION index 46105c5628..f292071326 100644 --- a/Task/Apply-a-callback-to-an-array/00DESCRIPTION +++ b/Task/Apply-a-callback-to-an-array/00DESCRIPTION @@ -1 +1,2 @@ -In this task, the goal is to take a combined set of elements and apply a function to each element. +In this task, the goal is to take a combined set of elements +and apply a function to each element. diff --git a/Task/Apply-a-callback-to-an-array/ACL2/apply-a-callback-to-an-array.acl2 b/Task/Apply-a-callback-to-an-array/ACL2/apply-a-callback-to-an-array.acl2 index 67dc40ae3a..64a1c032ed 100644 --- a/Task/Apply-a-callback-to-an-array/ACL2/apply-a-callback-to-an-array.acl2 +++ b/Task/Apply-a-callback-to-an-array/ACL2/apply-a-callback-to-an-array.acl2 @@ -1,5 +1,8 @@ -(defun sq-each (xs) +(defun apply-to-each (xs) (if (endp xs) nil - (cons (* (first xs) (first xs)) + (cons (fn-to-apply (first xs)) (sq-each (rest xs))))) + +(defun fn-to-apply (x) + (* x x)) diff --git a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime index 2c2299ebcb..15f9021028 100644 --- a/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime +++ b/Task/Apply-a-callback-to-an-array/Aime/apply-a-callback-to-an-array.aime @@ -5,7 +5,7 @@ map(list l, void (*fp) (object)) i = 0; while (i < l_length(l)) { - fp(l_query(l, i)); + fp(l[i]); i += 1; } } diff --git a/Task/Apply-a-callback-to-an-array/AppleScript/apply-a-callback-to-an-array.applescript b/Task/Apply-a-callback-to-an-array/AppleScript/apply-a-callback-to-an-array.applescript new file mode 100644 index 0000000000..855c9661ae --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/AppleScript/apply-a-callback-to-an-array.applescript @@ -0,0 +1,11 @@ +on callback for arg + -- Returns a string like "arc has 3 letters" + arg & " has " & (count arg) & " letters" +end callback + +set alist to {"arc", "be", "circle"} +repeat with aref in alist + -- Passes a reference to some item in alist + -- to callback, then speaks the return value. + say (callback for aref) +end repeat diff --git a/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-1.pb b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-1.pb new file mode 100644 index 0000000000..4e9cd2b5d5 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-1.pb @@ -0,0 +1,6 @@ +((main + { (1 1 2 3 5 8 13 21) dup + {double !} each + {%d ' ' . <<} each}) + +(double { dup 2 * set })) diff --git a/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-2.pb b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-2.pb new file mode 100644 index 0000000000..3723d68068 --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-2.pb @@ -0,0 +1,9 @@ +((main + { (1 1 2 3 5 8 13 21) + {double !} each + collect ! + {%d ' ' . <<} each}) + +(double { 2 * }) + +(collect { -1 take })) diff --git a/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb new file mode 100644 index 0000000000..959e3fdc9c --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Babel/apply-a-callback-to-an-array-3.pb @@ -0,0 +1,9 @@ +((main + { [val 1 1 2 3 5 8 13 21] + {double !} eachar + collect ! + {%d ' ' . <<} each}) + +(double { 2 * }) + +(collect { -1 take })) diff --git a/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat new file mode 100644 index 0000000000..ee2c7be23f --- /dev/null +++ b/Task/Apply-a-callback-to-an-array/Bracmat/apply-a-callback-to-an-array.bracmat @@ -0,0 +1,29 @@ +( ( callbackFunction1 + = location value + . !arg:(?location,?value) + & out$(str$(array[ !location "] = " !!value)) + ) +& ( callbackFunction2 + = location value + . !arg:(?location,?value) + & !!value^2:?!value + ) +& ( map + = arr len callback i + . !arg:(?arr,?len,?callback) + & 0:?i + & whl + ' ( !i: -P := new T - +P := new T where T is the type of an allocated object and P is a [[reference]] to the object. The storage pool chosen by the allocator can be determined by either: diff --git a/Task/Arena-storage-pool/Go/arena-storage-pool.go b/Task/Arena-storage-pool/Go/arena-storage-pool.go new file mode 100644 index 0000000000..75c0c99fc8 --- /dev/null +++ b/Task/Arena-storage-pool/Go/arena-storage-pool.go @@ -0,0 +1,56 @@ +package main + +import ( + "fmt" + "runtime" + "sync" +) + +// New to Go 1.3 are sync.Pools, basically goroutine-safe free lists. +// There is overhead in the goroutine-safety and if you do not need this +// you might do better by implementing your own free list. + +func main() { + // Task 1: Define a pool (of ints). Just as the task says, a sync.Pool + // allocates individually and can free as a group. + p := sync.Pool{New: func() interface{} { + fmt.Println("pool empty") + return new(int) + }} + // Task 2: Allocate some ints. + i := new(int) + j := new(int) + // Show that they're usable. + *i = 1 + *j = 2 + fmt.Println(*i + *j) // prints 3 + // Task 2 continued: Put allocated ints in pool p. + // Task explanation: Variable p has a pool as its value. Another pool + // could be be created and assigned to a different variable. You choose + // a pool simply by using the appropriate variable, p here. + p.Put(i) + p.Put(j) + // Drop references to i and j. This allows them to be garbage collected; + // that is, freed as a group. + i = nil + j = nil + // Get ints for i and j again, this time from the pool. P.Get may reuse + // an object allocated above as long as objects haven't been garbage + // collected yet; otherwise p.Get will allocate a new object. + i = p.Get().(*int) + j = p.Get().(*int) + *i = 4 + *j = 5 + fmt.Println(*i + *j) // prints 9 + // One more test, this time forcing a garbage collection. + p.Put(i) + p.Put(j) + i = nil + j = nil + runtime.GC() + i = p.Get().(*int) + j = p.Get().(*int) + *i = 7 + *j = 8 + fmt.Println(*i + *j) // prints 15 +} diff --git a/Task/Arithmetic-Complex/00DESCRIPTION b/Task/Arithmetic-Complex/00DESCRIPTION index 8451e12ddd..619526418f 100644 --- a/Task/Arithmetic-Complex/00DESCRIPTION +++ b/Task/Arithmetic-Complex/00DESCRIPTION @@ -1,4 +1,5 @@ -A '''[[wp:Complex number|complex number]]''' is a number which can be written as "a + b \times i" (sometimes shown as "b + a \times i") where a and b are real numbers and [[wp:Imaginary_unit|i is the square root of -1]]. Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by i. +A '''[[wp:Complex number|complex number]]''' is a number which can be written as "a + b \times i" (sometimes shown as "b + a \times i") where a and b are real numbers and [[wp:Imaginary_unit|i is the square root of -1]]. +Typically, complex numbers are represented as a pair of real numbers called the "imaginary part" and "real part", where the imaginary part is the number to be multiplied by i. * Show addition, multiplication, negation, and inversion of complex numbers in separate functions. (Subtraction and division operations can be made with pairs of these operations.) Print the results for each operation tested. * ''Optional:'' Show complex conjugation. By definition, the [[wp:complex conjugate|complex conjugate]] of a + bi is a - bi. diff --git a/Task/Arithmetic-Complex/Bracmat/arithmetic-complex.bracmat b/Task/Arithmetic-Complex/Bracmat/arithmetic-complex.bracmat new file mode 100644 index 0000000000..85ee88ffe1 --- /dev/null +++ b/Task/Arithmetic-Complex/Bracmat/arithmetic-complex.bracmat @@ -0,0 +1,28 @@ + (add=a b.!arg:(?a,?b)&!a+!b) +& ( multiply + = a b.!arg:(?a,?b)&1+!a*!b+-1 + ) +& (negate=.1+-1*!arg+-1) +& ( conjugate + = a b + . !arg:i&-i + | !arg:-i&i + | !arg:?a_?b&(conjugate$!a)_(conjugate$!b) + | !arg + ) +& ( invert + = conjugated + . conjugate$!arg:?conjugated + & multiply$(!arg,!conjugated)^-1*!conjugated + ) +& out$("(a+i*b)+(a+i*b) =" add$(a+i*b,a+i*b)) +& out$("(a+i*b)+(a+-i*b) =" add$(a+i*b,a+-i*b)) +& out$("(a+i*b)*(a+i*b) =" multiply$(a+i*b,a+i*b)) +& out$("(a+i*b)*(a+-i*b) =" multiply$(a+i*b,a+-i*b)) +& out$("-1*(a+i*b) =" negate$(a+i*b)) +& out$("-1*(a+-i*b) =" negate$(a+-i*b)) +& out$("sin$x = " sin$x) +& out$("conjugate sin$x =" conjugate$(sin$x)) +& out + $ ("sin$x minus conjugate sin$x =" sin$x+negate$(conjugate$(sin$x))) +& done; diff --git a/Task/Arithmetic-Complex/Clojure/arithmetic-complex.clj b/Task/Arithmetic-Complex/Clojure/arithmetic-complex.clj new file mode 100644 index 0000000000..c7fe70a40b --- /dev/null +++ b/Task/Arithmetic-Complex/Clojure/arithmetic-complex.clj @@ -0,0 +1,37 @@ +(ns rosettacode.arithmetic.cmplx + (:require [clojure.algo.generic.arithmetic :as ga]) + (:import [java.lang Number])) + +(defrecord Complex [^Number r ^Number i] + Object + (toString [{:keys [r i]}] + (apply str + (cond + (zero? r) [(if (= i 1) "" i) "i"] + (zero? i) [r] + :else [r (if (neg? i) "-" "+") i "i"])))) + +(defmethod ga/+ [Complex Complex] + [x y] (map->Complex (merge-with + x y))) + +(defmethod ga/+ [Complex Number] ; reals become y + 0i + [{:keys [r i]} y] (->Complex (+ r y) i)) + +(defmethod ga/- Complex + [x] (->> x vals (map -) (apply ->Complex))) + +(defmethod ga/* [Complex Complex] + [x y] (map->Complex (merge-with * x y))) + +(defmethod ga/* [Complex Number] + [{:keys [r i]} y] (->Complex (* r y) (* i y))) + +(ga/defmethod* ga / Complex + [x] (->> x vals (map /) (apply ->Complex))) + +(defn conj [^Complex {:keys [r i]}] + (->Complex r (- i))) + +(defn inv [^Complex {:keys [r i]}] + (let [m (+ (* r r) (* i i))] + (->Complex (/ r m) (- (/ i m))))) diff --git a/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex.coffee b/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex.coffee new file mode 100644 index 0000000000..66c7b3b817 --- /dev/null +++ b/Task/Arithmetic-Complex/CoffeeScript/arithmetic-complex.coffee @@ -0,0 +1,60 @@ +# create an immutable Complex type +class Complex + constructor: (@r=0, @i=0) -> + @magnitude = @r*@r + @i*@i + + plus: (c2) -> + new Complex( + @r + c2.r, + @i + c2.i + ) + + times: (c2) -> + new Complex( + @r*c2.r - @i*c2.i, + @r*c2.i + @i*c2.r + ) + + negation: -> + new Complex( + -1 * @r, + -1 * @i + ) + + inverse: -> + throw Error "no inverse" if @magnitude is 0 + new Complex( + @r / @magnitude, + -1 * @i / @magnitude + ) + + toString: -> + return "#{@r}" if @i == 0 + return "#{@i}i" if @r == 0 + if @i > 0 + "#{@r} + #{@i}i" + else + "#{@r} - #{-1 * @i}i" + +# test +do -> + a = new Complex(5, 3) + b = new Complex(4, -3) + + sum = a.plus b + console.log "(#{a}) + (#{b}) = #{sum}" + + product = a.times b + console.log "(#{a}) * (#{b}) = #{product}" + + negation = b.negation() + console.log "-1 * (#{b}) = #{negation}" + + diff = a.plus negation + console.log "(#{a}) - (#{b}) = #{diff}" + + inverse = b.inverse() + console.log "1 / (#{b}) = #{inverse}" + + quotient = product.times inverse + console.log "(#{product}) / (#{b}) = #{quotient}" diff --git a/Task/Arithmetic-Complex/Groovy/arithmetic-complex-1.groovy b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-1.groovy index 085c50b795..e427908bb1 100644 --- a/Task/Arithmetic-Complex/Groovy/arithmetic-complex-1.groovy +++ b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-1.groovy @@ -1,62 +1,68 @@ class Complex { final Number real, imag - static final Complex I = [0,1] as Complex + static final Complex i = [0,1] as Complex - Complex(Number real) { this(real, 0) } + Complex(Number r, Number i = 0) { (real, imag) = [r, i] } - Complex(real, imag) { this.real = real; this.imag = imag } + Complex(Map that) { (real, imag) = [that.real ?: 0, that.imag ?: 0] } Complex plus (Complex c) { [real + c.real, imag + c.imag] as Complex } - Complex plus (Number n) { [real + n, imag] as Complex } Complex minus (Complex c) { [real - c.real, imag - c.imag] as Complex } - Complex minus (Number n) { [real - n, imag] as Complex } Complex multiply (Complex c) { [real*c.real - imag*c.imag , imag*c.real + real*c.imag] as Complex } - Complex multiply (Number n) { [real*n , imag*n] as Complex } Complex div (Complex c) { this * c.recip() } - Complex div (Number n) { this * (1/n) } Complex negative () { [-real, -imag] as Complex } - /** the complex conjugate of this complex number. - * Overloads the bitwise complement (~) operator. */ + /** the complex conjugate of this complex number. Overloads the bitwise complement (~) operator. */ Complex bitwiseNegate () { [real, -imag] as Complex } /** the magnitude of this complex number. */ - // could also use Math.sqrt( (this * (~this)).real ) - Number abs () { Math.sqrt( real*real + imag*imag ) } + // could also use Math.sqrt( (this * (~this)).real ) + Number getAbs() { Math.sqrt( real*real + imag*imag ) } + /** the magnitude of this complex number. */ + Number abs() { this.abs } - /** the complex reciprocal of this complex number. */ - Complex recip() { (~this) / ((this * (~this)).real) } + /** the reciprocal of this complex number. */ + Complex getRecip() { (~this) / (ρ**2) } + /** the reciprocal of this complex number. */ + Complex recip() { this.recip } - /** derived angle θ (theta) for polar form. - * Normalized to 0 ≤ θ < 2π. */ + /** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */ Number getTheta() { - def theta = Math.atan2(imag,real) - theta = theta < 0 ? theta + 2 * Math.PI : theta + def θ = Math.atan2(imag,real) + θ = θ < 0 ? θ + 2 * Math.PI : θ } + /** derived polar angle θ (theta) for polar form. Normalized to 0 ≤ θ < 2π. */ + Number getΘ() { this.theta } // this is greek uppercase theta - /** derived magnitude ρ (rho) for polar form. */ - Number getRho() { this.abs() } + /** derived polar magnitude ρ (rho) for polar form. */ + Number getRho() { this.abs } + /** derived polar magnitude ρ (rho) for polar form. */ + Number getΡ() { this.abs } // this is greek uppercase rho, not roman P /** Runs Euler's polar-to-Cartesian complex conversion, - * converting [ρ, θ] inputs into a [real, imag]-based complex number */ - static Complex fromPolar(Number rho, Number theta) { - [rho * Math.cos(theta), rho * Math.sin(theta)] as Complex + * converting [ρ, θ] inputs into a [real, imag]-based complex number */ + static Complex fromPolar(Number ρ, Number θ) { + [ρ * Math.cos(θ), ρ * Math.sin(θ)] as Complex } - /** Creates new complex with same magnitude ρ, but different angle θ */ - Complex withTheta(Number theta) { fromPolar(this.rho, theta) } + /** Creates new complex with same magnitude ρ, but different angle θ */ + Complex withTheta(Number θ) { fromPolar(this.rho, θ) } + /** Creates new complex with same magnitude ρ, but different angle θ */ + Complex withΘ(Number θ) { fromPolar(this.rho, θ) } - /** Creates new complex with same angle θ, but different magnitude ρ */ - Complex withRho(Number rho) { fromPolar(rho, this.theta) } + /** Creates new complex with same angle θ, but different magnitude ρ */ + Complex withRho(Number ρ) { fromPolar(ρ, this.θ) } + /** Creates new complex with same angle θ, but different magnitude ρ */ + Complex withΡ(Number ρ) { fromPolar(ρ, this.θ) } // this is greek uppercase rho, not roman P static Complex exp(Complex c) { fromPolar(Math.exp(c.real), c.imag) } @@ -72,10 +78,10 @@ class Complex { Complex power(Number n) { this ** ([n, 0] as Complex) } - boolean equals(other) { - other != null && (other instanceof Complex \ - ? [real, imag] == [other.real, other.imag] \ - : other instanceof Number && [real, imag] == [other, 0]) + boolean equals(that) { + that != null && (that instanceof Complex \ + ? [this.real, this.imag] == [that.real, that.imag] \ + : that instanceof Number && [this.real, this.imag] == [that, 0]) } int hashCode() { [real, imag].hashCode() } diff --git a/Task/Arithmetic-Complex/Groovy/arithmetic-complex-2.groovy b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-2.groovy index c42cc548b5..2401a1d2c7 100644 --- a/Task/Arithmetic-Complex/Groovy/arithmetic-complex-2.groovy +++ b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-2.groovy @@ -1,36 +1,17 @@ -def tol = 0.000000001 // tolerance: acceptable "wrongness" to account for rounding error +import org.codehaus.groovy.runtime.DefaultGroovyMethods -println 'Demo 1: functionality as requested' -def a = [5,3] as Complex -println 'a == ' + a -def b = [0.5,6] as Complex -println 'b == ' + b +class ComplexCategory { + static Complex getI (Number a) { [0, a] as Complex } -println "a + b == (${a}) + (${b}) == " + (a + b) -println "a * b == (${a}) * (${b}) == " + (a * b) -assert a + (-a) == 0 -println "-a == -(${a}) == " + (-a) -assert (a * a.recip() - 1).abs() < tol -println "1/a == (${a}).recip() == " + (a.recip()) -println() + static Complex plus (Number a, Complex b) { b + a } + static Complex minus (Number a, Complex b) { -b + a } + static Complex multiply (Number a, Complex b) { b * a } + static Complex div (Number a, Complex b) { ([a] as Complex) / b } + static Complex power (Number a, Complex b) { ([a] as Complex) ** b } -println 'Demo 2: other functionality not requested, but important for completeness' -println "a - b == (${a}) - (${b}) == " + (a - b) -println "a / b == (${a}) / (${b}) == " + (a / b) -println "a ** b == (${a}) ** (${b}) == " + (a ** b) -println 'a.real == ' + a.real -println 'a.imag == ' + a.imag -println 'a.rho == ' + a.rho -println 'a.theta == ' + a.theta -println '|a| == ' + a.abs() -println 'a_bar == ' + ~a - -def rho = 10 -def piOverTheta = 3 -def theta = Math.PI / piOverTheta -def fromPolar1 = Complex.fromPolar(rho, theta) // direct polar-to-cartesian conversion -def fromPolar2 = Complex.exp(Complex.I * theta) * rho // Euler's equation -println "rho*cos(theta) + rho*i*sin(theta) == ${rho}*cos(pi/${piOverTheta}) + ${rho}*i*sin(pi/${piOverTheta}) == " + fromPolar1 -println "rho * exp(i * theta) == ${rho} * exp(i * pi/${piOverTheta}) == " + fromPolar2 -assert (fromPolar1 - fromPolar2).abs() < tol -println() + static T asType (Number a, Class type) { + type == Complex \ + ? [a] as Complex + : DefaultGroovyMethods.asType(a, type) + } +} diff --git a/Task/Arithmetic-Complex/Groovy/arithmetic-complex-3.groovy b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-3.groovy new file mode 100644 index 0000000000..6f1a1107b1 --- /dev/null +++ b/Task/Arithmetic-Complex/Groovy/arithmetic-complex-3.groovy @@ -0,0 +1,63 @@ +import static Complex.* + +Number.metaClass.mixin ComplexCategory + +def ε = 0.000000001 // tolerance (epsilon): acceptable "wrongness" to account for rounding error + +println 'Demo 1: functionality as requested' +def a = [5,3] as Complex +def a1 = [real:5, imag:3] as Complex +def a2 = 5 + 3.i +def a3 = 5 + 3*i +assert a == a1 && a == a2 && a == a3 +println 'a == ' + a +def b = [0.5,6] as Complex +println 'b == ' + b + +println "a + b == (${a}) + (${b}) == " + (a + b) +println "a * b == (${a}) * (${b}) == " + (a * b) +assert a + (-a) == 0 +println "-a == -(${a}) == " + (-a) +assert (a * a.recip - 1).abs < ε +println "1/a == (${a}).recip == " + (a.recip) +println "a * 1/a == " + (a * a.recip) +println() + +println 'Demo 2: other functionality not requested, but important for completeness' +def c = 10 +def d = 10 as Complex +assert d instanceof Complex && c instanceof Number && d == c +assert a + c == c + a +println "a + 10 == 10 + a == " + (c + a) +assert c - a == -(a - c) +println "10 - a == -(a - 10) == " + (c - a) +println "a - b == (${a}) - (${b}) == " + (a - b) +assert c * a == a * c +println "10 * a == a * 10 == " + (c * a) +assert (c / a - (a / c).recip).abs < ε +println "10 / a == 1 / (a / 10) == " + (c / a) +println "a / b == (${a}) / (${b}) == " + (a / b) +assert (a ** 2 - a * a).abs < ε +println "a ** 2 == a * a == " + (a ** 2) +println "0.9 ** b == " + (0.9 ** b) +println "a ** b == (${a}) ** (${b}) == " + (a ** b) +println 'a.real == ' + a.real +println 'a.imag == ' + a.imag +println '|a| == ' + a.abs +println 'a.rho == ' + a.rho +println 'a.ρ == ' + a.ρ +println 'a.theta == ' + a.theta +println 'a.θ == ' + a.θ +println '~a (conjugate) == ' + ~a + +def ρ = 10 +def π = Math.PI +def n = 3 +def θ = π / n + +def fromPolar1 = fromPolar(ρ, θ) // direct polar-to-cartesian conversion +def fromPolar2 = exp(θ.i) * ρ // Euler's equation +println "ρ*cos(θ) + i*ρ*sin(θ) == ${ρ}*cos(π/${n}) + i*${ρ}*sin(π/${n})" +println " == 10*0.5 + i*10*√(3/4) == " + fromPolar1 +println "ρ*exp(i*θ) == ${ρ}*exp(i*π/${n}) == " + fromPolar2 +assert (fromPolar1 - fromPolar2).abs < ε diff --git a/Task/Arithmetic-Complex/Haskell/arithmetic-complex.hs b/Task/Arithmetic-Complex/Haskell/arithmetic-complex.hs new file mode 100644 index 0000000000..3bcc29321b --- /dev/null +++ b/Task/Arithmetic-Complex/Haskell/arithmetic-complex.hs @@ -0,0 +1,14 @@ +import Data.Complex + +main = do + let a = 1.0 :+ 2.0 -- complex number 1+2i + let b = 4 -- complex number 4+0i + -- 'b' is inferred to be complex because it's used in + -- arithmetic with 'a' below. + putStrLn $ "Add: " ++ show (a + b) + putStrLn $ "Subtract: " ++ show (a - b) + putStrLn $ "Multiply: " ++ show (a * b) + putStrLn $ "Divide: " ++ show (a / b) + putStrLn $ "Negate: " ++ show (-a) + putStrLn $ "Inverse: " ++ show (recip a) + putStrLn $ "Conjugate:" ++ show (conjugate a) diff --git a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx index 1a58d71a92..2cf9a24144 100644 --- a/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx +++ b/Task/Arithmetic-Complex/REXX/arithmetic-complex.rexx @@ -1,25 +1,23 @@ /*REXX program to show how to support math functions for complex numbers*/ +x = '(5,3i)' /*this little piggy uses "I" (or "i") ···*/ +y = '( .5, 6j)' /*this little piggy uses "J" (or "j") ···*/ -x = '(5,3i)' /*this little piggy uses "I" (or "i") ... */ -y = '( .5, 6j)' /*this little piggy uses "J" (or "j") ... */ - -sum = Cadd(x,y); say ' addition: ' x " + " y ' = ' sum -dif = Csub(x,y); say ' subtration: ' x " + " y ' = ' dif -prod = Cmul(x,y); say 'multiplication: ' x " * " y ' = ' prod -quot = Cdiv(x,y); say ' division: ' x " ÷ " y ' = ' quot -inv = Cinv(x); say ' inverse: ' x " = " inv -cnjX = Ccnj(x); say ' conjugate of: ' x " = " cnjX -negX = Cneg(x); say ' negation of: ' x " = " negX +sum = Cadd(x,y) ; say ' addition: ' x " + " y ' = ' sum +dif = Csub(x,y) ; say ' subtraction: ' x " + " y ' = ' dif +prod = Cmul(x,y) ; say 'multiplication: ' x " * " y ' = ' prod +quot = Cdiv(x,y) ; say ' division: ' x " ÷ " y ' = ' quot +inv = Cinv(x) ; say ' inverse: ' x " = " inv +cnjX = Ccnj(x) ; say ' conjugate of: ' x " = " cnjX +negX = Cneg(x) ; say ' negation of: ' x " = " negX exit /*stick a fork in it, we're done.*/ - -/*─────────────────────────────────────one─liners───────────────────────*/ -Ccnj: procedure;arg a ',' b,c ',' d;call Cg;r1=a;r2=-b;return Cr() -Cadd: procedure;arg a ',' b,c ',' d;call Cg;r1=a+c;r2=b+d;return Cr() -Csub: procedure;arg a ',' b,c ',' d;call Cg;r1=a-c;r2=b-d;return Cr() -Cmul: procedure;arg a ',' b,c ',' d;call Cg;r1=a*c-b*d; r2=b*c+a*d;return Cr() -Cdiv: procedure;arg a ',' b,c ',' d;call Cg;_=c*c+d*d;r1=(a*c+b*d)/_;r2=(b*c-a*d)/_;return Cr() -Cg: a=Cdej(a); b=Cdej(b); c=Cdej(c); d=Cdej(d); return -Cr: _='['r1; if r2\=0 then _=_','r2"j"; return _']' -Cdej: return word(translate(arg(1),,'{[(JI)]}') 0,1) -Cneg: return Cmul(arg(1),-1) -Cinv: return Cdiv(1,arg(1)) +/*─────────────────────────────────────one─liners──────────────────────────────────────────────*/ +Ccnj: procedure; arg a ',' b,c ',' d; call Cg; r1=a; r2=-b; return Cr() +Cadd: procedure; arg a ',' b,c ',' d; call Cg; r1=a+c; r2=b+d; return Cr() +Csub: procedure; arg a ',' b,c ',' d; call Cg; r1=a-c; r2=b-d; return Cr() +Cmul: procedure; arg a ',' b,c ',' d; call Cg; r1=a*c-b*d; r2=b*c+a*d; return Cr() +Cdiv: procedure; arg a ',' b,c ',' d; call Cg;_=c*c+d*d;r1=(a*c+b*d)/_;r2=(b*c-a*d)/_;return Cr() +Cdej: return word(translate(arg(1), , '{[(JI)]}') 0, 1) +Cg: a=Cdej(a); b=Cdej(b); c=Cdej(c); d=Cdej(d); return +Cinv: return Cdiv(1, arg(1)) +Cneg: return Cmul(arg(1), -1) +Cr: _='['r1; if r2\=0 then _=_','r2"j"; return _']' diff --git a/Task/Arithmetic-Complex/UNIX-Shell/arithmetic-complex.sh b/Task/Arithmetic-Complex/UNIX-Shell/arithmetic-complex.sh new file mode 100644 index 0000000000..4c999d528a --- /dev/null +++ b/Task/Arithmetic-Complex/UNIX-Shell/arithmetic-complex.sh @@ -0,0 +1,75 @@ +typeset -T Complex_t=( + float real=0 + float imag=0 + + function to_s { + print -- "${_.real} + ${_.imag} i" + } + + function dup { + nameref other=$1 + _=( real=${other.real} imag=${other.imag} ) + } + + function add { + typeset varname + for varname; do + nameref other=$varname + (( _.real += other.real )) + (( _.imag += other.imag )) + done + } + + function negate { + (( _.real *= -1 )) + (( _.imag *= -1 )) + } + + function conjugate { + (( _.imag *= -1 )) + } + + function multiply { + typeset varname + for varname; do + nameref other=$varname + float a=${_.real} b=${_.imag} c=${other.real} d=${other.imag} + (( _.real = a*c - b*d )) + (( _.imag = b*c + a*d )) + done + } + + function inverse { + if (( _.real == 0 && _.imag == 0 )); then + print -u2 "division by zero" + return 1 + fi + float denom=$(( _.real*_.real + _.imag*_.imag )) + (( _.real = _.real / denom )) + (( _.imag = -1 * _.imag / denom )) + } +) + +Complex_t a=(real=1 imag=1) +a.to_s # 1 + 1 i + +Complex_t b=(real=3.14159 imag=1.2) +b.to_s # 3.14159 + 1.2 i + +Complex_t c +c.add a b +c.to_s # 4.14159 + 2.2 i + +c.negate +c.to_s # -4.14159 + -2.2 i + +c.conjugate +c.to_s # -4.14159 + 2.2 i + +c.dup a +c.multiply b +c.to_s # 1.94159 + 4.34159 i + +Complex_t d=(real=2 imag=1) +d.inverse +d.to_s # 0.4 + -0.2 i diff --git a/Task/Arithmetic-Integer/00DESCRIPTION b/Task/Arithmetic-Integer/00DESCRIPTION index d99ae33ac0..8db20921a2 100644 --- a/Task/Arithmetic-Integer/00DESCRIPTION +++ b/Task/Arithmetic-Integer/00DESCRIPTION @@ -1,3 +1,6 @@ -{{basic data operation}}Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different. +{{basic data operation}} [[Category:Simple]] +Get two integers from the user, and then output the sum, difference, product, integer quotient and remainder of those numbers. Don't include error handling. +For quotient, indicate how it rounds (e.g. towards 0, towards negative infinity, etc.). +For remainder, indicate whether its sign matches the sign of the first operand or of the second operand, if they are different. Also include the exponentiation operator if one exists. diff --git a/Task/Arithmetic-Integer/00META.yaml b/Task/Arithmetic-Integer/00META.yaml index a4efa5b7bb..511c100b1d 100644 --- a/Task/Arithmetic-Integer/00META.yaml +++ b/Task/Arithmetic-Integer/00META.yaml @@ -1,4 +1,5 @@ --- category: - Arithmetic operations +- Arithmetic note: Basic language learning diff --git a/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper b/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper index 63b9ff17a3..03facbba13 100644 --- a/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper +++ b/Task/Arithmetic-Integer/Clipper/arithmetic-integer.clipper @@ -1,4 +1,4 @@ -Function( a, b ) +procedure Test( a, b ) ? "a+b", a + b ? "a-b", a - b ? "a*b", a * b @@ -8,4 +8,4 @@ Function( a, b ) ? "a%b", a % b // Exponentiation is also a base arithmetic operation ? "a**b", a ** b -Return Nil + return diff --git a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena index 46de656c81..42ee66cfa1 100644 --- a/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena +++ b/Task/Arithmetic-Integer/Elena/arithmetic-integer.elena @@ -1,16 +1,17 @@ #define system. +#define system'math. #define extensions. // --- Program --- #symbol program = [ - #var a := consoleEx readLine:(Integer new). - #var b := consoleEx readLine:(Integer new). + #var(type:int) a := consoleEx readLine:(Integer new) int. + #var(type:int)b := consoleEx readLine:(Integer new) int. - 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 << " = " << (a~mathOp mod:b) << "%n". // matches sign of first operand + consoleEx writeLine:a:" + ": b:" = ":(a + b). + consoleEx writeLine:a:" - ": b:" = ":(a - b). + consoleEx writeLine:a:" * ": b:" = ":(a * b). + consoleEx writeLine:a:" / ": b:" = ":(a / b). // truncates towards 0 + consoleEx writeLine:a:" %% ":b:" = ":(a mod:b). // matches sign of first operand ]. diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-1.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-1.excel new file mode 100644 index 0000000000..2024bfc6c7 --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-1.excel @@ -0,0 +1 @@ +=$A1+$B1 diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-2.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-2.excel new file mode 100644 index 0000000000..c98108e83d --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-2.excel @@ -0,0 +1 @@ +=$A1-$B1 diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-3.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-3.excel new file mode 100644 index 0000000000..d104bda94f --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-3.excel @@ -0,0 +1 @@ +=$A1*$B1 diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-4.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-4.excel new file mode 100644 index 0000000000..ce92066885 --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-4.excel @@ -0,0 +1 @@ +=QUOTIENT($A1,$B1) diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-5.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-5.excel new file mode 100644 index 0000000000..81fff82a2d --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-5.excel @@ -0,0 +1 @@ +=MOD($A1,$B1) diff --git a/Task/Arithmetic-Integer/Excel/arithmetic-integer-6.excel b/Task/Arithmetic-Integer/Excel/arithmetic-integer-6.excel new file mode 100644 index 0000000000..363ac33d9d --- /dev/null +++ b/Task/Arithmetic-Integer/Excel/arithmetic-integer-6.excel @@ -0,0 +1 @@ +=$A1^$B1 diff --git a/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia b/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia new file mode 100644 index 0000000000..bd12750a36 --- /dev/null +++ b/Task/Arithmetic-Integer/Julia/arithmetic-integer.julia @@ -0,0 +1,5 @@ +function arithmetic (a = int(readline()), b = int(readline())) + for op in [+,-,*,div,rem] + println("a $op b = $(op(a,b))") + end +end diff --git a/Task/Arithmetic-Integer/Prolog/arithmetic-integer-1.pro b/Task/Arithmetic-Integer/Prolog/arithmetic-integer-1.pro new file mode 100644 index 0000000000..6b54b4f80a --- /dev/null +++ b/Task/Arithmetic-Integer/Prolog/arithmetic-integer-1.pro @@ -0,0 +1,9 @@ +print_expression_and_result(M, N, Operator) :- + Expression =.. [Operator, M, N], + Result is Expression, + format('~w ~8|is ~d~n', [Expression, Result]). + +arithmetic_integer :- + read(M), + read(N), + maplist( print_expression_and_result(M, N), [+,-,*,//,rem,^] ). diff --git a/Task/Arithmetic-Integer/Prolog/arithmetic-integer-2.pro b/Task/Arithmetic-Integer/Prolog/arithmetic-integer-2.pro new file mode 100644 index 0000000000..d7326e4ad6 --- /dev/null +++ b/Task/Arithmetic-Integer/Prolog/arithmetic-integer-2.pro @@ -0,0 +1,10 @@ +?- arithmetic_integer. +|: 5. +|: 7. +5+7 is 12 +5-7 is -2 +5*7 is 35 +5//7 is 0 +5 rem 7 is 5 +5^7 is 78125 +true. diff --git a/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb b/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb index c9644f4b27..a6c6ba4d2e 100644 --- a/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb +++ b/Task/Arithmetic-Integer/Ruby/arithmetic-integer.rb @@ -1,10 +1,11 @@ puts 'Enter x and y' -x=gets.to_i # to check errors, use x=Integer(gets) -y=gets.to_i +x = gets.to_i # to check errors, use x=Integer(gets) +y = gets.to_i puts "Sum: #{x+y}", "Difference: #{x-y}", "Product: #{x*y}", - "Quotient: #{x/y}", # truncates towards negative infinity - "Remainder: #{x%y}", # same sign as second operand + "Quotient: #{x/y}", # truncates towards negative infinity + "Quotient: #{x.fdiv(y)}", # float + "Remainder: #{x%y}", # same sign as second operand "Exponentiation: #{x**y}" diff --git a/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust b/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust new file mode 100644 index 0000000000..e01ae1105c --- /dev/null +++ b/Task/Arithmetic-Integer/Rust/arithmetic-integer.rust @@ -0,0 +1,14 @@ +use std::io; + +fn main() { + #![allow(unstable)] // Currently required whilst Rust 1.0 is finalised + let a: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); + let b: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); + + let sum = a + b; + println!("a + b = {0}" , sum); + println!("a - b = {0}" , a - b); + println!("a * b = {0}" , a * b); + println!("quotient of a / b = {0}" , a / b); // truncates towards 0 + println!("remainder of a / b = {0}" , a % b); // same sign as first operand +} diff --git a/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala b/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala index aaaaa50d93..7fe182cea2 100644 --- a/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala +++ b/Task/Arithmetic-Integer/Scala/arithmetic-integer.scala @@ -1,9 +1,9 @@ val a = Console.readInt val b = Console.readInt -val sum = a + b;//integer addition is discouraged in print statements due to confusion with String concatenation -println("a + b = " + sum); -println("a - b = " + (a - b)); -println("a * b = " + (a * b)); -println("quotient of a / b = " + (a / b)); // truncates towards 0 -println("remainder of a / b = " + (a % b)); // same sign as first operand +val sum = a + b //integer addition is discouraged in print statements due to confusion with String concatenation +println("a + b = " + sum) +println("a - b = " + (a - b)) +println("a * b = " + (a * b)) +println("quotient of a / b = " + (a / b)) // truncates towards 0 +println("remainder of a / b = " + (a % b)) // same sign as first operand diff --git a/Task/Arithmetic-Integer/Vim-Script/arithmetic-integer.vim b/Task/Arithmetic-Integer/Vim-Script/arithmetic-integer.vim new file mode 100644 index 0000000000..8d4c47c98a --- /dev/null +++ b/Task/Arithmetic-Integer/Vim-Script/arithmetic-integer.vim @@ -0,0 +1,10 @@ +let a = float2nr(input("Number 1: ") + 0) +let b = float2nr(input("Number 2: ") + 0) +echo "\nSum: " . (a + b) +echo "Difference: " . (a - b) +echo "Product: " . (a * b) +" The result of an integer division is truncated +echo "Quotient: " . (a / b) +" The sign of the result of the remainder operation matches the sign of +" the first operand +echo "Remainder: " . (a % b) diff --git a/Task/Arithmetic-Rational/D/arithmetic-rational.d b/Task/Arithmetic-Rational/D/arithmetic-rational.d index 6c4858d11b..47642df05e 100644 --- a/Task/Arithmetic-Rational/D/arithmetic-rational.d +++ b/Task/Arithmetic-Rational/D/arithmetic-rational.d @@ -1,11 +1,11 @@ import std.bigint, std.traits, std.conv; // std.numeric.gcd doesn't work with BigInt. -T gcd(T)(in T a, in T b) pure /*nothrow*/ { +T gcd(T)(in T a, in T b) pure nothrow { return (b != 0) ? gcd(b, a % b) : (a < 0) ? -a : a; } -T lcm(T)(in T a, in T b) pure /*nothrow*/ { +T lcm(T)(in T a, in T b) pure nothrow { return a / gcd(a, b) * b; } @@ -28,7 +28,7 @@ struct RationalT(T) if (!isUnsigned!T) { den = 1UL; } - this(U, V)(in U n, in V d) pure /*nothrow*/ { + this(U, V)(in U n, in V d) pure nothrow { num = toT(n); den = toT(d); const common = gcd(num, den); @@ -71,7 +71,7 @@ struct RationalT(T) if (!isUnsigned!T) { return ((num < 0) ? "-" : "+") ~ "infRat"; } - real toReal() pure const /*nothrow*/ { + real toReal() pure const nothrow { static if (is(T == BigInt)) return num.toLong / real(den.toLong); else @@ -79,7 +79,7 @@ struct RationalT(T) if (!isUnsigned!T) { } RationalT opBinary(string op)(in RationalT r) - const pure /*nothrow*/ if (op == "+" || op == "-") { + const pure nothrow if (op == "+" || op == "-") { T common = lcm(den, r.den); T n = mixin("common / den * num" ~ op ~ "common / r.den * r.num" ); @@ -87,28 +87,28 @@ struct RationalT(T) if (!isUnsigned!T) { } RationalT opBinary(string op)(in RationalT r) - const pure /*nothrow*/ if (op == "*") { + const pure nothrow if (op == "*") { return RationalT(num * r.num, den * r.den); } RationalT opBinary(string op)(in RationalT r) - const pure /*nothrow*/ if (op == "/") { + const pure nothrow if (op == "/") { return RationalT(num * r.den, den * r.num); } RationalT opBinary(string op, U)(in U r) - const pure /*nothrow*/ if (isIntegral!U && (op == "+" || + const pure nothrow if (isIntegral!U && (op == "+" || op == "-" || op == "*" || op == "/")) { return opBinary!op(RationalT(r)); } RationalT opBinary(string op)(in size_t p) - const pure /*nothrow*/ if (op == "^^") { + const pure nothrow if (op == "^^") { return RationalT(num ^^ p, den ^^ p); } RationalT opBinaryRight(string op, U)(in U l) - const pure /*nothrow*/ if (isIntegral!U) { + const pure nothrow if (isIntegral!U) { return RationalT(l).opBinary!op(RationalT(num, den)); } @@ -118,7 +118,7 @@ struct RationalT(T) if (!isUnsigned!T) { } RationalT opUnary(string op)() - const pure /*nothrow*/ if (op == "+" || op == "-") { + const pure nothrow if (op == "+" || op == "-") { return RationalT(mixin(op ~ "num"), den); } @@ -133,10 +133,10 @@ struct RationalT(T) if (!isUnsigned!T) { return num == rhs.num && den == rhs.den; } - int opCmp(U)(in U r) const pure { + int opCmp(U)(in U r) const pure nothrow { auto rhs = RationalT(r); if (type() == Type.NaRAT || rhs.type() == Type.NaRAT) - throw new Exception("Compare involve a NaRAT."); + throw new Error("Compare involve a NaRAT."); if (type() != Type.NORMAL || rhs.type() != Type.NORMAL) // for infinite return (type() == rhs.type()) ? 0 : @@ -154,12 +154,12 @@ struct RationalT(T) if (!isUnsigned!T) { } } -RationalT!U rational(U)(in U n) pure /*nothrow*/ { +RationalT!U rational(U)(in U n) pure nothrow { return typeof(return)(n); } RationalT!(CommonType!(U1, U2)) -rational(U1, U2)(in U1 n, in U2 d) pure /*nothrow*/ { +rational(U1, U2)(in U1 n, in U2 d) pure nothrow { return typeof(return)(n, d); } diff --git a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy index 150460ab5a..92147c18af 100644 --- a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy +++ b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-1.groovy @@ -1,113 +1,102 @@ class Rational implements Comparable { - final BigInteger numerator, denominator + final BigInteger num, denom - static final Rational ONE = new Rational(1, 1) - - static final Rational ZERO = new Rational(0, 1) - - Rational(BigInteger whole) { this(whole, 1) } + static final Rational ONE = new Rational(1) + static final Rational ZERO = new Rational(0) Rational(BigDecimal decimal) { this( - decimal.scale() < 0 ? decimal.unscaledValue()*10**(-decimal.scale()) : decimal.unscaledValue(), - decimal.scale() < 0 ? 1 : 10**(decimal.scale()) - ) + decimal.scale() < 0 ? decimal.unscaledValue()*10**(-decimal.scale()) : decimal.unscaledValue(), + decimal.scale() < 0 ? 1 : 10**(decimal.scale())) } - Rational(num, denom) { - assert denom != 0 : "Denominator must not be 0" - def values = denom > 0 ? [num, denom] : [-num, -denom] //reduce(num, denom) - - numerator = values[0] - denominator = values[1] + Rational(BigInteger n, BigInteger d = 1) { + if (!d || n == null) { n/d } + (num, denom) = reduce(n, d) } - private List reduce(BigInteger num, BigInteger denom) { - BigInteger sign = ((num < 0) != (denom < 0)) ? -1 : 1 - num = num.abs() - denom = denom.abs() - BigInteger commonFactor = gcd(num, denom) + private List reduce(BigInteger n, BigInteger d) { + BigInteger sign = ((n < 0) != (d < 0)) ? -1 : 1 + (n, d) = [n.abs(), d.abs()] + BigInteger commonFactor = gcd(n, d) - [num.intdiv(commonFactor) * sign, denom.intdiv(commonFactor)] + [n.intdiv(commonFactor) * sign, d.intdiv(commonFactor)] } - public Rational toLeastTerms() { - def reduced = reduce(numerator, denominator) - new Rational(reduced[0], reduced[1]) + public Rational toLeastTerms() { reduce(num, denom) as Rational } + + private BigInteger gcd(BigInteger n, BigInteger m) { + n == 0 ? m : { while(m%n != 0) { (n, m) = [m%n, n] }; n }() } - private BigInteger gcd(BigInteger n, BigInteger m) { n == 0 ? m : { while(m%n != 0) { def t=n; n=m%n; m=t }; n }() } + Rational plus(Rational r) { [num*r.denom + r.num*denom, denom*r.denom] } + Rational plus(BigInteger n) { [num + n*denom, denom] } + Rational plus(Number n) { this + ([n] as Rational) } - Rational plus (Rational r) { new Rational(numerator*r.denominator + r.numerator*denominator, denominator*r.denominator) } + Rational next() { [num + denom, denom] } - Rational plus (BigInteger n) { new Rational(numerator + n*denominator, denominator) } + Rational minus(Rational r) { [num*r.denom - r.num*denom, denom*r.denom] } + Rational minus(BigInteger n) { [num - n*denom, denom] } + Rational minus(Number n) { this - ([n] as Rational) } - Rational next () { new Rational(numerator + denominator, denominator) } + Rational previous() { [num - denom, denom] } - Rational minus (Rational r) { new Rational(numerator*r.denominator - r.numerator*denominator, denominator*r.denominator) } + Rational multiply(Rational r) { [num*r.num, denom*r.denom] } + Rational multiply(BigInteger n) { [num*n, denom] } + Rational multiply(Number n) { this * ([n] as Rational) } - Rational minus (BigInteger n) { new Rational(numerator - n*denominator, denominator) } - Rational previous () { new Rational(numerator - denominator, denominator) } + Rational div(Rational r) { new Rational(num*r.denom, denom*r.num) } + Rational div(BigInteger n) { new Rational(num, denom*n) } + Rational div(Number n) { this / ([n] as Rational) } - Rational multiply (Rational r) { new Rational(numerator*r.numerator, denominator*r.denominator) } + BigInteger intdiv(BigInteger n) { num.intdiv(denom*n) } - Rational multiply (BigInteger n) { new Rational(numerator*n, denominator) } + Rational negative() { [-num, denom] } - Rational div (Rational r) { new Rational(numerator*r.denominator, denominator*r.numerator) } + Rational abs() { [num.abs(), denom] } - Rational div (BigInteger n) { new Rational(numerator, denominator*n) } + Rational reciprocal() { new Rational(denom, num) } - BigInteger intdiv (BigInteger n) { numerator.intdiv(denominator*n) } + Rational power(BigInteger n) { + def (nu, de) = (n < 0 ? [denom, num] : [num, denom])*.power(n.abs()) + new Rational (nu, de) + } - Rational negative () { new Rational(-numerator, denominator) } + boolean asBoolean() { num != 0 } - Rational abs () { new Rational(numerator.abs(), denominator) } + BigDecimal toBigDecimal() { (num as BigDecimal)/(denom as BigDecimal) } - Rational reciprocal() { new Rational(denominator, numerator) } - - Rational power(BigInteger n) { new Rational(numerator ** n, denominator ** n) } - - boolean asBoolean() { numerator != 0 } - - BigDecimal toBigDecimal() { (numerator as BigDecimal)/(denominator as BigDecimal) } - - BigInteger toBigInteger() { numerator.intdiv(denominator) } + BigInteger toBigInteger() { num.intdiv(denom) } Double toDouble() { toBigDecimal().toDouble() } - double doubleValue() { toDouble() as double } Float toFloat() { toBigDecimal().toFloat() } - float floatValue() { toFloat() as float } Integer toInteger() { toBigInteger().toInteger() } - int intValue() { toInteger() as int } Long toLong() { toBigInteger().toLong() } - long longValue() { toLong() as long } Object asType(Class type) { switch (type) { - case this.getClass(): return this - case Boolean.class: return asBoolean() - case BigDecimal.class: return toBigDecimal() - case BigInteger.class: return toBigInteger() - case Double.class: return toDouble() - case Float.class: return toFloat() - case Integer.class: return toInteger() - case Long.class: return toLong() - case String.class: return toString() - default: throw new ClassCastException("Cannot convert from type Rational to type " + type) + case this.getClass(): return this + case [Boolean.class,Boolean.TYPE]: return asBoolean() + case BigDecimal.class: return toBigDecimal() + case BigInteger.class: return toBigInteger() + case [Double.class,Double.TYPE]: return toDouble() + case [Float.class,Float.TYPE]: return toFloat() + case [Integer.class,Integer.TYPE]: return toInteger() + case [Long.class,Long.TYPE]: return toLong() + case String.class: return toString() + default: throw new ClassCastException("Cannot convert from type Rational to type " + type) } } - boolean equals(o) { - compareTo(o) == 0 - } + boolean equals(o) { compareTo(o) == 0 } int compareTo(o) { o instanceof Rational \ @@ -116,15 +105,12 @@ class Rational implements Comparable { ? compareTo(o as Number)\ : (Double.NaN as int) } + int compareTo(Rational r) { num*r.denom <=> denom*r.num } + int compareTo(Number n) { num <=> denom*(n as BigInteger) } - int compareTo(Rational r) { numerator*r.denominator <=> denominator*r.numerator } - - int compareTo(Number n) { numerator <=> denominator*(n as BigInteger) } - - int hashCode() { [numerator, denominator].hashCode() } + int hashCode() { [num, denom].hashCode() } String toString() { - def reduced = reduce(numerator, denominator) - "${reduced[0]}//${reduced[1]}" + "${num}//${denom}" } } diff --git a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-2.groovy b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-2.groovy index 4638a46b10..c97bf0d70a 100644 --- a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-2.groovy +++ b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-2.groovy @@ -1,74 +1,14 @@ -def x = new Rational(5, 20) -def y = new Rational(9, 12) -def z = new Rational(0, 10000) +import org.codehaus.groovy.runtime.DefaultGroovyMethods -println x -println y -println z -println (x <=> y) -println ((x as Rational).compareTo(y)) -assert x*3 == y -assert (z + 1) <= y*4 -assert x != y +class RationalCategory { + static Rational plus (Number a, Rational b) { ([a] as Rational) + b } + static Rational minus (Number a, Rational b) { ([a] as Rational) - b } + static Rational multiply (Number a, Rational b) { ([a] as Rational) * b } + static Rational div (Number a, Rational b) { ([a] as Rational) / b } -println "x + y == ${x} + ${y} == ${x + y}" -println "x + z == ${x} + ${z} == ${x + z}" -println "x - y == ${x} - ${y} == ${x - y}" -println "x - z == ${x} - ${z} == ${x - z}" -println "x * y == ${x} * ${y} == ${x * y}" -println "y ** 3 == ${y} ** 3 == ${y ** 3}" -println "x * z == ${x} * ${z} == ${x * z}" -println "x / y == ${x} / ${y} == ${x / y}" -try { print "x / z == ${x} / ${z} == "; println "${x / z}" } -catch (Throwable t) { println t.message } - -println "-x == -${x} == ${-x}" -println "-y == -${y} == ${-y}" -println "-z == -${z} == ${-z}" - -print "x as int == ${x} as int == "; println x.intValue() -print "x as double == ${x} as double == "; println x.doubleValue() -print "1 / x as int == 1 / ${x} as int == "; println x.reciprocal().intValue() -print "1.0 / x == 1.0 / ${x} == "; println x.reciprocal().doubleValue() -print "y as int == ${y} as int == "; println y.intValue() -print "y as double == ${y} as double == "; println y.doubleValue() -print "1 / y as int == 1 / ${y} as int == "; println y.reciprocal().intValue() -print "1.0 / y == 1.0 / ${y} == "; println y.reciprocal().doubleValue() -print "z as int == ${z} as int == "; println z.intValue() -print "z as double == ${z} as double == "; println z.doubleValue() -try { print "1 / z as int == 1 / ${z} as int == "; println z.reciprocal().intValue() } -catch (Throwable t) { println t.message } -try { print "1.0 / z == 1.0 / ${z} == "; println z.reciprocal().doubleValue() } -catch (Throwable t) { println t.message } - -println "++x == ++ ${x} == ${++x}" -println "++y == ++ ${y} == ${++y}" -println "++z == ++ ${z} == ${++z}" -println "-- --x == -- -- ${x} == ${-- (--x)}" -println "-- --y == -- -- ${y} == ${-- (--y)}" -println "-- --z == -- -- ${z} == ${-- (--z)}" -println x -println y -println z - -println (x <=> y) -assert x*3 == y -assert (z + 1) <= y*4 -assert (x < y) - -println (new Rational(25)) -println (new Rational(25.0)) -println (new Rational(0.25)) - -println Math.PI -println (new Rational(Math.PI)) -println ((new Rational(Math.PI)).toBigDecimal()) -println ((new Rational(Math.PI)) as BigDecimal) -println ((new Rational(Math.PI)) as Double) -println ((new Rational(Math.PI)) as double) -println ((new Rational(Math.PI)) as boolean) -println (z as boolean) -try { println ((new Rational(Math.PI)) as Date) } -catch (Throwable t) { println t.message } -try { println ((new Rational(Math.PI)) as char) } -catch (Throwable t) { println t.message } + static T asType (Number a, Class type) { + type == Rational \ + ? [a] as Rational + : DefaultGroovyMethods.asType(a, type) + } +} diff --git a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-3.groovy b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-3.groovy index 1421eca833..2660a87164 100644 --- a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-3.groovy +++ b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-3.groovy @@ -1,26 +1,87 @@ -def factorize = { target -> - if (target == 1L) { - return [1L] - } else if ([2L, 3L].contains(target)) { - return [1L, target] - } - def targetSqrt = Math.ceil(Math.sqrt(target)) as long - def lowfactors = (2L..(targetSqrt)).findAll { (target % it) == 0 } +Number.metaClass.mixin RationalCategory - if (lowfactors.isEmpty()) { - return [1L, target] - } +def x = [5, 20] as Rational +def y = [9, 12] as Rational +def z = [0, 10000] as Rational - def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1 : 0) +println x +println y +println z +println (x <=> y) +println (x.compareTo(y)) +assert x < y +assert x*3 == y +assert x*5.5 == 5.5*x +assert (z + 1) <= y*4 +assert x + 1.3 == 1.3 + x +assert 24 - y == -(y - 24) +assert 3 / y == (y / 3).reciprocal() +assert x != y - return ([1L] + lowfactors + ((nhalf-1)..0).collect { target.intdiv(lowfactors[it]) } + [target]).unique() -} +println "x + y == ${x} + ${y} == ${x + y}" +println "x + z == ${x} + ${z} == ${x + z}" +println "x - y == ${x} - ${y} == ${x - y}" +println "x - z == ${x} - ${z} == ${x - z}" +println "x * y == ${x} * ${y} == ${x * y}" +println "y ** 3 == ${y} ** 3 == ${y ** 3}" +println "y ** -3 == ${y} ** -3 == ${y ** -3}" +println "x * z == ${x} * ${z} == ${x * z}" +println "x / y == ${x} / ${y} == ${x / y}" +try { print "x / z == ${x} / ${z} == "; println "${x / z}" } +catch (Throwable t) { println t.message } -1.upto(2**19) { - if ((it % 100000) == 0) { println "HT" } - else if ((it % 1000) == 0) { print "." } +println "-x == -${x} == ${-x}" +println "-y == -${y} == ${-y}" +println "-z == -${z} == ${-z}" - def factors = factorize(it) - def isPerfect = factors.collect{ factor -> new Rational( factor ).reciprocal() }.sum() == new Rational(2) - if (isPerfect) { println() ; println ([perfect: it, factors: factors]) } -} +print "x as int == ${x} as int == "; println x.intValue() +print "x as double == ${x} as double == "; println x.doubleValue() +print "1 / x as int == 1 / ${x} as int == "; println x.reciprocal().intValue() +print "1.0 / x == 1.0 / ${x} == "; println x.reciprocal().doubleValue() +print "y as int == ${y} as int == "; println y.intValue() +print "y as double == ${y} as double == "; println y.doubleValue() +print "1 / y as int == 1 / ${y} as int == "; println y.reciprocal().intValue() +print "1.0 / y == 1.0 / ${y} == "; println y.reciprocal().doubleValue() +print "z as int == ${z} as int == "; println z.intValue() +print "z as double == ${z} as double == "; println z.doubleValue() +try { print "1 / z as int == 1 / ${z} as int == "; println z.reciprocal().intValue() } +catch (Throwable t) { println t.message } +try { print "1.0 / z == 1.0 / ${z} == "; println z.reciprocal().doubleValue() } +catch (Throwable t) { println t.message } + +println "++x == ++ ${x} == ${++x}" +println "++y == ++ ${y} == ${++y}" +println "++z == ++ ${z} == ${++z}" +println "-- --x == -- -- ${x} == ${-- (--x)}" +println "-- --y == -- -- ${y} == ${-- (--y)}" +println "-- --z == -- -- ${z} == ${-- (--z)}" +println x +println y +println z + +println (x <=> y) +assert x*3 == y +assert (z + 1) <= y*4 +assert (x < y) + +println 25 as Rational +println 25.0 as Rational +println 0.25 as Rational + +def ε = 0.000000001 // tolerance (epsilon): acceptable "wrongness" to account for rounding error + +def π = Math.PI +def α = π as Rational +assert (π - (α as BigDecimal)).abs() < ε +println π +println α +println (α.toBigDecimal()) +println (α as BigDecimal) +println (α as Double) +println (α as double) +println (α as boolean) +println (z as boolean) +try { println (α as Date) } +catch (Throwable t) { println t.message } +try { println (α as char) } +catch (Throwable t) { println t.message } diff --git a/Task/Arithmetic-Rational/Groovy/arithmetic-rational-4.groovy b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-4.groovy new file mode 100644 index 0000000000..04e0583e15 --- /dev/null +++ b/Task/Arithmetic-Rational/Groovy/arithmetic-rational-4.groovy @@ -0,0 +1,25 @@ +Number.metaClass.mixin RationalCategory + +def factorize = { target -> + assert target > 0 + if (target == 1L) { return [1L] } + if ([2L, 3L].contains(target)) { return [1L, target] } + def targetSqrt = Math.sqrt(target) + def lowFactors = (2L..targetSqrt).findAll { (target % it) == 0 } + + if (!lowFactors) { return [1L, target] } + def highFactors = lowFactors[-1..0].findResults { target.intdiv(it) } - lowFactors[-1] + + return [1L] + lowFactors + highFactors + [target] +} + +def perfect = { + def factors = factorize(it) + 2 as Rational == factors.sum{ factor -> new Rational(1, factor) } \ + ? [perfect: it, factors: factors] + : null +} + +def trackProgress = { if ((it % (100*1000)) == 0) { println it } else if ((it % 1000) == 0) { print "." } } + +(1..(2**19)).findResults { trackProgress(it); perfect(it) }.each { println(); print it } diff --git a/Task/Arithmetic-Rational/PL-I/arithmetic-rational.pli b/Task/Arithmetic-Rational/PL-I/arithmetic-rational.pli new file mode 100644 index 0000000000..bbdb074567 --- /dev/null +++ b/Task/Arithmetic-Rational/PL-I/arithmetic-rational.pli @@ -0,0 +1,246 @@ +*process source attributes xref or(!); + arat: Proc Options(main); + /*-------------------------------------------------------------------- + * Rational Arithmetic + * (Mis)use the Complex data type to represent fractions + * real(x) is used as numerator + * imag(x) is used as denominator + * Output: + * a=-3/7 b=9/2 + * a*b=-27/14 + * a+b=57/14 + * a-b=-69/14 + * a/b=-2/21 + * -3/7<9/2 + * 9/2>-3/7 + * -3/7=-3/7 + * 26.01.2015 handle 0/0 + *-------------------------------------------------------------------*/ + Dcl (abs,imag,mod,real,sign,trim) Builtin; + Dcl sysprint Print; + Dcl (candidate,max2,factor) Dec Fixed(15); + Dcl sum complex Dec Fixed(15); + Dcl one complex Dec Fixed(15); + + one=mk_fr(1,1); + Put Edit('First solve the task at hand')(Skip,a); + Do candidate = 2 to 10000; + sum = mk_fr(1, candidate); + max2 = sqrt(candidate); + Do factor = 2 to max2; + If mod(candidate,factor)=0 Then Do; + sum=fr_add(sum,mk_fr(1,factor)); + sum=fr_add(sum,mk_fr(1,candidate/factor)); + End; + End; + If fr_cmp(sum,one)='=' Then Do; + Put Edit(candidate,' is a perfect number')(Skip,f(7),a); + Do factor = 2 to candidate-1; + If mod(candidate,factor)=0 Then + Put Edit(factor)(f(5)); + End; + End; + End; + + Put Edit('','Then try a few things')(Skip,a); + Dcl a Complex Dec Fixed(15); + Dcl b Complex Dec Fixed(15); + Dcl p Complex Dec Fixed(15); + Dcl s Complex Dec Fixed(15); + Dcl d Complex Dec Fixed(15); + Dcl q Complex Dec Fixed(15); + Dcl zero Complex Dec Fixed(15); + zero=mk_fr(0,1); Put Edit('zero=',fr_rep(zero))(Skip,2(a)); + a=mk_fr(0,0); Put Edit('a=',fr_rep(a))(Skip,2(a)); + /*-------------------------------------------------------------------- + a=mk_fr(-3333,0); Put Edit('a=',fr_rep(a))(Skip,2(a)); + => Request mk_fr(-3333,0) + Denominator must not be 0 + IBM0280I ONCODE=0009 The ERROR condition was raised + by a SIGNAL statement. + At offset +00000276 in procedure with entry FT + *-------------------------------------------------------------------*/ + a=mk_fr(0,3333); Put Edit('a=',fr_rep(a))(Skip,2(a)); + Put Edit('-3,7')(Skip,a); + a=mk_fr(-3,7); + b=mk_fr(9,2); + p=fr_mult(a,b); + s=fr_add(a,b); + d=fr_sub(a,b); + q=fr_div(a,b); + r=fr_div(b,a); + Put Edit('a=',fr_rep(a))(Skip,2(a)); + Put Edit('b=',fr_rep(b))(Skip,2(a)); + Put Edit('a*b=',fr_rep(p))(Skip,2(a)); + Put Edit('a+b=',fr_rep(s))(Skip,2(a)); + Put Edit('a-b=',fr_rep(d))(Skip,2(a)); + Put Edit('a/b=',fr_rep(q))(Skip,2(a)); + Put Edit('b/a=',fr_rep(r))(Skip,2(a)); + Put Edit(fr_rep(a),fr_cmp(a,b),fr_rep(b))(Skip,3(a)); + Put Edit(fr_rep(b),fr_cmp(b,a),fr_rep(a))(Skip,3(a)); + Put Edit(fr_rep(a),fr_cmp(a,a),fr_rep(a))(Skip,3(a)); + + mk_fr: Proc(n,d) Recursive Returns(Dec Fixed(15) Complex); + /*-------------------------------------------------------------------- + * make a Complex number + * normalize and cancel + *-------------------------------------------------------------------*/ + Dcl (n,d) Dec Fixed(15); + Dcl (na,da) Dec Fixed(15); + Dcl res Dec Fixed(15) Complex; + Dcl x Dec Fixed(15); + na=abs(n); + da=abs(d); + Select; + When(n=0) Do; + real(res)=0; + imag(res)=1; + End; + When(d=0) Do; + Put Edit('Request mk_fr('!!n_rep(n)!!','!!n_rep(d)!!')') + (Skip,a); + Put Edit('Denominator must not be 0')(Skip,a); + Signal error; + End; + Otherwise Do; + x=gcd(na,da); + real(res)=sign(n)*sign(d)*na/x; + imag(res)=da/x; + End; + End; + Return(res); + End; + + fr_add: Proc(a,b) Returns(Dec Fixed(15) Complex); + /*-------------------------------------------------------------------- + * add 'fractions' a and b + *-------------------------------------------------------------------*/ + Dcl (a,b,res) Dec Fixed(15) Complex; + Dcl (an,ad,bn,bd) Dec Fixed(15); + Dcl (rd,rn) Dec Fixed(15); + Dcl x Dec Fixed(15); + an=real(a); + ad=imag(a); + bn=real(b); + bd=imag(b); + rd=ad*bd; + rn=an*bd+bn*ad; + x=gcd(rd,rn); + real(res)=rn/x; + imag(res)=rd/x; + Return(res); + End; + + fr_sub: Proc(a,b) Returns(Dec Fixed(15) Complex); + /*-------------------------------------------------------------------- + * subtract 'fraction' b from a + *-------------------------------------------------------------------*/ + Dcl (a,b) Dec Fixed(15) Complex; + Dcl b2 Dec Fixed(15) Complex; + real(b2)=-real(b); + imag(b2)=imag(b); + Return(fr_add(a,b2)); + End; + + fr_mult: Proc(a,b) Returns(Dec Fixed(15) Complex); + /*-------------------------------------------------------------------- + * multiply 'fractions' a and b + *-------------------------------------------------------------------*/ + Dcl (a,b,res) Dec Fixed(15) Complex; + real(res)=real(a)*real(b); + imag(res)=imag(a)*imag(b); + Return(res); + End; + + fr_div: Proc(a,b) Returns(Dec Fixed(15) Complex); + /*-------------------------------------------------------------------- + * divide 'fraction' a by b + *-------------------------------------------------------------------*/ + Dcl (a,b) Dec Fixed(15) Complex; + Dcl b2 Dec Fixed(15) Complex; + real(b2)=imag(b); + imag(b2)=real(b); + If real(a)=0 & real(b)=0 Then + Return(mk_fr(1,1)); + Return(fr_mult(a,b2)); + End; + + fr_cmp: Proc(a,b) Returns(char(1)); + /*-------------------------------------------------------------------- + * compare 'fractions' a and b + *-------------------------------------------------------------------*/ + Dcl (a,b) Dec Fixed(15) Complex; + Dcl (an,ad,bn,bd) Dec Fixed(15); + Dcl (a2,b2) Dec Fixed(15); + Dcl (rd) Dec Fixed(15); + Dcl res Char(1); + an=real(a); + ad=imag(a); + If ad=0 Then Do; + Put Edit('ad=',ad,'candidate=',candidate)(Skip,a,f(10)); + Signal Error; + End; + bn=real(b); + bd=imag(b); + rd=ad*bd; + a2=abs(an*bd)*sign(an)*sign(ad); + b2=abs(bn*ad)*sign(bn)*sign(bd); + Select; + When(a2b2) res='>'; + Otherwise Do; + res='='; + End; + End; + Return(res); + End; + + fr_rep: Proc(f) Returns(char(15) Var); + /*-------------------------------------------------------------------- + * Return the representation of 'fraction' f + *-------------------------------------------------------------------*/ + Dcl f Dec Fixed(15) Complex; + Dcl res Char(15) Var; + Dcl (n,d) Pic'(14)Z9'; + Dcl x Dec Fixed(15); + Dcl s Dec Fixed(15); + n=abs(real(f)); + d=abs(imag(f)); + x=gcd(n,d); + s=sign(real(f))*sign(imag(f)); + res=trim(n/x)!!'/'!!trim(d/x); + If s<0 Then + res='-'!!res; + Return(res); + End; + + n_rep: Proc(x) Returns(char(15) Var); + /*-------------------------------------------------------------------- + * Return the representation of x + *-------------------------------------------------------------------*/ + Dcl x Dec Fixed(15); + Dcl res Char(15) Var; + Put String(res) List(x); + res=trim(res); + Return(res); + End; + + gcd: Proc(a,b) Returns(Dec Fixed(15)) Recursive; + /*-------------------------------------------------------------------- + * Compute the greatest common divisor + *-------------------------------------------------------------------*/ + Dcl (a,b) Dec Fixed(15) Nonassignable; + If b=0 then Return (abs(a)); + Return(gcd(abs(b),mod(abs(a),abs(b)))); + End gcd; + + lcm: Proc(a,b) Returns(Dec Fixed(15)); + /*-------------------------------------------------------------------- + * Compute the least common multiple + *-------------------------------------------------------------------*/ + Dcl (a,b) Dec Fixed(15) Nonassignable; + if a=0 ! b=0 then Return (0); + Return(abs(a*b)/gcd(a,b)); + End lcm; + + End; diff --git a/Task/Arithmetic-Rational/Ruby/arithmetic-rational.rb b/Task/Arithmetic-Rational/Ruby/arithmetic-rational.rb index cc7253623d..18e0602c10 100644 --- a/Task/Arithmetic-Rational/Ruby/arithmetic-rational.rb +++ b/Task/Arithmetic-Rational/Ruby/arithmetic-rational.rb @@ -1,6 +1,6 @@ require 'rational' #Only needed in Ruby < 1.9 -for candidate in 2 .. 2**19: +for candidate in 2 .. 2**19 sum = Rational(1, candidate) for factor in 2 ... candidate**0.5 if candidate % factor == 0 diff --git a/Task/Arithmetic-evaluation/Common-Lisp/arithmetic-evaluation.lisp b/Task/Arithmetic-evaluation/Common-Lisp/arithmetic-evaluation.lisp index a93c80a5fd..09516f34c4 100644 --- a/Task/Arithmetic-evaluation/Common-Lisp/arithmetic-evaluation.lisp +++ b/Task/Arithmetic-evaluation/Common-Lisp/arithmetic-evaluation.lisp @@ -9,15 +9,15 @@ collect (read-char stream) into digits finally (return (parse-integer (coerce digits 'string)))))) (consume-whitespace) - (let ((c (peek-char nil stream nil nil))) - (let ((token (case c - ((nil) nil) - ((#\() :lparen) - ((#\)) :rparen) - ((#\*) '*) - ((#\/) '/) - ((#\+) '+) - ((#\-) '-) + (let* ((c (peek-char nil stream nil nil))) + (token (case c + (nil nil) + (#\( :lparen) + (#\) :rparen) + (#\* '*) + (#\/ '/) + (#\+ '+) + (#\- '-) (otherwise (unless (digit-char-p c) (cerror "Skip it." "Unexpected character ~w." c) @@ -27,7 +27,7 @@ (read-integer))))) (unless (or (null token) (integerp token)) (read-char stream)) - token)))) + token))) (defun group-parentheses (tokens &optional (delimited nil)) (do ((new-tokens '())) @@ -37,12 +37,12 @@ (values (nreverse new-tokens) '())) (let ((token (pop tokens))) (case token - ((:lparen) + (:lparen (multiple-value-bind (group remaining-tokens) (group-parentheses tokens t) (setf new-tokens (cons group new-tokens) tokens remaining-tokens))) - ((:rparen) + (:rparen (if (not delimited) (cerror "Ignore it." "Unexpected right parenthesis.") (return (values (nreverse new-tokens) tokens)))) diff --git a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d index f1ca2ae58f..e3854826d0 100644 --- a/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d +++ b/Task/Arithmetic-evaluation/D/arithmetic-evaluation.d @@ -4,12 +4,13 @@ import std.stdio, std.string, std.ascii, std.conv, std.array, struct Stack(T) { T[] data; alias data this; - void push(T top) pure nothrow { data ~= top; } + void push(T top) pure nothrow @safe { data ~= top; } - T pop(bool discard = true)() pure { + T pop(bool discard = true)() pure @nogc @safe { + immutable static exc = new immutable(Exception)("Stack Empty"); if (data.empty) - throw new Exception("Stack Empty"); - auto top = data.back; + throw exc; + auto top = data[$ - 1]; static if (discard) data.popBack; return top; @@ -20,7 +21,7 @@ enum Type { Num, OBkt, CBkt, Add, Sub, Mul, Div } immutable opChar = ["#", "(", ")", "+", "-", "*", "/"]; immutable opPrec = [ 0, -9, -9, 1, 1, 2, 2]; -abstract class Visitor { void visit(XP e); } +abstract class Visitor { void visit(XP e) pure @safe; } final class XP { immutable Type type; @@ -28,7 +29,7 @@ final class XP { immutable int pos; // Optional, to dispaly AST struct. XP LHS, RHS; - this(string s=")", int p = -1) nothrow { + this(string s=")", int p = -1) pure nothrow @safe { str = s; pos = p; auto localType = Type.Num; @@ -38,13 +39,13 @@ final class XP { this.type = localType; } - override int opCmp(Object other) pure { + override int opCmp(Object other) pure @safe { auto rhs = cast(XP)other; enforce(rhs !is null); return opPrec[type] - opPrec[rhs.type]; } - void accept(Visitor v) { v.visit(this); } + void accept(Visitor v) pure @safe { v.visit(this); } } final class AST { @@ -53,13 +54,13 @@ final class AST { string xpr, token; int xpHead, xpTail; - void joinXP(XP x) pure { + void joinXP(XP x) pure @safe { x.RHS = num.pop; x.LHS = num.pop; num.push(x); } - string nextToken() pure { + string nextToken() pure @safe { while (xpHead < xpr.length && xpr[xpHead] == ' ') xpHead++; // Skip spc. xpTail = xpHead; @@ -82,7 +83,7 @@ final class AST { return null; } // End nextToken. - AST parse(in string s) { + AST parse(in string s) /*@safe*/ { bool expectingOP; xpr = s; try { @@ -147,7 +148,7 @@ final class AST { // To display AST fancy struct. void ins(ref char[][] s, in string v, in int p, in int l) -pure nothrow { +pure nothrow @safe { if (l + 1 > s.length) s.length++; while (s[l].length < p + v.length + 1) @@ -160,7 +161,7 @@ final class CalcVis : Visitor { string resultStr; char[][] Tree; - static void opCall(AST a) { + static void opCall(AST a) @safe { if (a && a.root) { auto c = new CalcVis; a.root.accept(c); @@ -187,7 +188,7 @@ final class CalcVis : Visitor { } // Calc. the value, display AST struct and eval order. - override void visit(XP xp) { + override void visit(XP xp) @safe { ins(Tree, xp.str, xp.pos, level); level++; if (xp.type == Type.Num) { @@ -212,9 +213,9 @@ final class CalcVis : Visitor { } } -void main(string[] args) { +void main(string[] args) /*@safe*/ { 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; + immutable exp = (args.length > 1) ? args[1 .. $].join(' ') : exp0; new AST().parse(exp).CalcVis; // Should be 60. } diff --git a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena index 24f07053ce..726a33956f 100644 --- a/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena +++ b/Task/Arithmetic-evaluation/Elena/arithmetic-evaluation-1.elena @@ -29,7 +29,7 @@ ^ aNode += self. ] - #method Number = convertor toReal:theValue. + #method Number = convertor toReal:(theValue value). } // --- Node --- @@ -294,7 +294,7 @@ #var aParser := Parser new. consoleEx writeLine:"=" :(aParser foreach:aText Number) - | ifFailed: + | if &e: [ consoleEx writeLine:"Invalid Expression". ]. diff --git a/Task/Arithmetic-evaluation/PicoLisp/arithmetic-evaluation-1.l b/Task/Arithmetic-evaluation/PicoLisp/arithmetic-evaluation-1.l index 62143b04b4..fb1cfb04d1 100644 --- a/Task/Arithmetic-evaluation/PicoLisp/arithmetic-evaluation-1.l +++ b/Task/Arithmetic-evaluation/PicoLisp/arithmetic-evaluation-1.l @@ -20,4 +20,4 @@ ((num? X) X) ((= "+" X) (term)) ((= "-" X) (list '- (term))) - ((= "(" X) (prog1 (aggregate) (pop '*L)))) ) ) ) + ((= "(" X) (prog1 (aggregate) (pop '*L)))) ) ) diff --git a/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx b/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx index a710022e93..552f0bee2f 100644 --- a/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx +++ b/Task/Arithmetic-evaluation/REXX/arithmetic-evaluation.rexx @@ -14,8 +14,8 @@ j=0; do forever; j=j+1; if j>L then leave; _=substr(x,j,1); _2=getX() end /* 2nd symbol.*/ z=z _ $; iterate end - if _=='+' | _=="-" then do; p_=word(z,words(z)) /*last Z token*/ - if p_=='(' then z=z 0 /*handle unary±*/ + if _=='+' | _=="-" then do; p_=word(z,words(z)) /*last Z token*/ + if p_=='(' then z=z 0 /*handle unary ±*/ z=z _ $; iterate end lets=0; sigs=0; #=_ @@ -24,17 +24,17 @@ j=0; do forever; j=j+1; if j>L then leave; _=substr(x,j,1); _2=getX() if lets==1 & sigs==0 then if _=='+' | _=='-' then do; sigs=1 #=# || _ iterate - end /*exp*/ + end if pos(_,nchars)==0 then leave lets=lets+datatype(_,'M') /*keep track of # of exponents. */ - #=# || translate(_,'EEEEE','eDdQq') /*keep building the num*/ + #=# || translate(_,'EEEEE','eDdQq') /*keep buildingthe num.*/ end /*j*/ j=j-1 - if \datatype(#,'N') then call serr 'invalid number: ' # + if \datatype(#,'N') then call serr 'invalid number: ' # z=z # $ end /*forever*/ -_=word(z,1); if _=='+' | _=='-' then z=0 z /*handle unary cases.*/ +_=word(z,1); if _=='+' | _=='-' then z=0 z /*handle unary cases.*/ x='(' space(z) ') '; tokens=words(x) /*force stacking for expression. */ do i=1 for tokens; @.i=word(x,i); end /*i*/ /*assign input tokens*/ L=max(20,length(x)) /*use 20 for the min show width. */ @@ -104,7 +104,7 @@ z=space(z stack) /*append any residual entries. */ say 'answer──►' z /*display the answer (result). */ parse source upper . how . /*invoked via C.L. or REXX pgm?*/ if how=='COMMAND' | , - \datatype(z,'W') then exit /*stick a fork in it, we're done.*/ + \datatype(z,'W') then exit /*stick a fork in it, we're done.*/ return z /*return Z ──► invoker (RESULT).*/ /*──────────────────────────────────subroutines─────────────────────────*/ isBit: return arg(1)==0 | arg(1)==1 /*returns 1 if arg1 is bin bit.*/ @@ -112,6 +112,6 @@ isOp: return pos(arg(1),rOp)\==0 /*is argument1 a "real" operator?*/ serr: say; say e arg(1); say; exit 13 /*issue an error message with txt*/ /*──────────────────────────────────GETX subroutine─────────────────────*/ getX: do Nj=j+1 to length(x); _n=substr(x,Nj,1); if _n==$ then iterate - if _n==$ then iterate; return substr(x,Nj,1) /*ignore blanks*/ + return substr(x,Nj,1) /* [↑] ignore any blanks in exp.*/ end /*Nj*/ return $ /*reached end-of-tokens, return $*/ diff --git a/Task/Arithmetic-evaluation/Ruby/arithmetic-evaluation-1.rb b/Task/Arithmetic-evaluation/Ruby/arithmetic-evaluation-1.rb index d6901b2f70..95d9339c4a 100644 --- a/Task/Arithmetic-evaluation/Ruby/arithmetic-evaluation-1.rb +++ b/Task/Arithmetic-evaluation/Ruby/arithmetic-evaluation-1.rb @@ -1,11 +1,11 @@ $op_priority = {"+" => 0, "-" => 0, "*" => 1, "/" => 1} -$op_function = { - "+" => lambda {|x, y| x + y}, - "-" => lambda {|x, y| x - y}, - "*" => lambda {|x, y| x * y}, - "/" => lambda {|x, y| x / y}} class TreeNode + OP_FUNCTION = { + "+" => lambda {|x, y| x + y}, + "-" => lambda {|x, y| x - y}, + "*" => lambda {|x, y| x * y}, + "/" => lambda {|x, y| x / y}} attr_accessor :info, :left, :right def initialize(info) @@ -23,10 +23,10 @@ class TreeNode left_s, right_s = @left.to_s(order), @right.to_s(order) strs = case order - when :prefix then [@info, left_s, right_s] - when :infix then [left_s, @info, right_s] + when :prefix then [@info, left_s, right_s] + when :infix then [left_s, @info, right_s] when :postfix then [left_s, right_s, @info] - else [] + else [] end "(" + strs.join(" ") + ")" @@ -35,7 +35,7 @@ class TreeNode def eval if !leaf? and operator?(@info) - $op_function[@info].call(@left.eval, @right.eval) + OP_FUNCTION[@info].call(@left.eval, @right.eval) else @info.to_f end @@ -46,6 +46,10 @@ def tokenize(exp) exp .gsub('(', ' ( ') .gsub(')', ' ) ') + .gsub('+', ' + ') + .gsub('-', ' - ') + .gsub('*', ' * ') + .gsub('/', ' / ') .split(' ') end diff --git a/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c b/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c index b9df3bf294..6daecaa99e 100644 --- a/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c +++ b/Task/Arithmetic-geometric-mean/C/arithmetic-geometric-mean.c @@ -1,32 +1,34 @@ -#include -#include -#include +/*Arithmetic Geometric Mean of 1 and 1/sqrt(2) -double agm( double a, double g ) { - /* arithmetic-geometric mean */ - double iota = 1.0E-16; - double a1, g1; + Nigel_Galloway + February 7th., 2012. +*/ - if( a*g < 0.0 ) { - printf( "arithmetic-geometric mean undefined when x*y<0\n" ); - exit(1); - } +#include "gmp.h" - while( fabs(a-g)>iota ) { - a1 = (a + g) / 2.0; - g1 = sqrt(a * g); - - a = a1; - g = g1; - } - - return a; +void agm (const mpf_t in1, const mpf_t in2, mpf_t out1, mpf_t out2) { + mpf_add (out1, in1, in2); + mpf_div_ui (out1, out1, 2); + mpf_mul (out2, in1, in2); + mpf_sqrt (out2, out2); } -int main( void ) { - double x, y; - printf( "Enter two numbers: " ); - scanf( "%lf%lf", &x, &y ); - printf( "The arithmetic-geometric mean is %lf\n", agm(x, y) ); - return 0; +int main (void) { + mpf_set_default_prec (65568); + mpf_t x0, y0, resA, resB; + + mpf_init_set_ui (y0, 1); + mpf_init_set_d (x0, 0.5); + mpf_sqrt (x0, x0); + mpf_init (resA); + mpf_init (resB); + + for(int i=0; i<7; i++){ + agm(x0, y0, resA, resB); + agm(resA, resB, x0, y0); + } + gmp_printf ("%.20000Ff\n", x0); + gmp_printf ("%.20000Ff\n\n", y0); + + return 0; } diff --git a/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d b/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d index 9022377511..9d12ef84ee 100644 --- a/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d +++ b/Task/Arithmetic-geometric-mean/D/arithmetic-geometric-mean.d @@ -1,15 +1,13 @@ -import std.stdio, std.math, std.typecons; +import std.stdio, std.math, std.typecons, std.typetuple; -real agm(real a, real g, in int bitPrecision=60) pure nothrow { +real agm(real a, real g, in int bitPrecision=60) pure nothrow @nogc @safe { do { - //(a, g) = tuple((a + g) / 2.0, sqrt(a * g)); - immutable ag = tuple((a + g) / 2.0, sqrt(a * g)); - a = ag[0]; - g = ag[1]; + //{a, g} = {(a + g) / 2.0, sqrt(a * g)}; + TypeTuple!(a, g) = tuple((a + g) / 2.0, sqrt(a * g)); } while (feqrel(a, g) < bitPrecision); return a; } -void main() { +void main() @safe { writefln("%0.19f", agm(1, 1 / sqrt(2.0))); } diff --git a/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-1.groovy b/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-1.groovy new file mode 100644 index 0000000000..d6b513087f --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-1.groovy @@ -0,0 +1,5 @@ +double agm (double a, double g) { + double an = a, gn = g + while ((an-gn).abs() >= 10.0**-14) { (an, gn) = [(an+gn)*0.5, (an*gn)**0.5] } + an +} diff --git a/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-2.groovy b/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-2.groovy new file mode 100644 index 0000000000..b1cc910690 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Groovy/arithmetic-geometric-mean-2.groovy @@ -0,0 +1,2 @@ +println "agm(1, 0.5**0.5) = agm(1, ${0.5**0.5}) = ${agm(1, 0.5**0.5)}" +assert (0.8472130847939792 - agm(1, 0.5**0.5)).abs() <= 10.0**-14 diff --git a/Task/Arithmetic-geometric-mean/Lua/arithmetic-geometric-mean.lua b/Task/Arithmetic-geometric-mean/Lua/arithmetic-geometric-mean.lua new file mode 100644 index 0000000000..8528fc4297 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Lua/arithmetic-geometric-mean.lua @@ -0,0 +1,11 @@ +function agm(a, b, tolerance) + if not tolerance or tolerance < 1e-15 then + tolerance = 1e-15 + end + repeat + a, b = (a + b) / 2, math.sqrt(a * b) + until math.abs(a-b) < tolerance + return a +end + +print(string.format("%.15f", agm(1, 1 / math.sqrt(2)))) diff --git a/Task/Arithmetic-geometric-mean/OOC/arithmetic-geometric-mean.ooc b/Task/Arithmetic-geometric-mean/OOC/arithmetic-geometric-mean.ooc new file mode 100644 index 0000000000..9807879fe1 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/OOC/arithmetic-geometric-mean.ooc @@ -0,0 +1,19 @@ +import math // import for sqrt() function + +amean: func (x: Double, y: Double) -> Double { + (x + y) / 2. +} +gmean: func (x: Double, y: Double) -> Double { + sqrt(x * y) +} +agm: func (a: Double, g: Double) -> Double { + while ((a - g) abs() > pow(10, -12)) { + (a1, g1) := (amean(a, g), gmean(a, g)) + (a, g) = (a1, g1) + } + a +} + +main: func { + "%.16f" printfln(agm(1., sqrt(0.5))) +} diff --git a/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean.rb b/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-1.rb similarity index 92% rename from Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean.rb rename to Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-1.rb index 07efa6f08b..8f84dbf4c8 100644 --- a/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean.rb +++ b/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-1.rb @@ -1,4 +1,3 @@ -# # The flt package (http://flt.rubyforge.org/) is useful for high-precision floating-point math. # It lets us control 'context' of numbers, individually or collectively -- including precision # (which adjusts the context's value of epsilon accordingly). @@ -8,7 +7,7 @@ include Flt BinNum.Context.precision = 512 # default 53 (bits) -def AGM(a,g) +def agm(a,g) new_a = BinNum a new_g = BinNum g while new_a - new_g > new_a.class.Context.epsilon do @@ -19,4 +18,4 @@ def AGM(a,g) new_g end -puts AGM 1, 1 / BinNum(2).sqrt +puts agm(1, 1 / BinNum(2).sqrt) diff --git a/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-2.rb b/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-2.rb new file mode 100644 index 0000000000..b2a24c08be --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Ruby/arithmetic-geometric-mean-2.rb @@ -0,0 +1,16 @@ +require 'bigdecimal' + +PRECISION = 100 +EPSILON = 0.1 ** (PRECISION/2) +BigDecimal::limit(PRECISION) + +def agm(a,g) + while a - g > EPSILON + a, g = (a+g)/2, (a*g).sqrt(PRECISION) + end + [a, g] +end + +a = BigDecimal(1) +g = 1 / BigDecimal(2).sqrt(PRECISION) +puts agm(a, g) diff --git a/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust b/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust new file mode 100644 index 0000000000..919af0b3e6 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/Rust/arithmetic-geometric-mean.rust @@ -0,0 +1,37 @@ +// http://rosettacode.org/wiki/Arithmetric-geometric_mean +// Accepts two command line arguments +// cargo run --name agm arg1 arg2 + +use std::num; + +#[cfg(not(test))] +fn main () { + let args = std::os::args(); + let args = args.as_slice(); + + let x = from_str::(args[1].as_slice()).unwrap() ; + let y = from_str::(args[2].as_slice()).unwrap() ; + + let result = agm(x,y); + println!("The arithmetic-geometric mean is {}", result); +} + +fn agm (x: f32, y: f32) -> f32 { + let e: f32 = 0.000001; + let mut a = x; + let mut g = y; + let mut a1: f32; + let mut g1: f32; + + if a * g < 0f32 { panic!("The arithmetric-geometric mean is undefined for numbers less than zero!"); } + else { + loop { + a1 = (a + g) / 2f32; + g1 = (a * g).sqrt(); + a = a1; + g = g1; + if num::abs( a - g) < e { return a; } + } + } + +} diff --git a/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-1.sh b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-1.sh new file mode 100644 index 0000000000..f31f54dc20 --- /dev/null +++ b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-1.sh @@ -0,0 +1,12 @@ +function agm { + float a=$1 g=$2 eps=${3:-1e-11} tmp + while (( abs(a-g) > eps )); do + print "debug: a=$a\tg=$g" + tmp=$(( (a+g)/2.0 )) + g=$(( sqrt(a*g) )) + a=$tmp + done + echo $a +} + +agm $((1/sqrt(2))) 1 diff --git a/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-2.sh b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-2.sh new file mode 100644 index 0000000000..b889f8d89d --- /dev/null +++ b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-2.sh @@ -0,0 +1 @@ +while (( abs(a-g) > eps )) diff --git a/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-3.sh b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-3.sh new file mode 100644 index 0000000000..3eace2b88a --- /dev/null +++ b/Task/Arithmetic-geometric-mean/UNIX-Shell/arithmetic-geometric-mean-3.sh @@ -0,0 +1 @@ +while [[ $a != $g ]] diff --git a/Task/Array-concatenation/Babel/array-concatenation.pb b/Task/Array-concatenation/Babel/array-concatenation.pb index 770d3d731d..cb81dcfd58 100644 --- a/Task/Array-concatenation/Babel/array-concatenation.pb +++ b/Task/Array-concatenation/Babel/array-concatenation.pb @@ -1 +1 @@ -main : { [1 2 3] [4 5 6] cat } +main : { [val 1 2 3] [val 4 5 6] cat } diff --git a/Task/Array-concatenation/Fortran/array-concatenation.f b/Task/Array-concatenation/Fortran/array-concatenation-1.f similarity index 100% rename from Task/Array-concatenation/Fortran/array-concatenation.f rename to Task/Array-concatenation/Fortran/array-concatenation-1.f diff --git a/Task/Array-concatenation/Fortran/array-concatenation-2.f b/Task/Array-concatenation/Fortran/array-concatenation-2.f new file mode 100644 index 0000000000..c75043d316 --- /dev/null +++ b/Task/Array-concatenation/Fortran/array-concatenation-2.f @@ -0,0 +1,12 @@ +program Concat_Arrays +implicit none + + integer, dimension(3) :: a = [ 1, 2, 3 ] + integer, dimension(3) :: b = [ 4, 5, 6 ] + integer, dimension(:), allocatable :: c + + c = [a, b] + + write(*,*) c + +end program Concat_Arrays diff --git a/Task/Array-concatenation/Oberon-2/array-concatenation.oberon-2 b/Task/Array-concatenation/Oberon-2/array-concatenation.oberon-2 new file mode 100644 index 0000000000..076ce3c689 --- /dev/null +++ b/Task/Array-concatenation/Oberon-2/array-concatenation.oberon-2 @@ -0,0 +1,50 @@ +MODULE ArrayConcat; +IMPORT + Out; +TYPE + IntArray = POINTER TO ARRAY OF INTEGER; +VAR + x, y, z: IntArray; + + PROCEDURE InitArray(VAR x: IntArray;from: INTEGER); + VAR + i: LONGINT; + BEGIN + FOR i := 0 TO LEN(x^) - 1 DO + x[i] := from; + INC(from) + END + END InitArray; + + PROCEDURE Concat(x,y: IntArray; VAR z: IntArray); + VAR + i: LONGINT; + 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 Show(x: IntArray); + VAR + i: INTEGER; + BEGIN + i := 0; + Out.Char('['); + WHILE (i < LEN(x^)) DO + Out.LongInt(x[i],3);IF i < LEN(x^) - 1 THEN Out.Char(',') END; + INC(i) + END; + Out.Char(']');Out.Ln + END Show; + +BEGIN + (* Standard types *) + NEW(x,5);InitArray(x,1); + NEW(y,10);InitArray(y,6); + NEW(z,LEN(x^) + LEN(y^)); + + Concat(x,y,z); + Show(z) + +END ArrayConcat. diff --git a/Task/Array-concatenation/RapidQ/array-concatenation.rapidq b/Task/Array-concatenation/RapidQ/array-concatenation.rapidq new file mode 100644 index 0000000000..a2fe9a2172 --- /dev/null +++ b/Task/Array-concatenation/RapidQ/array-concatenation.rapidq @@ -0,0 +1,6 @@ +DEFINT A(1 to 4) = {1, 2, 3, 4} +DEFINT B(1 to 4) = {10, 20, 30, 40} + +'Append array B to array A +Redim A(1 to 8) as integer +MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4) diff --git a/Task/Array-concatenation/Yacas/array-concatenation.yacas b/Task/Array-concatenation/Yacas/array-concatenation.yacas new file mode 100644 index 0000000000..5a43c49e8f --- /dev/null +++ b/Task/Array-concatenation/Yacas/array-concatenation.yacas @@ -0,0 +1,3 @@ +Concat({1,2,3}, {4,5,6}) + +Out> {1, 2, 3, 4, 5, 6} diff --git a/Task/Arrays/00DESCRIPTION b/Task/Arrays/00DESCRIPTION index 86eaa73a1b..2066a46b45 100644 --- a/Task/Arrays/00DESCRIPTION +++ b/Task/Arrays/00DESCRIPTION @@ -1,5 +1,6 @@ -This task is about arrays. For hashes or associative arrays, please -see [[Creating an Associative Array]]. +This task is about arrays. +For hashes or associative arrays, please see [[Creating an Associative Array]]. +For a definition and in-depth discussion of what an array is, see [[Array]]. In this task, the goal is to show basic array syntax in your language. Basically, create an array, assign a value to it, and diff --git a/Task/Arrays/00META.yaml b/Task/Arrays/00META.yaml index 659c8686af..3548159ac8 100644 --- a/Task/Arrays/00META.yaml +++ b/Task/Arrays/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Basic language learning diff --git a/Task/Arrays/Babel/arrays-1.pb b/Task/Arrays/Babel/arrays-1.pb new file mode 100644 index 0000000000..7726202274 --- /dev/null +++ b/Task/Arrays/Babel/arrays-1.pb @@ -0,0 +1 @@ +[val 1 2 3] diff --git a/Task/Arrays/Babel/arrays-2.pb b/Task/Arrays/Babel/arrays-2.pb new file mode 100644 index 0000000000..3f857b9578 --- /dev/null +++ b/Task/Arrays/Babel/arrays-2.pb @@ -0,0 +1 @@ +[ptr 1 2 3] diff --git a/Task/Arrays/Babel/arrays-3.pb b/Task/Arrays/Babel/arrays-3.pb new file mode 100644 index 0000000000..bef3d4dbc9 --- /dev/null +++ b/Task/Arrays/Babel/arrays-3.pb @@ -0,0 +1 @@ +[val 1 2 3] 1 th diff --git a/Task/Arrays/Babel/arrays-4.pb b/Task/Arrays/Babel/arrays-4.pb new file mode 100644 index 0000000000..626f75e4f0 --- /dev/null +++ b/Task/Arrays/Babel/arrays-4.pb @@ -0,0 +1 @@ +[val 1 2 3] 7 1 paste diff --git a/Task/Arrays/Babel/arrays-5.pb b/Task/Arrays/Babel/arrays-5.pb new file mode 100644 index 0000000000..f47500a0bd --- /dev/null +++ b/Task/Arrays/Babel/arrays-5.pb @@ -0,0 +1 @@ +[ptr 1 2 3] [ptr 7] 1 paste diff --git a/Task/Arrays/Babel/arrays-6.pb b/Task/Arrays/Babel/arrays-6.pb new file mode 100644 index 0000000000..61d084c5e4 --- /dev/null +++ b/Task/Arrays/Babel/arrays-6.pb @@ -0,0 +1 @@ +[ptr 'foo' 'bar' 'baz' 'bop'] 1 3 slice diff --git a/Task/Arrays/Babel/arrays-7.pb b/Task/Arrays/Babel/arrays-7.pb new file mode 100644 index 0000000000..d8519d96ee --- /dev/null +++ b/Task/Arrays/Babel/arrays-7.pb @@ -0,0 +1,4 @@ + [ptr 1 2 3] dup + <- arlen 1 + newin dup dup -> + 0 paste + [ptr 4] 3 paste diff --git a/Task/Arrays/Babel/arrays-8.pb b/Task/Arrays/Babel/arrays-8.pb new file mode 100644 index 0000000000..f89a344f06 --- /dev/null +++ b/Task/Arrays/Babel/arrays-8.pb @@ -0,0 +1,2 @@ + [ptr 1 2 3] + ar2ls (4) unshift bons diff --git a/Task/Arrays/Boo/arrays.boo b/Task/Arrays/Boo/arrays.boo new file mode 100644 index 0000000000..8acd841f4a --- /dev/null +++ b/Task/Arrays/Boo/arrays.boo @@ -0,0 +1,8 @@ +myArray as (int) = (1, 2, 3) // Size based on initialization +fixedArray as (int) = array(int, 1) // Given size(1 in this case) + +myArray[0] = 10 + +myArray = myArray + fixedArray // Append arrays + +print myArray[0] diff --git a/Task/Arrays/Bracmat/arrays.bracmat b/Task/Arrays/Bracmat/arrays.bracmat new file mode 100644 index 0000000000..6df6aa2f99 --- /dev/null +++ b/Task/Arrays/Bracmat/arrays.bracmat @@ -0,0 +1,11 @@ +( tbl$(mytable,100) +& 5:?(30$mytable) +& 9:?(31$mytable) +& out$(!(30$mytable)) +& out$(!(-169$mytable)) { -169 mod 100 == 31 } +& out$!mytable { still index 31 } +& tbl$(mytable,0) +& (!mytable & out$"mytable still exists" + | out$"mytable is gone" + ) +); diff --git a/Task/Arrays/C++/arrays.cpp b/Task/Arrays/C++/arrays.cpp new file mode 100644 index 0000000000..307163eede --- /dev/null +++ b/Task/Arrays/C++/arrays.cpp @@ -0,0 +1,44 @@ +#include +#include + +// These headers are only needed for the demonstration +#include +#include +#include +#include + +// This is a template function that works for any array-like object +template +void demonstrate(Array& array) +{ + // Array element access + array[2] = "Three"; // Fast, but unsafe - if the index is out of bounds you + // get undefined behaviour + array.at(1) = "Two"; // *Slightly* less fast, but safe - if the index is out + // of bounds, an exception is thrown + + // Arrays can be used with standard algorithms + std::reverse(begin(array), end(array)); + std::for_each(begin(array), end(array), + [](typename Array::value_type const& element) // in C++14, you can just use auto + { + std::cout << element << ' '; + }); + + std::cout << '\n'; +} + +int main() +{ + // Compile-time sized fixed-size array + auto fixed_size_array = std::array{ "One", "Four", "Eight" }; + // If you do not supply enough elements, the remainder are default-initialized + + // Dynamic array + auto dynamic_array = std::vector{ "One", "Four" }; + dynamic_array.push_back("Eight"); // Dynamically grows to accept new element + + // All types of arrays can be used more or less interchangeably + demonstrate(fixed_size_array); + demonstrate(dynamic_array); +} diff --git a/Task/Arrays/Oberon-2/arrays.oberon-2 b/Task/Arrays/Oberon-2/arrays.oberon-2 new file mode 100644 index 0000000000..86d0ee9fd7 --- /dev/null +++ b/Task/Arrays/Oberon-2/arrays.oberon-2 @@ -0,0 +1,36 @@ +MODULE Arrays; +IMPORT + Out; + + PROCEDURE Static; + VAR + x: ARRAY 5 OF LONGINT; + BEGIN + x[0] := 10; + x[1] := 11; + x[2] := 12; + x[3] := 13; + x[4] := x[0]; + + Out.String("Static at 4: ");Out.LongInt(x[4],0);Out.Ln; + END Static; + + PROCEDURE Dynamic; + VAR + x: POINTER TO ARRAY OF LONGINT; + BEGIN + NEW(x,5); + + x[0] := 10; + x[1] := 11; + x[2] := 12; + x[3] := 13; + x[4] := x[0]; + + Out.String("Dynamic at 4: ");Out.LongInt(x[4],0);Out.Ln; + END Dynamic; + +BEGIN + Static; + Dynamic +END Arrays. diff --git a/Task/Arrays/REXX/arrays-1.rexx b/Task/Arrays/REXX/arrays-1.rexx index 98beeeab34..d3a6e4d897 100644 --- a/Task/Arrays/REXX/arrays-1.rexx +++ b/Task/Arrays/REXX/arrays-1.rexx @@ -1,7 +1,7 @@ /*REXX program demonstrates a simple array usage. */ a.='not found' /*value for all a.xxx (so far).*/ do j=1 to 100 /*start at 1, define 100 elements*/ - a.j=-j*100 /*define as negative J thousand. */ + a.j=-j*1000 /*define as negative J thousand. */ end /*j*/ /*the above defines 100 elements.*/ say 'element 50 is:' a.50 diff --git a/Task/Arrays/REXX/arrays-3.rexx b/Task/Arrays/REXX/arrays-3.rexx index 83f0292649..cbcaccf54b 100644 --- a/Task/Arrays/REXX/arrays-3.rexx +++ b/Task/Arrays/REXX/arrays-3.rexx @@ -1,5 +1,5 @@ /*REXX program demonstrates array usage with mimicry. */ -a. = 'not found' /*value for all a.xxx (so far). */ +a. = 00 /*value for all a.xxx (so far). */ do j=1 to 100 /*start at 1, define 100 elements*/ a.j = -j * 100 /*define element as -J hundred. */ end /*j*/ /*the above defines 100 elements.*/ diff --git a/Task/Arrays/REXX/arrays-4.rexx b/Task/Arrays/REXX/arrays-4.rexx index cfbad6de11..6f976ce2ad 100644 --- a/Task/Arrays/REXX/arrays-4.rexx +++ b/Task/Arrays/REXX/arrays-4.rexx @@ -2,7 +2,7 @@ array. = 'out of range' /*define ALL elements to this. */ do j=-3000 to 3000 /*start at -3k, going up to +3k.*/ - array.j=j**2 /*define element as it's square. */ + array.j=j**2 /*define element as its square. */ end /*j*/ /* [↑] defines 6,001 elements. */ g=-7 say g "squared is:" array.g diff --git a/Task/Arrays/Vim-Script/arrays.vim b/Task/Arrays/Vim-Script/arrays.vim new file mode 100644 index 0000000000..60506fb67a --- /dev/null +++ b/Task/Arrays/Vim-Script/arrays.vim @@ -0,0 +1,19 @@ +" Creating a dynamic array with some initial values +let array = [3, 4] + +" Retrieving an element +let four = array[1] + +" Modifying an element +let array[0] = 2 + +" Appending a new element +call add(array, 5) + +" Prepending a new element +call insert(array, 1) + +" Inserting a new element before another element +call insert(array, 3, 2) + +echo array diff --git a/Task/Arrays/Visual-Basic-.NET/arrays.visual b/Task/Arrays/Visual-Basic-.NET/arrays.visual new file mode 100644 index 0000000000..da50171596 --- /dev/null +++ b/Task/Arrays/Visual-Basic-.NET/arrays.visual @@ -0,0 +1,31 @@ + 'Example of array of 10 int types: + Dim numbers As Integer() = New Integer(0) {} + 'Example of array of 4 string types: + Dim words As String() = {"hello", "world", "from", "mars"} + 'You can also declare the size of the array and initialize the values at the same time: + Dim more_numbers As Integer() = New Integer(2) {21, 14, 63} + + 'For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. + 'The following creates a 3x2 int matrix + Dim number_matrix As Integer(,) = New Integer(2, 1) {} + + + 'As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces. + Dim string_matrix As String(,) = {{"I", "swam"}, {"in", "the"}, {"freezing", "water"}} + 'or + Dim funny_matrix As String(,) = New String(1, 1) {{"clowns", "are"}, {"not", "funny"}} + + Dim array As Integer() = New Integer(9) {} + array(0) = 1 + array(1) = 3 + Console.WriteLine(array(0)) + + + 'Dynamic + Imports System + Imports System.Collections.Generic + Dim list As New List(Of Integer)() + list.Add(1) + list.Add(3) + list(0) = 2 + Console.WriteLine(list(0)) diff --git a/Task/Assertions/UNIX-Shell/assertions.sh b/Task/Assertions/UNIX-Shell/assertions.sh new file mode 100644 index 0000000000..12b1179b8c --- /dev/null +++ b/Task/Assertions/UNIX-Shell/assertions.sh @@ -0,0 +1,11 @@ +assert() { + if test ! $1; then + [[ $2 ]] && echo "$2" >&2 + exit 1 + fi +} +x=42 +assert "$x -eq 42" "that's not the answer" +((x--)) +assert "$x -eq 42" "that's not the answer" +echo "won't get here" diff --git a/Task/Associative-array-Creation/Babel/associative-array-creation.pb b/Task/Associative-array-Creation/Babel/associative-array-creation.pb new file mode 100644 index 0000000000..2801c59285 --- /dev/null +++ b/Task/Associative-array-Creation/Babel/associative-array-creation.pb @@ -0,0 +1,4 @@ + [map + ("foo" 13) + ("bar" 42) + ("baz" 77)] diff --git a/Task/Associative-array-Creation/Dao/associative-array-creation.dao b/Task/Associative-array-Creation/Dao/associative-array-creation.dao index 0ac21b343b..d14148da2e 100644 --- a/Task/Associative-array-Creation/Dao/associative-array-creation.dao +++ b/Task/Associative-array-Creation/Dao/associative-array-creation.dao @@ -1,5 +1,5 @@ -m = { => } # empty, future inserted keys will be ordered -h = { : } # empty, future inserted keys will not be ordered +m = { => } # empty ordered map, future inserted keys will be ordered +h = { -> } # empty hash map, future inserted keys will not be ordered m = { 'foo' => 42, 'bar' => 100 } # with ordered keys -h = { 'foo' : 42, 'bar' : 100 } # with unordered keys +h = { 'foo' -> 42, 'bar' -> 100 } # with unordered keys diff --git a/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-1.l b/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-1.l new file mode 100644 index 0000000000..f47891d3fe --- /dev/null +++ b/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-1.l @@ -0,0 +1,2 @@ +(setq my-table (make-hash-table)) +(puthash 'key 'value my-table) diff --git a/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-2.l b/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-2.l new file mode 100644 index 0000000000..9162695045 --- /dev/null +++ b/Task/Associative-array-Creation/Emacs-Lisp/associative-array-creation-2.l @@ -0,0 +1,2 @@ +(setq my-table (make-hash-table :test 'equal)) +(puthash "key" 123 my-table) diff --git a/Task/Associative-array-Creation/Go/associative-array-creation.go b/Task/Associative-array-Creation/Go/associative-array-creation.go index e601819708..4146fe9662 100644 --- a/Task/Associative-array-Creation/Go/associative-array-creation.go +++ b/Task/Associative-array-Creation/Go/associative-array-creation.go @@ -1,16 +1,23 @@ // declare a nil map variable, for maps from string to int -var x map[string] int +var x map[string]int // make an empty map -x = make(map[string] int) +x = make(map[string]int) // make an empty map with an initial capacity -x = make(map[string] int, 42) +x = make(map[string]int, 42) // set a value x["foo"] = 3 +// getting values +y1 := x["bar"] // zero value returned if no map entry exists for the key +y2, ok := x["bar"] // ok is a boolean, true if key exists in the map + +// removing keys +delete(x, "foo") + // make a map with a literal -x = map[string] int { - "foo": 2, "bar": 42, "baz": -1, +x = map[string]int{ + "foo": 2, "bar": 42, "baz": -1, } diff --git a/Task/Associative-array-Creation/Julia/associative-array-creation.julia b/Task/Associative-array-Creation/Julia/associative-array-creation.julia new file mode 100644 index 0000000000..601e0df921 --- /dev/null +++ b/Task/Associative-array-Creation/Julia/associative-array-creation.julia @@ -0,0 +1,27 @@ +julia> hash = {'a' => 97, 'b' => 98} # list keys/values +{'a'=>97,'b'=>98} + +julia> hash = {c => int(c) for c = 'a':'d'} # dict comprehension +{'a'=>97,'c'=>99,'b'=>98,'d'=>100} + +julia> hash['é'] = 233 ; hash # add an element +{'a'=>97,'c'=>99,'b'=>98,'é'=>233,'d'=>100} + +julia> hash = Dict() # create an empty dict +Dict{Any,Any}() + +julia> for c = 'a':'d' hash[c] = int(c) end ; hash # fill it +{'a'=>97,'c'=>99,'b'=>98,'d'=>100} + +julia> hash = (Char=>Int64)['a' => 97, 'b' => 98] # create a typed dict +['a'=>97,'b'=>98] + +julia> hash["a"] = 1 # type mismatch +ERROR: no method convert(Type{Char}, ASCIIString) + in setindex! at dict.jl:533 + +julia> hash = Dict(['a','b','c'], [97,98,99]) # constructor +['a'=>97,'c'=>99,'b'=>98] + +julia> typeof(hash) # type is infered correctly +Dict{Char,Int64} (constructor with 3 methods diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-4.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-4.m new file mode 100644 index 0000000000..b1a5395b32 --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-4.m @@ -0,0 +1 @@ +m = containers.Map({'a' 'b' 'C'}, [1 2 3]); diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-5.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-5.m new file mode 100644 index 0000000000..45c9db8eb2 --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-5.m @@ -0,0 +1,4 @@ +m = containers.Map; +m('a') = 1; +m('b') = 2; +m('C') = 3; diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-6.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-6.m new file mode 100644 index 0000000000..fa620955bf --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-6.m @@ -0,0 +1 @@ +m = containers.Map([51 72 37], {'fiftyone' 'seventytwo' 'thirtyseven'}); diff --git a/Task/Associative-array-Creation/MATLAB/associative-array-creation-7.m b/Task/Associative-array-Creation/MATLAB/associative-array-creation-7.m new file mode 100644 index 0000000000..a277eecb44 --- /dev/null +++ b/Task/Associative-array-Creation/MATLAB/associative-array-creation-7.m @@ -0,0 +1,4 @@ +m = containers.Map('KeyType', 'double', 'ValueType', 'any'); +m(51) = 'fiftyone'; +m(72) = 'seventytwo'; +m(37) = 'thirtyseven'; diff --git a/Task/Associative-array-Creation/Oberon-2/associative-array-creation.oberon-2 b/Task/Associative-array-Creation/Oberon-2/associative-array-creation.oberon-2 new file mode 100644 index 0000000000..6cdd9f8bf4 --- /dev/null +++ b/Task/Associative-array-Creation/Oberon-2/associative-array-creation.oberon-2 @@ -0,0 +1,41 @@ +MODULE AssociativeArray; +IMPORT + ADT:Dictionary, + Object:Boxed, + Out; +TYPE + Key = STRING; + Value = Boxed.LongInt; + +VAR + assocArray: Dictionary.Dictionary(Key,Value); + iterK: Dictionary.IterKeys(Key,Value); + iterV: Dictionary.IterValues(Key,Value); + aux: Value; + k: Key; + +BEGIN + assocArray := NEW(Dictionary.Dictionary(Key,Value)); + assocArray.Set("ten",NEW(Value,10)); + assocArray.Set("eleven",NEW(Value,11)); + + aux := assocArray.Get("ten"); + Out.LongInt(aux.value,0);Out.Ln; + aux := assocArray.Get("eleven"); + Out.LongInt(aux.value,0);Out.Ln;Out.Ln; + + (* Iterate keys *) + iterK := assocArray.IterKeys(); + WHILE (iterK.Next(k)) DO + Out.Object(k);Out.Ln + END; + + Out.Ln; + + (* Iterate values *) + iterV := assocArray.IterValues(); + WHILE (iterV.Next(aux)) DO + Out.LongInt(aux.value,0);Out.Ln + END + +END AssociativeArray. diff --git a/Task/Associative-array-Creation/PL-SQL/associative-array-creation.sql b/Task/Associative-array-Creation/PL-SQL/associative-array-creation.sql index fc80f8ac1c..5d961a237c 100644 --- a/Task/Associative-array-Creation/PL-SQL/associative-array-creation.sql +++ b/Task/Associative-array-Creation/PL-SQL/associative-array-creation.sql @@ -1,10 +1,10 @@ DECLARE - type assocArrayType is record ( + type ThisIsNotAnAssocArrayType is record ( myShape VARCHAR2(20), mySize number, isActive BOOLEAN ); - assocArray assocArrayType; + assocArray ThisIsNotAnAssocArrayType ; BEGIN assocArray.myShape := 'circle'; diff --git a/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx b/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx index b6684d3977..908c889146 100644 --- a/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx +++ b/Task/Associative-array-Creation/REXX/associative-array-creation-1.rexx @@ -3,8 +3,8 @@ key0 = '0' key1 = 'key0' -stem. = '.' /* Initialize the associative array 'stem' to '.' */ -stem.key1 = 'value0' /* Set a specific key/value pair */ +stem. = '.' /* Initialize the associative array 'stem' to '.' */ +stem.key1 = 'value0' /* Set a specific key/value pair */ -Say '' /* Display a value for a key that wasn't set */ -Say '' /* Display a value for a key that was set */ +Say 'stem.key0= 'stem.key /* Display a value for a key that wasn't set */ +Say 'stem.key1= 'stem.key1 /* Display a value for a key that was set */ diff --git a/Task/Associative-array-Creation/SQL/associative-array-creation.sql b/Task/Associative-array-Creation/SQL/associative-array-creation.sql new file mode 100644 index 0000000000..49ff1535ef --- /dev/null +++ b/Task/Associative-array-Creation/SQL/associative-array-creation.sql @@ -0,0 +1,6 @@ +REM Create a table to associate keys with values +CREATE TABLE associative_array ( KEY_COLUMN VARCHAR2(10), VALUE_COLUMN VARCHAR2(100)); . +REM Insert a Key Value Pair +INSERT (KEY_COLUMN, VALUE_COLUMN) VALUES ( 'VALUE','KEY');. +REM Retrieve a key value pair +SELECT aa.value_column FROM associative_array aa where aa.key_column = 'KEY'; diff --git a/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh new file mode 100644 index 0000000000..31e987dfdd --- /dev/null +++ b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-1.sh @@ -0,0 +1,4 @@ +typeset -A hash +hash=( [key1]=val1 [key2]=val2 ) +hash[key3]=val3 +echo "${hash[key3]}" diff --git a/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh new file mode 100644 index 0000000000..895c6026b1 --- /dev/null +++ b/Task/Associative-array-Creation/UNIX-Shell/associative-array-creation-2.sh @@ -0,0 +1 @@ +declare -A hash diff --git a/Task/Associative-array-Creation/Vim-Script/associative-array-creation.vim b/Task/Associative-array-Creation/Vim-Script/associative-array-creation.vim new file mode 100644 index 0000000000..0b222d276e --- /dev/null +++ b/Task/Associative-array-Creation/Vim-Script/associative-array-creation.vim @@ -0,0 +1,20 @@ +" Creating a dictionary with some initial values +let dict = {"one": 1, "two": 2} + +" Retrieving a value +let two_a = dict["two"] +let two_b = dict.two +let two_c = get(dict, "two", "default value for missing key") + +" Modifying a value +let dict["one"] = 1.0 +let dict.two = 2.0 + +" Adding a new value +let dict["three"] = 3 +let dict.four = 4 + +" Removing a value +let one = remove(dict, "one") +unlet dict["two"] +unlet dict.three diff --git a/Task/Associative-array-Iteration/00DESCRIPTION b/Task/Associative-array-Iteration/00DESCRIPTION index 49d6d55f8b..ed3f7656d0 100644 --- a/Task/Associative-array-Iteration/00DESCRIPTION +++ b/Task/Associative-array-Iteration/00DESCRIPTION @@ -1,3 +1,6 @@ -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. +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. {{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 index e59605268a..4b2aabd8a6 100644 --- a/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime +++ b/Task/Associative-array-Iteration/Aime/associative-array-iteration.aime @@ -7,6 +7,6 @@ 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"); + o_form("key ~, value ~ (~)\n", s, r[s], r_type(r, s)); } while (r_greater(r, s, s)); } diff --git a/Task/Associative-array-Iteration/Babel/associative-array-iteration.pb b/Task/Associative-array-Iteration/Babel/associative-array-iteration.pb new file mode 100644 index 0000000000..c7a28ec225 --- /dev/null +++ b/Task/Associative-array-Iteration/Babel/associative-array-iteration.pb @@ -0,0 +1,21 @@ +((main + { (('foo' 12) + ('bar' 33) + ('baz' 42)) + mkhash ! + + entsha + dup + {1 ith nl <<} each + + "-----\n" << + + {2 ith %d nl <<} each}) + +(mkhash + { <- newha -> + { <- dup -> + dup 1 ith + <- 0 ith -> + inskha } + each })) diff --git a/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp b/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp index 1268cbb3f6..07ffb4c47f 100644 --- a/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp +++ b/Task/Associative-array-Iteration/C++/associative-array-iteration-1.cpp @@ -1,12 +1,9 @@ -#include #include -#include -#include +#include +#include int main() { - using MyDict = std::map; - - MyDict dict = { + std::map dict { {"One", 1}, {"Two", 2}, {"Three", 7} @@ -15,15 +12,6 @@ int main() { dict["Three"] = 3; std::cout << "One: " << dict["One"] << std::endl; - - // Make vector of the keys from our map - std::vector keys; - std::transform(dict.begin(), dict.end(), std::back_inserter(keys), - [](MyDict::value_type& kv) { return kv.first; }); - - std::cout << "Keys: " << std::endl; - for(auto& key: keys) std::cout << " " << key << std::endl; - std::cout << "Key/Value pairs: " << std::endl; for(auto& kv: dict) { std::cout << " " << kv.first << ": " << kv.second << std::endl; diff --git a/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp b/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp index b36f44ece5..95419e0ae7 100644 --- a/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp +++ b/Task/Associative-array-Iteration/C++/associative-array-iteration-2.cpp @@ -4,9 +4,9 @@ myDict["world"] = 2; myDict["!"] = 3; // iterating over key-value pairs: -for (std::map::iterator it = myDict.begin(); it != myDict.end(); it++) { - // the thing pointed to by the iterator is a pair - std::string key = it->first; - int value = it->second; +for (std::map::iterator it = myDict.begin(); it != myDict.end(); ++it) { + // the thing pointed to by the iterator is an std::pair& + const std::string& key = it->first; + int& value = it->second; std::cout << "key = " << key << ", value = " << value << std::endl; } diff --git a/Task/Associative-array-Iteration/Dao/associative-array-iteration.dao b/Task/Associative-array-Iteration/Dao/associative-array-iteration.dao index fd1353d431..a71bb1966a 100644 --- a/Task/Associative-array-Iteration/Dao/associative-array-iteration.dao +++ b/Task/Associative-array-Iteration/Dao/associative-array-iteration.dao @@ -1,3 +1,7 @@ -m = { 'def' => 1, 'abc' => 2 } -for( kv in m ) io.writeln( kv ); -for( k in m.keys(); v in m.values() ) io.writeln( k, v ) +dict = { 'def' => 1, 'abc' => 2 } + +for( keyvalue in dict ) io.writeln( keyvalue ); +for( key in dict.keys(); value in dict.values() ) io.writeln( key, value ) +dict.iterate { [key, value] + io.writeln( key, value ) +} diff --git a/Task/Associative-array-Iteration/Forth/associative-array-iteration.fth b/Task/Associative-array-Iteration/Forth/associative-array-iteration-1.fth similarity index 100% rename from Task/Associative-array-Iteration/Forth/associative-array-iteration.fth rename to Task/Associative-array-Iteration/Forth/associative-array-iteration-1.fth diff --git a/Task/Associative-array-Iteration/Forth/associative-array-iteration-2.fth b/Task/Associative-array-Iteration/Forth/associative-array-iteration-2.fth new file mode 100644 index 0000000000..5f9cace8b4 --- /dev/null +++ b/Task/Associative-array-Iteration/Forth/associative-array-iteration-2.fth @@ -0,0 +1,137 @@ +\ Written in ANS-Forth; tested under VFX. +\ Requires the novice package: http://www.forth.org/novice.html +\ The following should already be done: +\ include novice.4th +\ include association.4th + +\ I would define high-level languages as those that allow programs to be written without explicit iteration. Iteration is a major source of bugs. +\ The example from the FFL library doesn't hide iteration, whereas this example from the novice-package does. + + +marker AssociationIteration.4th + +\ ****** +\ ****** The following defines a node in an association (each node is derived from ELEMENT). +\ ****** + +element + w field .inventor +constant language \ describes a programming language + +: init-language ( inventor name node -- node ) + init-element >r + hstr r@ .inventor ! + r> ; + +: new-language ( inventor name -- node ) + language alloc + init-language ; + +: show-language ( count node -- ) + >r + 1+ \ -- count+1 + cr r@ .key @ count colorless type ." invented by: " r@ .inventor @ count type + rdrop ; + +: show-languages-forward ( handle -- ) + 0 \ -- handle count + swap .root @ ['] show-language walk> + cr ." count: " . + cr ; + +: show-languages-backward ( handle -- ) + 0 \ -- handle count + swap .root @ ['] show-language r + ['] compare ['] kill-language-attachments ['] copy-language-attachments + r> init-association ; + +: new-languages ( -- record ) + languages alloc + init-languages ; + + +\ ****** +\ ****** The following filters one association into another, including everything that matches a particular inventor. +\ ****** + +: { inventor handle new-handle node -- inventor handle new-handle } + inventor count node .inventor @ count compare A=B = if + node handle dup-element new-handle insert then + inventor handle new-handle ; + +: filter-inventor ( inventor handle -- new-handle ) + dup similar-association \ -- inventor handle new-handle + over .root @ ['] walk> \ -- inventor handle new-handle + nip nip ; + +\ ****** +\ ****** The following is a demonstration with some sample data. +\ ****** + + +new-languages + c" Moore, Chuck" c" Forth " new-language over insert + c" Ichiah, Jean" c" Ada " new-language over insert + c" Wirth, Niklaus" c" Pascal " new-language over insert + c" Wirth, Niklaus" c" Oberon " new-language over insert + c" McCarthy, John" c" Lisp " new-language over insert + c" van Rossum, Guido" c" Python " new-language over insert + c" Gosling, Jim" c" Java " new-language over insert + c" Ierusalimschy, Roberto" c" Lua " new-language over insert + c" Matsumoto, Yukihiro" c" Ruby " new-language over insert + c" Pestov, Slava" c" Factor " new-language over insert + c" Gosling, James" c" Java " new-language over insert + c" Wirth, Niklaus" c" Modula-2 " new-language over insert + c" Ritchie, Dennis" c" C " new-language over insert + c" Stroustrup, Bjarne" c" C++ " new-language over insert +constant some-languages + + +cr .( everything in SOME-LANGUAGES ordered forward: ) + +some-languages show-languages-forward + + +cr .( everything in SOME-LANGUAGES ordered backward: ) + +some-languages show-languages-backward + + +cr .( everything in SOME-LANGUAGES invented by Wirth: ) + +c" Wirth, Niklaus" some-languages filter-inventor dup show-languages-forward kill-association + + +cr .( everything in SOME-LANGUAGES within 'F' and 'L': ) + +c" F" c" L" some-languages filter within dup show-languages-forward kill-association + + +cr .( everything in SOME-LANGUAGES not within 'F' and 'L': ) + +c" F" c" L" some-languages filter without dup show-languages-forward kill-association + + +some-languages kill-association diff --git a/Task/Associative-array-Iteration/Java/associative-array-iteration.java b/Task/Associative-array-Iteration/Java/associative-array-iteration-1.java similarity index 100% rename from Task/Associative-array-Iteration/Java/associative-array-iteration.java rename to Task/Associative-array-Iteration/Java/associative-array-iteration-1.java diff --git a/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java b/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java new file mode 100644 index 0000000000..8c0bf2391c --- /dev/null +++ b/Task/Associative-array-Iteration/Java/associative-array-iteration-2.java @@ -0,0 +1,15 @@ +Map myDict = new HashMap<>(); +myDict.put("hello", 1); +myDict.put("world", 2); +myDict.put("!", 3); + +// iterating over key-value pairs: +myDict.forEach((k, v) -> { + System.out.printf("key = %s, value = %s%n", k, v); +}); + +// iterating over keys: +myDict.keySet().forEach(k -> System.out.printf("key = %s%n", k)); + +// iterating over values: +myDict.values().forEach(v -> System.out.printf("value = %s%n", v)); diff --git a/Task/Associative-array-Iteration/Lua/associative-array-iteration.lua b/Task/Associative-array-Iteration/Lua/associative-array-iteration.lua index 9db20748c5..0c8e355945 100644 --- a/Task/Associative-array-Iteration/Lua/associative-array-iteration.lua +++ b/Task/Associative-array-Iteration/Lua/associative-array-iteration.lua @@ -1,8 +1,9 @@ -local table = { +local t = { ["foo"] = "bar", ["baz"] = 6, - 42 = 7, + fortytwo = 7 } -for key,val in pairs(table) do - print(string.format("%s: %s\n", key, val) + +for key,val in pairs(t) do + print(string.format("%s: %s", key, val)) end diff --git a/Task/Associative-array-Iteration/Maple/associative-array-iteration-1.maple b/Task/Associative-array-Iteration/Maple/associative-array-iteration-1.maple new file mode 100644 index 0000000000..5879619f7c --- /dev/null +++ b/Task/Associative-array-Iteration/Maple/associative-array-iteration-1.maple @@ -0,0 +1,9 @@ +> T := table( [ "A" = 1, "B" = 2, "C" = 3, "D" = 4 ] ); +> for i in indices( T, nolist ) do print(i ) end: + "A" + + "B" + + "C" + + "D" diff --git a/Task/Associative-array-Iteration/Maple/associative-array-iteration-2.maple b/Task/Associative-array-Iteration/Maple/associative-array-iteration-2.maple new file mode 100644 index 0000000000..2f7466683e --- /dev/null +++ b/Task/Associative-array-Iteration/Maple/associative-array-iteration-2.maple @@ -0,0 +1,7 @@ +> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ): +> for i in indices( T ) do print( i, T[ op( i ) ] ) end: + ["a"], 1 + + ["b"], 2 + + ["c", "d"], 3 diff --git a/Task/Associative-array-Iteration/Maple/associative-array-iteration-3.maple b/Task/Associative-array-Iteration/Maple/associative-array-iteration-3.maple new file mode 100644 index 0000000000..d0da64675c --- /dev/null +++ b/Task/Associative-array-Iteration/Maple/associative-array-iteration-3.maple @@ -0,0 +1,6 @@ +> for i in indices( T, pairs ) do print( i) end: + "a" = 1 + + "b" = 2 + + ("c", "d") = 3 diff --git a/Task/Associative-array-Iteration/Maple/associative-array-iteration-4.maple b/Task/Associative-array-Iteration/Maple/associative-array-iteration-4.maple new file mode 100644 index 0000000000..2f661794c7 --- /dev/null +++ b/Task/Associative-array-Iteration/Maple/associative-array-iteration-4.maple @@ -0,0 +1,6 @@ +> for i in entries( T ) do print( i) end: + [1] + + [3] + + [2] diff --git a/Task/Associative-array-Iteration/Maple/associative-array-iteration.maple b/Task/Associative-array-Iteration/Maple/associative-array-iteration.maple deleted file mode 100644 index 9e035253a6..0000000000 --- a/Task/Associative-array-Iteration/Maple/associative-array-iteration.maple +++ /dev/null @@ -1,21 +0,0 @@ -> T := table( [ "a" = 1, "b" = 2, ("c","d") = 3 ] ): -> for i in indices( T ) do print( i, T[ op( i ) ] ) end: - ["a"], 1 - - ["c", "d"], 3 - - ["b"], 2 - -> for i in indices( T ) do print( op( i ) ) end: - "a" - - "c", "d" - - "b" - -> for i in entries( T ) do print( i) end: - [1] - - [3] - - [2] diff --git a/Task/Associative-array-Iteration/NewLISP/associative-array-iteration.newlisp b/Task/Associative-array-Iteration/NewLISP/associative-array-iteration.newlisp new file mode 100644 index 0000000000..72c119319f --- /dev/null +++ b/Task/Associative-array-Iteration/NewLISP/associative-array-iteration.newlisp @@ -0,0 +1,12 @@ +;; using an association list: +(setq alist '(("A" "a") ("B" "b") ("C" "c"))) + +;; list keys +(map first alist) + +;; list values +(map last alist) + +;; loop over the assocation list: +(dolist (elem alist) + (println (format "%s -> %s" (first elem) (last elem)))) diff --git a/Task/Associative-array-Iteration/Oberon-2/associative-array-iteration.oberon-2 b/Task/Associative-array-Iteration/Oberon-2/associative-array-iteration.oberon-2 new file mode 100644 index 0000000000..6cdd9f8bf4 --- /dev/null +++ b/Task/Associative-array-Iteration/Oberon-2/associative-array-iteration.oberon-2 @@ -0,0 +1,41 @@ +MODULE AssociativeArray; +IMPORT + ADT:Dictionary, + Object:Boxed, + Out; +TYPE + Key = STRING; + Value = Boxed.LongInt; + +VAR + assocArray: Dictionary.Dictionary(Key,Value); + iterK: Dictionary.IterKeys(Key,Value); + iterV: Dictionary.IterValues(Key,Value); + aux: Value; + k: Key; + +BEGIN + assocArray := NEW(Dictionary.Dictionary(Key,Value)); + assocArray.Set("ten",NEW(Value,10)); + assocArray.Set("eleven",NEW(Value,11)); + + aux := assocArray.Get("ten"); + Out.LongInt(aux.value,0);Out.Ln; + aux := assocArray.Get("eleven"); + Out.LongInt(aux.value,0);Out.Ln;Out.Ln; + + (* Iterate keys *) + iterK := assocArray.IterKeys(); + WHILE (iterK.Next(k)) DO + Out.Object(k);Out.Ln + END; + + Out.Ln; + + (* Iterate values *) + iterV := assocArray.IterValues(); + WHILE (iterV.Next(aux)) DO + Out.LongInt(aux.value,0);Out.Ln + END + +END AssociativeArray. diff --git a/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx b/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx index 7f69e7efcc..f1f2dcf6f9 100644 --- a/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx +++ b/Task/Associative-array-Iteration/REXX/associative-array-iteration.rexx @@ -1,10 +1,10 @@ /*REXX program shows how to set/display values for an associative array.*/ /*┌────────────────────────────────────────────────────────────────────┐ - │ The (below) two REXX statements aren't really necessary, but it │ + │ The (below) two REXX statements aren't really necessary, but it │ │ shows how to define any and all entries in a associative array so │ │ that if a "key" is used that isn't defined, it can be displayed to │ - │ indicate such, or its value can be checked to determine if it has │ - │ been set. │ + │ indicate such, or its value can be checked to determine if a │ + │ particular associative array element has been set (defined). │ └────────────────────────────────────────────────────────────────────┘*/ stateF.=' [not defined yet] ' /*sets any/all state former caps.*/ stateN.=' [not defined yet] ' /*sets any/all state names. */ @@ -12,13 +12,11 @@ stateN.=' [not defined yet] ' /*sets any/all state names. */ │ In REXX, when a "key" is used, it's normally stored (internally) │ │ as uppercase characters (as in the examples below). Actually, any │ │ characters can be used, including blank(s) and non-displayable │ - │ characters (including '00'x, 'ff'x, commas, periods, quotes, ...).│ + │ characters (including '00'x, 'ff'x, commas, periods, quotes, ···).│ └────────────────────────────────────────────────────────────────────┘*/ -stateL='' /*list of states (empty now). */ - /*nice to be in alphabetic order,*/ - /*they'll be listed in this order*/ - /*With a little more code, they */ - /* could be sorted quite easily.*/ +stateL='' /*list of states (empty now). It's nice to be in alpha-*/ + /*betic order; they'll be listed in this order. With a */ + /*little more code, they could be sorted quite easily. */ call setSC 'al', "Alabama" ,'Tuscaloosa' call setSC 'ca', "California" ,'Benicia' @@ -46,14 +44,14 @@ call setSC 'sc', "South Carolina" ,'Charlestown' call setSC 'tn', "Tennessee" ,'Murfreesboro' call setSC 'vt', "Vermont" ,'Windsor' - do j=1 for words(stateL) /*list all capitals that were set*/ - q=word(stateL,j) - say 'the former capital of ('q")" stateN.q "was" stateC.q - end /*j*/ + do j=1 for words(stateL) /*show all capitals that were set*/ + q=word(stateL,j) /*get the next state in the list.*/ + say 'the former capital of ('q") " stateN.q " was " stateC.q + end /*j*/ /* [↑] display states defined. */ exit /*stick a fork in it, we're done.*/ /*─────────────────────────────────────setSC subroutine─────────────────*/ setSC: arg code; parse arg ,name,cap /*get upper code, get name & cap.*/ stateL=stateL code /*keep a list of all state codes.*/ stateN.code=name /*set the state's name. */ stateC.code=cap /*set the state's capital. */ -return +return /*return to invoker, SET is done.*/ diff --git a/Task/Associative-array-Iteration/Ruby/associative-array-iteration.rb b/Task/Associative-array-Iteration/Ruby/associative-array-iteration-1.rb similarity index 100% rename from Task/Associative-array-Iteration/Ruby/associative-array-iteration.rb rename to Task/Associative-array-Iteration/Ruby/associative-array-iteration-1.rb diff --git a/Task/Associative-array-Iteration/Ruby/associative-array-iteration-2.rb b/Task/Associative-array-Iteration/Ruby/associative-array-iteration-2.rb new file mode 100644 index 0000000000..4d58d8e90c --- /dev/null +++ b/Task/Associative-array-Iteration/Ruby/associative-array-iteration-2.rb @@ -0,0 +1,11 @@ +for key, value in myDict + puts "key = #{key}, value = #{value}" +end + +for key in myDict.keys + puts "key = #{key}" +end + +for value in myDict.values + puts "value = #{value}" +end diff --git a/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust b/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust new file mode 100644 index 0000000000..404f6d6d96 --- /dev/null +++ b/Task/Associative-array-Iteration/Rust/associative-array-iteration.rust @@ -0,0 +1,16 @@ +use std::collections::HashMap; +fn main() { + let mut squares = HashMap::new(); + squares.insert("one", 1i32); + squares.insert("two", 4); + squares.insert("three", 9); + for key in squares.keys() { + println!("Key {}", key); + } + for value in squares.values() { + println!("Value {}", value); + } + for (key, value) in squares.iter() { + println!("{} => {}", key, value); + } +} diff --git a/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala b/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala index a93d8d8cc6..263aa4cebb 100644 --- a/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala +++ b/Task/Associative-array-Iteration/Scala/associative-array-iteration.scala @@ -1,7 +1,7 @@ - val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands") +val m = Map("Amsterdam" -> "Netherlands", "New York" -> "USA", "Heemstede" -> "Netherlands") - 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") +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/Associative-array-Iteration/Scheme/associative-array-iteration-1.ss b/Task/Associative-array-Iteration/Scheme/associative-array-iteration-1.ss new file mode 100644 index 0000000000..9bfa1d75cf --- /dev/null +++ b/Task/Associative-array-Iteration/Scheme/associative-array-iteration-1.ss @@ -0,0 +1,11 @@ +;; Create an associative array (hash-table) whose keys are strings: +(define table (hash-table 'string=? + '("hello" . 0) '("world" . 22) '("!" . 999))) + +;; Iterate over the table, passing the key and the value of each entry +;; as arguments to a function: +(hash-table-for-each + table + ;; Create by "partial application" a function that accepts 2 arguments, + ;; the key and the value: + (pa$ format #t "Key = ~a, Value = ~a\n")) diff --git a/Task/Associative-array-Iteration/Scheme/associative-array-iteration-2.ss b/Task/Associative-array-Iteration/Scheme/associative-array-iteration-2.ss new file mode 100644 index 0000000000..89046a8bd0 --- /dev/null +++ b/Task/Associative-array-Iteration/Scheme/associative-array-iteration-2.ss @@ -0,0 +1,11 @@ +;; Iterate over the table and create a list of the keys and the +;; altered values: +(hash-table-map + table + (lambda (key val) (list key (+ val 5000)))) + +;; Create a new table that has the same keys but altered values. +(use gauche.collection) +(map-to + (lambda (k-v) (cons (car k-v) (+ (cdr k-v) 5000))) + table) diff --git a/Task/Associative-array-Iteration/UNIX-Shell/associative-array-iteration-1.sh b/Task/Associative-array-Iteration/UNIX-Shell/associative-array-iteration-1.sh index d7b05c8817..a0d98b02ea 100644 --- a/Task/Associative-array-Iteration/UNIX-Shell/associative-array-iteration-1.sh +++ b/Task/Associative-array-Iteration/UNIX-Shell/associative-array-iteration-1.sh @@ -1,4 +1,4 @@ -a=([key1]=value1 [key2]=value2) +typeset -A a=([key1]=value1 [key2]=value2) # just keys printf '%s\n' "${!a[@]}" diff --git a/Task/Associative-array-Iteration/Vim-Script/associative-array-iteration.vim b/Task/Associative-array-Iteration/Vim-Script/associative-array-iteration.vim new file mode 100644 index 0000000000..44b961203f --- /dev/null +++ b/Task/Associative-array-Iteration/Vim-Script/associative-array-iteration.vim @@ -0,0 +1,18 @@ +let dict = {"apples": 11, "oranges": 25, "pears": 4} + +echo "Iterating over key-value pairs" +for [key, value] in items(dict) + echo key " => " value +endfor +echo "\n" + +echo "Iterating over keys" +for key in keys(dict) + echo key +endfor +echo "\n" + +echo "Iterating over values" +for value in values(dict) + echo value +endfor diff --git a/Task/Average-loop-length/D/average-loop-length.d b/Task/Average-loop-length/D/average-loop-length.d index cc1773e523..e2043a62a9 100644 --- a/Task/Average-loop-length/D/average-loop-length.d +++ b/Task/Average-loop-length/D/average-loop-length.d @@ -1,7 +1,7 @@ -import std.stdio, std.random, std.math, std.algorithm, std.range; +import std.stdio, std.random, std.math, std.algorithm, std.range, std.format; -real analytical(in int n) /*pure nothrow*/ { - enum aux = (int k)=> reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1)); +real analytical(in int n) pure nothrow @safe /*@nogc*/ { + enum aux = (int k) => reduce!q{a * b}(1.0L, iota(n - k + 1, n + 1)); return iota(1, n + 1) .map!(k => (aux(k) * k ^^ 2) / (real(n) ^^ (k + 1))) .sum; diff --git a/Task/Average-loop-length/Haskell/average-loop-length.hs b/Task/Average-loop-length/Haskell/average-loop-length.hs new file mode 100644 index 0000000000..56bd3875ef --- /dev/null +++ b/Task/Average-loop-length/Haskell/average-loop-length.hs @@ -0,0 +1,54 @@ +import System.Random +import qualified Data.Set as S +import Text.Printf + +findRep :: (Random a, Integral a, RandomGen b) => a -> b -> (a, b) +findRep n gen = findRep' (S.singleton 1) 1 gen + where + findRep' seen len gen' + | S.member fx seen = (len, gen'') + | otherwise = findRep' (S.insert fx seen) (len + 1) gen'' + where + (fx, gen'') = randomR (1, n) gen' + +statistical :: (Integral a, Random b, Integral b, RandomGen c, Fractional d) => + a -> b -> c -> (d, c) +statistical samples size gen = + let (total, gen') = sar samples gen 0 + in ((fromIntegral total) / (fromIntegral samples), gen') + where + sar 0 gen' acc = (acc, gen') + sar samples' gen' acc = + let (len, gen'') = findRep size gen' + in sar (samples' - 1) gen'' (acc + len) + +factorial :: (Integral a) => a -> a +factorial n = foldl (*) 1 [1..n] + +analytical :: (Integral a, Fractional b) => a -> b +analytical n = sum [fromIntegral num / + fromIntegral (factorial (n - i)) / + fromIntegral (n ^ i) | + i <- [1..n]] + where num = factorial n + +test :: (Integral a, Random b, Integral b, PrintfArg b, RandomGen c) => + a -> [b] -> c -> IO c +test _ [] gen = return gen +test samples (x:xs) gen = do + let (st, gen') = statistical samples x gen + an = analytical x + err = abs (st - an) / st * 100.0 + str = printf "%3d %9.4f %12.4f (%6.2f%%)\n" + x (st :: Float) (an :: Float) (err :: Float) + putStr str + test samples xs gen' + +main :: IO () +main = do + putStrLn " N average analytical (error)" + putStrLn "=== ========= ============ =========" + let samples = 10000 :: Integer + range = [1..20] :: [Integer] + _ <- test samples range $ mkStdGen 0 + return () diff --git a/Task/Average-loop-length/PicoLisp/average-loop-length.l b/Task/Average-loop-length/PicoLisp/average-loop-length.l new file mode 100644 index 0000000000..d81e3f1a66 --- /dev/null +++ b/Task/Average-loop-length/PicoLisp/average-loop-length.l @@ -0,0 +1,42 @@ +(scl 4) +(seed (in "/dev/urandom" (rd 8))) + +(de fact (N) + (if (=0 N) 1 (apply * (range 1 N))) ) + +(de analytical (N) + (sum + '((I) + (/ + (* (fact N) 1.0) + (** N I) + (fact (- N I)) ) ) + (range 1 N) ) ) + +(de testing (N) + (let (C 0 N (dec N) X 0 B 0 I 1000000) + (do I + (zero B) + (one X) + (while (=0 (& B X)) + (inc 'C) + (setq + B (| B X) + X (** 2 (rand 0 N)) ) ) ) + (*/ C 1.0 I) ) ) + +(let F (2 8 8 6) + (tab F "N" "Avg" "Exp" "Diff") + (for I 20 + (let (A (testing I) B (analytical I)) + (tab F + I + (round A 4) + (round B 4) + (round + (* + (abs (- (*/ A 1.0 B) 1.0)) + 100 ) + 2 ) ) ) ) ) + +(bye) diff --git a/Task/Average-loop-length/REXX/average-loop-length.rexx b/Task/Average-loop-length/REXX/average-loop-length.rexx index 57e34ef7a7..6308b61663 100644 --- a/Task/Average-loop-length/REXX/average-loop-length.rexx +++ b/Task/Average-loop-length/REXX/average-loop-length.rexx @@ -1,4 +1,4 @@ -/*REXX pgmm computes avg loop length mapping a random field 1..N to 1..N*/ +/*REXX pgm 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.*/ diff --git a/Task/Average-loop-length/Seed7/average-loop-length.seed7 b/Task/Average-loop-length/Seed7/average-loop-length.seed7 new file mode 100644 index 0000000000..374413d64a --- /dev/null +++ b/Task/Average-loop-length/Seed7/average-loop-length.seed7 @@ -0,0 +1,64 @@ +$ include "seed7_05.s7i"; + include "float.s7i"; + +const integer: TESTS is 1000000; + +const func float: factorial (in integer: number) is func + result + var float: factorial is 1.0; + local + var integer: i is 0; + begin + for i range 2 to number do + factorial *:= flt(i); + end for; + end func; + +const func float: analytical (in integer: number) is func + result + var float: sum is 0.0; + local + var integer: i is 0; + begin + for i range 1 to number do + sum +:= factorial(number) / factorial(number - i) / flt(number)**i; + end for; + end func; + +const func float: experimental (in integer: number) is func + result + var float: experimental is 0.0; + local + var integer: run is 0; + var set of integer: seen is EMPTY_SET; + var integer: current is 1; + var integer: count is 0; + begin + for run range 1 to TESTS do + current := 1; + seen := EMPTY_SET; + while current not in seen do + incr(count); + incl(seen, current); + current := rand(1, number); + end while; + end for; + experimental := flt(count) / flt(TESTS); + end func; + +const proc: main is func + local + var integer: number is 0; + var float: analytical is 0.0; + var float: experimental is 0.0; + var float: err is 0.0; + begin + writeln(" N avg calc %diff"); + for number range 1 to 20 do + analytical := analytical(number); + experimental := experimental(number); + err := abs(experimental - analytical) / analytical * 100.0; + writeln(number lpad 2 <& experimental digits 4 lpad 7 <& + analytical digits 4 lpad 7 <& err digits 3 lpad 7); + end for; + end func; diff --git a/Task/Averages-Arithmetic-mean/Babel/averages-arithmetic-mean.pb b/Task/Averages-Arithmetic-mean/Babel/averages-arithmetic-mean.pb new file mode 100644 index 0000000000..c17778a27e --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Babel/averages-arithmetic-mean.pb @@ -0,0 +1,12 @@ +((main { + (2 3 5 7 11 13 17 19 23) + avg ! + %d nl <<}) + +(avg { + dup + <- sum ! -> + len + cudiv }) + +(sum { <- 0 -> {+} each })) diff --git a/Task/Averages-Arithmetic-mean/Befunge/averages-arithmetic-mean.bf b/Task/Averages-Arithmetic-mean/Befunge/averages-arithmetic-mean.bf index d98e5a5668..63a0960380 100644 --- a/Task/Averages-Arithmetic-mean/Befunge/averages-arithmetic-mean.bf +++ b/Task/Averages-Arithmetic-mean/Befunge/averages-arithmetic-mean.bf @@ -1,3 +1,2 @@ -0001>p&: #v_$::01g/.@ - ^10+1g10+< -Enter 0 (zero) to finish. +&:0\:!v!:-1< + @./\$_\&+\^ diff --git a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-1.d b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-1.d index ebeaf8b920..2cb30938e5 100644 --- a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-1.d +++ b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-1.d @@ -1,6 +1,4 @@ -import std.stdio; - -real mean(Range)(Range r) { +real mean(Range)(Range r) pure nothrow @nogc { real sum = 0.0; int count; @@ -16,8 +14,10 @@ real mean(Range)(Range r) { } void main() { + import std.stdio; + int[] data; - writeln("mean: ", data.mean()); + writeln("Mean: ", data.mean); data = [3, 1, 4, 1, 5, 9]; - writeln("mean: ", data.mean()); + writeln("Mean: ", data.mean); } diff --git a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d index 15bfc75418..5e1cd00e7d 100644 --- a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d +++ b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-2.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range; -real mean(Range)(Range r) pure nothrow { +real mean(Range)(Range r) pure nothrow @nogc { return r.sum / max(1.0L, r.count); } diff --git a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-3.d b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-3.d index 6d2aed0863..52d2c50cea 100644 --- a/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-3.d +++ b/Task/Averages-Arithmetic-mean/D/averages-arithmetic-mean-3.d @@ -1,10 +1,10 @@ import std.stdio, std.conv, std.algorithm, std.math, std.traits; -CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!(T)) { - alias CommonType!(T, real) E; +CommonType!(T, real) mean(T)(T[] n ...) if (isNumeric!T) { + alias E = CommonType!(T, real); auto num = n.dup; - schwartzSort!(abs, "a > b")(num); - return reduce!q{a+b}(0.0L, map!(to!E)(num)) / max(1, num.length); + num.schwartzSort!(abs, "a > b"); + return num.map!(to!E).sum(0.0L) / max(1, num.length); } void main() { diff --git a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena index 3c59afbe81..c01bddc2cc 100644 --- a/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena +++ b/Task/Averages-Arithmetic-mean/Elena/averages-arithmetic-mean.elena @@ -21,12 +21,12 @@ theValue += aValue. ] - #method number = theValue / theCount. + #method value = theValue / theCount. } // --- Program --- #symbol program = [ - console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) number). + console writeLine:(MeanAction new foreach:(1, 2, 3, 4, 5, 6, 7, 8) value). ]. diff --git a/Task/Averages-Arithmetic-mean/Elixir/averages-arithmetic-mean.elixir b/Task/Averages-Arithmetic-mean/Elixir/averages-arithmetic-mean.elixir new file mode 100644 index 0000000000..020fc02d88 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Elixir/averages-arithmetic-mean.elixir @@ -0,0 +1,3 @@ +defmodule RC do + def mean(list), do: Enum.sum(list) / Enum.count(list) +end diff --git a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-1.js b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-1.js index c526a731c5..650845e25d 100644 --- a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-1.js +++ b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-1.js @@ -9,3 +9,4 @@ function mean(array) } alert( mean( [1,2,3,4,5] ) ); // 3 +alert( mean( [] ) ); // 0 diff --git a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-2.js b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-2.js index 8d7acbc6b3..13ed6f7099 100644 --- a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-2.js +++ b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-2.js @@ -1,4 +1,9 @@ -function mean(a) -{ - return a.length ? Functional.reduce('+', 0, a) / a.length : 0; -} +function mean(array) { + var sum = 0; + array.forEach(function(value){ + sum += value; + }); + return array.length ? sum / array.length : 0; + } + +alert( mean( [1,2,3,4,5] ) ); // 3 diff --git a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-3.js b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-3.js new file mode 100644 index 0000000000..58cc2b41b4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-3.js @@ -0,0 +1,9 @@ +function mean(array) { + return !array.length ? 0 + : array.reduce(function(pre, cur, i) { + return (pre * i + cur) / (i + 1); + }); + } + +alert( mean( [1,2,3,4,5] ) ); // 3 +alert( mean( [] ) ); // 0 diff --git a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-4.js b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-4.js new file mode 100644 index 0000000000..7d6d47f16a --- /dev/null +++ b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-4.js @@ -0,0 +1,9 @@ +Array.prototype.mean = function() { + return !this.length ? 0 + : this.reduce(function(pre, cur, i) { + return (pre * i + cur) / (i + 1); + }); + } + +alert( [1,2,3,4,5].mean() ); // 3 +alert( [].mean() ); // 0 diff --git a/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-5.js b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-5.js new file mode 100644 index 0000000000..8d7acbc6b3 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/JavaScript/averages-arithmetic-mean-5.js @@ -0,0 +1,4 @@ +function mean(a) +{ + return a.length ? Functional.reduce('+', 0, a) / a.length : 0; +} diff --git a/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-1.mercury b/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-1.mercury new file mode 100644 index 0000000000..5e88ce6063 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-1.mercury @@ -0,0 +1,20 @@ +:- module arithmetic_mean. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module float, list, require. + +main(!IO) :- + io.print_line(mean([1.0, 2.0, 3.0, 4.0, 5.0]), !IO). + +:- func mean(list(float)) = float. + +mean([]) = func_error("mean: emtpy list"). +mean(Ns @ [_ | _]) = foldl((+), Ns, 0.0) / float(length(Ns)). + +:- end_module arithmetic_mean. diff --git a/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-2.mercury b/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-2.mercury new file mode 100644 index 0000000000..7928c5d4d2 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Mercury/averages-arithmetic-mean-2.mercury @@ -0,0 +1,3 @@ +:- func mean(list(float)::in(non_empty_list)) = (float::out). + +mean(Ns) = foldl((+), Ns, 0.0) / float(length(Ns)). diff --git a/Task/Averages-Arithmetic-mean/Prolog/averages-arithmetic-mean.pro b/Task/Averages-Arithmetic-mean/Prolog/averages-arithmetic-mean.pro new file mode 100644 index 0000000000..91614ccfc9 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Prolog/averages-arithmetic-mean.pro @@ -0,0 +1,4 @@ +mean(List, Mean) :- + length(List, Length), + sumlist(List, Sum), + Mean is Sum / Length. diff --git a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx index ba4851fe06..fddfdee535 100644 --- a/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx +++ b/Task/Averages-Arithmetic-mean/REXX/averages-arithmetic-mean.rexx @@ -1,20 +1,22 @@ /*REXX pgm finds the averages/arithmetic mean of several lists (vectors)*/ -@.1 = 10 9 8 7 6 5 4 3 2 1 -@.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 -@.3 = '10 20 30 40 50 -100 4.7 -11e2' -@.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2' -@.5 = 'World War I & World War II' -@.6 = '' - do j=1 for 6 - say 'numbers = ' @.j; say 'average = ' avg(@.j); say - end /*t*/ + @.1 = 10 9 8 7 6 5 4 3 2 1 + @.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11 + @.3 = '10 20 30 40 50 -100 4.7 -11e2' + @.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2' + @.5 = 'World War I & World War II' + @.6 = + do j=1 for 6 + say 'numbers = ' @.j; say 'average = ' avg(@.j); say copies('═',60) + end /*t*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────AVG subroutine──────────────────────*/ -avg: procedure; parse arg x; w=words(x); s=0; $=left('',20) -if w==0 then return 'N/A: ───[null vector.]' - do k=1 for w; _=word(x,k) - if datatype(_,'N') then do; s=s+_; iterate; end - say $ '***error!*** non-numeric: ' _; w=w-1 /*adjust W*/ - end /*k*/ -if w==0 then return 'N/A: ───[no numeric values.]' +avg: procedure; parse arg x; w=words(x); s=0; $=left('',20) +if w==0 then return 'N/A: ───[null vector.]' + + do k=1 for w; _=word(x,k) + if datatype(_,'N') then do; s=s+_; iterate; end + say $ '***error!*** non-numeric: ' _; w=w-1 /*adjust W*/ + end /*k*/ + +if w==0 then return 'N/A: ───[no numeric values.]' return s/max(1,w) diff --git a/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb b/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb index 7d29191e59..1e1b1411e9 100644 --- a/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb +++ b/Task/Averages-Arithmetic-mean/Ruby/averages-arithmetic-mean.rb @@ -1,2 +1,9 @@ +def mean(nums) + nums.inject(0.0, :+) / nums.size +end + nums = [3, 1, 4, 1, 5, 9] -nums.empty? ? 0 : nums.inject(:+) / Float(nums.size) +nums.size.downto(0) do |i| + ary = nums[0,i] + puts "array size #{ary.size} : #{mean(ary)}" +end diff --git a/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust b/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust new file mode 100644 index 0000000000..14dfeeaea1 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Rust/averages-arithmetic-mean.rust @@ -0,0 +1,15 @@ +fn sum(arr: &[f64]) -> f64 { + return arr.iter().fold(0.0, |p,q| p + *q); +} + +fn mean(arr: &[f64]) -> f64 { + return sum(arr) / arr.len() as f64; +} + +fn main() { + let v = &[2.0, 3.0, 5.0, 7.0, 13.0, 21.0, 33.0, 54.0]; + println!("mean of {}: {}", v, mean(v)); + + let w = &[]; + println!("mean of {}: {}", w, mean(w)); +} diff --git a/Task/Averages-Arithmetic-mean/Vim-Script/averages-arithmetic-mean.vim b/Task/Averages-Arithmetic-mean/Vim-Script/averages-arithmetic-mean.vim new file mode 100644 index 0000000000..ae162afc70 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/Vim-Script/averages-arithmetic-mean.vim @@ -0,0 +1,10 @@ +function Mean(lst) + if empty(a:lst) + throw "Empty" + endif + let sum = 0.0 + for i in a:lst + let sum += i + endfor + return sum / len(a:lst) +endfunction diff --git a/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-1.xslt b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-1.xslt new file mode 100644 index 0000000000..6d550b3a73 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-1.xslt @@ -0,0 +1 @@ +sum($values) div count($values) diff --git a/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-2.xslt b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-2.xslt new file mode 100644 index 0000000000..6a505e85e4 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-2.xslt @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-3.xslt b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-3.xslt new file mode 100644 index 0000000000..cf3a1cdaf2 --- /dev/null +++ b/Task/Averages-Arithmetic-mean/XSLT/averages-arithmetic-mean-3.xslt @@ -0,0 +1,8 @@ + + + 1 + 1 + 2 + 3 + 5 + diff --git a/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk b/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk index fcc0bc11ad..cb3d1e526f 100644 --- a/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk +++ b/Task/Averages-Mean-angle/AutoHotkey/averages-mean-angle.ahk @@ -4,10 +4,11 @@ MsgBox, % MeanAngle(Angles[1]) "`n" . MeanAngle(Angles[3]) MeanAngle(a, x=0, y=0) { - c := ATan(1) / 45 - for k, v in a + static c := ATan(1) / 45 + for k, v in a { x += Cos(v * c) / a.MaxIndex() - , y += Sin(v * c) / a.MaxIndex() + y += Sin(v * c) / a.MaxIndex() + } return atan2(x, y) / c } diff --git a/Task/Averages-Mean-angle/D/averages-mean-angle.d b/Task/Averages-Mean-angle/D/averages-mean-angle.d index 3a292109f0..1decaefa93 100644 --- a/Task/Averages-Mean-angle/D/averages-mean-angle.d +++ b/Task/Averages-Mean-angle/D/averages-mean-angle.d @@ -1,10 +1,10 @@ import std.stdio, std.algorithm, std.complex; 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; } +auto radians(T)(in T d) pure nothrow @nogc { return d * PI / 180; } +auto degrees(T)(in T r) pure nothrow @nogc { return r * 180 / PI; } -real meanAngle(T)(in T[] D) pure nothrow { +real meanAngle(T)(in T[] D) pure nothrow @nogc { 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/Euphoria/averages-mean-angle.euphoria b/Task/Averages-Mean-angle/Euphoria/averages-mean-angle.euphoria new file mode 100644 index 0000000000..4cd862d7a7 --- /dev/null +++ b/Task/Averages-Mean-angle/Euphoria/averages-mean-angle.euphoria @@ -0,0 +1,26 @@ +include std/console.e +include std/mathcons.e + +sequence AngleList = {{350,10},{90,180,270,360},{10,20,30}} + +function atan2(atom y, atom x) + return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y) +end function + +function MeanAngle(sequence angles) + atom x = 0, y = 0 + integer l = length(angles) + + for i = 1 to length(angles) do + x += cos(angles[i] * PI / 180) + y += sin(angles[i] * PI / 180) + end for + + return atan2(y / l, x / l) * 180 / PI +end function + +for i = 1 to length(AngleList) do + printf(1,"Mean Angle for set %d: %3.5f\n",{i,MeanAngle(AngleList[i])}) +end for + +if getc(0) then end if diff --git a/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go b/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go index d058dd06b0..27ab3a15e9 100644 --- a/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go +++ b/Task/Averages-Mean-angle/Go/averages-mean-angle-1.go @@ -1,22 +1,28 @@ package main import ( - "fmt" - "math" - "math/cmplx" + "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)) + 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)) - } + 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 index b3ea82dfd0..5a610a6d67 100644 --- a/Task/Averages-Mean-angle/Go/averages-mean-angle-2.go +++ b/Task/Averages-Mean-angle/Go/averages-mean-angle-2.go @@ -1,9 +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 + 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/Haskell/averages-mean-angle.hs b/Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs similarity index 100% rename from Task/Averages-Mean-angle/Haskell/averages-mean-angle.hs rename to Task/Averages-Mean-angle/Haskell/averages-mean-angle-1.hs diff --git a/Task/Averages-Mean-angle/Haskell/averages-mean-angle-2.hs b/Task/Averages-Mean-angle/Haskell/averages-mean-angle-2.hs new file mode 100644 index 0000000000..b3184a3e06 --- /dev/null +++ b/Task/Averages-Mean-angle/Haskell/averages-mean-angle-2.hs @@ -0,0 +1,17 @@ +-- file: trigdeg.fs + +deg2rad deg = deg*pi/180.0 +rad2deg rad = rad*180.0/pi + +sind = sin . deg2rad +cosd = cos . deg2rad +tand = tan . deg2rad +atand = rad2deg . atan +atan2d y x = rad2deg (atan2 y x ) + +avg_angle angles = atan2d y x + where + y = mean (map sind angles) + x = mean (map cosd angles) + +-- End of trigdeg.fs -------- diff --git a/Task/Averages-Mean-angle/Logo/averages-mean-angle.logo b/Task/Averages-Mean-angle/Logo/averages-mean-angle.logo new file mode 100644 index 0000000000..f1c0fe8b25 --- /dev/null +++ b/Task/Averages-Mean-angle/Logo/averages-mean-angle.logo @@ -0,0 +1,13 @@ +to mean_angle :angles + local "avgsin + make "avgsin quotient apply "sum map "sin :angles count :angles + local "avgcos + make "avgcos quotient apply "sum map "cos :angles count :angles + output (arctan :avgcos :avgsin) +end + +foreach [[350 10] [90 180 270 360] [10 20 30]] [ + print (sentence [The average of \(] ? [\) is] (mean_angle ?)) +] + +bye diff --git a/Task/Averages-Mean-angle/Pascal/averages-mean-angle.pascal b/Task/Averages-Mean-angle/Pascal/averages-mean-angle.pascal new file mode 100644 index 0000000000..72b4482923 --- /dev/null +++ b/Task/Averages-Mean-angle/Pascal/averages-mean-angle.pascal @@ -0,0 +1,71 @@ +program MeanAngle; +{$IFDEF DELPHI} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + math;// sincos and atan2 +type + tAngles = array of double; + +function MeanAngle(const a:tAngles;cnt:longInt):double; +// calculates mean angle. +// returns 0.0 if direction is not sure. +const + eps = 1e-10; + +var + i : LongInt; + s,c, + Sumsin,SumCos : extended; +begin + IF cnt = 0 then + Begin + MeanAngle := 0.0; + EXIT; + end; + + SumSin:= 0; + SumCos:= 0; + For i := Cnt-1 downto 0 do + Begin + sincos(DegToRad(a[i]),s,c); + Sumsin := sumSin+s; + SumCos := sumCos+c; + end; + s := SumSin/cnt; + c := sumCos/cnt; + IF c > eps then + MeanAngle := RadToDeg(arctan2(s,c)) + else + // Not meaningful + MeanAngle := 0.0; +end; + +Procedure OutMeanAngle(const a:tAngles;cnt:longInt); +var + i : longInt; +Begin + IF cnt > 0 then + Begin + write('The mean angle of ['); + For i := 0 to Cnt-2 do + write(a[i]:0:2,','); + write(a[Cnt-1]:0:2,'] => '); + writeln(MeanAngle(a,cnt):0:16); + end; +end; + +var + a:tAngles; +Begin + setlength(a,4); + + a[0] := 350;a[1] := 10; + OutMeanAngle(a,2); + a[0] := 90;a[1] := 180;a[2] := 270;a[3] := 360; + OutMeanAngle(a,4); + a[0] := 10;a[1] := 20;a[2] := 30; + OutMeanAngle(a,3); + + setlength(a,0); +end. diff --git a/Task/Averages-Mean-angle/Perl/averages-mean-angle.pl b/Task/Averages-Mean-angle/Perl/averages-mean-angle.pl new file mode 100644 index 0000000000..c18e8ad955 --- /dev/null +++ b/Task/Averages-Mean-angle/Perl/averages-mean-angle.pl @@ -0,0 +1,17 @@ +sub Pi () { 3.1415926535897932384626433832795028842 } + +sub meanangle { + my($x, $y) = (0,0); + ($x,$y) = ($x + sin($_), $y + cos($_)) for @_; + my $atan = atan2($x,$y); + $atan += 2*Pi while $atan < 0; # Ghetto fmod + $atan -= 2*Pi while $atan > 2*Pi; + $atan; +} + +sub meandegrees { + meanangle( map { $_ * Pi/180 } @_ ) * 180/Pi; +} + +print "The mean angle of [@$_] is: ", meandegrees(@$_), " degrees\n" + for ([350,10], [90,180,270,360], [10,20,30]); diff --git a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx index b164c8b536..f99093ee21 100644 --- a/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx +++ b/Task/Averages-Mean-angle/REXX/averages-mean-angle.rexx @@ -1,57 +1,56 @@ -/*REXX program to compute the mean angle (angles expressed in degrees).*/ -numeric digits 50 /*use fifty digits of precision. */ -showDigs=10 /* ... but only show ten digits. */ -#=350 10 ; say showit(#, meanAngleD(#)) -#=90 180 270 360 ; say showit(#, meanAngleD(#)) -#=10 20 30 ; say showit(#, meanAngleD(#)) +/*REXX program computes the mean angle (angles expressed in degrees). */ +numeric digits 50 /*use fifty digits of precision, */ + showDig=10 /*··· but only display 10 digits.*/ +# = 350 10 ; say showit(#, meanAngleD(#) ) +# = 90 180 270 360 ; say showit(#, meanAngleD(#) ) +# = 10 20 30 ; say showit(#, meanAngleD(#) ) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────MEANANGD subroutine─────────────────*/ -meanAngleD: procedure; arg x; _sin=0; _cos=0 -numeric digits $d()+$d()%4 -n=words(x); do j=1 for n - xr = d2r(d2d(word(x,j))) - _sin = _sin + sin(xr) - _cos = _cos + cos(xr) - end /*j*/ -return r2d(atan2(_sin/n, _cos/n)) -/*═════════════════════════════general 1-line subs══════════════════════*/ -/*The 1-line subs were broken up into multiple lines for easier reading.*/ -d2d: return arg(1)//360 -d2r: return r2r(d2d(arg(1))/180*pi()) -r2d: return d2d((r2r(arg(1))/pi())*180) -r2r: return arg(1)//(2*pi()) -p: return word(arg(1),1) -$d: return p(arg(1) digits()) -$fuzz: return min(arg(1),max(1,$d()-arg(2))) -showit: procedure expose showDigs; numeric digits showDigs; arg a,ma - return left('angles='a,30) 'mean angle=' format(ma,,showDigs,0)/1 -acos: procedure; arg x; if x<-1 | x>1 then call $81r -1,1,x,"ACOS" - return .5*pi() - asin(x) /* $81r subroutine not included here.*/ -atan: if abs(arg(1))=1 then return pi()*.25*sign(arg(1)) - return asin(arg(1) / sqrt(1+arg(1)**2)) -asin: procedure; arg x; if x<-1 | x>1 then call $81r -1,1,x,"ASIN" - s=x*x; if abs(x)>=.7 then return sign(x)*acos(sqrt(1-s),'-ASIN') - z=x; o=x; p=z; do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1) - if z=p then leave; p=z; end; return z -atan2: procedure; arg y,x; pi=pi(); s=sign(y) - select; when x=0 then z=s*pi*.5; when x<0 then if y=0 then z=pi - else z=s*(pi-abs(atan(y/x)));otherwise z=s*atan(y/x);end; return z -cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz $fuzz(5,3) - if a=0 then return 1; if a=pi() then return -1 - if a=pi()*.5 | a=pi()*1.5 then return 0;if a=pi()/3 then return .5 - if a=2*pi()/3 then return -.5; return .sincos(1,1,-1) -sin: procedure; arg x; x=r2r(x); numeric fuzz $fuzz(5,3) - if x=pi()*.5 then return 1; if x==pi()*1.5 then return -1 - if abs(x)=pi() | x=0 then return 0; return .sincos(x,x,1) -.sincos: parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_ - if z=p then leave; p=z; end; return z -sqrt: procedure; parse arg x; if x=0 then return 0; d=digits() - numeric digits 11; g=.sqrtGuess(); 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 -.sqrtGuess: if x<0 then call er 02,x p($.ff 'SQRT') "negative" - /*The above IF statement was left here to show checking for x<0.*/ - numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .;return g*.5'E'_%2 -pi: return , -3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148 +meanAngleD: procedure; parse arg x; numeric digits digits()+digits()%4 +_sin=0; _cos=0; n=words(x); do j=1 for n; !=d2r(word(x,j)) + _sin = _sin + sin(!) + _cos = _cos + cos(!) + end /*j*/ +return r2d(atan2(_sin/n, _cos/n)) +/*─────────────────────────────one─line subroutines──────────────────────────────────────────*/ +.sinCos: arg z,_,i; x=x*x; do k=2 by 2 until p=z; p=z; _=-_*x/(k*(k+i)); z=z+_; end; return z +$fuzz: return min(arg(1), max(1, digits() - arg(2) ) ) +acos: procedure; parse arg x; return pi() * .5 - asin(x) +atan: parse arg x; if abs(x)=1 then return pi()*.25 * sign(x); return asin(x/sqrt(1 + x*x)) +d2d: return arg(1) // 360 +d2r: return r2r(d2d(arg(1)) / 180 * pi() ) +r2d: return d2d((r2r(arg(1)) / pi()) * 180) +r2r: return arg(1) // (pi() * 2) +p: return word(arg(1), 1) +pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862;return pi +/*───────────────────────────────────ASIN subroutine────────────────────*/ +asin: procedure; parse arg x 1 z 1 o 1 p; xx=x*x + if xx>=.5 then return sign(x) * acos(sqrt(1-xx)) + do j=2 by 2 until p=z; p=z; o=o*xx*(j-1)/j; z=z+o/(j+1); end + return z /* [↑] compute until no noise.*/ +/*───────────────────────────────────ATAN2 subroutine───────────────────*/ +atan2: procedure; parse arg y,x; call pi; s=sign(y) + select + when x=0 then z=s * pi * .5 + when x<0 then if y=0 then z=pi; else z=s*(pi-abs(atan(y/x))) + otherwise z=s * atan(y/x) + end /*select*/; return z +/*───────────────────────────────────COS subroutine─────────────────────*/ +cos: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) + a=abs(x); if a=0 then return 1; if a=pi then return -1 + if a=pi*.5 | a=pi*1.5 then return 0; if a=pi/3 then return .5 + if a=pi*2/3 then return -.5; return .sinCos(1, 1, -1) +/*───────────────────────────────────SHOWIT subroutine──────────────────*/ +showit: procedure expose showDig; numeric digits showDig; parse arg a,mA + return left('angles='a,30) 'mean angle=' format(mA,,showDig,0)/1 +/*───────────────────────────────────COS subroutine─────────────────────*/ +sin: procedure; parse arg x; x=r2r(x); numeric fuzz $fuzz(5, 3) + if x=pi*.5 then return 1; if x==pi*1.5 then return -1 + if abs(x)=pi | x=0 then return 0; return .sinCos(x, x, +1) +/*───────────────────────────────────SQRT subroutine────────────────────*/ +sqrt: procedure; parse arg x,i; if x=0 then return 0; d=digits(); m.=11 + if x<0 then i='i'; numeric digits 11; numeric form; p=d+d%4+2 + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 + do j=0 while p>9; m.j=p; p=p%2+1; end /*j*/ + do k=j+5 to 0 by -1; if m.k>11 then numeric digits m.k + g=.5*(g+x/g); end /*k*/; numeric digits d; return g/1 diff --git a/Task/Averages-Mean-angle/Scala/averages-mean-angle.scala b/Task/Averages-Mean-angle/Scala/averages-mean-angle.scala new file mode 100644 index 0000000000..881560f30f --- /dev/null +++ b/Task/Averages-Mean-angle/Scala/averages-mean-angle.scala @@ -0,0 +1,19 @@ +trait MeanAnglesComputation { + import scala.math.{Pi, atan2, cos, sin} + + def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { + val sums = angles.foldLeft((.0, .0))((r, c) => { + val rads = c / convFactor + (r._1 + sin(rads), r._2 + cos(rads)) + }) + val result = atan2(sums._1, sums._2) + (result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor + } +} + +object MeanAngles extends App with MeanAnglesComputation { + assert(meanAngle(List(350, 10), 180.0 / math.Pi).round == 360, "Unexpected result with 350, 10") + assert(meanAngle(List(90, 180, 270, 360)).round == 270, "Unexpected result with 90, 180, 270, 360") + assert(meanAngle(List(10, 20, 30)).round == 20, "Unexpected result with 10, 20, 30") + println("Successfully completed without errors.") +} diff --git a/Task/Averages-Mean-time-of-day/00DESCRIPTION b/Task/Averages-Mean-time-of-day/00DESCRIPTION index d8388a8008..db02a1ceaa 100644 --- a/Task/Averages-Mean-time-of-day/00DESCRIPTION +++ b/Task/Averages-Mean-time-of-day/00DESCRIPTION @@ -1,3 +1,9 @@ A particular activity of bats occurs at these times of the day: :23:00:17, 23:40:20, 00:12:45, 00:17:19 -Using the idea that there are twenty-four hours in a day, which is analogous to there being 360 degrees in a circle, map times of day to and from angles; and using the ideas of [[Averages/Mean angle]] compute and show the average time of the nocturnal activity to an accuracy of one second of time. + +Using the idea that there are twenty-four hours in a day, +which is analogous to there being 360 degrees in a circle, +map times of day to and from angles; +and using the ideas of [[Averages/Mean angle]] +compute and show the average time of the nocturnal activity +to an accuracy of one second of time. diff --git a/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk b/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk index 6a32497daf..4e3d7269fa 100644 --- a/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk +++ b/Task/Averages-Mean-time-of-day/AutoHotkey/averages-mean-time-of-day.ahk @@ -1,12 +1,13 @@ MsgBox, % "The mean time is: " MeanTime(["23:00:17", "23:40:20", "00:12:45", "00:17:19"]) MeanTime(t, x=0, y=0) { - c := ATan(1) / 45 - for k, v in t + static c := ATan(1) / 45 + for k, v in t { n := StrSplit(v, ":") - , r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240 - , x += Cos(r) - , y += Sin(r) + r := c * (n[1] * 3600 + n[2] * 60 + n[3]) / 240 + x += Cos(r) + y += Sin(r) + } r := atan2(x, y) / c r := (r < 0 ? r + 360 : r) / 15 h := SubStr("00" Round(r // 1, 0), -1) diff --git a/Task/Averages-Mean-time-of-day/C-sharp/averages-mean-time-of-day.cs b/Task/Averages-Mean-time-of-day/C-sharp/averages-mean-time-of-day.cs new file mode 100644 index 0000000000..f9ac15aefb --- /dev/null +++ b/Task/Averages-Mean-time-of-day/C-sharp/averages-mean-time-of-day.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace RosettaCode +{ + class Program + { + static void Main(string[] args) + { + Func TimeToDegrees = (time) => + 360 * time.Hours / 24.0 + + 360 * time.Minutes / (24 * 60.0) + + 360 * time.Seconds / (24 * 3600.0); + Func, double> MeanAngle = (angles) => + { + double y_part = 0.0d, x_part = 0.0d; + int numItems = angles.Count; + + for (int i = 0; i < numItems; i++) + { + x_part += Math.Cos(angles[i] * Math.PI / 180); + y_part += Math.Sin(angles[i] * Math.PI / 180); + } + + return Math.Atan2(y_part / numItems, x_part / numItems) * 180 / Math.PI; + }; + Func TimeFromDegrees = (angle) => + new TimeSpan( + (int)(24 * 60 * 60 * angle / 360) / 3600, + ((int)(24 * 60 * 60 * angle / 360) % 3600 - (int)(24 * 60 * 60 * angle / 360) % 60) / 60, + (int)(24 * 60 * 60 * angle / 360) % 60); + List digitimes = new List(); + TimeSpan digitime; + string input; + + Console.WriteLine("Enter times, end with no input: "); + do + { + input = Console.ReadLine(); + if (!(string.IsNullOrWhiteSpace(input))) + { + if (TimeSpan.TryParse(input, out digitime)) + digitimes.Add(TimeToDegrees(digitime)); + else + Console.WriteLine("Seems this is wrong input: ignoring time"); + } + } while (!string.IsNullOrWhiteSpace(input)); + + if(digitimes.Count() > 0) + Console.WriteLine("The mean time is : {0}", TimeFromDegrees(360 + MeanAngle(digitimes))); + } + } +} diff --git a/Task/Averages-Mean-time-of-day/D/averages-mean-time-of-day.d b/Task/Averages-Mean-time-of-day/D/averages-mean-time-of-day.d new file mode 100644 index 0000000000..858fe06fbe --- /dev/null +++ b/Task/Averages-Mean-time-of-day/D/averages-mean-time-of-day.d @@ -0,0 +1,39 @@ +import std.stdio, std.range, std.algorithm, std.complex, std.math, + std.format, std.conv; + +double radians(in double d) pure nothrow @safe @nogc { + return d * PI / 180; +} + +double degrees(in double r) pure nothrow @safe @nogc { + return r * 180 / PI; +} + +double meanAngle(in double[] deg) pure nothrow @safe @nogc { + return (deg.map!(d => fromPolar(1, d.radians)).sum / deg.length).arg.degrees; +} + +string meanTime(in string[] times) pure @safe { + auto t = times.map!(times => times.split(':').to!(int[3])); + assert(t.all!(hms => 24.iota.canFind(hms[0]) && + 60.iota.canFind(hms[1]) && + 60.iota.canFind(hms[2])), + "Invalid time"); + + auto seconds = t.map!(hms => hms[2] + hms[1] * 60 + hms[0] * 3600); + enum day = 24 * 60 * 60; + const to_angles = seconds.map!(s => s * 360.0 / day).array; + + immutable mean_as_angle = to_angles.meanAngle; + auto mean_seconds_fp = mean_as_angle * day / 360.0; + if (mean_seconds_fp < 0) + mean_seconds_fp += day; + immutable mean_seconds = mean_seconds_fp.to!uint; + immutable h = mean_seconds / 3600; + immutable m = mean_seconds % 3600; + return "%02d:%02d:%02d".format(h, m / 60, m % 60); +} + +void main() @safe { + ["23:00:17", "23:40:20", "00:12:45", "00:17:19"].meanTime.writeln; +} diff --git a/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.euphoria b/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.euphoria new file mode 100644 index 0000000000..243f11d54f --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Euphoria/averages-mean-time-of-day.euphoria @@ -0,0 +1,63 @@ +include std/console.e +include std/math.e +include std/mathcons.e +include std/sequence.e +include std/get.e + +function T2D(sequence TimeSeq) + return (360 * TimeSeq[1] / 24 + 360 * TimeSeq[2] / (24 * 60) + + 360 * TimeSeq[3] / (24 * 3600)) +end function + +function D2T(atom angle) + sequence TimeSeq = {0,0,0} + atom seconds = 24 * 60 * 60 * angle / 360 + + TimeSeq[3] = mod(seconds,60) + TimeSeq[2] = (mod(seconds,3600) - TimeSeq[3]) / 60 + TimeSeq[1] = seconds / 3600 + + return TimeSeq +end function + +function MeanAngle(sequence angles) + atom x = 0, y = 0 + integer l = length(angles) + + for i = 1 to length(angles) do + x += cos(angles[i] * PI / 180) + y += sin(angles[i] * PI / 180) + end for + + return atan2(y / l, x / l) * 180 / PI +end function + +sequence TimeEntry, TimeList = {}, TimeSeq + +puts(1,"Enter times. Enter with no input to end\n") +while 1 do + TimeEntry = prompt_string("") + if equal(TimeEntry,"") then -- no more entries + for i = 1 to length(TimeList) do + TimeList[i] = split(TimeList[i],":") -- split the times into sequences + for j = 1 to 3 do + TimeList[i][j] = defaulted_value(TimeList[i][j],0) -- convert to numerical values + end for + end for + exit + end if + TimeList = append(TimeList,TimeEntry) +end while + +sequence AngleList = repeat({},length(TimeList)) + +for i = 1 to length(AngleList) do + AngleList[i] = T2D(TimeList[i]) +end for + +sequence MeanTime = D2T(360+MeanAngle(AngleList)) + +printf(1,"\nMean Time: %d:%d:%d\n",MeanTime) + + +if getc(0) then end if diff --git a/Task/Averages-Mean-time-of-day/PL-I/averages-mean-time-of-day.pli b/Task/Averages-Mean-time-of-day/PL-I/averages-mean-time-of-day.pli new file mode 100644 index 0000000000..b928b0a999 --- /dev/null +++ b/Task/Averages-Mean-time-of-day/PL-I/averages-mean-time-of-day.pli @@ -0,0 +1,46 @@ +*process source attributes xref; + avt: Proc options(main); + /*-------------------------------------------------------------------- + * 25.06.2014 Walter Pachl taken from REXX + *-------------------------------------------------------------------*/ + Dcl (addr,hbound,sin,cos,atan) Builtin; + Dcl sysprint Print; + Dcl times(4) Char(8) Init('23:00:17','23:40:20','00:12:45','00:17:19'); + Dcl time Char(8); + Dcl (alpha,x,y,ss,ww) Dec Float(18) Init(0); + Dcl day Bin Fixed(31) Init(86400); + Dcl pi Dec Float(18) Init(3.14159265358979323846); + Dcl (i,h,m,s) bin Fixed(31) Init(0); + Do i=1 To hbound(times); /* loop over times */ + time=times(i); /* pick a time */ + alpha=t2a(time); /* convert to angle (radians) */ + x=x+sin(alpha); /* accumulate sines */ + y=y+cos(alpha); /* accumulate cosines */ + End; + ww=atan(x/y); /* compute average angle */ + ss=ww*day/(2*pi); /* convert to seconds */ + If ss<0 Then ss=ss+day; /* avoid negative value */ + m=ss/60; /* split into hh mm ss */ + s=ss-m*60; + h=m/60; + m=m-h*60; + Put Edit(h,':',m,':',s)(Skip,3(p'99',a)); + + t2a: Procedure(t) Returns(Bin Float(18)); /* convert time to angle */ + Dcl t Char(8); + Dcl 1 tt Based(addr(t)), + 2 hh Pic'99', + 2 * Char(1), + 2 mm Pic'99', + 2 * Char(1), + 2 ss Pic'99'; + Dcl sec Bin Fixed(31); + Dcl a Bin Float(18); + sec=(hh*60+mm)*60+ss; + If sec>(day/2) Then + sec=sec-day; + a=2*pi*sec/day; + Return (a); + End; + + End; diff --git a/Task/Averages-Mean-time-of-day/REXX/averages-mean-time-of-day.rexx b/Task/Averages-Mean-time-of-day/REXX/averages-mean-time-of-day.rexx new file mode 100644 index 0000000000..11848b4bee --- /dev/null +++ b/Task/Averages-Mean-time-of-day/REXX/averages-mean-time-of-day.rexx @@ -0,0 +1,100 @@ +/* REXX --------------------------------------------------------------- +* 25.06.2014 Walter Pachl +* taken from ooRexx using my very aged sin/cos/artan functions +*--------------------------------------------------------------------*/ +times='23:00:17 23:40:20 00:12:45 00:17:19' +sum=0 +day=86400 +pi=3.14159265358979323846264 +x=0 +y=0 +Do i=1 To words(times) /* loop over times */ + time.i=word(times,i) /* pick a time */ + alpha.i=t2a(time.i) /* convert to angle (radians) */ + /* Say time.i format(alpha.i,6,9) */ + x=x+sin(alpha.i) /* accumulate sines */ + y=y+cos(alpha.i) /* accumulate cosines */ + End +ww=arctan(x/y) /* compute average angle */ +ss=ww*86400/(2*pi) /* convert to seconds */ +If ss<0 Then ss=ss+day /* avoid negative value */ +m=ss%60 /* split into hh mm ss */ +s=ss-m*60 +h=m%60 +m=m-h*60 +Say f2(h)':'f2(m)':'f2(s) /* show the mean time */ +Exit + +t2a: Procedure Expose day pi /* convert time to angle */ + Parse Arg hh ':' mm ':' ss + sec=(hh*60+mm)*60+ss + If sec>(day/2) Then + sec=sec-day + a=2*pi*sec/day + Return a + +f2: return right(format(arg(1),2,0),2,0) + + +sin: Procedure Expose pi + Parse Arg x + prec=digits() + Numeric Digits (2*prec) + Do While x>pi + x=x-pi + End + Do While x<-pi + x=x+pi + End + o=x + u=1 + r=x + Do i=3 By 2 + ra=r + o=-o*x*x + u=u*i*(i-1) + r=r+(o/u) + If r=ra Then Leave + End + Numeric Digits prec + Return r+0 + +cos: Procedure Expose pi + Parse Arg x + prec=digits() + Numeric Digits (2*prec) + Numeric Fuzz 3 + o=1 + u=1 + r=1 + Do i=1 By 2 + ra=r + o=-o*x*x + u=u*i*(i+1) + r=r+(o/u) + If r=ra Then Leave + End + Numeric Digits prec + Return r+0 + +arctan: Procedure + Parse Arg x + prec=digits() + Numeric Digits (2*prec) + Numeric Fuzz 3 + o=x + u=1 + r=x + k=0 + Do i=3 By 2 + ra=r + o=-o*x*x + r=r+(o/i) + If r=ra Then + Leave + k=k+1 + If k//1000=0 Then + Say i left(r,40) format(abs(o/i),15,5) + End + Numeric Digits (prec) + Return r+0 diff --git a/Task/Averages-Mean-time-of-day/Scala/averages-mean-time-of-day.scala b/Task/Averages-Mean-time-of-day/Scala/averages-mean-time-of-day.scala new file mode 100644 index 0000000000..cf90a1735a --- /dev/null +++ b/Task/Averages-Mean-time-of-day/Scala/averages-mean-time-of-day.scala @@ -0,0 +1,30 @@ +import java.time.LocalTime +import scala.compat.Platform + +trait MeanAnglesComputation { + import scala.math.{Pi, atan2, cos, sin} + + def meanAngle(angles: List[Double], convFactor: Double = 180.0 / Pi) = { + val sums = angles.foldLeft((.0, .0))((r, c) => { + val rads = c / convFactor + (r._1 + sin(rads), r._2 + cos(rads)) + }) + val result = atan2(sums._1, sums._2) + (result + (if (result.signum == -1) 2 * Pi else 0.0)) * convFactor + } +} + +object MeanBatTime extends App with MeanAnglesComputation { + val dayInSeconds = 60 * 60 * 24 + + def times = batTimes.map(t => afterMidnight(t).toDouble) + + def afterMidnight(twentyFourHourTime: String) = { + val t = LocalTime.parse(twentyFourHourTime) + (if (t.isBefore(LocalTime.NOON)) dayInSeconds else 0) + LocalTime.parse(twentyFourHourTime).toSecondOfDay + } + + def batTimes = List("23:00:17", "23:40:20", "00:12:45", "00:17:19") + assert(LocalTime.MIN.plusSeconds(meanAngle(times, dayInSeconds).round).toString == "23:47:40") + println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") +} diff --git a/Task/Averages-Median/D/averages-median.d b/Task/Averages-Median/D/averages-median.d index 7cba44a690..edcb313c51 100644 --- a/Task/Averages-Median/D/averages-median.d +++ b/Task/Averages-Median/D/averages-median.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm; -T median(T)(T[] nums) /*pure nothrow*/ { +T median(T)(T[] nums) pure nothrow { nums.sort(); if (nums.length & 1) return nums[$ / 2]; @@ -10,8 +10,8 @@ T median(T)(T[] nums) /*pure nothrow*/ { void main() { auto a1 = [5.1, 2.6, 6.2, 8.8, 4.6, 4.1]; - writeln("Even median: ", median(a1)); + writeln("Even median: ", a1.median); auto a2 = [5.1, 2.6, 8.8, 4.6, 4.1]; - writeln("Odd median: ", median(a2)); + writeln("Odd median: ", a2.median); } diff --git a/Task/Averages-Median/Elixir/averages-median.elixir b/Task/Averages-Median/Elixir/averages-median.elixir new file mode 100644 index 0000000000..907e363c2f --- /dev/null +++ b/Task/Averages-Median/Elixir/averages-median.elixir @@ -0,0 +1,9 @@ +defmodule RC do + def median(list) do + len = Enum.count(list) + sorted = Enum.sort(list) + mid = div(len, 2) + rem = rem(len, 2) + (Enum.at(sorted, mid + rem) + Enum.at(sorted, mid - 1)) / 2 + end +end diff --git a/Task/Averages-Median/REXX/averages-median.rexx b/Task/Averages-Median/REXX/averages-median.rexx index b892fee8b6..05751387c6 100644 --- a/Task/Averages-Median/REXX/averages-median.rexx +++ b/Task/Averages-Median/REXX/averages-median.rexx @@ -1,32 +1,31 @@ -/*REXX program finds the median of a vector (& displays vector,median)*/ - +/*REXX program finds the median of a vector (and displays vector,median)*/ /*────────vector────────── ───show vector─── ───────show result─────────*/ -v='1 9 2 4' ; say 'vector=' v; say 'median=' median(v); say -v='3 1 4 1 5 9 7 6' ; say 'vector= 'v; say 'median=' median(v); say -v='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 +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.*/ /*──────────────────────────────────MEDIAN subroutine───────────────────*/ -median: procedure; parse arg x +median: procedure; parse arg x /*obtain the X argument. */ call makeArray x /*make into scalar array (faster)*/ call Esort /*(ESORT is an overkill for this)*/ -m=@.0%2 /* % is REXX integer division.*/ -n=m+1 -if @.0//2==1 then return @.n /*(odd?) // is REXX modulus.*/ - return (@.m+@.n)/2 /*process an even-element vector.*/ +m=@.0%2 /* % is REXX integer division. */ +n=m+1 /*N: the next element after M. */ +if @.0//2==1 then return @.n /*(odd?) // is REXX remainder.*/ + 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 /*j*/ + 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 - parse value @.j @.k with @.k @.j /*swap two values. */ - if h>=j then leave - j=j-h; k=k-h +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 /*sort lower section*/ + do while @.k<@.j /* [↓] swap while <*/ + parse value @.j @.k with @.k @.j /*swap two values. */ + if h>=j then leave /*leave if h≥j */ + j=j-h; k=k-h /*diminish J and K. */ end /*while @.k<@.j*/ end /*i*/ end /*while h>l*/ diff --git a/Task/Averages-Mode/D/averages-mode.d b/Task/Averages-Mode/D/averages-mode.d index 71537ef17d..38e0203682 100644 --- a/Task/Averages-Mode/D/averages-mode.d +++ b/Task/Averages-Mode/D/averages-mode.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.array; -auto mode(T)(T[] items) /*pure nothrow*/ { +auto mode(T)(T[] items) pure /*nothrow @safe*/ { int[T] aa; foreach (item; items) aa[item]++; @@ -8,7 +8,7 @@ auto mode(T)(T[] items) /*pure nothrow*/ { return aa.byKey.filter!(k => aa[k] == m); } -void main() { +void main() /*@safe*/ { auto data = [1, 2, 3, 1, 2, 4, 2, 5, 3, 3, 1, 3, 6]; writeln("Mode: ", data.mode); diff --git a/Task/Averages-Mode/Maple/averages-mode.maple b/Task/Averages-Mode/Maple/averages-mode.maple new file mode 100644 index 0000000000..3225cc150a --- /dev/null +++ b/Task/Averages-Mode/Maple/averages-mode.maple @@ -0,0 +1,2 @@ +Statistics:-Mode([1, 2.1, 2.1, 3]); +Statistics:-Mode([1, 2.1, 2.1, 3.2, 3.2, 5]); diff --git a/Task/Averages-Mode/REXX/averages-mode-1.rexx b/Task/Averages-Mode/REXX/averages-mode-1.rexx index 1df655d058..a21c3e8d56 100644 --- a/Task/Averages-Mode/REXX/averages-mode-1.rexx +++ b/Task/Averages-Mode/REXX/averages-mode-1.rexx @@ -1,34 +1,29 @@ /*REXX program finds the mode (most occurring element) of a vector. */ - -/*────────vector────────── ───show vector─── ────show result────── */ -v='1 8 6 0 1 9 4 6 1 9 9 9' ; say 'vector='v; say 'mode='mode(v); say -v='1 2 3 4 5 6 7 8 9 10 11' ; say 'vector='v; say 'mode='mode(v); say -v='8 8 8 2 2 2' ; say 'vector='v; say 'mode='mode(v); say +/*════════vector══════════ ═══show vector═══ ════show result══════ */ +v= 1 8 6 0 1 9 4 6 1 9 9 9 ; say 'vector='v; say 'mode='mode(v); say +v= 1 2 3 4 5 6 7 8 9 11 10 ; say 'vector='v; say 'mode='mode(v); say +v= 8 8 8 2 2 2 ; say 'vector='v; say 'mode='mode(v); say v='cat kat Cat emu emu Kat' ; say 'vector='v; say 'mode='mode(v); say - exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────MAKEARRAY subroutine────────────────*/ -makeArray: procedure expose @.; parse arg v; @.0=words(v) /*make array*/ - do k=1 for @.0; @.k=word(v,k); end /*k*/ -return /*──────────────────────────────────ESORT subroutine────────────────────*/ -esort: procedure expose @.; h=@.0 /*exchange sort.*/ - do while h>1; h=h%2 - do i=1 for @.0-h; j=i; k=h+i - do while @.k<@.j;t=@.j;@.j=@.k;@.k=t;if h>=j then leave;j=j-h;k=k-h;end - end /*i*/ - end /*while h>1*/ +Esort: procedure expose @.; h=@.0 /* [↓] exchange sort. */ + do while h>1; h=h%2 /*% is integer divide.*/ + do i=1 for @.0-h; j=i; k=h+i /* [↓] perform exchange*/ + do while @.k<@.j & h1*/ return /*──────────────────────────────────MODE subroutine─────────────────────*/ mode: procedure expose @.; parse arg x /*finds the MODE of a vector. */ -call makeArray x /*make an array out of the vector*/ -call esort @.0 /*sort the array elements. */ +@.0=words(x) /* [↓] make an array from vector.*/ + do k=1 for @.0; @.k=word(x,k); end /*k*/ +call Esort @.0 /*sort the elements in the array.*/ ?=@.1 /*assume 1st element is the mode.*/ -freq=1 /*the frequency of the occurance.*/ - do j=1 for @.0; _=j-freq - if @.j==@._ then do - freq=freq+1 /*bump the frequency count. */ - ?=@.j /*this is the one. */ +freq=1 /*the frequency of the occurrence*/ + do j=1 for @.0; _=j-freq /*traipse through the elements. */ + if @.j==@._ then do /*this element same as previous? */ + freq=freq+1 /*bump the frequency counter. */ + ?=@.j /*this element is the mode,so far*/ end - end /*j*/ -return ? + end /*j*/ +return ? /*return the node to the invoker.*/ diff --git a/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d b/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d index a69b369cf8..f283517f38 100644 --- a/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d +++ b/Task/Averages-Pythagorean-means/D/averages-pythagorean-means.d @@ -1,14 +1,14 @@ import std.stdio, std.algorithm, std.range, std.functional; -auto aMean(T)(T data) { +auto aMean(T)(T data) pure nothrow @nogc { return data.sum / data.length; } -auto gMean(T)(T data) pure { +auto gMean(T)(T data) pure /*@nogc*/ { return data.reduce!q{a * b} ^^ (1.0 / data.length); } -auto hMean(T)(T data) pure { +auto hMean(T)(T data) pure /*@nogc*/ { return data.length / data.reduce!q{ 1.0 / a + b }; } diff --git a/Task/Averages-Pythagorean-means/Elixir/averages-pythagorean-means.elixir b/Task/Averages-Pythagorean-means/Elixir/averages-pythagorean-means.elixir new file mode 100644 index 0000000000..14bb4a7c9d --- /dev/null +++ b/Task/Averages-Pythagorean-means/Elixir/averages-pythagorean-means.elixir @@ -0,0 +1,16 @@ +defmodule Means do + def arithmetic(list) do + Enum.sum(list) / Enum.count(list) + end + def geometric(list) do + :math.pow(Enum.reduce(list, &(&1 * &2)), 1 / Enum.count(list)) + end + def harmonic(list) do + 1 / arithmetic(Enum.map(list, &(1 / &1))) + end +end + +IO.puts "Arithmetic mean: #{am = Means.arithmetic(1..10)}" +IO.puts "Geometric mean: #{gm = Means.geometric(1..10)}" +IO.puts "Harmonic mean: #{hm = Means.harmonic(1..10)}" +IO.puts "(#{am} >= #{gm} >= #{hm}) is #{am >= gm and gm >= hm}" diff --git a/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means.erl b/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means.erl new file mode 100644 index 0000000000..4e3dce6f9f --- /dev/null +++ b/Task/Averages-Pythagorean-means/Erlang/averages-pythagorean-means.erl @@ -0,0 +1,35 @@ +%% Author: Abhay Jain + +-module(mean_calculator). +-export([find_mean/0]). + +find_mean() -> +%% This is function calling. First argument is the the beginning number +%% and second argument is the initial value of sum for AM & HM and initial value of product for GM. + arithmetic_mean(1, 0), + geometric_mean(1, 1), + harmonic_mean(1, 0). + +%% Function to calculate Arithmetic Mean +arithmetic_mean(Number, Sum) when Number > 10 -> + AM = Sum / 10, + io:format("Arithmetic Mean ~p~n", [AM]); +arithmetic_mean(Number, Sum) -> + NewSum = Sum + Number, + arithmetic_mean(Number+1, NewSum). + +%% Function to calculate Geometric Mean +geometric_mean(Number, Product) when Number > 10 -> + GM = math:pow(Product, 0.1), + io:format("Geometric Mean ~p~n", [GM]); +geometric_mean(Number, Product) -> + NewProd = Product * Number, + geometric_mean(Number+1, NewProd). + +%% Function to calculate Harmonic Mean +harmonic_mean(Number, Sum) when Number > 10 -> + HM = 10 / Sum, + io:format("Harmonic Mean ~p~n", [HM]); +harmonic_mean(Number, Sum) -> + NewSum = Sum + (1/Number), + harmonic_mean(Number+1, NewSum). diff --git a/Task/Averages-Pythagorean-means/Julia/averages-pythagorean-means.julia b/Task/Averages-Pythagorean-means/Julia/averages-pythagorean-means.julia new file mode 100644 index 0000000000..e8144827f4 --- /dev/null +++ b/Task/Averages-Pythagorean-means/Julia/averages-pythagorean-means.julia @@ -0,0 +1,5 @@ +amean(A) = sum(A)/length(A) + +gmean(A) = prod(A)^(1/length(A)) + +hmean(A) = length(A)/sum(1./A) diff --git a/Task/Averages-Pythagorean-means/Maple/averages-pythagorean-means.maple b/Task/Averages-Pythagorean-means/Maple/averages-pythagorean-means.maple new file mode 100644 index 0000000000..c4b75c0e7d --- /dev/null +++ b/Task/Averages-Pythagorean-means/Maple/averages-pythagorean-means.maple @@ -0,0 +1,8 @@ +x := [ seq( 1 .. 10 ) ]; +Means := proc( x ) + uses Statistics; + return Mean( x ), GeometricMean( x ), HarmonicMean( x ); +end proc: +Arithmeticmean, Geometricmean, Harmonicmean := Means( x ); + +is( Arithmeticmean >= Geometricmean and Geometricmean >= Harmonicmean ); diff --git a/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-2.ocaml b/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-2.ocaml index c7e1d99a9a..2c2707a557 100644 --- a/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-2.ocaml +++ b/Task/Averages-Pythagorean-means/OCaml/averages-pythagorean-means-2.ocaml @@ -1,2 +1,9 @@ -means (Array.init 10 (function i -> (float_of_int (i+1)))) ;; -(* (5.5, 4.5287286881167654, 3.4141715214740551) *) +let means v = + let (a, b, c) = + Array.fold_left + (fun (a, b, c) x -> (a+.x, b*.x, c+.1./.x)) + (0.,1.,0.) v + in + let n = float_of_int (Array.length v) in + (a /. n, b ** (1./.n), n /. c) +;; diff --git a/Task/Averages-Pythagorean-means/Objeck/averages-pythagorean-means.objeck b/Task/Averages-Pythagorean-means/Objeck/averages-pythagorean-means.objeck new file mode 100644 index 0000000000..050565b90b --- /dev/null +++ b/Task/Averages-Pythagorean-means/Objeck/averages-pythagorean-means.objeck @@ -0,0 +1,47 @@ +class PythagMeans { + function : Main(args : String[]) ~ Nil { + array := [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]; + arithmetic := ArithmeticMean(array); + geometric := GeometricMean(array); + harmonic := HarmonicMean(array); + + arith_geo := arithmetic >= geometric; + geo_harm := geometric >= harmonic; + + "A = {$arithmetic}, G = {$geometric}, H = {$harmonic}"->PrintLine(); + "A >= G is {$arith_geo}, G >= H is {$geo_harm}"->PrintLine(); + } + + function : native : ArithmeticMean(numbers : Float[]) ~ Float { + if(numbers->Size() = 0) { return -1.0; }; + + mean := 0.0; + each(i : numbers) { + mean += numbers[i]; + }; + + return mean / numbers->Size(); + } + + function : native : GeometricMean(numbers : Float[]) ~ Float { + if(numbers->Size() = 0) { return -1.0; }; + + mean := 1.0; + each(i : numbers) { + mean *= numbers[i]; + }; + + return mean->Power(1.0 / numbers->Size()); + } + + function : native : HarmonicMean(numbers : Float[]) ~ Float { + if(numbers->Size() = 0) { return -1.0; }; + + mean := 0.0; + each(i : numbers) { + mean += (1.0 / numbers[i]); + }; + + return numbers->Size() / mean; + } +} diff --git a/Task/Averages-Pythagorean-means/Perl-6/averages-pythagorean-means.pl6 b/Task/Averages-Pythagorean-means/Perl-6/averages-pythagorean-means.pl6 index 16df1421e8..5a46da412c 100644 --- a/Task/Averages-Pythagorean-means/Perl-6/averages-pythagorean-means.pl6 +++ b/Task/Averages-Pythagorean-means/Perl-6/averages-pythagorean-means.pl6 @@ -1,6 +1,6 @@ -sub A(@x) { ([+] @x) / @x.elems } -sub G(@x) { ([*] @x) ** (1 / @x.elems) } -sub H(@x) { @x.elems / [+] @x.map: 1/* } +sub A { ([+] @_) / @_ } +sub G { ([*] @_) ** (1 / @_) } +sub H { @_ / [+] 1 X/ @_ } say "A(1,...,10) = ", A(1..10); say "G(1,...,10) = ", G(1..10); diff --git a/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-2.ps b/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-2.ps index 2ac2e335ed..3bb75fdb94 100644 --- a/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-2.ps +++ b/Task/Averages-Pythagorean-means/PostScript/averages-pythagorean-means-2.ps @@ -1,3 +1,9 @@ -Arithmetic Mean : 5.5 -Geometric Mean : 4.52873 -Harmonic Mean : 3.41417 +/numbers {[1 10] 1 range}. +/recip {1 exch div}. + +% Arithmetic mean +numbers dup 0 {+} fold exch length div +% Geometric mean +numbers dup 1 {*} fold exch length recip exp +% Harmonic mean +numbers dup 0 {recip +} fold exch length exch div diff --git a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx index 46ab67c07e..d596c23098 100644 --- a/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx +++ b/Task/Averages-Pythagorean-means/REXX/averages-pythagorean-means.rexx @@ -48,7 +48,7 @@ d=5 /*start with 5 digits accuracy. When the */ /*then turning the volume all the way up. */ do forever /* ◄─────────────────┐ keep plugging as digs increases*/ - d=min(d+d,a) /* │ limit the digits to orig digs┐5*/ + d=min(d+d,a) /* │ limit the digits to orig digs+5*/ numeric digits d /* │ keep increasing the accuracy. */ old=0 /* │ define old (guess). */ /* │ */ diff --git a/Task/Averages-Pythagorean-means/Ruby/averages-pythagorean-means.rb b/Task/Averages-Pythagorean-means/Ruby/averages-pythagorean-means.rb index c712e326dd..f05ed484aa 100644 --- a/Task/Averages-Pythagorean-means/Ruby/averages-pythagorean-means.rb +++ b/Task/Averages-Pythagorean-means/Ruby/averages-pythagorean-means.rb @@ -1,6 +1,6 @@ class Array def arithmetic_mean - inject(:+).to_f / length + inject(0.0, :+) / length end def geometric_mean @@ -8,7 +8,7 @@ class Array end def harmonic_mean - length.to_f / inject(0) {|s, m| s += 1.0/m} + length / inject(0.0) {|s, m| s + 1.0/m} end end diff --git a/Task/Averages-Pythagorean-means/Scala/averages-pythagorean-means.scala b/Task/Averages-Pythagorean-means/Scala/averages-pythagorean-means.scala index b21d41f0e7..2fc1b27ce3 100644 --- a/Task/Averages-Pythagorean-means/Scala/averages-pythagorean-means.scala +++ b/Task/Averages-Pythagorean-means/Scala/averages-pythagorean-means.scala @@ -3,7 +3,6 @@ def geometricMean(n: Seq[Int]) = math.pow(n.foldLeft(1.0)(_*_), 1.0 / n.size.to def harmonicMean(n: Seq[Int]) = n.size / n.map(1.0 / _).sum var nums = 1 to 10 - var a = arithmeticMean(nums) var g = geometricMean(nums) var h = harmonicMean(nums) diff --git a/Task/Averages-Root-mean-square/C++/averages-root-mean-square.cpp b/Task/Averages-Root-mean-square/C++/averages-root-mean-square.cpp index 7a9059968a..4bdad4e804 100644 --- a/Task/Averages-Root-mean-square/C++/averages-root-mean-square.cpp +++ b/Task/Averages-Root-mean-square/C++/averages-root-mean-square.cpp @@ -7,7 +7,7 @@ int main( ) { std::vector numbers ; for ( int i = 1 ; i < 11 ; i++ ) numbers.push_back( i ) ; - double meansquare = sqrt ( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ))/10.0 ); - std::cout << "The quadratic mean of the numbers 1 .. 10 is " << meansquare << " !\n" ; + double meansquare = sqrt( ( std::inner_product( numbers.begin(), numbers.end(), numbers.begin(), 0 ) ) / static_cast( numbers.size() ) ); + std::cout << "The quadratic mean of the numbers 1 .. " << numbers.size() << " is " << meansquare << " !\n" ; return 0 ; } diff --git a/Task/Averages-Root-mean-square/Elixir/averages-root-mean-square.elixir b/Task/Averages-Root-mean-square/Elixir/averages-root-mean-square.elixir new file mode 100644 index 0000000000..98e724a758 --- /dev/null +++ b/Task/Averages-Root-mean-square/Elixir/averages-root-mean-square.elixir @@ -0,0 +1,7 @@ +defmodule RC do + def root_mean_square(list) do + :math.sqrt(Enum.reduce(list, 0, &(&2 + &1 * &1)) / Enum.count(list)) + end +end + +IO.puts RC.root_mean_square(1..10) diff --git a/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-1.l b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-1.l new file mode 100644 index 0000000000..3a4bbaf2a4 --- /dev/null +++ b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-1.l @@ -0,0 +1,5 @@ +(defun rms (nums) + ;; `/' returns a float only when given floats + (setq nums (mapcar 'float nums)) + (sqrt (/ (apply '+ (mapcar (lambda (x) (* x x)) nums)) + (length nums)))) diff --git a/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l new file mode 100644 index 0000000000..5795de2d6f --- /dev/null +++ b/Task/Averages-Root-mean-square/Emacs-Lisp/averages-root-mean-square-2.l @@ -0,0 +1,6 @@ +(defun rms (nums) + (setq nums (mapcar 'float nums)) + (sqrt (/ (apply '+ (cl-map 'list '* nums nums)) + (length nums)))) + +(rms '(1 2 3 4 5 6 7 8 9 10)) diff --git a/Task/Averages-Root-mean-square/Excel/averages-root-mean-square.excel b/Task/Averages-Root-mean-square/Excel/averages-root-mean-square.excel new file mode 100644 index 0000000000..9445fa5125 --- /dev/null +++ b/Task/Averages-Root-mean-square/Excel/averages-root-mean-square.excel @@ -0,0 +1 @@ +=SQRT(SUMSQ($A1:$A10)/COUNT($A1:$A10)) diff --git a/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-1.max b/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-1.max new file mode 100644 index 0000000000..9d3a82c809 --- /dev/null +++ b/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-1.max @@ -0,0 +1,6 @@ +fn RMS arr = +( + local sumSquared = 0 + for i in arr do sumSquared += i^2 + return (sqrt (sumSquared/arr.count as float)) +) diff --git a/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-2.max b/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-2.max new file mode 100644 index 0000000000..4582c562db --- /dev/null +++ b/Task/Averages-Root-mean-square/MAXScript/averages-root-mean-square-2.max @@ -0,0 +1,2 @@ +rms #{1..10} +6.20484 diff --git a/Task/Averages-Root-mean-square/Maple/averages-root-mean-square.maple b/Task/Averages-Root-mean-square/Maple/averages-root-mean-square.maple new file mode 100644 index 0000000000..c6093cd258 --- /dev/null +++ b/Task/Averages-Root-mean-square/Maple/averages-root-mean-square.maple @@ -0,0 +1,5 @@ +y := [ seq(1..10) ]: +RMS := proc( x ) + return sqrt( Statistics:-Mean( x ^~ 2 ) ); +end proc: +RMS( y ); diff --git a/Task/Averages-Root-mean-square/PL-I/averages-root-mean-square.pli b/Task/Averages-Root-mean-square/PL-I/averages-root-mean-square.pli index 5da5c25f0a..601a5e958a 100644 --- a/Task/Averages-Root-mean-square/PL-I/averages-root-mean-square.pli +++ b/Task/Averages-Root-mean-square/PL-I/averages-root-mean-square.pli @@ -1,3 +1,7 @@ -declare A(10) fixed decimal static initial (1,2,3,4,5,6,7,8,9,10); -n = hbound(A,1); -RMS = sqrt(sum(A**2)/n); + atest: Proc Options(main); + declare A(10) Dec Float(15) static initial (1,2,3,4,5,6,7,8,9,10); + declare (n,RMS) Dec Float(15); + n = hbound(A,1); + RMS = sqrt(sum(A**2)/n); + put Skip Data(rms); + End; diff --git a/Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square.pl6 b/Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-1.pl6 similarity index 100% rename from Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square.pl6 rename to Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-1.pl6 diff --git a/Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-2.pl6 b/Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-2.pl6 new file mode 100644 index 0000000000..e813d829a8 --- /dev/null +++ b/Task/Averages-Root-mean-square/Perl-6/averages-root-mean-square-2.pl6 @@ -0,0 +1 @@ +sub rms { sqrt @_ R/ [+] @_ X** 2 } diff --git a/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx b/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx index 8e2cdef991..2c66552434 100644 --- a/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx +++ b/Task/Averages-Root-mean-square/REXX/averages-root-mean-square.rexx @@ -1,19 +1,16 @@ -/*REXX program to compute the root mean square of a series of numbers.*/ - +/*REXX program computes the root mean square of a series of numbers. */ parse arg n . /*get the argument (maybe). */ -if n=='' then n=10 /*Not specified? Then assume 10.*/ +if n=='' then n=10 /*Not specified? Then assume 10.*/ numeric digits 50 /*let's go a little overboard. */ sum=0 /*sum of numbers squared (so far)*/ - do j=1 for n /*step through N integers. */ + do j=1 for n /*step through N integers. */ sum=sum+j**2 /*sum the squares of the integers*/ end /*j*/ rms=sqrt(sum/n) /*divide by N, then get SQRT. */ -say 'root mean square for 1──►'n "is" rms /*show & tell.*/ +say 'root mean square for 1──►'n "is" rms /*display it.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SQRT subroutine─────────────────────────*/ sqrt: procedure; parse arg x;if x=0 then return 0;d=digits();numeric digits 11 -g=.sqrtGuess(); do j=0 while p>9; m.j=p; p=p%2+1; end; do k=j+5 to 0 by -1 +numeric form; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2 +p=d+d%4+2; m.=11; 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 - -.sqrtGuess: if x<0 then say 'negative number' x; numeric form; m.=11 -p=d+d%4+2; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 diff --git a/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-1.rb b/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-1.rb index 71c6f3f4af..40942c5d7f 100644 --- a/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-1.rb +++ b/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-1.rb @@ -1,6 +1,6 @@ class Array def quadratic_mean - Math.sqrt( self.inject(0) {|s, y| s += y*y}.to_f / self.length ) + Math.sqrt( self.inject(0.0) {|s, y| s + y*y} / self.length ) end end @@ -10,4 +10,4 @@ class Range end end -(1..10).quadratic_mean # => 6.20483682299543 +(1..10).quadratic_mean # => 6.2048368229954285 diff --git a/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-2.rb b/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-2.rb index 89f07f17cb..c438bacdeb 100644 --- a/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-2.rb +++ b/Task/Averages-Root-mean-square/Ruby/averages-root-mean-square-2.rb @@ -1,4 +1,4 @@ def rms(seq) - Math.sqrt(seq.inject(0.0) {|sum, x| sum += x*x} / seq.length) + Math.sqrt(seq.inject(0.0) {|sum, x| sum + x*x} / seq.length) end -puts rms (1..10).to_a # => 6.2048368229954285 +puts rms (1..10).to_a # => 6.2048368229954285 diff --git a/Task/Averages-Root-mean-square/Yacas/averages-root-mean-square.yacas b/Task/Averages-Root-mean-square/Yacas/averages-root-mean-square.yacas new file mode 100644 index 0000000000..757ad96f63 --- /dev/null +++ b/Task/Averages-Root-mean-square/Yacas/averages-root-mean-square.yacas @@ -0,0 +1 @@ +Sqrt(Add((1 .. 10)^2)/10) diff --git a/Task/Averages-Simple-moving-average/00DESCRIPTION b/Task/Averages-Simple-moving-average/00DESCRIPTION index 2cb853c620..ff29f84efa 100644 --- a/Task/Averages-Simple-moving-average/00DESCRIPTION +++ b/Task/Averages-Simple-moving-average/00DESCRIPTION @@ -4,7 +4,8 @@ The task is to: :''Create a [[wp:Stateful|stateful]] function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far.'' '''Description'''
-A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period. It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA(). +A simple moving average is a method for computing an average of a stream of numbers by only averaging the last P numbers from the stream, where P is known as the period. +It can be implemented by calling an initialing routine with P as its argument, I(P), which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last P of them, lets call this SMA(). The word stateful in the task description refers to the need for SMA() to remember certain information between calls to it: * The period, P diff --git a/Task/Averages-Simple-moving-average/Bracmat/averages-simple-moving-average.bracmat b/Task/Averages-Simple-moving-average/Bracmat/averages-simple-moving-average.bracmat new file mode 100644 index 0000000000..51b0436290 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Bracmat/averages-simple-moving-average.bracmat @@ -0,0 +1,38 @@ +( ( I + = buffer + . (new$=):?freshEmptyBuffer + & + ' ( buffer avg + . ( avg + = L S n + . 0:?L:?S + & whl + ' ( !arg:%?n ?arg + & !n+!S:?S + & 1+!L:?L + ) + & (!L:0&0|!S*!L^-1) + ) + & (buffer=$freshEmptyBuffer) + & !arg !(buffer.):?(buffer.) + & ( !(buffer.):?(buffer.) [($arg) ? + | + ) + & avg$!(buffer.) + ) + ) +& ( pad + = len w + . @(!arg:? [?len) + & @(" ":? [!len ?w) + & !w !arg + ) +& I$3:(=?sma3) +& I$5:(=?sma5) +& 1 2 3 4 5 5 4 3 2 1:?K +& whl + ' ( !K:%?k ?K + & out + $ (str$(!k " - sma3:" pad$(sma3$!k) " sma5:" pad$(sma5$!k))) + ) +); diff --git a/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average.coffee b/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average.coffee new file mode 100644 index 0000000000..14477dbd6d --- /dev/null +++ b/Task/Averages-Simple-moving-average/CoffeeScript/averages-simple-moving-average.coffee @@ -0,0 +1,44 @@ +I = (P) -> + # The cryptic name "I" follows the problem description; + # it returns a function that computes a moving average + # of successive values over the period P, using closure + # variables to maintain state. + cq = circular_queue(P) + num_elems = 0 + sum = 0 + + SMA = (n) -> + sum += n + if num_elems < P + cq.add(n) + num_elems += 1 + sum / num_elems + else + old = cq.replace(n) + sum -= old + sum / P + +circular_queue = (n) -> + # queue that only ever stores up to n values; + # Caller shouldn't call replace until n values + # have been added. + i = 0 + arr = [] + + add: (elem) -> + arr.push elem + replace: (elem) -> + # return value whose age is "n" + old_val = arr[i] + arr[i] = elem + i = (i + 1) % n + old_val + +# The output of the code below should convince you that +# calling I multiple times returns functions with independent +# state. +sma3 = I(3) +sma7 = I(7) +sma11 = I(11) +for i in [1..10] + console.log i, sma3(i), sma7(i), sma11(i) diff --git a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d index 5381b293c6..f5b0b0a52c 100644 --- a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d +++ b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-1.d @@ -1,11 +1,11 @@ import std.stdio, std.traits, std.algorithm; -auto sma(T, int period)() { +auto sma(T, int period)() pure nothrow @safe { T[period] data = 0; T sum = 0; int index, nFilled; - return (in T v) nothrow { + return (in T v) nothrow @safe @nogc { sum += -data[index] + v; data[index] = v; index = (index + 1) % period; @@ -19,6 +19,5 @@ void main() { immutable s5 = sma!(double, 5); foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) - writefln("Added %d, sma(3) = %f, sma(5) = %f", - e, s3(e), s5(e)); + writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e)); } diff --git a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d index 9f9e6132d8..a6359d7a2b 100644 --- a/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d +++ b/Task/Averages-Simple-moving-average/D/averages-simple-moving-average-2.d @@ -5,7 +5,7 @@ struct SMA(T, int period) { T sum = 0; int index, nFilled; - auto opCall(in T v) pure nothrow { + auto opCall(in T v) pure nothrow @safe @nogc { sum += -data[index] + v; data[index] = v; index = (index + 1) % period; @@ -19,6 +19,5 @@ void main() { SMA!(double, 5) s5; foreach (immutable e; [1, 2, 3, 4, 5, 5, 4, 3, 2, 1]) - writefln("Added %d, sma(3) = %f, sma(5) = %f", - e, s3(e), s5(e)); + writefln("Added %d, sma(3) = %f, sma(5) = %f", e, s3(e), s5(e)); } diff --git a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena index 502913567d..c7483737b9 100644 --- a/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena +++ b/Task/Averages-Simple-moving-average/Elena/averages-simple-moving-average.elena @@ -3,52 +3,53 @@ #define system'collections. #define extensions. -#class SMAExtender +#class SMA { #field thePeriod. + #field theList. #constructor new : aPeriod [ thePeriod := aPeriod. + theList := List new. ] - #method add : aNumber + #method append : aNumber [ - self += aNumber. + theList += aNumber. - #var aCount := self length. + #var aCount := theList length. ^ aCount => 0 ? [ 0.0r ] ! [ (aCount > thePeriod)? [ - self remove &index:0. + theList remove &index:0. + + aCount := thePeriod. ]. - #var aSum := Summing new:(Real new:0) foreach:self. - ^ aSum / self length. + #var aSum := Summing new:(Real new &int:0) foreach:theList. + + ^ aSum / aCount. ]. ] } -#symbol sma = (:aPeriod) [ Extension(SMAExtender new:aPeriod, List new) ]. - -// --- Program --- - #symbol program = [ - #var SMA3 := sma:3. - #var SMA5 := sma:5. + #var SMA3 := SMA new:3. + #var SMA5 := SMA new:5. - control from:1 &to:5 &do: i + control forrange &int:1 &int:5 &do: (&int:i) [ - consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 + i number). - consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 + i number). + consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 += i). + consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 += i). ]. - control from:5 &backTo:1 &do: i + control forrange &int:5 &int:1 &do: (&int:i) [ - consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 + i number). - consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 + i number). + consoleEx writeLine:"sma3 + " :i :" = ": (SMA3 += i). + consoleEx writeLine:"sma5 + " :i :" = ": (SMA5 += i). ]. ]. diff --git a/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-1.hs b/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-1.hs new file mode 100644 index 0000000000..eec5d6b0c2 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-1.hs @@ -0,0 +1,26 @@ +import Control.Monad +import Data.List +import Data.IORef + +mean :: Fractional a => [a] -> a +mean xs = sum xs / (genericLength xs) + +series = [1,2,3,4,5,5,4,3,2,1] + +simple_moving_averager period = do + numsRef <- newIORef [] + return (\x -> do + nums <- readIORef numsRef + let xs = take period (x:nums) + writeIORef numsRef xs + return $ mean xs + ) + +main = do + sma3 <- simple_moving_averager 3 + sma5 <- simple_moving_averager 5 + forM_ series (\n -> do + mm3 <- sma3 n + mm5 <- sma5 n + putStrLn $ "Next number = " ++ (show n) ++ ", SMA_3 = " ++ (show mm3) ++ ", SMA_5 = " ++ (show mm5) + ) diff --git a/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average.hs b/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-2.hs similarity index 100% rename from Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average.hs rename to Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-2.hs diff --git a/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-3.hs b/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-3.hs new file mode 100644 index 0000000000..b3616b06e6 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Haskell/averages-simple-moving-average-3.hs @@ -0,0 +1,28 @@ +import Control.Monad +import Control.Monad.State + +period :: Int +period = 3 + +type SMAState = [Float] + +computeSMA :: Float -> State SMAState Float +computeSMA x = do + previousValues <- get + let values = previousValues ++ [x] + let newAverage = if length values <= period then (sum values) / (fromIntegral $ length remainingValues :: Float) + else (sum remainingValues) / (fromIntegral $ length remainingValues :: Float) + where remainingValues = dropIf period values + put $ dropIf period values + return newAverage + +dropIf :: Int -> [a] -> [a] +dropIf x xs = drop ((length xs) - x) xs + +demostrateSMA :: State SMAState [Float] +demostrateSMA = mapM computeSMA [1, 2, 3, 4, 5, 5, 4, 3, 2, 1] + +main :: IO () +main = putStrLn $ (show result) + where + (result, _) = runState demostrateSMA [] diff --git a/Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average.js b/Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-1.js similarity index 100% rename from Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average.js rename to Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-1.js diff --git a/Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-2.js b/Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-2.js new file mode 100644 index 0000000000..de3b3fe6d5 --- /dev/null +++ b/Task/Averages-Simple-moving-average/JavaScript/averages-simple-moving-average-2.js @@ -0,0 +1,10 @@ +// single-sided +Array.prototype.simpleSMA=function(N) { +return this.map(function(x,i,v) { + if(ii-N; }).reduce(function(a,b){ return a+b; })/N; +}); }; + +g=[1,2,3,4,5,8,5,4]; +console.log(g.simpleSMA(3)) +console.log(g.simpleSMA(5)) diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia new file mode 100644 index 0000000000..e978b52eba --- /dev/null +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-1.julia @@ -0,0 +1,3 @@ +SMA(N) = let buffer = Number[] + x -> (push!(buffer, x) ; mean(buffer[max(1,end-N+1):end])) + end diff --git a/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia new file mode 100644 index 0000000000..bbb0d9c796 --- /dev/null +++ b/Task/Averages-Simple-moving-average/Julia/averages-simple-moving-average-2.julia @@ -0,0 +1,6 @@ +SMA(N, buffer = Number[]) = + x -> begin + push!(buffer, x) + if length(buffer) == N+1 shift!(buffer) end + mean(buffer) + end diff --git a/Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average.pli b/Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-1.pli similarity index 100% rename from Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average.pli rename to Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-1.pli diff --git a/Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-2.pli b/Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-2.pli new file mode 100644 index 0000000000..35c6939b7c --- /dev/null +++ b/Task/Averages-Simple-moving-average/PL-I/averages-simple-moving-average-2.pli @@ -0,0 +1,45 @@ +*process source attributes xref; + mat: Proc Options(main); + Dcl a(10) Dec Fixed(8,6); + Dcl s Dec Fixed(10,8); + Dcl n Bin Fixed(31) init(hbound(a)); /* number of items in the list. */ + Dcl p Bin Fixed(31) init(3); /* the 1st period */ + Dcl q Bin Fixed(31) init(5); /* the 2nd period */ + Dcl m Bin Fixed(31); + Call i(a); + + Put Edit(' SMA with SMA with', + ' number period 3 period 5', + ' -------- ---------- ----------') + (Skip,a); + Do m=1 To n; + Put Edit(m,sma(p,m),sma(q,m))(Skip,f(5),2(f(13,6))); + End; + + i: Proc(a); + Dcl a(*) Dec Fixed(8,6); + Dcl (j,m) Bin Fixed(31); + Do j=1 To hbound(a)/2; + a(j)=j; /* ··· increasing values. */ + End; + Do k=hbound(a)/2 To 1 By -1; + a(j)=k; /* ··· decreasing values. */ + j+=1; + End; + End; + + sma: Proc(p,j) Returns(Dec Fixed(8,6)); + Dcl s Dec fixed(8,6) Init(0); + Dcl i Bin Fixed(31) Init(0); + Dcl j Bin Fixed(31) Init((hbound(a)+1)); + Dcl (p,i,k,ka,kb) Bin Fixed(31); + ka=max(1,j-p+1); + kb=j+p; + Do k=ka To kb While(k<=j); + i+=1; + s+=a(k) + End; + s=s/i+0.5e-6; + Return(s); + End; + End; diff --git a/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx index ce756c022e..dc73d270de 100644 --- a/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx +++ b/Task/Averages-Simple-moving-average/REXX/averages-simple-moving-average.rexx @@ -1,35 +1,24 @@ -/*REXX program is illustrate simple moving average. */ -arg p q n . /*get some arguments (maybe). */ -if p=='' then p=3 /*the 1st period (default: 3).*/ -if q=='' then q=5 /* " 2nd " " 5 */ -if n=='' then n=10 /*number of items in the list.*/ -a.=0 - do j=1 for n%2 /*build beginning of the list,*/ - a.j=j /* ... increasing values. */ - end /*j*/ - - do k=n%2 to 1 by -1 /* ... decreasing values. */ - a.j=k - j=j+1 - end /*k*/ - - do i=1 for n /*show an indented item list. */ - say left('',60) 'item' right(i,3)'='right(a.i,3) - end /*i*/ - do m=1 for n /*OK the, let's start the SMA.*/ - smaP=sma(p,m) /*simple moving average for P.*/ - smaQ=sma(q,m) /* " " " " Q.*/ - - /*show 2 nicely formated SMAs.*/ - say 'm='right(m,3), /*show where we're at in list.*/ - " sma("p')='left(sma(p,m),11), /*show nicely aligned sma P. */ - " sma("q')='left(sma(q,m),11) /* " " " " Q. */ - end /*m*/ -exit -/*────────────────────────────────────────SMA subroutine────────────────*/ -sma: procedure expose A.; arg p,j; s=0; i=0 - do k=max(1,j-p+1) to j+p for p while k<=j - i=i+1 - s=s+a.k - end +/*REXX program illustrates simple moving average using a simple list. */ +parse arg p q n . /*get some arguments (maybe). */ +if p=='' then p=3 /*the 1st period (default: 3).*/ +if q=='' then q=5 /* " 2nd " " 5 */ +if n=='' then n=10 /*number of items in the list.*/ +@.=0 /*define stemmed array, init 0*/ +/*──────────────────────────────────────────build 1st half of the list. */ + do j=1 for n%2; @.j=j; end /* ··· increasing values.*/ +/*──────────────────────────────────────────build 2nd half of the list. */ + do k=n%2 to 1 by -1; @.j=k; j=j+1; end /* ··· decreasing values.*/ +/*──────────────────────────────────────────perform a simple moving avg.*/ +say ' ' " SMA with " ' SMA with ' +say ' number ' " period" p' ' ' period' q +say ' ──────── ' "──────────" '──────────' + do m=1 for n + say center(@.m,10) left(sma(p,m),11) left(sma(q,m),11) + end /*m*/ /* [↑] show simple moving avg.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────SMA subroutine──────────────────────*/ +sma: procedure expose @.; parse arg p,j; s=0; i=0 + do k=max(1,j-p+1) to j+p for p while k<=j; i=i+1 + s=s+@.k + end /*k*/ return s/i diff --git a/Task/Balanced-brackets/Aime/balanced-brackets.aime b/Task/Balanced-brackets/Aime/balanced-brackets.aime index 5257bf1549..61cc7e0260 100644 --- a/Task/Balanced-brackets/Aime/balanced-brackets.aime +++ b/Task/Balanced-brackets/Aime/balanced-brackets.aime @@ -6,7 +6,7 @@ unbalanced(text s) b = 0; i = 0; while (i < length(s)) { - if (character(s, i) == '[') { + if (s[i] == '[') { b += 1; } else { b -= 1; diff --git a/Task/Balanced-brackets/D/balanced-brackets-3.d b/Task/Balanced-brackets/D/balanced-brackets-3.d index fd5bfc2655..269f45ca33 100644 --- a/Task/Balanced-brackets/D/balanced-brackets-3.d +++ b/Task/Balanced-brackets/D/balanced-brackets-3.d @@ -1,7 +1,7 @@ import std.stdio, std.random, std.range, std.algorithm; -bool isBalanced(in string s, in string pars="[]") pure nothrow { - bool bal(in string t, in int nb = 0) pure nothrow { +bool isBalanced(in string s, in char[2] pars="[]") pure nothrow @safe @nogc { + bool bal(in string t, in int nb = 0) pure nothrow @safe @nogc { if (!nb && t.empty) return true; if (t.empty || nb < 0) return false; if (t[0] == pars[0]) return bal(t.dropOne, nb + 1); diff --git a/Task/Balanced-brackets/Elena/balanced-brackets.elena b/Task/Balanced-brackets/Elena/balanced-brackets.elena index 7c8b6be330..9aa5068604 100644 --- a/Task/Balanced-brackets/Elena/balanced-brackets.elena +++ b/Task/Balanced-brackets/Elena/balanced-brackets.elena @@ -2,32 +2,40 @@ #define system'routines. #define extensions. -#symbol randomBrackets = &&:aLength +// --- RandomBrackets --- + +#symbol randomBrackets = (:aLength) [ - #var aBrackets := Array new &type'length:aLength &function: &&:i[ CharValue new:91 ] + Array new &type'length:aLength &function: &&:i[ CharValue new:93 ]. + ^ (0 == aLength) + ? [ emptyLiteralValue ] + ! [ + #var aBrackets := arrayControl new &length:(aLength int) &each: i[ CharValue new &short:91 ] + arrayControl new &length:(aLength int) &each: i[ CharValue new &short:93 ]. - randomControl randomize:(aLength * 2) &array:aBrackets. + randomControl randomize:(aLength * 2) &array:aBrackets. - ^ Summing new:(String new) foreach:aBrackets Literal. + ^ Summing new:(String new) foreach:aBrackets literal. + ]. ]. -#symbol isBalanced = &&:aLiteral +#symbol isBalanced = (:aLiteral) [ #var aCounter := Integer new:0. - control foreach:aLiteral &until: &&:aChar [ aCounter append:(aChar => "[" ? [ 1 ] "]" ? [ -1 ]) < 0 ]. + control foreach:aLiteral &until: aChar [ aCounter append:(aChar => "[" ? [ 1 ] "]" ? [ -1 ]) < 0 ]. ^ (0 == aCounter). ]. +// --- Program --- + #symbol program = [ - control from:0 &till:10 &do: &&:aLength + control forrange &int:0 &int:9 &do: (&int:aLength) [ #var anStr := randomBrackets:aLength. #var balanced := isBalanced:anStr. - console write:"""" write:anStr write:"""" writeLine:(balanced => true ? [ " is balanced" ] false ? [ " is not balanced" ]). + consoleEx writeLine:"""":anStr:"""":(balanced => true ? [ " is balanced" ] false ? [ " is not balanced" ]). ]. console readChar. diff --git a/Task/Balanced-brackets/Go/balanced-brackets.go b/Task/Balanced-brackets/Go/balanced-brackets.go index d3354589e8..f3fe0ab64d 100644 --- a/Task/Balanced-brackets/Go/balanced-brackets.go +++ b/Task/Balanced-brackets/Go/balanced-brackets.go @@ -21,17 +21,16 @@ func generate(n uint) string { } func testBalanced(s string) { - fmt.Printf("%s: ", s) - var open int - for i := 0; i < len(s); i++ { - switch s[i] { + fmt.Print(s + ": ") + open := 0 + for _,c := range s { + switch c { case '[': open++ case ']': if open == 0 { fmt.Println("not ok") return - } open-- default: diff --git a/Task/Balanced-brackets/Perl/balanced-brackets-3.pl b/Task/Balanced-brackets/Perl/balanced-brackets-3.pl index 13224bdd8b..556b263558 100644 --- a/Task/Balanced-brackets/Perl/balanced-brackets-3.pl +++ b/Task/Balanced-brackets/Perl/balanced-brackets-3.pl @@ -1,8 +1,5 @@ +use Regexp::Common 'balanced'; +my $re = qr/^$RE{balanced}{-parens=>'[]'}$/; sub balanced { - my $depth = 0; - for (split //, shift) { - if ($_ eq '[') { ++$depth } - elsif ($_ eq ']') { return if --$depth < 0 } - } - return !$depth + return shift =~ $re; } diff --git a/Task/Balanced-brackets/Perl/balanced-brackets-4.pl b/Task/Balanced-brackets/Perl/balanced-brackets-4.pl new file mode 100644 index 0000000000..13224bdd8b --- /dev/null +++ b/Task/Balanced-brackets/Perl/balanced-brackets-4.pl @@ -0,0 +1,8 @@ +sub balanced { + my $depth = 0; + for (split //, shift) { + if ($_ eq '[') { ++$depth } + elsif ($_ eq ']') { return if --$depth < 0 } + } + return !$depth +} diff --git a/Task/Balanced-brackets/Scala/balanced-brackets-2.scala b/Task/Balanced-brackets/Scala/balanced-brackets-2.scala index 232602ae22..054692fb5f 100644 --- a/Task/Balanced-brackets/Scala/balanced-brackets-2.scala +++ b/Task/Balanced-brackets/Scala/balanced-brackets-2.scala @@ -1,25 +1,21 @@ -import scala.util.Random +import scala.util.Random.shuffle -object BalancedParensApp extends App { +object BalancedBracketsApp 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") + for (length <- 0 until 10) { + val str = randomBrackets(length) + if (is_balanced(str)) + println(s"$str - ok") + else + println(s"$str - NOT ok") } - def randomString(length: Int) = { - val parensPairs = ("[]" * length).toSeq - val parensOfGivenLength = parensPairs.take(length) - val shuffledParens = Random.shuffle(parensOfGivenLength) - shuffledParens.mkString - } + def randomBrackets(length: Int): String = + shuffle(("[]" * length).toSeq).mkString - def isBalanced(parensString: String): Boolean = { + def isBalanced(bracketString: String): Boolean = { var balance = 0 - parensString.foreach { char => + for (char <- bracketString) { char match { case '[' => balance += 1 case ']' => balance -= 1 diff --git a/Task/Balanced-brackets/Scala/balanced-brackets-3.scala b/Task/Balanced-brackets/Scala/balanced-brackets-3.scala new file mode 100644 index 0000000000..853e09b4fc --- /dev/null +++ b/Task/Balanced-brackets/Scala/balanced-brackets-3.scala @@ -0,0 +1,19 @@ +import scala.util.Random.shuffle +import scala.annotation.tailrec + + // ... + + def isBalanced(str: String): Boolean = isBalanced(str.toList, balance = 0) + + @tailrec + def isBalanced(str: List[Char], balance: Int = 0): Boolean = + str match { + case _ if (balance < 0) => false + case Nil => balance == 0 + case char :: rest => + val newBalance = char match { + case '[' => balance + 1 + case ']' => balance -1 + } + isBalanced(rest, newBalance) + } diff --git a/Task/Balanced-brackets/TXR/balanced-brackets.txr b/Task/Balanced-brackets/TXR/balanced-brackets.txr index 4b6139ff39..4242645417 100644 --- a/Task/Balanced-brackets/TXR/balanced-brackets.txr +++ b/Task/Balanced-brackets/TXR/balanced-brackets.txr @@ -7,16 +7,16 @@ ((< i len) (list-vector vec)) ((inc i)) (let ((j (random r len)) - (temp (vecref vec i))) - (set (vecref vec i) (vecref vec j)) - (set (vecref vec j) temp)))) + (temp [vec i])) + (set [vec i] [vec j]) + (set [vec j] temp)))) + (defun generate-1 (count) - (for ((i 0) chars) ((< i count) (cat-str (shuffle chars) "")) ((inc i)) - (push #\[ chars) - (push #\] chars))) + (let ((bkt (repeat "[]" count))) + (cat-str (shuffle bkt)))) + (defun generate-list (num count) - (for ((i 0) list) ((< i num) list) ((inc i)) - (push (generate-1 count) list)))) + [[generate tf (op generate-1 count)] 0..num])) @(next :list @(generate-list 22 6)) @(output) INPUT MATCHED REST diff --git a/Task/Balanced-brackets/UNIX-Shell/balanced-brackets.sh b/Task/Balanced-brackets/UNIX-Shell/balanced-brackets.sh new file mode 100644 index 0000000000..77bf260029 --- /dev/null +++ b/Task/Balanced-brackets/UNIX-Shell/balanced-brackets.sh @@ -0,0 +1,38 @@ +generate() { + local b=() + local i j tmp + for ((i=1; i<=$1; i++)); do + b+=( '[' ']') + done + for ((i=${#b[@]}-1; i>0; i--)); do + j=$(rand $i) + tmp=${b[j]} + b[j]=${b[i]} + b[i]=$tmp + done + local IFS= + echo "${b[*]}" +} + +# a random number in the range [0,n) +rand() { + echo $(( $RANDOM % $1 )) +} + +balanced() { + local -i lvl=0 + local i + for ((i=0; i<${#1}; i++)); do + case ${1:i:1} in + '[') ((lvl++));; + ']') (( --lvl < 0 )) && return 1;; + esac + done + (( lvl == 0 )); return $? +} + +for ((i=0; i<=10; i++)); do + test=$(generate $i) + balanced "$test" && result=OK || result="NOT OK" + printf "%s\t%s\n" "$test" "$result" +done diff --git a/Task/Balanced-ternary/ATS/balanced-ternary.ats b/Task/Balanced-ternary/ATS/balanced-ternary.ats new file mode 100644 index 0000000000..fdad9a32e4 --- /dev/null +++ b/Task/Balanced-ternary/ATS/balanced-ternary.ats @@ -0,0 +1,213 @@ +(* +** This one is +** translated into ATS from the Ocaml entry +*) + +(* ****** ****** *) +// +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o bternary bternary.dats +// +(* ****** ****** *) + +#include +"share/atspre_staload.hats" + +(* ****** ****** *) + +datatype btd = P | Z | N; typedef btern = List0(btd) + +(* ****** ****** *) + +fun +btd2int (d: btd): int = + (case+ d of P() => 1 | Z() => 0 | N() => ~1) + +(* ****** ****** *) + +fun +btd2string (d:btd): string = +( +case+ d of P() => "+" | Z() => "0" | N() => "-" +) + +(* ****** ****** *) + +fun +btern2string +( + ds: btern +) : string = + strptr2string(res) where +{ + val xs = list_map_cloref (ds, lam d => btd2string(d)) + val xs = list_vt_reverse (xs) + val res = stringlst_concat($UNSAFE.castvwtp1{List(string)}(xs)) + val () = list_vt_free (xs) +} + +(* ****** ****** *) + +fun +from_string + (inp: string): btern = let +// +fun +loop{n:nat} +( + inp: string(n), ds: btern +) : btern = +( +// + if isneqz(inp) + then let + val c = inp.head + val d = + (case- c of '+' => P | '0' => Z | '-' => N): btd + // end of [val] + in + loop (inp.tail, list_cons(d, ds)) + end // end of [then] + else ds // end of [else] +// +) (* end of [loop] *) +// +in + loop (g1ofg0(inp), list_nil) +end // end of [from_string] + +(* ****** ****** *) + +fun +to_int (ds: btern): int = +( +case+ ds of +| list_nil () => 0 +| list_cons (d, ds) => 3*to_int(ds) + btd2int(d) +) (* end of [to_int] *) + +fun +from_int (n: int): btern = +( +if +n = 0 +then list_nil +else let + val r = n mod 3 +in + if r = 0 + then list_cons (Z, from_int (n/3)) + else if (r = 1 || r = ~2) + then list_cons (P, from_int ((n-1)/3)) + else list_cons (N, from_int ((n+1)/3)) +end // end of [else] +) (* end of [from_int] *) + +(* ****** ****** *) + +fun +neg_btern + (ds: btern): btern = +list_vt2t +( +list_map_cloref + (ds, lam d => case+ d of P() => N() | Z() => Z() | N() => P()) +) (* end of [neg_btern] *) + +overload ~ with neg_btern + +(* ****** ****** *) +// +extern +fun +add_btern_btern: (btern, btern) -> btern +and +sub_btern_btern: (btern, btern) -> btern +overload + with add_btern_btern of 100 +overload - with sub_btern_btern of 100 +// +extern +fun +mul_btern_btern: (btern, btern) -> btern +overload * with mul_btern_btern of 110 +// +(* ****** ****** *) + +#define :: list_cons + +(* ****** ****** *) + +local + +fun aux0 (ds: btern): btern = +( + case+ ds of nil() => ds | _ => Z()::ds +) + +fun succ(ds:btern) = ds+list_sing(P()) +fun pred(ds:btern) = ds+list_sing(N()) + +in (* in-of-local *) + +implement +add_btern_btern + (ds1, ds2) = +( +case+ (ds1, ds2) of +| (nil(), _) => ds2 +| (_, nil()) => ds1 +| (P()::ds1, N()::ds2) => aux0 (ds1+ds2) +| (Z()::ds1, Z()::ds2) => aux0 (ds1+ds2) +| (N()::ds1, P()::ds2) => aux0 (ds1+ds2) +| (P()::ds1, P()::ds2) => N() :: succ(ds1 + ds2) +| (N()::ds1, N()::ds2) => P() :: pred(ds1 + ds2) +| (Z()::ds1, btd::ds2) => btd :: (ds1 + ds2) +| (btd::ds1, Z()::ds2) => btd :: (ds1 + ds2) +) + +implement +sub_btern_btern (ds1, ds2) = ds1 + (~ds2) + +implement +mul_btern_btern (ds1, ds2) = +( +case+ ds2 of +| nil() => nil() +| Z()::ds2 => aux0 (ds1 * ds2) +| P()::ds2 => aux0 (ds1 * ds2) + ds1 +| N()::ds2 => aux0 (ds1 * ds2) - ds1 +) + +end // end of [local] + +(* ****** ****** *) + +typedef charptr = $extype"char*" + +(* ****** ****** *) + +implement main0 () = +{ +// +val a = +from_string "+-0++0+" +// +val b = from_int (~436) +val c = from_string "+-++-" +// +val d = a * (b - c) +// +val () = +$extfcall +( + void +, "printf" +, "a = %d\nb = %d\nc = %d\na * (b - c) = %s = %d\n" +, to_int(a) +, to_int(b) +, to_int(c) +, $UNSAFE.cast{charptr}(btern2string(d)) +, to_int(d) +) (* end of [val] *) +// +} (* end of [main0] *) diff --git a/Task/Balanced-ternary/D/balanced-ternary.d b/Task/Balanced-ternary/D/balanced-ternary.d index e5b67a83da..565af1dabf 100644 --- a/Task/Balanced-ternary/D/balanced-ternary.d +++ b/Task/Balanced-ternary/D/balanced-ternary.d @@ -23,11 +23,11 @@ struct BalancedTernary { this.digits = inp.retro.map!(c => str2dig[c]).array; } - this(in long inp) const pure /*nothrow*/ { + this(in long inp) const pure nothrow { this.digits = _bint2ternary(inp.BigInt); } - this(in BigInt inp) const pure /*nothrow*/ { + this(in BigInt inp) const pure nothrow { this.digits = _bint2ternary(inp); } @@ -36,12 +36,12 @@ struct BalancedTernary { this.digits = inp.digits; } - private this(in Dig[] inp) /*inout*/ pure nothrow { + private this(in Dig[] inp) pure nothrow { this.digits = inp; } - static Dig[] _bint2ternary(in BigInt n) pure /*nothrow*/ { - static py_div(T1, T2)(in T1 a, in T2 b) pure /*nothrow*/ { + static Dig[] _bint2ternary(in BigInt n) pure nothrow { + static py_div(T1, T2)(in T1 a, in T2 b) pure nothrow { if (a < 0) { return (b < 0) ? -a / -b : @@ -62,7 +62,7 @@ struct BalancedTernary { } } - @property BigInt toBint() const pure /*nothrow*/ { + @property BigInt toBint() const pure nothrow { return reduce!((y, x) => x + 3 * y)(0.BigInt, digits.retro); } @@ -139,6 +139,6 @@ void main() { immutable c = BalancedTernary("+-++-"); writeln("c: ", c.toBint, ' ', c); - immutable r = a * (b - c); + const /*immutable*/ r = a * (b - c); writeln("a * (b - c): ", r.toBint, ' ', r); } diff --git a/Task/Balanced-ternary/Icon/balanced-ternary.icon b/Task/Balanced-ternary/Icon/balanced-ternary.icon new file mode 100644 index 0000000000..646cc3da54 --- /dev/null +++ b/Task/Balanced-ternary/Icon/balanced-ternary.icon @@ -0,0 +1,90 @@ +procedure main() + a := "+-0++0+" + write("a = +-0++0+"," = ",cvtFromBT("+-0++0+")) + write("b = -436 = ",b := cvtToBT(-436)) + c := "+-++-" + write("c = +-++- = ",cvtFromBT("+-++-")) + d := mul(a,sub(b,c)) + write("a(b-c) = ",d," = ",cvtFromBT(d)) +end + +procedure bTrim(s) + return s[upto('+-',s):0] | "0" +end + +procedure cvtToBT(n) + if n=0 then return "0" + if n<0 then return map(cvtToBT(-n),"+-","-+") + return bTrim(case n%3 of { + 0: cvtToBT(n/3)||"0" + 1: cvtToBT(n/3)||"+" + 2: cvtToBT((n+1)/3)||"-" + }) +end + +procedure cvtFromBT(n) + sum := 0 + i := -1 + every c := !reverse(n) do { + sum +:= case c of { + "+" : 1 + "-" : -1 + "0" : 0 + }*(3^(i+:=1)) + } + return sum +end + +procedure neg(n) + return map(n,"+-","-+") +end + +procedure add(a,b) + if *b > *a then a :=: b + b := repl("0",*a-*b)||b + c := "0" + sum := "" + every place := 1 to *a do { + ds := addDigits(a[-place],b[-place],c) + c := if *ds > 1 then c := ds[1] else "0" + sum := ds[-1]||sum + } + return bTrim(c||sum) +end + +procedure addDigits(a,b,c) + sum1 := addDigit(a,b) + sum2 := addDigit(sum1[-1],c) + if *sum1 = 1 then return sum2 + if *sum2 = 1 then return sum1[1]||sum2 + return sum1[1] +end + +procedure addDigit(a,b) + return case(a||b) of { + "00"|"0+"|"0-": b + "+0"|"-0" : a + "++" : "+-" + "+-"|"-+" : "0" + "--" : "-+" + } +end + +procedure sub(a,b) + return add(a,neg(b)) +end + +procedure mul(a,b) + if b[1] == "-" then { + b := neg(b) + negate := "yes" + } + b := cvtFromBT(b) + i := "+" + mul := "0" + while cvtFromBT(i) <= b do { + mul := add(mul,a) + i := add(i,"+") + } + return (\negate,map(mul,"+-","-+")) | mul +end diff --git a/Task/Balanced-ternary/PicoLisp/balanced-ternary.l b/Task/Balanced-ternary/PicoLisp/balanced-ternary.l new file mode 100644 index 0000000000..ead3cf9480 --- /dev/null +++ b/Task/Balanced-ternary/PicoLisp/balanced-ternary.l @@ -0,0 +1,122 @@ +(seed (in "/dev/urandom" (rd 8))) + +(setq *G '((0 -1) (1 -1) (-1 0) (0 0) (1 0) (-1 1) (0 1))) + +# For humans +(de negh (L) + (mapcar + '((I) + (case I + (- '+) + (+ '-) + (T 0) ) ) + L ) ) + +(de trih (X) + (if (num? X) + (let (S (lt0 X) X (abs X) R NIL) + (if (=0 X) + (push 'R 0) + (until (=0 X) + (push 'R + (case (% X 3) + (0 0) + (1 '+) + (2 (inc 'X) '-) ) ) + (setq X (/ X 3)) ) ) + (if S (pack (negh R)) (pack R)) ) + (let M 1 + (sum + '((C) + (prog1 + (unless (= C "0") ((intern C) M)) + (setq M (* 3 M)) ) ) + (flip (chop X)) ) ) ) ) + +# For robots +(de neg (L) + (mapcar + '((I) + (case I (-1 1) (1 -1) (T 0)) ) + L ) ) + +(de tri (X) + (if (num? X) + (let (S (lt0 X) X (abs X) R NIL) + (if (=0 X) + (push 'R 0) + (until (=0 X) + (push 'R + (case (% X 3) + (0 0) + (1 1) + (2 (inc 'X) (- 1)) ) ) + (setq X (/ X 3)) ) ) + (flip (if S (neg R) R)) ) + (let M 1 + (sum + '((C) + (prog1 (* C M) (setq M (* 3 M))) ) + X ) ) ) ) + +(de add (D1 D2) + (let + (L (max (length D1) (length D2)) + D1 (need (- L) D1 0) + D2 (need (- L) D2 0) + C 0 ) + (mapcon + '((L1 L2) + (let R + (get + *G + (+ 4 (+ (car L1) (car L2) C)) ) + (ifn (cdr L1) + R + (setq C (cadr R)) + (cons (car R)) ) ) ) + D1 + D2 ) ) ) + +(de mul (D1 D2) + (ifn (and D1 D2) + 0 + (add + (case (car D1) + (0 0) + (1 D2) + (-1 (neg D2)) ) + (cons 0 (mul (cdr D1) D2) ) ) ) ) + +(de sub (D1 D2) + (add D1 (neg D2)) ) + +# Random testing +(let (X 0 Y 0 C 2048) + (do C + (setq + X (rand (- C) C) + Y (rand (- C) C) ) + (test X (trih (trih X))) + (test X (tri (tri X))) + (test + (+ X Y) + (tri (add (tri X) (tri Y))) ) + (test + (- X Y) + (tri (sub (tri X) (tri Y))) ) + (test + (* X Y) + (tri (mul (tri X) (tri Y))) ) ) ) + +(println 'A (trih 523) (trih "+-0++0+")) +(println 'B (trih -436) (trih "-++-0--")) +(println 'C (trih 65) (trih "+-++-")) +(let R + (tri + (mul + (tri (trih "+-0++0+")) + (sub (tri -436) (tri (trih "+-++-"))) ) ) + (println 'R (trih R) R) ) + +(bye) diff --git a/Task/Best-shuffle/D/best-shuffle-1.d b/Task/Best-shuffle/D/best-shuffle-1.d index 521da02365..170d0d460d 100644 --- a/Task/Best-shuffle/D/best-shuffle-1.d +++ b/Task/Best-shuffle/D/best-shuffle-1.d @@ -1,7 +1,7 @@ import std.stdio, std.random, std.algorithm, std.conv, std.range, std.traits, std.typecons; -auto bestShuffle(S)(in S orig) if (isSomeString!S) { +auto bestShuffle(S)(in S orig) @safe if (isSomeString!S) { static if (isNarrowString!S) immutable o = orig.dtext; else @@ -32,9 +32,9 @@ auto bestShuffle(S)(in S orig) if (isSomeString!S) { assert("".bestShuffle[1] == 0); } -void main(in string[] args) { +void main(in string[] args) @safe { if (args.length > 1) { - immutable entry = args.dropOne.join(" "); + immutable entry = args.dropOne.join(' '); const res = entry.bestShuffle; writefln("%s : %s (%d)", entry, res[]); } diff --git a/Task/Best-shuffle/D/best-shuffle-2.d b/Task/Best-shuffle/D/best-shuffle-2.d index bf7f514b31..c2e0f73174 100644 --- a/Task/Best-shuffle/D/best-shuffle-2.d +++ b/Task/Best-shuffle/D/best-shuffle-2.d @@ -5,7 +5,7 @@ extern(C) pure nothrow void* alloca(in size_t size); void bestShuffle(in char[] txt, ref char[] result) pure nothrow { // Assume alloca to be pure. //extern(C) pure nothrow void* alloca(in size_t size); - enum size_t NCHAR = cast(size_t)char.max + 1; + enum size_t NCHAR = size_t(char.max + 1); enum size_t MAX_VLA_SIZE = 1024; immutable size_t len = txt.length; if (len == 0) @@ -19,7 +19,7 @@ void bestShuffle(in char[] txt, ref char[] result) pure nothrow { // how many of each character? size_t[NCHAR] counts; size_t fmax = 0; - foreach (char c; txt) { + foreach (immutable char c; txt) { counts[c]++; if (fmax < counts[c]) fmax = counts[c]; @@ -38,7 +38,7 @@ void bestShuffle(in char[] txt, ref char[] result) pure nothrow { } { int pos = 0; - foreach (size_t ch; 0 .. NCHAR) + foreach (immutable size_t ch; 0 .. NCHAR) if (counts[ch]) foreach (j, char c; txt) if (c == ch) { @@ -57,7 +57,7 @@ void bestShuffle(in char[] txt, ref char[] result) pure nothrow { } { size_t n, m; - foreach (size_t i; 0 .. len) { + foreach (immutable size_t i; 0 .. len) { ndx2[i] = ndx1[n]; n += fmax; if (n >= len) { @@ -67,27 +67,27 @@ void bestShuffle(in char[] txt, ref char[] result) pure nothrow { } } - // how long can our cyclic groups be? + // How long can our cyclic groups be? immutable size_t grp = 1 + (len - 1) / fmax; - // how many of them are full length? + // How many of them are full length? immutable size_t lng = 1 + (len - 1) % fmax; - // rotate each group + // Rotate each group. { size_t j; - foreach (size_t i; 0 .. fmax) { + foreach (immutable size_t i; 0 .. fmax) { immutable size_t first = ndx2[j]; immutable size_t glen = grp - (i < lng ? 0 : 1); - foreach (size_t k; 1 .. glen) + foreach (immutable size_t k; 1 .. glen) ndx1[j + k - 1] = ndx2[j + k]; ndx1[j + glen - 1] = first; j += glen; } } - // result is original permuted according to our cyclic groups - foreach (size_t i; 0 .. len) + // Result is original permuted according to our cyclic groups. + foreach (immutable size_t i; 0 .. len) result[ndx2[i]] = txt[ndx1[i]]; } @@ -97,7 +97,7 @@ void main() { foreach (txt; data) { auto result = txt.dup; bestShuffle(txt, result); - immutable nEqual = zip(txt, result).count!q{a[0] == a[1]}(); + immutable nEqual = zip(txt, result).count!q{ a[0] == a[1] }; writefln("%s, %s, (%d)", txt, result, nEqual); } } diff --git a/Task/Best-shuffle/Elena/best-shuffle.elena b/Task/Best-shuffle/Elena/best-shuffle.elena index fe4607a0c9..1ccc792cce 100644 --- a/Task/Best-shuffle/Elena/best-shuffle.elena +++ b/Task/Best-shuffle/Elena/best-shuffle.elena @@ -1,24 +1,27 @@ #define system. #define system'routines. +#define extensions. + +// --- shuffle --- #symbol shuffle = (:aLiteral) [ #var aLength := aLiteral length. #var aShuffled := literalControl toArray:aLiteral. - control from:0 &till:aLength &do: i + control forrange &int:0 &int::(aLength-1) &do: (&int:i) [ #var aChar := aLiteral@i. (aChar == (aShuffled@i)) ? [ - control from:0 &till:aLength &do: j + control forrange &int:0 &int::(aLength-1) &do: (&int:j) [ #var anAltChar := aShuffled@j. (anAltChar != aChar)and:[ anAltChar != (aLiteral@i) ]and:[aChar != (aLiteral@j)] ? [ arrayControl exchange:i &with:j &in:aShuffled. - #break nil. + #break. ]. ]. ]. @@ -27,24 +30,27 @@ ^ Summing new:(String new) foreach:aShuffled literal. ]. +// --- ShuffleScore --- + #symbol scoreShuffle = (:anOriginal:aShuffled) [ #var aScore := Integer new. - control from:0 &till:(anOriginal length) &do: i + control forrange &int:0 &int:(anOriginal length - 1) &do: (&int:i) [ (anOriginal @ i) == (aShuffled @ i) ? [ aScore += 1. ]. ]. - ^ aScore number. + ^ aScore value. ]. +// --- Program --- + #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:")". + consoleEx writeLine:"The best shuffle of ":aWord:" is ":aShuffled:"(":(scoreShuffle:aWord:aShuffled):")". ]. console readChar. diff --git a/Task/Best-shuffle/Go/best-shuffle.go b/Task/Best-shuffle/Go/best-shuffle.go index 1126be2d4f..effc83ee5b 100644 --- a/Task/Best-shuffle/Go/best-shuffle.go +++ b/Task/Best-shuffle/Go/best-shuffle.go @@ -17,8 +17,8 @@ func main() { t[i] = s[r] } // algorithm of Icon solution - for i := 0; i < len(s); i++ { - for j := 0; j < len(s); j++ { + for i := range t { + for j := range t { if i != j && t[i] != s[j] && t[j] != s[i] { t[i], t[j] = t[j], t[i] break diff --git a/Task/Best-shuffle/Java/best-shuffle.java b/Task/Best-shuffle/Java/best-shuffle.java index 2195492059..3cdea1b922 100644 --- a/Task/Best-shuffle/Java/best-shuffle.java +++ b/Task/Best-shuffle/Java/best-shuffle.java @@ -1,4 +1,4 @@ -import java.util.*; +import java.util.Random; public class BestShuffle { @@ -10,7 +10,7 @@ public class BestShuffle { public static String bestShuffle(final String s1) { char[] s2 = s1.toCharArray(); - Collections.shuffle(Arrays.asList(s2)); + shuffle(s2); for (int i = 0; i < s2.length; i++) { if (s2[i] != s1.charAt(i)) continue; @@ -26,6 +26,16 @@ public class BestShuffle { return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")"; } + public static void shuffle(char[] text) { + Random rand = new Random(); + for (int i = text.length - 1; i > 0; i--) { + int r = rand.nextInt(i + 1); + char tmp = text[i]; + text[i] = text[r]; + text[r] = tmp; + } + } + private static int count(final String s1, final char[] s2) { int count = 0; for (int i = 0; i < s2.length; i++) diff --git a/Task/Best-shuffle/Python/best-shuffle-2.py b/Task/Best-shuffle/Python/best-shuffle-2.py index f300254142..d54235219d 100644 --- a/Task/Best-shuffle/Python/best-shuffle-2.py +++ b/Task/Best-shuffle/Python/best-shuffle-2.py @@ -25,7 +25,7 @@ def best_shuffle(s): # Add character to list. Remove it from supply. r.append(best) count[best] -= 1 - if count[best] == 0: del count[best] + if count[best] >= 0: del count[best] # If the final letter became stuck (as "ababcd" became "bacabd", # and the final "d" became stuck), then fix it. diff --git a/Task/Best-shuffle/REXX/best-shuffle-2.rexx b/Task/Best-shuffle/REXX/best-shuffle-2.rexx index c39f7425d1..f5ef7adc8a 100644 --- a/Task/Best-shuffle/REXX/best-shuffle-2.rexx +++ b/Task/Best-shuffle/REXX/best-shuffle-2.rexx @@ -3,19 +3,18 @@ def best_shuffle(s) # that we want to fill them. pos = [] # g["a"] = [2, 4] implies that s[2] == s[4] == "a" - g = (0...s.length).group_by { |i| s[i] } + g = s.length.times.group_by { |i| s[i] } # k sorts letters from low to high count - k = g.sort_by { |k, v| v.length }.map! { |k, v| k } + k = g.sort_by { |k, v| v.length }.map { |k, v| k } until g.empty? - k.each { |letter| + k.each do |letter| g[letter] or next pos.push(g[letter].pop) g[letter].empty? and g.delete letter - } + end end - pos.reverse! # Now fill in _new_ with _letters_ according to each position # in _pos_, but skip ahead in _letters_ if we can avoid @@ -23,7 +22,7 @@ def best_shuffle(s) letters = s.dup new = "?" * s.length until letters.empty? - i, p = 0, pos.shift + i, p = 0, pos.pop i += 1 while letters[i] == s[p] and i < (letters.length - 1) new[p] = letters.slice! i end @@ -32,6 +31,6 @@ def best_shuffle(s) [new, score] end -%w(abracadabra seesaw elk grrrrrr up a).each { |word| - printf "%s, %s, (%d)\n", word, *best_shuffle(word) -} +%w(abracadabra seesaw elk grrrrrr up a).each do |word| + puts "%s, %s, (%d)" % [word, *best_shuffle(word)] +end diff --git a/Task/Binary-digits/Aime/binary-digits.aime b/Task/Binary-digits/Aime/binary-digits.aime index 2d43e17b65..67472e18e2 100644 --- a/Task/Binary-digits/Aime/binary-digits.aime +++ b/Task/Binary-digits/Aime/binary-digits.aime @@ -4,5 +4,4 @@ o_xinteger(2, 5); o_byte('\n'); o_xinteger(2, 50); o_byte('\n'); -o_xinteger(2, 9000); -o_byte('\n'); +o_form("/x2/\n", 9000); diff --git a/Task/Binary-digits/C++/binary-digits.cpp b/Task/Binary-digits/C++/binary-digits.cpp index 2932ef8353..659f7df6a8 100644 --- a/Task/Binary-digits/C++/binary-digits.cpp +++ b/Task/Binary-digits/C++/binary-digits.cpp @@ -1,25 +1,22 @@ -#include #include +#include +#include #include -#include -void print_bin(int n) -{ - // convert to binary, then to string - std::string str = std::bitset(n).to_string(); - // trim leading zeroes - if(n == 0) - str = "0"; - else - str = str.substr(str.find('1')); - // output - std::cout << str << '\n'; +void print_bin(unsigned int n) { + std::string str = "0"; + + if (n > 0) { + str = std::bitset::digits>(n).to_string(); + str = str.substr(str.find('1')); // remove leading zeros + } + + std::cout << str << '\n'; } -int main() -{ - print_bin(0); - print_bin(5); - print_bin(50); - print_bin(9000); +int main() { + print_bin(0); + print_bin(5); + print_bin(50); + print_bin(9000); } diff --git a/Task/Binary-digits/D/binary-digits.d b/Task/Binary-digits/D/binary-digits.d index 45dba745d2..7503982bdd 100644 --- a/Task/Binary-digits/D/binary-digits.d +++ b/Task/Binary-digits/D/binary-digits.d @@ -1,6 +1,6 @@ -import std.stdio; - void main() { - foreach (i; 0 .. 16) + import std.stdio; + + foreach (immutable i; 0 .. 16) writefln("%b", i); } diff --git a/Task/Binary-digits/Delphi/binary-digits.delphi b/Task/Binary-digits/Delphi/binary-digits.delphi index 561c069b5e..0c8c72ebb7 100644 --- a/Task/Binary-digits/Delphi/binary-digits.delphi +++ b/Task/Binary-digits/Delphi/binary-digits.delphi @@ -1,4 +1,37 @@ -function IntToBinStr(AInt : integer) : string; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,Regvar,ASMCSE,CSE,PEEPHOLE} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + sysutils; //only for timing + +function IntToBinStrNew(AInt : LongWord):string; +const + IO : array[0..1] of char = ('.','X'); +var + idx,m : LongWord; + pC : pChar; +begin + IF AInt = 0 then Begin + result := IO[0];EXIT;end; + // search for the first set bit + idx:= 32;m := 1 shl (idx-1); + While ORD((AInt AND m) = 0)+ORD(m>0) = 2 do begin + dec(idx);m := m shr 1;end; + + //set right length and insert one by one + setlength(result,idx); + pC := @result[1]; + repeat + pC^ := IO[ORD((AInt and m) <> 0)]; + m := m shr 1; + inc(pC); + until m=0; +end; + +function IntToBinStr(AInt : LongWord) : string; begin Result := ''; repeat @@ -9,7 +42,24 @@ end; procedure Binary_Digits; begin - writeln(' 5: '+IntToBinStr(5)); - writeln(' 50: '+IntToBinStr(50)); + writeln(' 5: ',IntToBinStr(5)); + writeln(' 5: ',IntToBinStrNew(5)); + writeln(' 50: ',IntToBinStr(50)); + writeln(' 50: ',IntToBinStrNew(50)); writeln('9000: '+IntToBinStr(9000)); + writeln('9000: '+IntToBinStrNew(9000)); end; + +var + i: LongInt; + t :TDateTime; +Begin + Binary_Digits; + //speed test + t := time; + For i := 1 to 10*1000*1000 do + IntToBinStrNew(i);t := time-t; Writeln(' New ',t*86400.0:6:3); + t := time; + For i := 1 to 10*1000*1000 do + IntToBinStr(i);t := time-t; Writeln(' Old ',t*86400.0:6:3); +end. diff --git a/Task/Binary-digits/Oberon-2/binary-digits.oberon-2 b/Task/Binary-digits/Oberon-2/binary-digits.oberon-2 new file mode 100644 index 0000000000..ea9c264318 --- /dev/null +++ b/Task/Binary-digits/Oberon-2/binary-digits.oberon-2 @@ -0,0 +1,85 @@ +MODULE BinaryDigits; +IMPORT + Object, + SYSTEM, + Out; + + PROCEDURE Reverse(VAR str: ARRAY OF CHAR); + VAR + s,e: LONGINT; + c: CHAR; + BEGIN + e := LEN(str) - 1; + WHILE (e >= 0) & (str[e] = 0X) DO DEC(e) END; + s := 0; + WHILE (s < e) DO + c := str[s]; + str[s] := str[e]; + str[e] := c; + INC(s);DEC(e) + END + END Reverse; + + + PROCEDURE IntToOct*(x: LONGINT):STRING; + VAR + i: LONGINT; + o: ARRAY 12 OF CHAR; + BEGIN + o[LEN(o) - 1] := 0X; + + i := 0; + WHILE (i < LEN(o) - 1) DO + o[i] := CHR(ORD('0') + (x MOD 8)); + INC(i);x := SYSTEM.LSH(x,-3) + END; + Reverse(o); + RETURN Object.NewLatin1(o) + END IntToOct; + + PROCEDURE IntToHex*(x: LONGINT):STRING; + VAR + i: LONGINT; + h: ARRAY 9 OF CHAR; + hexDigit: LONGINT; + BEGIN + h[LEN(h) - 1] := 0X; + + i := 0; + WHILE (i < LEN(h) - 1) DO + hexDigit := x MOD 16; + IF (hexDigit >= 0) & (hexDigit <= 9) THEN + h[i] := CHR(ORD('0') + hexDigit); + ELSE + h[i] := CHR(ORD('A') + (hexDigit - 10)); + END; + INC(i);x := SYSTEM.LSH(x,-4) + END; + Reverse(h); + RETURN Object.NewLatin1(h) + END IntToHex; + + PROCEDURE IntToBin*(x: LONGINT):STRING; + VAR + i: LONGINT; + b: ARRAY 33 OF CHAR; + BEGIN + b[LEN(b) - 1] := 0X; + i := 0; + WHILE (i < LEN(b) - 1) DO + b[i] := CHR(ORD('0') + (x MOD 2)); + INC(i);x := SYSTEM.LSH(x,-1) + END; + + Reverse(b); + RETURN Object.NewLatin1(b); + END IntToBin; + +BEGIN + + Out.Object("12 :> " + IntToBin(12));Out.Ln; + Out.Object("-12 :> " + IntToBin(-12));Out.Ln; + Out.Object("MAX(LONGINT) :> " + IntToBin(MAX(LONGINT)));Out.Ln; + Out.Object("MIN(LONGINT) :> " + IntToBin(MIN(LONGINT)));Out.Ln; + +END BinaryDigits. diff --git a/Task/Binary-digits/Rust/binary-digits.rust b/Task/Binary-digits/Rust/binary-digits.rust new file mode 100644 index 0000000000..173bd19418 --- /dev/null +++ b/Task/Binary-digits/Rust/binary-digits.rust @@ -0,0 +1,5 @@ +fn main() { + for i in range(0, 16) { + println!("{:t}", i) + } +} diff --git a/Task/Binary-digits/Scala/binary-digits.scala b/Task/Binary-digits/Scala/binary-digits.scala index 8090fc3054..421aee8b26 100644 --- a/Task/Binary-digits/Scala/binary-digits.scala +++ b/Task/Binary-digits/Scala/binary-digits.scala @@ -1,9 +1,8 @@ -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 -} +scala> (5 toBinaryString) +res0: String = 101 + +scala> (50 toBinaryString) +res1: String = 110010 + +scala> (9000 toBinaryString) +res2: String = 10001100101000 diff --git a/Task/Binary-digits/Seed7/binary-digits.seed7 b/Task/Binary-digits/Seed7/binary-digits.seed7 index 8e0d6a8e02..63ff4fff92 100644 --- a/Task/Binary-digits/Seed7/binary-digits.seed7 +++ b/Task/Binary-digits/Seed7/binary-digits.seed7 @@ -5,6 +5,6 @@ const proc: main is func var integer: number is 0; begin for number range 0 to 16 do - writeln(str(number, 2)); + writeln(number radix 2); end for; end func; diff --git a/Task/Binary-digits/Vim-Script/binary-digits.vim b/Task/Binary-digits/Vim-Script/binary-digits.vim new file mode 100644 index 0000000000..b5e27ca7f7 --- /dev/null +++ b/Task/Binary-digits/Vim-Script/binary-digits.vim @@ -0,0 +1,21 @@ +function Num2Bin(n) + let n = a:n + let s = "" + if n == 0 + let s = "0" + else + while n + if n % 2 == 0 + let s = "0" . s + else + let s = "1" . s + endif + let n = n / 2 + endwhile + endif + return s +endfunction + +echo Num2Bin(5) +echo Num2Bin(50) +echo Num2Bin(9000) diff --git a/Task/Binary-search/CoffeeScript/binary-search-1.coffee b/Task/Binary-search/CoffeeScript/binary-search-1.coffee new file mode 100644 index 0000000000..dcd52f077b --- /dev/null +++ b/Task/Binary-search/CoffeeScript/binary-search-1.coffee @@ -0,0 +1,8 @@ +binarySearch = (xs, x) -> + do recurse = (low = 0, high = xs.length - 1) -> + mid = Math.floor (low + high) / 2 + switch + when high < low then NaN + when xs[mid] > x then recurse low, mid - 1 + when xs[mid] < x then recurse mid + 1, high + else mid diff --git a/Task/Binary-search/CoffeeScript/binary-search-2.coffee b/Task/Binary-search/CoffeeScript/binary-search-2.coffee new file mode 100644 index 0000000000..cdcd2a16d4 --- /dev/null +++ b/Task/Binary-search/CoffeeScript/binary-search-2.coffee @@ -0,0 +1,9 @@ +binarySearch = (xs, x) -> + [low, high] = [0, xs.length - 1] + while low <= high + mid = Math.floor (low + high) / 2 + switch + when xs[mid] > x then high = mid - 1 + when xs[mid] < x then low = mid + 1 + else return mid + NaN diff --git a/Task/Binary-search/CoffeeScript/binary-search-3.coffee b/Task/Binary-search/CoffeeScript/binary-search-3.coffee new file mode 100644 index 0000000000..8915681804 --- /dev/null +++ b/Task/Binary-search/CoffeeScript/binary-search-3.coffee @@ -0,0 +1,8 @@ +do (n = 12) -> + odds = (it for it in [1..n] by 2) + result = (it for it in \ + (binarySearch odds, it for it in [0..n]) \ + when not isNaN it) + console.assert "#{result}" is "#{[0...odds.length]}" + console.log "#{odds} are odd natural numbers" + console.log "#{it} is ordinal of #{odds[it]}" for it in result diff --git a/Task/Binary-search/CoffeeScript/binary-search.coffee b/Task/Binary-search/CoffeeScript/binary-search.coffee deleted file mode 100644 index b78af45ce3..0000000000 --- a/Task/Binary-search/CoffeeScript/binary-search.coffee +++ /dev/null @@ -1,16 +0,0 @@ -binsearch = (arr, k) -> - low = 0 - high = arr.length - 1 - while low <= high - mid = Math.floor (low + high) / 2 - return mid if arr[mid] == k - if arr[mid] < k - low = mid + 1 - else - high = mid - 1 - null - -arr = [1,3,5,7,9,11] -for i in [0..12] - pos = binsearch arr, i - console.log "found #{i} at pos #{pos}" if pos? diff --git a/Task/Binary-search/D/binary-search.d b/Task/Binary-search/D/binary-search.d index 1e1425f697..7e1860f65c 100644 --- a/Task/Binary-search/D/binary-search.d +++ b/Task/Binary-search/D/binary-search.d @@ -1,9 +1,8 @@ import std.stdio, std.array, std.range, std.traits; /// Recursive. -bool binarySearch(R, T)(/*in*/ R data, in T x) -pure nothrow if (isRandomAccessRange!R && - is(Unqual!T == Unqual!(ElementType!R))) { +bool binarySearch(R, T)(/*in*/ R data, in T x) pure nothrow @nogc +if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) { if (data.empty) return false; immutable i = data.length / 2; @@ -16,9 +15,8 @@ pure nothrow if (isRandomAccessRange!R && } /// Iterative. -bool binarySearchIt(R, T)(/*in*/ R data, in T x) -pure nothrow if (isRandomAccessRange!R && - is(Unqual!T == Unqual!(ElementType!R))) { +bool binarySearchIt(R, T)(/*in*/ R data, in T x) pure nothrow @nogc +if (isRandomAccessRange!R && is(Unqual!T == Unqual!(ElementType!R))) { while (!data.empty) { immutable i = data.length / 2; immutable mid = data[i]; @@ -34,7 +32,7 @@ pure nothrow if (isRandomAccessRange!R && void main() { /*const*/ auto items = [2, 4, 6, 8, 9].assumeSorted; - foreach (x; [1, 8, 10, 9, 5, 2]) + foreach (const x; [1, 8, 10, 9, 5, 2]) writefln("%2d %5s %5s %5s", x, items.binarySearch(x), items.binarySearchIt(x), diff --git a/Task/Binary-search/Eiffel/binary-search.e b/Task/Binary-search/Eiffel/binary-search.e new file mode 100644 index 0000000000..e326200925 --- /dev/null +++ b/Task/Binary-search/Eiffel/binary-search.e @@ -0,0 +1,120 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + local + a: ARRAY [INTEGER] + keys: ARRAY [INTEGER] + do + a := <<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>> + keys := <<0, 42, 45, 24324, 99999>> + across keys as k loop + if has_binary (a, k.item) then + print ("The array has an element " + k.item.out) + else + print ("The array has NOT an element " + k.item.out) + end + print ("%N") + end + end + +feature -- Search + + has_binary (a: ARRAY [INTEGER]; key: INTEGER): BOOLEAN + -- Does `a[a.lower..a.upper]' include an element `key'? + require + is_sorted (a, a.lower, a.upper) + local + i: INTEGER + do + i := where_binary (a, key) + if a.lower <= i and i <= a.upper then + Result := True + else + Result := False + end + end + + where_binary (a: ARRAY [INTEGER]; key: INTEGER): INTEGER + -- The index of an element `key' within `a[a.lower..a.upper]' if it exists. + -- Otherwise an integer outside `[a.lower..a.upper]' + require + is_sorted (a, a.lower, a.upper) + do + Result := where_binary_range (a, key, a.lower, a.upper) + end + + where_binary_range (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): INTEGER + -- The index of an element `key' within `a[low..high]' if it exists. + -- Otherwise an integer outside `[low..high]' + note + source: "http://arxiv.org/abs/1211.4470" + require + is_sorted (a, low, high) + local + i, j, mid: INTEGER + do + if low > high then + Result := low - 1 + else + from + i := low + j := high + mid := low + Result := low - 1 + invariant + low <= i and i <= mid + 1 + low <= mid and mid <= j and j <= high + i <= j + has (a, key, i, j) = has (a, key, low, high) + until + i >= j + loop + mid := i + (j - i) // 2 + if a [mid] < key then + i := mid + 1 + else + j := mid + end + variant + j - i + end + if a [i] = key then + Result := i + end + end + ensure + low <= Result and Result <= high implies a [Result] = key + Result < low or Result > high implies not has (a, key, low, high) + end + +feature -- Implementation + + is_sorted (a: ARRAY [INTEGER]; low, high: INTEGER): BOOLEAN + -- Is `a[low..high]' sorted in nondecreasing order? + require + a.lower <= low + high <= a.upper + do + Result := across low |..| (high - 1) as i all a [i.item] <= a [i.item + 1] end + end + + has (a: ARRAY [INTEGER]; key: INTEGER; low, high: INTEGER): BOOLEAN + -- Is there an element `key' in `a[low..high]'? + require + a.lower <= low + high <= a.upper + do + Result := across low |..| high as i some a [i.item] = key end + end + +end diff --git a/Task/Binary-search/Julia/binary-search-1.julia b/Task/Binary-search/Julia/binary-search-1.julia index 9b022926a6..23fb98a5b3 100644 --- a/Task/Binary-search/Julia/binary-search-1.julia +++ b/Task/Binary-search/Julia/binary-search-1.julia @@ -8,8 +8,8 @@ function binary_search(l, value) elseif l[mid] < value low = mid+1 else - return l[mid] + return mid end end - return -1 + return -1 end diff --git a/Task/Binary-search/Lua/binary-search-2.lua b/Task/Binary-search/Lua/binary-search-2.lua index 5e57d23c09..fa9c1be045 100644 --- a/Task/Binary-search/Lua/binary-search-2.lua +++ b/Task/Binary-search/Lua/binary-search-2.lua @@ -1,5 +1,6 @@ function binarySearch (list, value) local function search(low, high) + if low > high then return false end local mid = math.floor((low+high)/2) if list[mid] > value then return search(low,mid-1) end if list[mid] < value then return search(mid+1,high) end diff --git a/Task/Binary-search/Prolog/binary-search.pro b/Task/Binary-search/Prolog/binary-search.pro new file mode 100644 index 0000000000..e2b5544262 --- /dev/null +++ b/Task/Binary-search/Prolog/binary-search.pro @@ -0,0 +1,23 @@ +bin_search(Elt,List,Result):- + length(List,N), bin_search_inner(Elt,List,1,N,Result). + +bin_search_inner(Elt,List,J,J,J):- + nth(J,List,Elt). +bin_search_inner(Elt,List,Begin,End,Mid):- + Begin < End, + Mid is (Begin+End) div 2, + nth(Mid,List,Elt). +bin_search_inner(Elt,List,Begin,End,Result):- + Begin < End, + Mid is (Begin+End) div 2, + nth(Mid,List,MidElt), + MidElt < Elt, + NewBegin is Mid+1, + bin_search_inner(Elt,List,NewBegin,End,Result). +bin_search_inner(Elt,List,Begin,End,Result):- + Begin < End, + Mid is (Begin+End) div 2, + nth(Mid,List,MidElt), + MidElt > Elt, + NewEnd is Mid-1, + bin_search_inner(Elt,List,Begin,NewEnd,Result). diff --git a/Task/Binary-search/Scala/binary-search.scala b/Task/Binary-search/Scala/binary-search-1.scala similarity index 100% rename from Task/Binary-search/Scala/binary-search.scala rename to Task/Binary-search/Scala/binary-search-1.scala diff --git a/Task/Binary-search/Scala/binary-search-2.scala b/Task/Binary-search/Scala/binary-search-2.scala new file mode 100644 index 0000000000..feee19e5b8 --- /dev/null +++ b/Task/Binary-search/Scala/binary-search-2.scala @@ -0,0 +1,10 @@ +def binarySearch[A <% Ordered[A]](xs: Seq[A], x: A): Option[Int] = { + var (low, high) = (0, xs.size - 1) + while (low <= high) + (low + high) / 2 match { + case mid if xs(mid) > x => high = mid - 1 + case mid if xs(mid) < x => low = mid + 1 + case mid => return Some(mid) + } + None +} diff --git a/Task/Binary-search/Scala/binary-search-3.scala b/Task/Binary-search/Scala/binary-search-3.scala new file mode 100644 index 0000000000..0bb5d8878a --- /dev/null +++ b/Task/Binary-search/Scala/binary-search-3.scala @@ -0,0 +1,10 @@ +def testBinarySearch(n: Int) = { + val odds = 1 to n by 2 + val result = (0 to n).flatMap(binarySearch(odds, _)) + assert(result == (0 until odds.size)) + println(s"$odds are odd natural numbers") + for (it <- result) + println(s"$it is ordinal of ${odds(it)}") +} + +def main() = testBinarySearch(12) diff --git a/Task/Binary-strings/D/binary-strings.d b/Task/Binary-strings/D/binary-strings.d index 764ec93ff5..d70e4a6fc0 100644 --- a/Task/Binary-strings/D/binary-strings.d +++ b/Task/Binary-strings/D/binary-strings.d @@ -1,45 +1,45 @@ -import std.array: empty; -import std.string: replace; +void main() /*@safe*/ { + import std.array: empty, replace; + import std.string: representation, assumeUTF; -void main() { // String creation (destruction is usually handled by - // the garbage collector) + // the garbage collector). ubyte[] str1; - // String assignments - str1 = cast(ubyte[])"blah"; - // hex string, same as "\x00\xFB\xCD\x32\xFD\x0A" - // whitespace and newlines are ignored + // String assignments. + str1 = "blah".dup.representation; + // Hex string, same as "\x00\xFB\xCD\x32\xFD\x0A" + // whitespace and newlines are ignored. str1 = cast(ubyte[])x"00 FBCD 32FD 0A"; - // String comparison + // String comparison. ubyte[] str2; - if (str1 == str2) {} // strings equal + if (str1 == str2) {} // Strings equal. - // String cloning and copying - str2 = str1.dup; // copy entire string or array + // String cloning and copying. + str2 = str1.dup; // Copy entire string or array. // Check if a string is empty - if (str1.empty) {} // string empty - if (str1.length) {} // string not empty - if (!str1.length) {} // string empty + if (str1.empty) {} // String empty. + if (str1.length) {} // String not empty. + if (!str1.length) {} // String empty. - // Append a ubyte to a string + // Append a ubyte to a string. str1 ~= x"0A"; str1 ~= 'a'; - // Extract a substring from a string - str1 = cast(ubyte[])"blork"; - // this takes off the first and last bytes and - // assigns them to the new ubyte string - // This is just a light slice, no string data copied - ubyte[] substr = str1[1 .. $-1]; + // Extract a substring from a string. + str1 = "blork".dup.representation; + // This takes off the first and last bytes and + // assigns them to the new ubyte string. + // This is just a light slice, no string data copied. + ubyte[] substr = str1[1 .. $ - 1]; // Replace every occurrence of a ubyte (or a string) - // in a string with another string - str1 = cast(ubyte[])"blah"; - replace(cast(char[])str1, "la", "al"); + // in a string with another string. + str1 = "blah".dup.representation; + replace(str1.assumeUTF, "la", "al"); - // Join strings + // Join two strings. ubyte[] str3 = str1 ~ str2; } diff --git a/Task/Bitcoin-address-validation/00DESCRIPTION b/Task/Bitcoin-address-validation/00DESCRIPTION index 45655b00a7..8a2490e412 100644 --- a/Task/Bitcoin-address-validation/00DESCRIPTION +++ b/Task/Bitcoin-address-validation/00DESCRIPTION @@ -1,4 +1,8 @@ -Write a program that takes a [[wp:bitcoin|bitcoin address]] as argument, and checks whether or not this address is valid. +{{omit from|Brlcad}} +{{omit from|GUISS}} + +Write a program that takes a [[wp:bitcoin|bitcoin address]] as argument, +and checks whether or not this address is valid. A bitcoin address uses a base58 encoding, which uses an alphabet of the characters 0 .. 9, A ..Z, a .. z, but without the four characters 0, O, I and l. @@ -17,6 +21,8 @@ Here is an example of a bitcoin address: 1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62i -It does not belong to anyone. It is part of the test suite of the bitcoin software. You can change a few characters in this string and check that it will fail the test. +It does not belong to anyone. +It is part of the test suite of the bitcoin software. +You can change a few characters in this string and check that it will fail the test. ''extra credit'': allow your code to deal with [http://bitcoin.stackexchange.com/questions/3059/what-is-a-compressed-bitcoin-key compressed keys] diff --git a/Task/Bitcoin-address-validation/00META.yaml b/Task/Bitcoin-address-validation/00META.yaml new file mode 100644 index 0000000000..397ec18e01 --- /dev/null +++ b/Task/Bitcoin-address-validation/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Checksums diff --git a/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d b/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d index 0e5d4cccbb..8567110b3e 100644 --- a/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d +++ b/Task/Bitcoin-address-validation/D/bitcoin-address-validation.d @@ -1,26 +1,26 @@ -import std.stdio, std.algorithm, std.array, std.string, sha_256; +import std.stdio, std.algorithm, std.array, std.string, sha_256_2; struct A25 { // Type for a 25 ubyte (not base58 encoded) bitcoin address. ubyte[25] enc; - ubyte bitcoinVersion() const pure nothrow { + ubyte bitcoinVersion() const pure nothrow @safe @nogc { return enc[0]; } - ubyte[4] embeddedChecksum() const pure nothrow { + ubyte[4] embeddedChecksum() return const pure nothrow @safe @nogc { return enc[$ - 4 .. $]; } /** Computes a double sha256 hash of the first 21 bytes of the address. Returns the full 32 ubyte sha256 hash. */ - ubyte[32] doubleSHA256() const pure nothrow { + ubyte[32] doubleSHA256() const pure nothrow @nogc { return SHA256.digest(SHA256.digest(enc[0 .. 21])); } /** Returns a four ubyte checksum computed from the first 21 bytes of the address. */ - ubyte[4] computeChecksum() const pure nothrow { + ubyte[4] computeChecksum() const pure nothrow @nogc { return doubleSHA256[0 .. 4]; } @@ -28,7 +28,7 @@ struct A25 { receiver. Errors are returned if the argument is not valid base58 or if the decoded value does not fit in the 25 ubyte address. The address is not otherwise checked for validity. */ - string set58(in ubyte[] s) pure nothrow { + string set58(in ubyte[] s) pure nothrow @safe @nogc { static immutable digits = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" .representation; @@ -60,7 +60,7 @@ if it can be decoded into a 25 ubyte 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. */ -string isValidA58(in ubyte[] a58) pure nothrow { +string isValidA58(in ubyte[] a58) pure nothrow @nogc { A25 a; immutable err = a.set58(a58); if (!err.empty) diff --git a/Task/Bitcoin-address-validation/Perl-6/bitcoin-address-validation.pl6 b/Task/Bitcoin-address-validation/Perl-6/bitcoin-address-validation.pl6 index 0b08155fe5..7f98d53dfa 100644 --- a/Task/Bitcoin-address-validation/Perl-6/bitcoin-address-validation.pl6 +++ b/Task/Bitcoin-address-validation/Perl-6/bitcoin-address-validation.pl6 @@ -18,7 +18,7 @@ sub unbase58(Str $str) { } sub check-bitcoin-address($addr) { - use Digest; + use Digest::SHA; my @byte = unbase58 $addr; !!! 'wrong checksum' unless @byte[21..24] ~~ sha256(sha256 Buf.new: @byte[0..20]).subbuf(0, 4).list; diff --git a/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl b/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl index 04c790a1c9..80d6da4533 100644 --- a/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl +++ b/Task/Bitcoin-address-validation/Perl/bitcoin-address-validation.pl @@ -8,22 +8,25 @@ my %b58 = map { $b58[$_] => $_ } 0 .. 57; sub unbase58 { use integer; my @out; - for my $c ( map { $b58{$_} } shift =~ /./g ) { + my $azeroes = length($1) if $_[0] =~ /^(1*)/; + for my $c ( map { $b58{$_} } $_[0] =~ /./g ) { for (my $j = 25; $j--; ) { $c += 58 * ($out[$j] // 0); $out[$j] = $c % 256; $c /= 256; } } + my $bzeroes = length($1) if join('', @out) =~ /^(0*)/; + die "not a 25 byte address\n" if $bzeroes != $azeroes; return @out; } sub check_bitcoin_address { - # does nothing if the address is valid + # Does nothing if address is valid # dies otherwise use Digest::SHA qw(sha256); my @byte = unbase58 shift; - die "wrong checksum" unless - join('', map { chr } @byte[21..24]) eq + die "wrong checksum\n" unless + (pack 'C*', @byte[21..24]) eq substr sha256(sha256 pack 'C*', @byte[0..20]), 0, 4; } diff --git a/Task/Bitcoin-address-validation/PicoLisp/bitcoin-address-validation.l b/Task/Bitcoin-address-validation/PicoLisp/bitcoin-address-validation.l new file mode 100644 index 0000000000..c1ba271192 --- /dev/null +++ b/Task/Bitcoin-address-validation/PicoLisp/bitcoin-address-validation.l @@ -0,0 +1,43 @@ +(setq *Alphabet + (chop "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")) + +# if returns NIL then adress is already invalid +(de base58 (Str) + (let N 0 + (for L (chop Str) + (setq N + (+ + (* N 58) + (index L *Alphabet) + -1 ) ) ) + + N ) +) + +(de sha256 (Lst) + (native "libcrypto.so" "SHA256" + '(B . 32) + (cons + NIL + (32) + (native "libcrypto.so" "SHA256" '(B . 32) + (cons NIL (32) Lst) (length Lst) '(NIL (32))) ) + 32 + '(NIL (32)) ) ) + +(de bytes25 (N) + (flip + (make + (do 25 + (link (% N 256)) + (setq N (/ N 256)) ) ) ) ) + +(de valid (Str) + (and + (base58 Str) + (bytes25 @) + (= + (head 4 (sha256 (head 21 @))) + (tail 4 @) ) ) ) + +(bye) diff --git a/Task/Bitcoin-address-validation/Ruby/bitcoin-address-validation.rb b/Task/Bitcoin-address-validation/Ruby/bitcoin-address-validation.rb new file mode 100644 index 0000000000..be48a4a05c --- /dev/null +++ b/Task/Bitcoin-address-validation/Ruby/bitcoin-address-validation.rb @@ -0,0 +1,16 @@ +# Validate Bitcoin address +# +# Nigel_Galloway +# October 13th., 2014 +require 'digest/sha2' +def convert g + i,e = '',[] + (0...g.length/2).each{|n| e[n] = g[n+=n]+g[n+1]; i+='H2'} + e.pack(i) +end +N = [0,1,2,3,4,5,6,7,8,nil,nil,nil,nil,nil,nil,nil,9,10,11,12,13,14,15,16,nil,17,18,19,20,21,nil,22,23,24,25,26,27,28,29,30,31,32,nil,nil,nil,nil,nil,nil,33,34,35,36,37,38,39,40,41,42,43,nil,44,45,46,47,48,49,50,51,52,53,54,55,56,57] +A = '1AGNa15ZQXAZUgFiqJ2i7Z2DPU2J6hW62x' +g = A.bytes.inject(0){|g,n| g*58+N[n-49]}.to_s(16) # A small and interesting piece of code to do the decoding of base58-encoded data. +n = g.slice!(0..-9) +(n.length...42).each{n.insert(0,'0')} +puts "I think the checksum should be #{g}\nI calculate that it is #{Digest::SHA256.hexdigest(Digest::SHA256.digest(convert(n)))[0,8]}" diff --git a/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d b/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d index 8ede076552..5026cafcb4 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d +++ b/Task/Bitmap-B-zier-curves-Cubic/D/bitmap-b-zier-curves-cubic.d @@ -6,7 +6,7 @@ void cubicBezier(size_t nSegments=20, Color) (Image!Color im, in Pt p1, in Pt p2, in Pt p3, in Pt p4, in Color color) -pure nothrow if (nSegments > 0) { +pure nothrow @nogc if (nSegments > 0) { Pt[nSegments + 1] points = void; foreach (immutable i, ref p; points) { diff --git a/Task/Bitmap-B-zier-curves-Cubic/XPL0/bitmap-b-zier-curves-cubic.xpl0 b/Task/Bitmap-B-zier-curves-Cubic/XPL0/bitmap-b-zier-curves-cubic.xpl0 index 4e09b21807..6d6902281c 100644 --- a/Task/Bitmap-B-zier-curves-Cubic/XPL0/bitmap-b-zier-curves-cubic.xpl0 +++ b/Task/Bitmap-B-zier-curves-Cubic/XPL0/bitmap-b-zier-curves-cubic.xpl0 @@ -1,22 +1,24 @@ include c:\cxpl\codes; \intrinsic 'code' declarations -func real Power(X, Y); \X raised to the Y power; (X > 0.0) -real X, Y; -return Exp(Y * Ln(X)); proc Bezier(P0, P1, P2, P3); \Draw cubic Bezier curve real P0, P1, P2, P3; def Segments = 8; int I; -real T, A, B, C, D, X, Y; +real S1, T, T2, T3, U, U2, U3, B, C, X, Y; [Move(fix(P0(0)), fix(P0(1))); +S1:= 1./float(Segments); +T:= 0.; for I:= 1 to Segments-1 do - [T:= float(I)/float(Segments); - A:= Power((1.-T), 3.); - B:= 3.*T*Power((1.-T), 2.); - C:= 3.*Power(T, 2.)*(1.-T); - D:= Power(T, 3.); - X:= A*P0(0) + B*P1(0) + C*P2(0) + D*P3(0); - Y:= A*P0(1) + B*P1(1) + C*P2(1) + D*P3(1); + [T:= T+S1; + T2:= T*T; + T3:= T2*T; + U:= 1.-T; + U2:= U*U; + U3:= U2*U; + B:= 3.*T*U2; + C:= 3.*T2*U; + X:= U3*P0(0) + B*P1(0) + C*P2(0) + T3*P3(0); + Y:= U3*P0(1) + B*P1(1) + C*P2(1) + T3*P3(1); Line(fix(X), fix(Y), $00FFFF); \cyan line segments ]; Line(fix(P3(0)), fix(P3(1)), $00FFFF); diff --git a/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d b/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d index a587bffe45..39483747d3 100644 --- a/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d +++ b/Task/Bitmap-B-zier-curves-Quadratic/D/bitmap-b-zier-curves-quadratic.d @@ -5,7 +5,7 @@ struct Pt { int x, y; } // Signed. void quadraticBezier(size_t nSegments=20, Color) (Image!Color im, in Pt p1, in Pt p2, in Pt p3, in Color color) -pure nothrow if (nSegments > 0) { +pure nothrow @nogc if (nSegments > 0) { Pt[nSegments + 1] points = void; foreach (immutable i, ref p; points) { diff --git a/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION b/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION index 9d3236572d..53a14ef3a8 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION +++ b/Task/Bitmap-Bresenhams-line-algorithm/00DESCRIPTION @@ -1 +1 @@ -Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster graphics images, draw a line given 2 points with the [[wp:Bresenham's_line_algorithm|Bresenham's algorithm]]. +Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster graphics images, draw a line given 2 points with the [[wp:Bresenham's line algorithm|Bresenham's line algorithm]]. diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Batch-File/bitmap-bresenhams-line-algorithm.bat b/Task/Bitmap-Bresenhams-line-algorithm/Batch-File/bitmap-bresenhams-line-algorithm.bat new file mode 100644 index 0000000000..b0ac5f1e04 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Batch-File/bitmap-bresenhams-line-algorithm.bat @@ -0,0 +1,128 @@ +@echo off +setlocal enabledelayedexpansion + +set width=87 +set height=51 + +mode %width%,%height% + +set "grid=" +set /a resolution=height*width +for /l %%i in (1,1,%resolution%) do ( + set "grid=!grid! " +) +call :line 1 1 5 5 +call :line 9 30 60 7 +call :line 9 30 60 50 +call :line 52 50 32 1 +echo:%grid% +pause>nul +exit + +:line + set x1=%1 + set y1=%2 + set x2=%3 + set y2=%4 + + set /a dx=x2-x1 + set /a dy=y2-y1 + + ::Clipping done to avoid overflow + + if %dx% neq 0 set /a o=y1 - ( x1 * dy / dx ) + if %x1% leq %x2% ( + if %x1% geq %width% goto :eof + if %x2% lss 0 goto :eof + + if %x1% lss 0 ( + if %dx% neq 0 set y1=%o% + set x1=0 + ) + if %x2% geq %width% ( + set /a x2= width - 1 + if %dx% neq 0 set /a "y2= x2 * dy / dx + o" + ) + ) else ( + if %x2% geq %width% goto :eof + if %x1% lss 0 goto :eof + + if %x2% lss 0 ( + if %dx% neq 0 set y2=%o% + set x2=0 + ) + if %x1% geq %width% ( + set /a x1=width - 1 + if %dx% neq 0 set /a "y1= x1 * dy / dx + o" + ) + ) + if %y1% leq %y2% ( + if %y1% geq %height% goto :eof + if %y2% lss 0 goto :eof + + if %y1% lss 0 ( + set y1=0 + if %dx% neq 0 set /a x1= - o * dx /dy + ) + if %y2% geq %height% ( + set /a y2=height-1 + if %dx% neq 0 set /a "x2= (y2 - o) * dx /dy" + ) + ) else ( + if %y2% geq %height% goto :eof + if %y1% lss 0 goto :eof + + if %y2% lss 0 ( + set y2=0 + if %dx% neq 0 set /a "x2= - o * dx /dy" + ) + if %y1% geq %height% ( + set /a y1=height-1 + if %dx% neq 0 set /a "x1= (y1 - o) * dx /dy" + ) + ) + + :: Start of Bresenham's algorithm + + set stepy=1 + set stepx=1 + + set /a dx=x2-x1 + set /a dy=y2-y1 + + if %dy% lss 0 set /a "dy=-dy","stepy=-1" + if %dx% lss 0 set /a "dx=-dx","stepx=-1" + + set /a "dy <<= 1" + set /a "dx <<= 1" + + if %dx% gtr %dy% ( + set /a "fraction=dy-(dx>>1)" + set /a "cursor=y1*width + x1" + for /l %%x in (%x1%,%stepx%,%x2%) do ( + set /a cursorP=cursor+1 + for /f "tokens=1-2" %%g in ("!cursor! !cursorP!") do set "grid=!grid:~0,%%g!Û!grid:~%%h!" + if !fraction! geq 0 ( + set /a y1+=stepy + set /a cursor+=stepy*width + set /a fraction-=dx + ) + set /a fraction+=dy + set /a cursor+=stepx + ) + ) else ( + set /a "fraction=dx-(dy>>1)" + set /a "cursor=y1*width + x1" + for /l %%y in (%y1%,%stepy%,%y2%) do ( + set /a cursorP=cursor+1 + for /f "tokens=1-2" %%g in ("!cursor! !cursorP!") do set "grid=!grid:~0,%%g!Û!grid:~%%h!" + if !fraction! geq 0 ( + set /a x1+=stepx + set /a cursor+=stepx + set /a fraction-=dy + ) + set /a fraction+=dx + set /a cursor+=width*stepy + ) + ) + goto :eof diff --git a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp index b47e43dd1e..6b003863c6 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp +++ b/Task/Bitmap-Bresenhams-line-algorithm/C++/bitmap-bresenhams-line-algorithm.cpp @@ -26,19 +26,19 @@ void Line( const float x1, const float y1, const float x2, const float y2, const for(int x=(int)x1; x dist-y dist-x)] (let [[x1 y1 x2 y2] (if steep [y1 x1 y2 x2] [x1 y1 x2 y2])] (let [[x1 y1 x2 y2] (if (> x1 x2) [x2 y2 x1 y1] [x1 y1 x2 y2])] (let [delta-x (- x2 x1) - delta-y (abs (- y1 y2)) + delta-y (Math/abs (- y1 y2)) y-step (if (< y1 y2) 1 -1)] (let [plot (if steep #(.setRGB buffer (int %1) (int %2) pixel) #(.setRGB buffer (int %2) (int %1) pixel))] - (loop [x x1 y y1 error (floor delta-x 2) ] + (loop [x x1 y y1 error (Math/floor (/ delta-x 2)) ] (plot x y) (if (< x x2) ; Rather then rebind error, test that it is less than delta-y rather than zero diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp b/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp index 200d7b7c46..1151b407a8 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp +++ b/Task/Bitmap-Bresenhams-line-algorithm/Common-Lisp/bitmap-bresenhams-line-algorithm.lisp @@ -3,26 +3,26 @@ (declare (type integer x1 y1 x2 y2)) (declare (type rgb-pixel pixel)) (let* ((dist-x (abs (- x1 x2))) - (dist-y (abs (- y1 y2))) - (steep (> dist-y dist-x))) + (dist-y (abs (- y1 y2))) + (steep (> dist-y dist-x))) (when steep (psetf x1 y1 y1 x1 - x2 y2 y2 x2)) + x2 y2 y2 x2)) (when (> x1 x2) (psetf x1 x2 x2 x1 - y1 y2 y2 y1)) + y1 y2 y2 y1)) (let* ((delta-x (- x2 x1)) - (delta-y (abs (- y1 y2))) - (error (floor delta-x 2)) - (y-step (if (< y1 y2) 1 -1)) - (y y1)) + (delta-y (abs (- y1 y2))) + (error (floor delta-x 2)) + (y-step (if (< y1 y2) 1 -1)) + (y y1)) (loop - :for x :upfrom x1 :to x2 - :do (progn (if steep - (setf (rgb-pixel buffer x y) pixel) - (setf (rgb-pixel buffer y x) pixel)) - (setf error (- error delta-y)) - (when (< error 0) - (incf y y-step) - (incf error delta-x))))) + :for x :upfrom x1 :to x2 + :do (if steep + (setf (rgb-pixel buffer x y) pixel) + (setf (rgb-pixel buffer y x) pixel)) + (setf error (- error delta-y)) + (when (< error 0) + (incf y y-step) + (incf error delta-x)))) buffer)) diff --git a/Task/Bitmap-Bresenhams-line-algorithm/D/bitmap-bresenhams-line-algorithm.d b/Task/Bitmap-Bresenhams-line-algorithm/D/bitmap-bresenhams-line-algorithm.d index 9b9fa72ff3..c7ec0b4e06 100644 --- a/Task/Bitmap-Bresenhams-line-algorithm/D/bitmap-bresenhams-line-algorithm.d +++ b/Task/Bitmap-Bresenhams-line-algorithm/D/bitmap-bresenhams-line-algorithm.d @@ -6,7 +6,7 @@ void drawLine(Color)(Image!Color img, size_t x1, size_t y1, in size_t x2, in size_t y2, in Color color) -pure nothrow { +pure nothrow @nogc { immutable int dx = x2 - x1; immutable int ix = (dx > 0) - (dx < 0); immutable size_t dx2 = abs(dx) * 2; diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi b/Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi new file mode 100644 index 0000000000..ac069eba49 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Delphi/bitmap-bresenhams-line-algorithm.delphi @@ -0,0 +1,72 @@ +procedure drawLine (bitmap : TBitmap; xStart, yStart, xEnd, yEnd : integer; color : TAlphaColor); +// Bresenham's Line Algorithm. Byte, March 1988, pp. 249-253. +// Modified from http://www.efg2.com/Lab/Library/Delphi/Graphics/Bresenham.txt and tested. +var + a, b : integer; // displacements in x and y + d : integer; // decision variable + diag_inc : integer; // d's increment for diagonal steps + dx_diag : integer; // diagonal x step for next pixel + dx_nondiag : integer; // nondiagonal x step for next pixel + dy_diag : integer; // diagonal y step for next pixel + dy_nondiag : integer; // nondiagonal y step for next pixel + i : integer; // loop index + nondiag_inc: integer; // d's increment for nondiagonal steps + swap : integer; // temporary variable for swap + x,y : integer; // current x and y coordinates +begin + x := xStart; // line starting point} + y := yStart; + // Determine drawing direction and step to the next pixel. + a := xEnd - xStart; // difference in x dimension + b := yEnd - yStart; // difference in y dimension + // Determine whether end point lies to right or left of start point. + if a < 0 then // drawing towards smaller x values? + begin + a := -a; // make 'a' positive + dx_diag := -1 + end + else + dx_diag := 1; + + // Determine whether end point lies above or below start point. + if b < 0 then // drawing towards smaller x values? + begin + b := -b; // make 'a' positive + dy_diag := -1 + end + else + dy_diag := 1; + // Identify octant containing end point. + if a < b then + begin + swap := a; + a := b; + b := swap; + dx_nondiag := 0; + dy_nondiag := dy_diag + end + else + begin + dx_nondiag := dx_diag; + dy_nondiag := 0 + end; + d := b + b - a; // initial value for d is 2*b - a + nondiag_inc := b + b; // set initial d increment values + diag_inc := b + b - a - a; + for i := 0 to a do + begin /// draw the a+1 pixels + drawPixel (bitmap, x, y, color); + if d < 0 then // is midpoint above the line? + begin // step nondiagonally + x := x + dx_nondiag; + y := y + dy_nondiag; + d := d + nondiag_inc // update decision variable + end + else + begin // midpoint is above the line; step diagonally} + x := x + dx_diag; + y := y + dy_diag; + d := d + diag_inc + end; + end; +end; diff --git a/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java b/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java new file mode 100644 index 0000000000..2f972c0178 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/Java/bitmap-bresenhams-line-algorithm.java @@ -0,0 +1,93 @@ +import java.awt.*; +import javax.swing.*; + +public class Bresenham extends JFrame { + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JFrame f = new Bresenham(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setVisible(true); + f.add(new BresenhamPanel(), BorderLayout.CENTER); + f.setTitle("Bresenham"); + f.setResizable(false); + f.pack(); + f.setLocationRelativeTo(null); + } + }); + } +} + +class BresenhamPanel extends JPanel { + final int centerX, centerY; + + public BresenhamPanel() { + int w = 600; + int h = 500; + centerX = w / 2; + centerY = h / 2; + setPreferredSize(new Dimension(w, h)); + setBackground(Color.white); + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + + drawLine(g, 0, 0, 8, 19); // NNE + drawLine(g, 0, 0, 19, 8); // ENE + drawLine(g, 0, 0, 19, -8); // ESE + drawLine(g, 0, 0, 8, -19); // SSE + drawLine(g, 0, 0, -8, -19); // SSW + drawLine(g, 0, 0, -19, -8); // WSW + drawLine(g, 0, 0, -19, 8); // WNW + drawLine(g, 0, 0, -8, 19); // NNW + } + + private void plot(Graphics g, int x, int y) { + g.setColor(Color.black); + g.drawOval(centerX + (x * 10), centerY + (-y * 10), 10, 10); + } + + private void drawLine(Graphics g, int x1, int y1, int x2, int y2) { + // delta of exact value and rounded value of the dependant variable + int d = 0; + + int dy = Math.abs(y2 - y1); + int dx = Math.abs(x2 - x1); + + int dy2 = (dy << 1); // slope scaling factors to avoid floating + int dx2 = (dx << 1); // point + + int ix = x1 < x2 ? 1 : -1; // increment direction + int iy = y1 < y2 ? 1 : -1; + + if (dy <= dx) { + for (;;) { + plot(g, x1, y1); + if (x1 == x2) + break; + x1 += ix; + d += dy2; + if (d > dx) { + y1 += iy; + d -= dx2; + } + } + } else { + for (;;) { + plot(g, x1, y1); + if (y1 == y2) + break; + y1 += iy; + d += dx2; + if (d > dy) { + x1 += ix; + d -= dy2; + } + } + } + } +} diff --git a/Task/Bitmap-Bresenhams-line-algorithm/PL-I/bitmap-bresenhams-line-algorithm-3.pli b/Task/Bitmap-Bresenhams-line-algorithm/PL-I/bitmap-bresenhams-line-algorithm-3.pli new file mode 100644 index 0000000000..f2fa69252d --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/PL-I/bitmap-bresenhams-line-algorithm-3.pli @@ -0,0 +1,51 @@ +*process source xref or(!); + brbn:Proc Options(main); + /********************************************************************* + * 21.05.2014 Walter Pachl + * Implementing the pseudo code of + * http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm + * under 'Simplification' (see also REXX version 2) + *********************************************************************/ +grid.= + dcl image(-2:7,-4:11) char(1); + image='.'; + image(*,0)='-'; + image(0,*)='|'; + image(0,0)='+'; + call draw_line(-1,-3,6,10); + Dcl (i,j) Bin Fixed(31); + Do j=11 To -4 By -1; + Put Edit(j,' ')(Skip,f(2),a); + Do i=-2 To 7; + Put Edit(image(i,j))(a); + End; + End; + Put Edit(' 2101234567')(Skip,a); + + draw_line: procedure (x0,y0,x1,y1); + dcl (x0,y0,x1,y1) fixed binary(31); + dcl (dx,dy,sx,sy,err,e2) fixed binary(31); + + dx = abs(x1-x0); + dy = abs(y1-y0); + if x0 < x1 then sx = 1; + else sx = -1; + if y0 < y1 then sy = 1; + else sy = -1; + err = dx-dy; + + Do Until(x0=x1&y0=y1); + image(x0,y0)='X'; + e2=err*2; + if e2>-dy then do; + err=err-dy; + x0=x0+sx; + End; + if e20->%If the difference is greater than one, add Y one to Y. + Y1 is Y+Sy, + send(Pict,pixel(X,Y1,colour(black))), + C2 is C+(2*DY-2*DX); + Y1 is Y, + send(Pict,pixel(X,Y,colour(black))), + C2 is C+(2*DY)), + X0 is X+Sx,%The next iteration + draw_recursive_line(Pict,X0,X2,DX,DY,Y1,Y2,C2,Sx,Sy). +isneg(X,O):- + ( X<0-> + + O is -1; + ( X\==0-> + O is 1; + O is 0)). + +draw_line(Pict,X1,Y1,X2,Y2):- + DY is abs(Y2-Y1), + DX is abs(X2-X1), + isneg(DX,Sx), + isneg(DY,Sy), + D = 2*DY-DX,%The slope of the line + draw_recursive_line(Pict,X1,X2,DX,DY,Y1,Y2,D,Sx,Sy). diff --git a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx new file mode 100644 index 0000000000..a665e53ed3 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-1.rexx @@ -0,0 +1,43 @@ +/*REXX program plots/draws line(s) using the Bresenham's line algorithm.*/ +@.='·' /*fill the array with middle─dots*/ +parse arg data /*allow data point specifications*/ +if data='' then data= '(1,8) (8,16) (16,8) (8,1) (1,8)' /*rhombus*/ +data=translate(data,,'()[]{}/,:;') /*elide chaff from data points. */ + /* [↓] data pt pairs ──► !.array.*/ + do points=1 while data\='' /*put data points into an array. */ + parse var data x y data; !.points=x y /*extract line segments.*/ + if points==1 then do; minX=x; maxX=x; minY=y; maxY=y; end /*1st case*/ + minX=min(minX,x); maxX=max(maxX,x); minY=min(minY,y); maxY=max(maxY,y) + end /*points*/ /* [↑] data points pairs in !. */ + +border=2 /*border=extra space around plot.*/ +minX=minX-border*2; maxX=maxX+border*2 /*min,max X for the plot display.*/ +minY=minY-border ; maxY=maxY+border /* " " Y " " " " */ + do x=minX to maxX; @.x.0='─'; end /*draw dash from left──► right.*/ + do y=minY to maxY; @.0.y='│'; end /*draw pipe from lowest──►highest*/ +@.0.0='┼' /*define the plot's axis point. */ + do seg=2 to points-1; _=seg-1 /*obtain the X,Y line coördinates*/ + call draw_line !._, !.seg /*draw (plot) a line segment. */ + end /*seg*/ /* [↑] drawing the line segments*/ + /* [↓] display the plot to term.*/ + do y=maxY to minY by -1; _= /*display plot one line at a time*/ + do x=minX to maxX /*traipse throught the X axis. */ + _=_ || @.x.y /*construct a "line" of the plot.*/ + end /*x*/ /*(a line is a "row" of points.) */ + say _ /*display a "line" of the plot. */ + end /*y*/ /* [↑] all done ploting the pts.*/ +exit /*stick a fork in it, we're done.*/ +/*────────────────────────────────DRAW_LINE subroutine──────────────────*/ +draw_line: procedure expose @.; parse arg x y,xf yf; plotChar='Θ' +dx=abs(xf-x); if x -dy then do; err=err-dy; x=x+sx; end + if err2 < dx then do; err=err+dx; y=y+sy; end + end /*forever*/ +return diff --git a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-2.rexx b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-2.rexx new file mode 100644 index 0000000000..6d5ed5d849 --- /dev/null +++ b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm-2.rexx @@ -0,0 +1,44 @@ +/* REXX *************************************************************** +* 21.05.2014 Walter Pachl +* Implementing the pseudo code of +* http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm +* under 'Simplification' +**********************************************************************/ +grid.='.' +Do i=-2 To 7; grid.i.0='-'; End +Do j=-4 To 11; grid.0.j='|'; End +grid.0.0='+' +Call line -1,-3,6,10 +Do j=11 To -4 By -1 + ol=format(j,2)' ' + Do i=-2 To 7 + ol=ol||grid.i.j + End + Say ol + End +Say ' 2101234567' +Exit +line: Procedure Expose grid. +Parse Arg x0, y0, x1, y1 +dx = abs(x1-x0) +dy = abs(y1-y0) +if x0 < x1 then sx = 1 + else sx = -1 +if y0 < y1 then sy = 1 + else sy = -1 +err = dx-dy + +Do Forever + grid.x0.y0='X' + if x0 = x1 & y0 = y1 Then Leave + e2 = 2*err + if e2 > -dy then do + err = err - dy + x0 = x0 + sx + end + if e2 < dx then do + err = err + dx + y0 = y0 + sy + end + end +Return diff --git a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm.rexx b/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm.rexx deleted file mode 100644 index 82bd2e10e4..0000000000 --- a/Task/Bitmap-Bresenhams-line-algorithm/REXX/bitmap-bresenhams-line-algorithm.rexx +++ /dev/null @@ -1,64 +0,0 @@ -/*REXX program plots/draws a line using the Bresenham's line algorithm. */ - -EoE = 1000 /*EOE = End Of Earth, er, plot. */ -image. = 'fa'x /*fill the array with middle-dots*/ -plotC = 'fe'x /*character used for plotting pts*/ - do j=-EoE to +EoE /*draw grid from lowest──>highest*/ - image.j.0 = '─' /*draw the horizontal axis. */ - image.0.j = '│' /* " " verical " */ - end /*j*/ -image.0.0='┼' /*"draw" the axis origin. */ -parse arg xi yi xf yf . /*allow specifying line-end pts. */ -if xi=='' | xi==',' then xi = -1 /*if not specified, use default. */ -if yi=='' | yi==',' then yi = -3 /* " " " " " */ -if xf=='' | xf==',' then xf = 6 /* " " " " " */ -if yf=='' | yf==',' then yf = 10 /* " " " " " */ -call draw_line xi, yi, xf, yf /*call subroutine and draw line. */ -call findMaxXY - do y=maxY by -1 to minY; aRow= - do x=minX to maxX - aRow=aRow || image.x.y - end /*x*/ - say aRow - end /*y*/ -exit -/*────────────────────────────────DRAW_LINE subroutine──────────────────*/ -draw_line: procedure expose image. plotC; error=0 -parse arg xi 1 x0, yi 1 y0 1 y, xf 1 x1, yf 1 y1 -steep= abs(y1-y0) > abs(x1-x0) -if steep then parse value x0 y0 x1 y1 with y0 x0 y1 x1 -if x0>x1 then parse value x0 x1 y0 y1 with x1 x0 y1 y0 - - if y0=.5 then do; y=y+yInc; error=error-1; end - end -return -/*────────────────────────────────FINDMAXXY subroutine──────────────────*/ -findMaxXY: extra=3 /*don't just show cropped plot. */ - do minX=-EoE to +EoE /*find min X in the plot field. */ - do y=-EoE to +EoE; if .isP(image.minX.y) then leave minX; end /*y*/ - end /*minX*/ - - do maxX=+EoE to -EoE by -1 /*find max X in the plot field. */ - do y=-EoE to +EoE; if .isP(image.maxX.y) then leave maxX; end /*y*/ - end /*maxX*/ - - do minY=-EoE to +EoE /*find min Y in the plot field. */ - do x=-EoE to +EoE; if .isP(image.x.minY) then leave minY; end /*x*/ - end /*minY*/ - - do maxY=+EoE to -EoE by -1 /*find max Y in the plot field. */ - do x=-EoE to +EoE; if .isP(image.X.maxy) then leave maxY; end /*x*/ - end /*maxY*/ - -minX=minX-extra*2; minY=minY-extra /*like showbiz, show a little more*/ -maxX=maxX+extra*2; maxY=maxY+extra /* " " " " " " */ -return /*go ye forth and show ye plot. */ -.isP: return pos(arg(1),plotC)\==0 diff --git a/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d b/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d index 91bd7568ed..e9e97f62f8 100644 --- a/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d +++ b/Task/Bitmap-Flood-fill/D/bitmap-flood-fill.d @@ -2,7 +2,7 @@ import std.array, bitmap; void floodFill(Color)(Image!Color img, in uint x, in uint y, in Color color) -pure nothrow in { +/*pure*/ nothrow in { assert (y < img.ny && x < img.nx); } body { immutable target = img[x, y]; @@ -22,7 +22,8 @@ pure nothrow in { } void main() { - auto img = loadPPM6(null, "unfilled_circ.ppm"); + Image!RGB img; + loadPPM6(img, "unfilled_circ.ppm"); img.floodFill(200, 200, RGB(127, 0, 0)); img.savePPM6("unfilled_circ_flooded.ppm"); } diff --git a/Task/Bitmap-Flood-fill/Scala/bitmap-flood-fill.scala b/Task/Bitmap-Flood-fill/Scala/bitmap-flood-fill.scala new file mode 100644 index 0000000000..b4a613e084 --- /dev/null +++ b/Task/Bitmap-Flood-fill/Scala/bitmap-flood-fill.scala @@ -0,0 +1,43 @@ +import java.awt.Color +import scala.collection.mutable + +object Flood { + def floodFillStack(bm:RgbBitmap, x: Int, y: Int, targetColor: Color): Unit = { + // validate + if (bm.getPixel(x,y) == targetColor) return + + // vars + val oldColor = bm.getPixel(x,y) + val pixels = new mutable.Stack[(Int,Int)] + + // candy coating methods + def paint(fx: Int, fy:Int) = bm.setPixel(fx,fy,targetColor) + def old(cx: Int, cy: Int): Boolean = bm.getPixel(cx,cy) == oldColor + def push(px: Int, py: Int) = pixels.push((px,py)) + + // starting point + push(x,y) + + // work + while (pixels.nonEmpty) { + val (x, y) = pixels.pop() + var y1 = y + while (y1 >= 0 && old(x, y1)) y1 -= 1 + y1 += 1 + var spanLeft = false + var spanRight = false + while (y1 < bm.height && old(x, y1)) { + paint(x,y1) + if (x > 0 && spanLeft != old(x-1,y1)) { + if (old(x - 1, y1)) push(x - 1, y1) + spanLeft = !spanLeft + } + if (x < bm.width - 1 && spanRight != old(x+1,y1)) { + if (old(x + 1, y1)) push(x + 1, y1) + spanRight = !spanRight + } + y1 += 1 + } + } + } +} diff --git a/Task/Bitmap-Flood-fill/Standard-ML/bitmap-flood-fill.ml b/Task/Bitmap-Flood-fill/Standard-ML/bitmap-flood-fill.ml new file mode 100644 index 0000000000..cef4d6a45d --- /dev/null +++ b/Task/Bitmap-Flood-fill/Standard-ML/bitmap-flood-fill.ml @@ -0,0 +1,49 @@ +(* For simplicity, we're going to fill black-and-white images. Nothing + * fundamental would change if we used more colors. *) +datatype color = Black | White +(* Represent an image as a 2D mutable array of pixels, since flood-fill + * is naturally an imperative algorithm. *) +type image = color array array + +(* Helper functions to construct images for testing. Map 0 -> White + * and 1 -> Black so we can write images concisely as lists. *) +fun intToColor 0 = White + | intToColor _ = Black + +fun listToImage (LL : int list list) : image = + Array.tabulate(List.length LL, + fn i => Array.tabulate (List.length (hd LL), + fn j => intToColor(List.nth(List.nth(LL,i),j)))) + +(* Is the given pixel within the image ? *) +fun inBounds (img : image) ((x,y) : int * int) : bool = + x >= 0 andalso y >= 0 andalso y < Array.length img + andalso x < Array.length (Array.sub(img, y)) + +(* Return an option containing the neighbors we should explore next, if any.*) +fun neighbors (img : image) (c : color) ((x,y) : int * int) : (int * int) list option = + if inBounds img (x,y) andalso Array.sub(Array.sub(img,y),x) <> c + then SOME [(x-1,y),(x+1,y),(x,y-1),(x,y+1)] + else NONE + +(* Update the given pixel of the image. *) +fun setPixel (img : image) ((x,y) : int * int) (c : color) : unit = + Array.update (Array.sub(img,y),x,c) + +(* Recursive fill around the given point using the given color. *) +fun fill (img : image) (c : color) ((x,y) : int * int) : unit = + case neighbors img c (x,y) of + SOME xys => (setPixel img (x,y) c; List.app (fill img c) xys) + | NONE => () + +val test = listToImage +[[0,0,1,1,0,1,0], + [1,0,1,0,1,0,0], + [1,0,0,0,0,0,1], + [0,1,0,0,0,1,0], + [1,0,0,0,0,0,1], + [0,0,1,1,1,0,0], + [0,1,0,0,0,1,0]] + +(* Fill the image with black starting at the center. *) +val () = fill test Black (3,3) diff --git a/Task/Bitmap-Histogram/D/bitmap-histogram.d b/Task/Bitmap-Histogram/D/bitmap-histogram.d index c1a5a1fe5e..9640ca91fb 100644 --- a/Task/Bitmap-Histogram/D/bitmap-histogram.d +++ b/Task/Bitmap-Histogram/D/bitmap-histogram.d @@ -1,7 +1,7 @@ import grayscale_image; Color findSingleChannelMedian(Color)(in Image!Color img) -nothrow if (Color.tupleof.length == 1) // Hack. +pure nothrow @nogc if (Color.tupleof.length == 1) // Hack. in { assert(img !is null); } body { @@ -30,7 +30,7 @@ in { Image!Color binarizeInPlace(Color)(Image!Color img, in Color thresh) -nothrow in { +pure nothrow @nogc in { assert(img !is null); } body { foreach (immutable i, ref c; img.image) diff --git a/Task/Bitmap-Histogram/Racket/bitmap-histogram.rkt b/Task/Bitmap-Histogram/Racket/bitmap-histogram.rkt new file mode 100644 index 0000000000..7dcbb99857 --- /dev/null +++ b/Task/Bitmap-Histogram/Racket/bitmap-histogram.rkt @@ -0,0 +1,62 @@ + #lang racket +(require racket/draw math/statistics racket/require + (filtered-in + (lambda (name) (regexp-replace #rx"unsafe-" name "")) + racket/unsafe/ops)) + +;; CIE formula as discussed in "Greyscale image" task +(define (L r g b) + ;; In fact there is no need, statistically for L to be divided by 10000 + (fx+ (fx* r 2126) (fx+ (fx* g 7152) (fx* b 722)))) + +(define (prepare-bytes bm depth load-content?) + (define w (send bm get-width)) + (define h (send bm get-height)) + (define rv (make-bytes (* w h depth))) + (define just-alpha? #f) + (define pre-multiply? #t); let racket cope with alpha-ness + (when load-content? (send bm get-argb-pixels 0 0 w h rv just-alpha? pre-multiply?)) + rv) + +(define (bitmap-histogram bm) + (unless (send bm is-color?) (error 'bitmap->histogram "bitmap must be colour")) + (define pxls (prepare-bytes bm 4 #t)) + (define l# (make-hash)) + (for ((r (in-bytes pxls 1 #f 4)) (g (in-bytes pxls 2 #f 4)) (b (in-bytes pxls 3 #f 4))) + (hash-update! l# (L r g b) add1 0)) + (define xs (hash-keys l#)) ; the colour values + (define ws (hash-values l#)) ; the "weights" i.e. counts for median + (values xs ws)) + +(define (bitmap-quantile q bm (hist-xs #f) (hist-ws #f)) + (define-values (xs ws) (if (and hist-xs hist-ws) + (values hist-xs hist-ws) + (bitmap-histogram bm))) + (quantile q < xs ws)) + +;; we don't return a 1-depth bitmap, so we can do more interesting things with colour +(define (bitmap->monochrome q bm (hist-xs #f) (hist-ws #f)) + (define Q (bitmap-quantile q bm hist-xs hist-ws)) + (define pxls (prepare-bytes bm 4 #t)) + (for ((r (in-bytes pxls 1 #f 4)) + (g (in-bytes pxls 2 #f 4)) + (b (in-bytes pxls 3 #f 4)) + (i (sequence-map (curry fx* 4) (in-naturals)))) + (define l (L r g b)) + (define rgb+ (cond [(fx< l Q) 0] [else 255])) + (bytes-set! pxls (fx+ i 1) rgb+) + (bytes-set! pxls (fx+ i 2) rgb+) + (bytes-set! pxls (fx+ i 3) rgb+)) + (define w (send bm get-width)) + (define h (send bm get-height)) + (define rv (make-bitmap w h #f)) + (send rv set-argb-pixels 0 0 w h pxls) + rv) + +(module+ main + (define bm (read-bitmap "271px-John_Constable_002.jpg")) + (define-values (xs ws) (bitmap-histogram bm)) + (void + (send (bitmap->monochrome 1/4 bm) save-file "histogram-racket-0.25.png" 'png) + (send (bitmap->monochrome 1/2 bm) save-file "histogram-racket-0.50.png" 'png) ; median + (send (bitmap->monochrome 3/4 bm xs ws) save-file "histogram-racket-0.75.png" 'png))) diff --git a/Task/Bitmap-Midpoint-circle-algorithm/00DESCRIPTION b/Task/Bitmap-Midpoint-circle-algorithm/00DESCRIPTION index fda28f160d..71e81dc582 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/00DESCRIPTION +++ b/Task/Bitmap-Midpoint-circle-algorithm/00DESCRIPTION @@ -1,2 +1,4 @@ -Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, write an implementation of the '''midpoint circle algorithm''' (also known as '''Bresenham's circle algorithm''').
+Using the data storage type defined [[Basic_bitmap_storage|on this page]] for raster images, +write an implementation of the '''midpoint circle algorithm''' +(also known as '''Bresenham's circle algorithm''').
([[wp:Midpoint_circle_algorithm|definition on Wikipedia]]). diff --git a/Task/Bitmap-Midpoint-circle-algorithm/D/bitmap-midpoint-circle-algorithm.d b/Task/Bitmap-Midpoint-circle-algorithm/D/bitmap-midpoint-circle-algorithm.d index 96c0649813..ad175721b7 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/D/bitmap-midpoint-circle-algorithm.d +++ b/Task/Bitmap-Midpoint-circle-algorithm/D/bitmap-midpoint-circle-algorithm.d @@ -1,7 +1,8 @@ import bitmap: Image, RGB; void circle(Color)(Image!Color img, in int x0, in int y0, - in int radius, in Color color) pure nothrow { + in int radius, in Color color) +pure nothrow @nogc @safe { int f = 1 - radius; int ddfX = 1; int ddfY = -2 * radius; @@ -32,9 +33,9 @@ void circle(Color)(Image!Color img, in int x0, in int y0, } } -void main() { +void main() @safe { auto img = new Image!RGB(25, 25); img.clear(RGB.white); circle(img, 12, 12, 12, RGB.black); - img.textualShow(); + img.textualShow; } diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 b/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 index ab00f34686..f367e6940c 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 +++ b/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-4.mod3 @@ -1,27 +1,36 @@ -let raster_circle ~img ~color ~c:(x0, y0) ~r = - let plot = put_pixel img color in - let x = 0 - and y = r - and m = 5 - 4 * r - in - let rec loop x y m = - plot (x0 + x) (y0 + y); - plot (x0 + y) (y0 + x); - plot (x0 - x) (y0 + y); - plot (x0 - y) (y0 + x); - plot (x0 + x) (y0 - y); - plot (x0 + y) (y0 - x); - plot (x0 - x) (y0 - y); - plot (x0 - y) (y0 - x); - let y, m = - if m > 0 - then (y - 1), (m - 8 * y) - else y, m - in - if x <= y then - let x = x + 1 in - let m = m + 8 * x + 4 in - loop x y m - in - loop x y m -;; +use MONKEY_TYPING; +augment class Pixel { method Str { "$.R $.G $.B" } } +augment class Bitmap { + method P3 { + join "\n", «P3 "$.width $.height" 255», + do for ^$.height { join ' ', @.data[]»[$_] } + } + method raster-circle ( $x0, $y0, $r, Pixel $value ) { + my $f = 1 - $r; + my $ddF_x = 0; + my $ddF_y = -2 * $r; + my ($x, $y) = 0, $r; + self.set-pixel($x0, $y0 + $r, $value); + self.set-pixel($x0, $y0 - $r, $value); + self.set-pixel($x0 + $r, $y0, $value); + self.set-pixel($x0 - $r, $y0, $value); + while $x < $y { + if $f >= 0 { + $y--; + $ddF_y += 2; + $f += $ddF_y; + } + $x++; + $ddF_x += 2; + $f += $ddF_x + 1; + self.set-pixel($x0 + $x, $y0 + $y, $value); + self.set-pixel($x0 - $x, $y0 + $y, $value); + self.set-pixel($x0 + $x, $y0 - $y, $value); + self.set-pixel($x0 - $x, $y0 - $y, $value); + self.set-pixel($x0 + $y, $y0 + $x, $value); + self.set-pixel($x0 - $y, $y0 + $x, $value); + self.set-pixel($x0 + $y, $y0 - $x, $value); + self.set-pixel($x0 - $y, $y0 - $x, $value); + } + } +} diff --git a/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 b/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 new file mode 100644 index 0000000000..ab00f34686 --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/Modula-3/bitmap-midpoint-circle-algorithm-5.mod3 @@ -0,0 +1,27 @@ +let raster_circle ~img ~color ~c:(x0, y0) ~r = + let plot = put_pixel img color in + let x = 0 + and y = r + and m = 5 - 4 * r + in + let rec loop x y m = + plot (x0 + x) (y0 + y); + plot (x0 + y) (y0 + x); + plot (x0 - x) (y0 + y); + plot (x0 - y) (y0 + x); + plot (x0 + x) (y0 - y); + plot (x0 + y) (y0 - x); + plot (x0 - x) (y0 - y); + plot (x0 - y) (y0 - x); + let y, m = + if m > 0 + then (y - 1), (m - 8 * y) + else y, m + in + if x <= y then + let x = x + 1 in + let m = m + 8 * x + 4 in + loop x y m + in + loop x y m +;; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm.pli b/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm.pli new file mode 100644 index 0000000000..53a26c45cf --- /dev/null +++ b/Task/Bitmap-Midpoint-circle-algorithm/PL-I/bitmap-midpoint-circle-algorithm.pli @@ -0,0 +1,52 @@ +/* Plot three circles. */ + +CIRCLE: PROCEDURE OPTIONS (MAIN); + declare image (-20:20, -20:20) character (1); + declare j fixed binary; + + image = '.'; + image(0,*) = '-'; + image(*,0) = '|'; + image(0,0) = '+'; + + CALL DRAW_CIRCLE (0, 0, 11); + CALL DRAW_CIRCLE (0, 0, 8); + CALL DRAW_CIRCLE (0, 0, 19); + + do j = hbound(image,1) to lbound(image,1) by -1; + put skip edit (image(j,*)) (a(1)); + end; + +draw_circle: procedure (x0, y0, radius); /* 14 May 2010. */ + declare ( x0, y0, radius ) fixed binary; + declare ( ddfx, ddfy, x, y, f ) fixed binary; + declare debug bit (1) aligned static initial ('0'b); + + f = 1-radius; + ddfx = 1; + ddfy = -2*radius; + x = 0; + y = radius; + image(x0, y0+radius) = '*'; /* Octet 0. */ + image(x0+radius, y0) = '*'; /* Octet 1. */ + image(x0, y0-radius) = '*'; /* Octet 2. */ + image(x0-radius, y0) = '*'; /* Octet 3. */ + + do while (x < y); + if f >= 0 then + do; y = y - 1; ddfy = ddfy +2; f = f + ddfy; end; + x = x + 1; + ddfx = ddfx + 2; + f = f + ddfx; + image(x0+x, y0+y) = '0'; /* Draws octant 0. */ + image(x0+y, y0+x) = '1'; /* Draws octant 1. */ + image(x0+y, y0-x) = '2'; /* Draws octant 2. */ + image(x0+x, y0-y) = '3'; /* Draws octant 3. */ + image(x0-x, y0-y) = '4'; /* Draws octant 4. */ + image(x0-y, y0-x) = '5'; /* Draws octant 5. */ + image(x0-y, y0+x) = '6'; /* Draws octant 6. */ + image(x0-x, y0+y) = '7'; /* Draws octant 7. */ + end; +end draw_circle; + +END CIRCLE; diff --git a/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx b/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx index f4c78b8ba1..a5ed2b3f8b 100644 --- a/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx +++ b/Task/Bitmap-Midpoint-circle-algorithm/REXX/bitmap-midpoint-circle-algorithm.rexx @@ -1,49 +1,43 @@ /*REXX pgm plots 3 circles using midpoint/Bresenham's circle algorithm. */ - EoE = 200 /*EOE = End Of Earth, er, plot. */ -image. = 'fa'x /*fill the array with middle-dots*/ -pChar = '*' - do j=-EoE to +EoE /*draw grid from lowest──>highest*/ - image.j.0 = '─' /*draw the horizontal axis. */ - image.0.j = '│' /* " " verical " */ - end /*j*/ -image.0.0='┼' /*"draw" the axis origin. */ -minX=0; maxX=0 -minY=0; maxY=0 -call draw_circle 0, 0, 8, '#' -call draw_circle 0, 0, 11, '$' -call draw_circle 0, 0, 19, '@' -border=2 -minX=minX-border*2; maxX=maxX+border*2 -minY=minY-border ; maxY=maxY+border - do y=maxY by -1 to minY; aRow= - do x=minX to maxX - aRow=aRow || image.x.y - end /*x*/ - say aRow - end /*y*/ +@. = '·' /*fill the array with middle-dots*/ +minX=0; maxX=0; minY=0; maxY=0 /*initialize minimums & maximums.*/ +call drawCircle 0, 0, 8, '#' /*plot 1st circle with pound char*/ +call drawCircle 0, 0, 11, '$' /* " 2nd " " dollar " */ +call drawCircle 0, 0, 19, '@' /* " 3rd " " commer. at*/ +border=2 /*BORDER: shows N extra grid pts*/ +minX=minX-border*2; maxX=maxX+border*2 /*adjust min&max X to show border*/ +minY=minY-border ; maxY=maxY+border /* " " " Y " " " */ +if @.0.0==@. then @.0.0='┼' /*maybe define plot's axis origin*/ + /* [↓] define horizontal grid. */ + do gx=minX to maxX; if @.gx.0==@. then @.gx.0='─'; end /*gx*/ + do gy=minY to maxY; if @.0.gy==@. then @.0.gy='│'; end /*gy*/ + /* [↑] define the vertical grid.*/ + do y=maxY by -1 to minY; aRow= /* [↓] draw grid from top to bot.*/ + do x=minX to maxX /* [↓] " " " left──►right*/ + aRow=aRow || @.x.y /*build a grid row, char by char.*/ + end /*x*/ /* [↑] a grid row should be done*/ + say aRow /*display signal row of the grid.*/ + end /*y*/ exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────DRAW_CIRCLE subroutine─────────────*/ -draw_circle: procedure expose image. minX maxX minY maxY -parse arg xx, yy, r, point; f=1-r; ddfx=1; ddfy=-2*r; y=r -_=yy+r; image.xx._='*' -_=xx+r; image._.yy='*' -_=yy-r; image.xx._='*' -_=xx-r; image._.yy='*' - do x=0 while x=0 then do; y=y-1; ddfy=ddfy+2; f=f+ddfy; end - ddfx=ddfx+2; f=f+ddfx - x_=xx+x; y_=yy+y; call plotXY x_, y_, point - x_=xx+y; y_=yy+x; call plotXY x_, y_, point - x_=xx+y; y_=yy-x; call plotXY x_, y_, point - x_=xx+x; y_=yy-y; call plotXY x_, y_, point - x_=xx-x; y_=yy-y; call plotXY x_, y_, point - x_=xx-y; y_=yy-x; call plotXY x_, y_, point - x_=xx-y; y_=yy+x; call plotXY x_, y_, point - x_=xx-x; y_=yy+y; call plotXY x_, y_, point - end /*x*/ +/*───────────────────────────────────DRAWCIRCLE subroutine──────────────*/ +drawCircle: procedure expose @. minX maxX minY maxY +parse arg xx,yy,r,plotChar; f=1-r; fx=1; fy=-2*r; y=r + + do x=0 while x=0 then do; y=y-1; fy=fy+2; f=f+fy; end + fx=fx+2; f=f+fx + call plotPoint xx+x, yy+y, plotChar + call plotPoint xx+y, yy+x, plotChar + call plotPoint xx+y, yy-x, plotChar + call plotPoint xx+x, yy-y, plotChar + call plotPoint xx-y, yy+x, plotChar + call plotPoint xx-x, yy+y, plotChar + call plotPoint xx-x, yy-y, plotChar + call plotPoint xx-y, yy-x, plotChar + end /*x*/ /* [↑] place plot points ══► plot*/ return -/*──────────────────────────────────PLOTXY subroutine───────────────────*/ -plotXY: procedure expose image. minX maxX minY maxY; parse arg xx, yy, p -image.xx.yy=p; minX=min(minX,xx); maxX=max(maxX,xx) - minY=min(minY,yy); maxY=max(maxY,yy) +/*──────────────────────────────────PLOTPOINT subroutine────────────────*/ +plotPoint: procedure expose @. minX maxX minY maxY +parse arg xx,yy,@.xx.yy; minX=min(minX,xx); maxX=max(maxX,xx) + minY=min(minY,yy); maxY=max(maxY,yy) return diff --git a/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-1.sh b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-1.sh new file mode 100644 index 0000000000..a16ee0d5a3 --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-1.sh @@ -0,0 +1,11 @@ + function setrgb { + _.r=$1 + _.g=$2 + _.b=$3 + } + function grayscale { + integer x=$(( round( 0.2126*_.r + 0.7152*_.g + 0.0722*_.b ) )) + _.r=$x + _.g=$x + _.b=$x + } diff --git a/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-2.sh b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-2.sh new file mode 100644 index 0000000000..2fbc39485e --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-2.sh @@ -0,0 +1,39 @@ + function grayscale { + RGBColor_t c + for ((y=0; y<_.height; y++)); do + for ((x=0; x<_.width; x++)); do + c.setrgb ${_.data[y][x]} + c.grayscale + _.data[y][x]=$(c.to_s) + done + done + } + + function read { + exec 4<"$1" + typeset filetype + read -u4 filetype + if [[ $filetype != "P3" ]]; then + print -u2 "error: I can only read P3 type PPM files" + else + read -u4 _.width _.height + integer maxval + read -u4 maxval + integer x y r g b + typeset -a bytes + for ((y=0; y<_.height; y++)); do + read -u4 -A bytes + for ((x=0; x<_.width; x++)); do + r=${bytes[3*x+0]} + g=${bytes[3*x+1]} + b=${bytes[3*x+2]} + if (( r > maxval || g > maxval || b > maxval )); then + print -u2 "error: invalid color ($r $g $b), max=$maxval" + return 1 + fi + _.data[y][x]="$r $g $b" + done + done + fi + exec 4<&- + } diff --git a/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-3.sh b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-3.sh new file mode 100644 index 0000000000..47099bdfee --- /dev/null +++ b/Task/Bitmap-Read-a-PPM-file/UNIX-Shell/bitmap-read-a-ppm-file-3.sh @@ -0,0 +1,13 @@ +Bitmap_t c +c.read "$HOME/tmp/bitmap.ppm" +c.to_s + +if [[ $(c.to_s) == $(cat "$HOME/tmp/bitmap.ppm") ]]; then + echo looks OK +else + echo something is wrong +fi + +c.grayscale +c.to_s +c.write "$HOME/tmp/bitmap_g.ppm" diff --git a/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-3.mod3 b/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-3.mod3 index 2bfe07248e..e49a671c7a 100644 --- a/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-3.mod3 +++ b/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-3.mod3 @@ -1,14 +1,7 @@ -let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = - let width = Bigarray.Array2.dim1 r_channel - and height = Bigarray.Array2.dim2 r_channel in - Printf.fprintf oc "P6\n%d %d\n255\n" width height; - for y = 0 to pred height do - for x = 0 to pred width do - output_char oc (char_of_int r_channel.{x,y}); - output_char oc (char_of_int g_channel.{x,y}); - output_char oc (char_of_int b_channel.{x,y}); - done; - done; - output_char oc '\n'; - flush oc; -;; +proc writePPM(img: Image, f: TFile) = + f.writeln "P6\n", img.w, " ", img.h, "\n255" + + for x,y in img.indices: + f.write char(img[x,y].r) + f.write char(img[x,y].g) + f.write char(img[x,y].b) diff --git a/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-4.mod3 b/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-4.mod3 new file mode 100644 index 0000000000..2bfe07248e --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/Modula-3/bitmap-write-a-ppm-file-4.mod3 @@ -0,0 +1,14 @@ +let output_ppm ~oc ~img:(_, r_channel, g_channel, b_channel) = + let width = Bigarray.Array2.dim1 r_channel + and height = Bigarray.Array2.dim2 r_channel in + Printf.fprintf oc "P6\n%d %d\n255\n" width height; + for y = 0 to pred height do + for x = 0 to pred width do + output_char oc (char_of_int r_channel.{x,y}); + output_char oc (char_of_int g_channel.{x,y}); + output_char oc (char_of_int b_channel.{x,y}); + done; + done; + output_char oc '\n'; + flush oc; +;; diff --git a/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 b/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 index f67346644c..657ea991df 100644 --- a/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 +++ b/Task/Bitmap-Write-a-PPM-file/Perl-6/bitmap-write-a-ppm-file.pl6 @@ -1,13 +1,12 @@ -sub MAIN ($filename = 'default.ppm') { - my $width = my $height = 125; - - # Since P6 is a binary format, open in binary mode - my $out = open( $filename, :w, :bin ) or die "$!\n"; - - $out.say("P6\n$width $height\n255"); - - for ^$height X ^$width -> $r, $g { - $out.write(Buf.new($r*2,$g*2,255-$r*2)); +role PPM { + method P6 returns Blob { + "P6\n{self.width} {self.height}\n255\n".encode('ascii') + ~ Blob.new: flat map { .R, .G, .B }, self.data } - $out.close; } +my Bitmap $b = Bitmap.new( width => 125, height => 125) but PPM; +for ^$b.height X ^$b.width -> $i, $j { + $b.pixel($i, $j) = Pixel.new: :R($i*2), :G($j*2), :B(255-$i*2); +} + +$*OUT.write: $b.P6; diff --git a/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-1.sh b/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-1.sh new file mode 100644 index 0000000000..b9f21bc52c --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-1.sh @@ -0,0 +1,3 @@ + function write { + _.to_s > "$1" + } diff --git a/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-2.sh b/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-2.sh new file mode 100644 index 0000000000..9c3642e06a --- /dev/null +++ b/Task/Bitmap-Write-a-PPM-file/UNIX-Shell/bitmap-write-a-ppm-file-2.sh @@ -0,0 +1,3 @@ +Bitmap_t b +# do stuff to b, and save it: +b.write '$HOME/tmp/bitmap.ppm' diff --git a/Task/Bitmap/00DESCRIPTION b/Task/Bitmap/00DESCRIPTION index 2f3738413b..882078c703 100644 --- a/Task/Bitmap/00DESCRIPTION +++ b/Task/Bitmap/00DESCRIPTION @@ -1,10 +1,15 @@ -Show a basic storage type to handle a simple RGB raster graphics image, and some primitive associated functions. +{{omit from|PARI/GP}} +Show a basic storage type to handle a simple RGB raster graphics image, +and some primitive associated functions. -If possible provide a function to allocate an uninitialised image, given its width and height, and provide 3 additional functions: +If possible provide a function to allocate an uninitialised image, +given its width and height, and provide 3 additional functions: * one to fill an image with a plain RGB color, * one to set a given pixel with a color, * one to get the color of a pixel. (If there are specificities about the storage or the allocation, explain those.) -''These functions are used as a base for the articles in the category [[Raster_graphics_operations|raster graphics operations]], and a basic output function to check the results is available in the article [[write ppm file]].'' +''These functions are used as a base for the articles in the category [[Raster_graphics_operations|raster graphics operations]], +and a basic output function to check the results +is available in the article [[write ppm file]].'' diff --git a/Task/Bitmap/D/bitmap.d b/Task/Bitmap/D/bitmap.d index 758942d625..5a6240d2a5 100644 --- a/Task/Bitmap/D/bitmap.d +++ b/Task/Bitmap/D/bitmap.d @@ -20,7 +20,7 @@ final class Image(T) { } void allocate(in int nxx=0, in int nyy=0, in bool inizialize=true) - pure nothrow in { + pure nothrow @safe in { assert(nxx >= 0 && nyy >= 0); } body { this.nx_ = nxx; @@ -34,8 +34,16 @@ final class Image(T) { } } + @property Image dup() const pure nothrow @safe { + auto result = new Image(); + result.image = this.image.dup; + result.nx_ = this.nx; + result.ny_ = this.ny; + return result; + } + static Image fromData(T[] data, in size_t nxx=0, in size_t nyy=0) - pure nothrow in { + pure nothrow @safe in { assert(nxx >= 0 && nyy >= 0 && data.length == nxx * nyy); } body { auto result = new Image(); @@ -45,10 +53,10 @@ final class Image(T) { return result; } - @property size_t nx() const pure nothrow { return nx_; } - @property size_t ny() const pure nothrow { return ny_; } + @property size_t nx() const pure nothrow @safe @nogc { return nx_; } + @property size_t ny() const pure nothrow @safe @nogc { return ny_; } - ref T opIndex(in size_t x, in size_t y) pure nothrow + ref T opIndex(in size_t x, in size_t y) pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); @@ -57,7 +65,7 @@ final class Image(T) { return image[x + y * nx_]; } - T opIndex(in size_t x, in size_t y) const pure nothrow + T opIndex(in size_t x, in size_t y) const pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); @@ -66,7 +74,8 @@ final class Image(T) { return image[x + y * nx_]; } - T opIndexAssign(in T color, in size_t x, in size_t y) pure nothrow + T opIndexAssign(in T color, in size_t x, in size_t y) + pure nothrow @safe @nogc in { assert(x < nx_ && y < ny_); //assert(x < nx_, format("opIndex, x=%d, nx=%d", x, nx)); @@ -75,14 +84,15 @@ final class Image(T) { return image[x + y * nx_] = color; } - void opIndexUnary(string op)(in size_t x, in size_t y) pure nothrow + void opIndexUnary(string op)(in size_t x, in size_t y) + pure nothrow @safe @nogc if (op == "++" || op == "--") in { assert(x < nx_ && y < ny_); } body { mixin("image[x + y * nx_] " ~ op ~ ";"); } - void clear(in T color=this.black) pure nothrow { + void clear(in T color=this.black) pure nothrow @safe @nogc { image[] = color; } @@ -94,7 +104,7 @@ final class Image(T) { .split .map!(row => row .filter!(c => c == one || c == zero) - .map!(c => cast(T)(c == one)) + .map!(c => T(c == one)) .array) .array; assert(M.join.length > 0); // Not empty. @@ -104,7 +114,7 @@ final class Image(T) { } /// The axis origin is at the top left. - void textualShow(in char bl='#', in char wh='.') const { + void textualShow(in char bl='#', in char wh='.') const nothrow { size_t i = 0; foreach (immutable y; 0 .. ny_) { foreach (immutable x; 0 .. nx_) @@ -122,7 +132,7 @@ struct RGB { } -Image!RGB loadPPM6(Image!RGB img, in string fileName) { +Image!RGB loadPPM6(ref Image!RGB img, in string fileName) { if (img is null) img = new Image!RGB; auto f = File(fileName, "rb"); diff --git a/Task/Bitmap/Go/bitmap-1.go b/Task/Bitmap/Go/bitmap-1.go new file mode 100644 index 0000000000..d6dd1a630b --- /dev/null +++ b/Task/Bitmap/Go/bitmap-1.go @@ -0,0 +1,57 @@ +package main + +import ( + "bytes" + "fmt" + "image" + "image/color" + "image/draw" + "image/png" +) + +func main() { + // A rectangle from 0,0 to 300,240. + r := image.Rect(0, 0, 300, 240) + + // Create an image + im := image.NewNRGBA(r) + + // set some color variables for convience + var ( + red = color.RGBA{0xff, 0x00, 0x00, 0xff} + blue = color.RGBA{0x00, 0x00, 0xff, 0xff} + ) + + // Fill with a uniform color + draw.Draw(im, r, &image.Uniform{red}, image.ZP, draw.Src) + + // Set individual pixels + im.Set(10, 20, blue) + im.Set(20, 30, color.Black) + im.Set(30, 40, color.RGBA{0x10, 0x20, 0x30, 0xff}) + + // Get the values of specific pixels as color.Color types. + // The color will be in the color.Model of the image (in this + // case color.NRGBA) but color models can convert their values + // to other models. + c1 := im.At(0, 0) + c2 := im.At(10, 20) + + // or directly as RGB components (scaled values) + redc, greenc, bluec, _ := c1.RGBA() + redc, greenc, bluec, _ = im.At(30, 40).RGBA() + + // Images can be read and writen in various formats + var buf bytes.Buffer + err := png.Encode(&buf, im) + if err != nil { + fmt.Println(err) + } + + fmt.Println("Image size:", im.Bounds().Dx(), "×", im.Bounds().Dy()) + fmt.Println(buf.Len(), "bytes when encoded as PNG.") + fmt.Printf("Pixel at %7v is %v\n", image.Pt(0, 0), c1) + fmt.Printf("Pixel at %7v is %#v\n", image.Pt(10, 20), c2) // %#v shows type details + fmt.Printf("Pixel at %7v has R=%d, G=%d, B=%d\n", + image.Pt(30, 40), redc, greenc, bluec) +} diff --git a/Task/Bitmap/Go/bitmap.go b/Task/Bitmap/Go/bitmap-2.go similarity index 100% rename from Task/Bitmap/Go/bitmap.go rename to Task/Bitmap/Go/bitmap-2.go diff --git a/Task/Bitmap/J/bitmap-2.j b/Task/Bitmap/J/bitmap-2.j index de25a9f397..1fe9432033 100644 --- a/Task/Bitmap/J/bitmap-2.j +++ b/Task/Bitmap/J/bitmap-2.j @@ -1,5 +1,6 @@ myimg=: makeRGB 5 8 NB. create a bitmap with height 5 and width 8 (black) myimg=: 255 makeRGB 5 8 NB. create a white bitmap with height 5 and width 8 + myimg=: 127 makeRGB 5 8 NB. create a gray bitmap with height 5 and width 8 myimg=: 0 255 0 makeRGB 5 8 NB. create a green bitmap with height 5 and width 8 myimg=: 0 0 255 fillRGB myimg NB. fill myimg with blue colors=: 0 255 {~ #: i.8 NB. black,blue,green,cyan,red,magenta,yellow,white diff --git a/Task/Bitmap/Perl-6/bitmap.pl6 b/Task/Bitmap/Perl-6/bitmap.pl6 index f30e367342..f13339f627 100644 --- a/Task/Bitmap/Perl-6/bitmap.pl6 +++ b/Task/Bitmap/Perl-6/bitmap.pl6 @@ -1,33 +1,27 @@ -class Pixel { - has Int $.R; - has Int $.G; - has Int $.B; -} - +class Pixel { has Int ($.R, $.G, $.B) } class Bitmap { - has @.data; - has Int $.width; - has Int $.height; + has Int ($.width, $.height); + has Pixel @.data; - method fill(Pixel $p) { - for ^$.width X ^$.height -> $i, $j { - @.data[$i][$j] = $p.clone; - } + method fill(Pixel $p) { + for ^$!width X ^$!height -> $i, $j { + self.pixel($i, $j) = $p.clone; } + } + method pixel( + $i where ^self.width, + $j where ^self.height + --> Pixel + ) is rw { @!data[$i*$!height + $j] } - method set-pixel ( $i, $j, Pixel $value) { - fail unless 0 <= $i <= $.width && 0 <= $j <= $.height; - @.data[$i][$j] = $value; - } - - method get-pixel ($i, $j) { - fail unless 0 <= $i <= $.width && 0 <= $j <= $.height; - @.data[$i][$j]; - } + method set-pixel ($i, $j, Pixel $p) { + self.pixel($i, $j) = $p.clone; + } + method get-pixel ($i, $j) returns Pixel { + self.pixel($i, $j); + } } -# Usage: - my Bitmap $b = Bitmap.new( width => 10, height => 10); $b.fill( Pixel.new( R => 0, G => 0, B => 200) ); diff --git a/Task/Bitmap/REXX/bitmap-1.rexx b/Task/Bitmap/REXX/bitmap-1.rexx new file mode 100644 index 0000000000..f8bed61a30 --- /dev/null +++ b/Task/Bitmap/REXX/bitmap-1.rexx @@ -0,0 +1,37 @@ +/*REXX pgm demonstrates how to handle a simple RGB raster graphics image*/ +red = '00000000 00000000 11111111'b /*define a red value. */ +blue = '11111111 00000000 00000000'b /*define a blue value. */ +blue = 'ff 00 00'x /*another way to define blue. */ +image.= /*"allocate" an "array" to nulls.*/ +call RGBfill red /*set the entire image to red. */ +call RGBset 10,40,blue /*set a pixel to blue. */ + +x=10; y=40; pix=RGBget(x,y) /*get the color of a pixel. */ +hexv = c2x(pix) /*get hex value of pix's color*/ +binv = x2b(hexv) /* " binary " " " " */ + +say 'pixel' x","y '=' binv /*show the binary value of 20,50 */ +bin3v = left(binv,8) substr(binv,9,8) right(binv,8) +say 'pixel' x","y '=' bin3v /*show again, but with spaces. */ +say /*show a blank between bin & hex.*/ +say 'pixel' x","y '=' hexv /*show again, but in hexadecimal.*/ +hex3v = left(hexv,2) substr(hexv,3,2) right(hexv,2) +say 'pixel' x","y '=' hex3v /*show again, but with spaces. */ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────RGBFILL subroutine──────────────────*/ +RGBfill: procedure expose image.; image.=arg(1); return +/*──────────────────────────────────RGBGET subroutine───────────────────*/ +RGBget: procedure expose image.; parse arg Xpixel,Ypixel +return image.Xpixel.Ypixel /*get & return the pixel's color.*/ +/*──────────────────────────────────RGBRASTER subroutine────────────────*/ +RGBraster: procedure expose image.; parse arg Xsize,Ysize,color; RGB= + do x=1 to Xsize; _= /*build raster 1 line at a time. */ + do y=1 to Ysize /* " a line " pixel " " " */ + _=_ || image.x.y /*append single pixel to the line*/ + end /*y*/ /* [↑] all done building a line.*/ + RGB=RGB || _ /*append a single line to raster.*/ + end /*x*/ /* [↑] all done building raster.*/ +return RGB /*return RGB raster to invoker. */ +/*──────────────────────────────────RGBSET subroutine───────────────────*/ +RGBset: procedure expose image.; parse arg Xpixel,Ypixel,color +image.Xpixel.Ypixel=color; return /*define pixel, return to invoker*/ diff --git a/Task/Bitmap/REXX/bitmap-2.rexx b/Task/Bitmap/REXX/bitmap-2.rexx new file mode 100644 index 0000000000..8dc4a5fa6c --- /dev/null +++ b/Task/Bitmap/REXX/bitmap-2.rexx @@ -0,0 +1,111 @@ +/* REXX *************************************************************** +* Draw a picture from pixels +* 16.06.2014 Walter Pachl +**********************************************************************/ +oid='pic.bmp'; 'erase' oid + +blue ='FF0000'x; +green='00FF00'x; +red ='0000FF'x; +white='ffffff'x; +black='000000'x; + +w=600 /* width */ +h=300 /* height */ +w3=w*3 + +bfType ='BM' +bfSize ='46000000'x +bfReserved ='00000000'x +bfOffBits ='36000000'x +biSize ='28000000'x +biWidth =lend(w) +biHeight =lend(h) +biPlanes ='0100'x +biBitCount ='1800'x +biCompression ='00000000'x +biSizeImage ='10000000'x +biXPelsPerMeter='00000000'x +biYPelsPerMeter='00000000'x +biClrUsed ='00000000'x +biClrImportant ='00000000'x + +s=bfType||, + bfSize||, + bfReserved||, + bfOffBits||, + biSize||, + biWidth||, + biHeight||, + biPlanes||, + biBitCount||, + biCompression||, + biSizeImage||, + biXPelsPerMeter||, + biYPelsPerMeter||, + biClrUsed||, + biClrImportant + +pic=copies(red,w*h) /* fill the rectangle with color red */ +Call rect 100,100,180,180,green /* draw a green rectangle */ +Call rect 100,100,160,160,blue /* and a blue rectangle within that */ +Call dot 120,120,white /* one pixel is hardly visible */ +Do x=98 To 102 /* draw a square of 25 pixels */ + Do y=98 To 102 + Call dot x,y,white + End + End +Call charout oid,s||pic /* write the picture to file */ +dmy=col(97,98) +dmy=col(98,98) +Exit + +lend: Procedure +/********************************************************************** +* compute the representation of a number (little endian) +**********************************************************************/ +Parse Arg n +res=reverse(d2c(n,4)) +rev=reverse(res) +say 'lend:' arg(1) '->' c2x(res) '=>' c2d(rev) +Return res + +rect: Procedure Expose pic w h w3 +/********************************************************************** +* Fill a rectangle with center at x,y and width/height = wr/hr +**********************************************************************/ +Parse Arg x,y,wr,hr,color +Say x y wr hr c2x(color) +i=w3*(y-1)+3*(x-1)+1 /* Pixel position of center */ +ia=max(w3*(y-1)+1,i-3*(wr%2)) /* position of left border */ +ib=min(i+3*wr%2,w3*y) /* position of right border */ +lc=ib-ia /* length of horizontal line */ +If lc>=0 Then Do + os=copies(color,lc%3) /* the horizontal line */ + Do hi=-hr%2 to hr%2 /* loop from lower to upper border*/ + i=trunc(ia+w3*hi) /* position of line's left border */ + If i>1 Then Do + pic=overlay(os,pic,i) /* put the line into the picture */ + j=i%w3 + End + End + End +Return + +dot: Procedure Expose pic w h w3 +/********************************************************************** +* Put a dot at position x/y into the picture +**********************************************************************/ +Parse Arg x,y,color +i=w3*(y-1)+3*(x-1) +pic=overlay(color,pic,i+1) +Return + +col: Procedure Expose pic w h w3 +/********************************************************************** +* get the color at position x/y +**********************************************************************/ +Parse Arg x,y,color +i=w3*(y-1)+3*(x-1) +say 'color at pixel' x'/'y'='c2x(substr(pic,i+1,3)) +Return c2x(substr(pic,i+1,3)) diff --git a/Task/Bitmap/REXX/bitmap.rexx b/Task/Bitmap/REXX/bitmap.rexx deleted file mode 100644 index 19b3aa3a38..0000000000 --- a/Task/Bitmap/REXX/bitmap.rexx +++ /dev/null @@ -1,35 +0,0 @@ -/*REXX program shows how to handle a simple RGB raster graphics image. */ -image.='00 00 00'x /*set entire array to hex zeroes.*/ - -red='00000000 00000000 11111111'b /*define a red value. */ -image.=red /*set the entire array to red. */ - -blue='11111111 00000000 00000000'b /*define a blue value. */ -blue='ff 00 00'x /*another way to define blue. */ -image.10.40=blue /*set a particular pixel. */ - -x=20 -y=50 -aPIXcolor=image.x.y /*obtain the color of a pixel. */ -hexv=c2x(aPixcolor) /*get the binary value of 20,50. */ -binv=x2b(hexv) /*get the binary value of 20,50. */ - -say 'pixel' x","y '=' binv /*show the binary value of 20,50 */ -bin3v=left(binv,8) substr(binv,9,8) right(binv,8) -say 'pixel' x","y '=' bin3v /*show again, but with spaces. */ - -say 'pixel' x","y '=' hexv /*show again, but in hexadecimal.*/ -hex3v=left(hexv,2) substr(hexv,3,2) right(hexv,2) -say 'pixel' x","y '=' hex3v /*show again, but with spaces. */ - -RGB= /*start with a clean slate. */ -xSize=500 /*size of the X axis. */ -YSize=800 /* " " " Y " */ - - do x=1 to xSize - do y=1 to Ysize - RGB=RGM || image.x.y /*build RBG one pixel at a time.*/ - end /*y*/ - end /*x*/ - -return RGM /*return the RGB image to invoker*/ diff --git a/Task/Bitmap/UNIX-Shell/bitmap.sh b/Task/Bitmap/UNIX-Shell/bitmap.sh new file mode 100644 index 0000000000..624118e428 --- /dev/null +++ b/Task/Bitmap/UNIX-Shell/bitmap.sh @@ -0,0 +1,74 @@ +typeset -T RGBColor_t=( + integer r g b + function to_s { + printf "%d %d %d" ${_.r} ${_.g} ${_.b} + } + function white { print "255 255 255"; } + function black { print "0 0 0"; } + function red { print "255 0 0"; } + function green { print "0 255 0"; } + function blue { print "0 0 255"; } + function yellow { print "255 255 0"; } + function magenta { print "255 0 255"; } + function cyan { print "0 255 255"; } +) + +typeset -T Bitmap_t=( + integer height + integer width + typeset -a data + + function fill { + typeset color=$1 + if [[ -z ${color:+set} ]]; then + print -u2 "error: no fill color specified" + return 1 + fi + integer x y + for ((y=0; y<_.height; y++)); do + for ((x=0; x<_.width; x++)); do + _.data[y][x]="$color" + done + done + } + + function setpixel { + integer x=$1 y=$2 + typeset color=$3 + _.data[y][x]=$color + } + + function getpixel { + integer x=$1 y=$2 + print "${_.data[y][x]}" + } + + function to_s { + typeset ppm="" + ppm+="P3"$'\n' + ppm+="${_.width} ${_.height}"$'\n' + ppm+="255"$'\n' + typeset sep + for ((y=0; y<_.height; y++)); do + sep="" + for ((x=0; x<_.width; x++)); do + ppm+="$sep${_.data[y][x]}" + sep=" " + done + ppm+=$'\n' + done + print -- "$ppm" + } +) + +RGBColor_t color +Bitmap_t b=( width=3 height=2 ) +b.fill "$(color.white)" +b.setpixel 0 0 "$(color.red)" +b.setpixel 1 0 "$(color.green)" +b.setpixel 2 0 "$(color.blue)" +b.setpixel 0 1 "$(color.yellow)" +b.setpixel 1 1 "$(color.white)" +b.setpixel 2 1 "$(color.black)" +echo "$(b.getpixel 0 0)" +b.to_s diff --git a/Task/Bitwise-IO/D/bitwise-io.d b/Task/Bitwise-IO/D/bitwise-io.d index cfcef91426..128493465a 100644 --- a/Task/Bitwise-IO/D/bitwise-io.d +++ b/Task/Bitwise-IO/D/bitwise-io.d @@ -1,5 +1,6 @@ import std.stdio: File; import core.stdc.stdio: FILE, fputc, fgetc; +import std.string: representation; /*********** Bitwise I/O, the file must be in binary mode, and its FILE* @@ -98,15 +99,16 @@ struct BitwiseFile { } nothrow ~this() { - detach(); + detach; } } void main() { // Demo code. import core.stdc.stdio: fopen, fclose; - import std.stdio; + import std.string: assumeUTF; + import std.stdio: writeln; - immutable data = cast(immutable(ubyte)[])"abcdefghijk".dup; + immutable data = "abcdefghijk".representation; enum n = data.length; // For each ubyte in data, write 7 bits skipping 1. @@ -127,5 +129,5 @@ void main() { // Demo code. fin.close(); // Should be the same chars as 'data'. - writeln(cast(string)result); + result.assumeUTF.writeln; } diff --git a/Task/Bitwise-operations/Babel/bitwise-operations-1.pb b/Task/Bitwise-operations/Babel/bitwise-operations-1.pb new file mode 100644 index 0000000000..ad3e53c29d --- /dev/null +++ b/Task/Bitwise-operations/Babel/bitwise-operations-1.pb @@ -0,0 +1,10 @@ +((main { (5 9) foo ! }) + +(foo { + ({cand} {cor} {cnor} {cxor} {cxnor} {cushl} {cushr} {cashr} {curol} {curor}) + { <- dup give -> + eval + %x nl <<} + each + give zap + cnot %x nl <<})) diff --git a/Task/Bitwise-operations/Babel/bitwise-operations-2.pb b/Task/Bitwise-operations/Babel/bitwise-operations-2.pb new file mode 100644 index 0000000000..e2b9e1f9a3 --- /dev/null +++ b/Task/Bitwise-operations/Babel/bitwise-operations-2.pb @@ -0,0 +1,11 @@ +1 +d +fffffff7 +c +fffffff3 +a00 +0 +0 +a00 +2800000 +fffffffa diff --git a/Task/Bitwise-operations/D/bitwise-operations.d b/Task/Bitwise-operations/D/bitwise-operations.d index d617fd75e4..383dd15714 100644 --- a/Task/Bitwise-operations/D/bitwise-operations.d +++ b/Task/Bitwise-operations/D/bitwise-operations.d @@ -1,4 +1,4 @@ -T rot(T)(in T x, in int shift) pure nothrow { +T rot(T)(in T x, in int shift) pure nothrow @nogc { return (x >>> shift) | (x << (T.sizeof * 8 - shift)); } diff --git a/Task/Bitwise-operations/Elena/bitwise-operations.elena b/Task/Bitwise-operations/Elena/bitwise-operations.elena index d4c1db44d0..e3309784b5 100644 --- a/Task/Bitwise-operations/Elena/bitwise-operations.elena +++ b/Task/Bitwise-operations/Elena/bitwise-operations.elena @@ -7,8 +7,8 @@ console write:x write:" or " write:y write:" = " writeLine:(x or:y). console write:x write:" xor " write:y write:" = " writeLine:(x xor:y). console write:"not " write:x write:" = " writeLine:(x not). - console write:x write:" shr " write:y write:" = " writeLine:(x shift:y). - console write:x write:" shl " write:y write:" = " writeLine:(x shift:(y negative)). + console write:x write:" shr " write:y write:" = " writeLine:(x shift &index:(y int)). + console write:x write:" shl " write:y write:" = " writeLine:(x shift &index:(y negative int)). ]. #symbol program = diff --git a/Task/Bitwise-operations/PHP/bitwise-operations.php b/Task/Bitwise-operations/PHP/bitwise-operations.php index 58bbadb916..141b568039 100644 --- a/Task/Bitwise-operations/PHP/bitwise-operations.php +++ b/Task/Bitwise-operations/PHP/bitwise-operations.php @@ -1,9 +1,15 @@ function bitwise($a, $b) { - echo '$a AND $b: ', $a & $b, "\n"; - echo '$a OR $b: ', $a | $b, "\n"; - echo '$a XOR $b: ', $a ^ $b, "\n"; - echo 'NOT $a: ', ~$a, "\n"; - echo '$a << $b: ', $a << $b, "\n"; // left shift - echo '$a >> $b: ', $a >> $b, "\n"; // arithmetic right shift + function zerofill($a,$b) { + if($a>=0) return $a>>$b; + if($b==0) return (($a>>1)&0x7fffffff)*2+(($a>>$b)&1); // this line shifts a 0 into the sign bit for compatibility, replace with "if($b==0) return $a;" if you need $b=0 to mean that nothing happens + return ((~$a)>>$b)^(0x7fffffff>>($b-1)); + + echo '$a AND $b: ' . $a & $b . '\n'; + echo '$a OR $b: ' . $a | $b . '\n'; + echo '$a XOR $b: ' . $a ^ $b . '\n'; + echo 'NOT $a: ' . ~$a . '\n'; + echo '$a << $b: ' . $a << $b . '\n'; // left shift + echo '$a >> $b: ' . $a >> $b . '\n'; // arithmetic right shift + echo 'zerofill($a, $b): ' . zerofill($a, $b) . '\n'; // logical right shift } diff --git a/Task/Bitwise-operations/PL-I/bitwise-operations.pli b/Task/Bitwise-operations/PL-I/bitwise-operations.pli index a57bff00e5..2e6e15dff4 100644 --- a/Task/Bitwise-operations/PL-I/bitwise-operations.pli +++ b/Task/Bitwise-operations/PL-I/bitwise-operations.pli @@ -3,8 +3,8 @@ k = iand(i,j); k = ior(i,j); k = inot(i,j); k = ieor(i,j); -k = ishl(i,n); /* unsigned shifts i left by n places. */ -k = ishr(i,n); /* unsigned shifts i right by n places. */ +k = isll(i,n); /* unsigned shifts i left by n places. */ +k = isrl(i,n); /* unsigned shifts i right by n places. */ k = lower2(i, n); /* arithmetic right shift i by n places. */ k = raise2(i, n); /* arithmetic left shift i by n places. */ @@ -17,3 +17,9 @@ u = s & t; /* logical and */ u = s | t; /* logical or */ u = ^ s; /* logical not */ u = s ^ t; /* exclusive or */ + +Built-in rotate functions are not available. +They can be readily implemented by the user, though: + +u = substr(s, length(s), 1) || substr(s, 1, length(s)-1); /* implements rotate right. */ +u = substr(s, 2) || substr(s, 1, 1); /* implements rotate left. */ diff --git a/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 new file mode 100644 index 0000000000..7eb25564d9 --- /dev/null +++ b/Task/Bitwise-operations/Perl-6/bitwise-operations.pl6 @@ -0,0 +1,28 @@ +constant MAXINT = uint.Range.max; +constant BITS = MAXINT.base(2).chars; + +# define rotate ops for the fun of it +multi sub infix:<⥁>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).rotate(b).reverse] } +multi sub infix:<⥀>(Int:D \a, Int:D \b) { :2[(a +& MAXINT).polymod(2 xx BITS-1).reverse.rotate(b)] } + +sub int-bits (Int $a, Int $b) { + say ''; + say_bit "$a", $a; + say ''; + say_bit "2's complement $a", +^$a; + say_bit "$a and $b", $a +& $b; + say_bit "$a or $b", $a +| $b; + say_bit "$a xor $b", $a +^ $b; + say_bit "$a unsigned shift right $b", ($a +& MAXINT) +> $b; + say_bit "$a signed shift right $b", $a +> $b; + say_bit "$a rotate right $b", $a ⥁ $b; + say_bit "$a shift left $b", $a +< $b; + say_bit "$a rotate left $b", $a ⥀ $b; +} + +int-bits(7,2); +int-bits(-65432,31); + +sub say_bit ($message, $value) { + printf("%30s: %{'0' ~ BITS}b\n", $message, $value +& MAXINT); +} diff --git a/Task/Bitwise-operations/REXX/bitwise-operations.rexx b/Task/Bitwise-operations/REXX/bitwise-operations.rexx index 5590015605..72bcc6df26 100644 --- a/Task/Bitwise-operations/REXX/bitwise-operations.rexx +++ b/Task/Bitwise-operations/REXX/bitwise-operations.rexx @@ -1,5 +1,5 @@ /*REXX program performs bitwise operations on integers: & | && ¬ «L »R */ -numeric digits 1000 /*be able to handle bit integers.*/ +numeric digits 1000 /*be able to handle big integers.*/ say center('decimal',9) center("value",9) center('bits',50) say copies('─',9) copies('─',9) copies('─',50) @@ -13,7 +13,6 @@ b = 3 ; call show b , 'B' /* show & tell B */ call show bNot(a) , '¬ A' /* not */ call show bShiftL(a,b) , 'A [«B]' /* shift left */ call show bShiftR(a,b) , 'A [»B]' /* shirt right */ - /*┌───────────────────────────────────────────────────────────────┐ │ Since REXX stores numbers (indeed, all values) as characters, │ │ it makes no sense to "rotate" a value, since there aren't any │ diff --git a/Task/Bitwise-operations/Scheme/bitwise-operations-1.ss b/Task/Bitwise-operations/Scheme/bitwise-operations-1.ss index 7d373deade..2ff1c8808f 100644 --- a/Task/Bitwise-operations/Scheme/bitwise-operations-1.ss +++ b/Task/Bitwise-operations/Scheme/bitwise-operations-1.ss @@ -1,3 +1,5 @@ +(import (rnrs arithmetic bitwise (6))) + (define (bitwise a b) (display (bitwise-and a b)) (newline) diff --git a/Task/Boolean-values/00DESCRIPTION b/Task/Boolean-values/00DESCRIPTION index 15155b6115..66ae9f6733 100644 --- a/Task/Boolean-values/00DESCRIPTION +++ b/Task/Boolean-values/00DESCRIPTION @@ -1,4 +1,5 @@ -Show how to represent the boolean states "true" and "false" in a language. If other objects represent "true" or "false" in conditionals, note it. +Show how to represent the boolean states "true" and "false" in a language. +If other objects represent "true" or "false" in conditionals, note it. ;Cf. * [[Logical operations]] diff --git a/Task/Boolean-values/00META.yaml b/Task/Boolean-values/00META.yaml index 659c8686af..3548159ac8 100644 --- a/Task/Boolean-values/00META.yaml +++ b/Task/Boolean-values/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Basic language learning diff --git a/Task/Boolean-values/Oberon-2/boolean-values.oberon-2 b/Task/Boolean-values/Oberon-2/boolean-values.oberon-2 new file mode 100644 index 0000000000..0c794e4152 --- /dev/null +++ b/Task/Boolean-values/Oberon-2/boolean-values.oberon-2 @@ -0,0 +1,6 @@ +VAR + a,b,c: BOOLEAN; +... + a := TRUE; + b := FALSE; + c := 1 > 2; diff --git a/Task/Boolean-values/PL-I/boolean-values-1.pli b/Task/Boolean-values/PL-I/boolean-values-1.pli new file mode 100644 index 0000000000..f64ec60ff3 --- /dev/null +++ b/Task/Boolean-values/PL-I/boolean-values-1.pli @@ -0,0 +1,3 @@ +Declare x bit(1); +x='1'b; /* True */ +x='0'b; /* False */ diff --git a/Task/Boolean-values/PL-I/boolean-values-2.pli b/Task/Boolean-values/PL-I/boolean-values-2.pli new file mode 100644 index 0000000000..94a3e59b10 --- /dev/null +++ b/Task/Boolean-values/PL-I/boolean-values-2.pli @@ -0,0 +1,11 @@ +*process source attributes xref macro or(!); + tf: proc options(main); + %Dcl true char; %true='''1''b'; + %Dcl false char; %false='''0''b'; + If true Then + Put Skip list('That''s true'); + If false Then + Put Skip List('ERROR'); + Else + Put Skip List('false was recognized'); + End; diff --git a/Task/Boolean-values/PL-I/boolean-values.pli b/Task/Boolean-values/PL-I/boolean-values.pli deleted file mode 100644 index 6d86fe38da..0000000000 --- a/Task/Boolean-values/PL-I/boolean-values.pli +++ /dev/null @@ -1 +0,0 @@ -true is '1'b and false is '0'b diff --git a/Task/Boolean-values/Vim-Script/boolean-values.vim b/Task/Boolean-values/Vim-Script/boolean-values.vim new file mode 100644 index 0000000000..a5b06dee66 --- /dev/null +++ b/Task/Boolean-values/Vim-Script/boolean-values.vim @@ -0,0 +1,5 @@ +if "foo" + echo "true" +else + echo "false" +endif diff --git a/Task/Box-the-compass/D/box-the-compass.d b/Task/Box-the-compass/D/box-the-compass-1.d similarity index 100% rename from Task/Box-the-compass/D/box-the-compass.d rename to Task/Box-the-compass/D/box-the-compass-1.d diff --git a/Task/Box-the-compass/D/box-the-compass-2.d b/Task/Box-the-compass/D/box-the-compass-2.d new file mode 100644 index 0000000000..3981fa8477 --- /dev/null +++ b/Task/Box-the-compass/D/box-the-compass-2.d @@ -0,0 +1,24 @@ +void main() { + import std.stdio; + + immutable box = [ + "North", "North by east", "North-northeast", "Northeast by north", + "Northeast", "Northeast by east", "East-northeast", "East by north", + "East", "East by south", "East-southeast", "Southeast by east", + "Southeast", "Southeast by south", "South-southeast", "South by east", + "South", "South by west", "South-southwest", "Southwest by south", + "Southwest", "Southwest by west", "West-southwest", "West by south", + "West", "West by north", "West-northwest", "Northwest by west", + "Northwest", "Northwest by north", "North-northwest", "North by west"]; + + immutable angles = [ + 0.0, 16.87, 16.88, 33.75, 50.62, 50.63, 67.5, 84.37, 84.38, + 101.25, 118.12, 118.13, 135.0, 151.87, 151.88, 168.75, 185.62, + 185.63, 202.5, 219.37, 219.38, 236.25, 253.12, 253.13, 270.0, + 286.87, 286.88, 303.75, 320.62, 320.63, 337.5, 354.37, 354.38]; + + foreach (immutable phi; angles) { + immutable i = (cast(int)(phi * 32.0 / 360.0 + 0.5)) % 32; + writefln("%2d %18s %6.2f", i + 1, box[i], phi); + } +} diff --git a/Task/Box-the-compass/OCaml/box-the-compass.ocaml b/Task/Box-the-compass/OCaml/box-the-compass.ocaml new file mode 100644 index 0000000000..43fb353352 --- /dev/null +++ b/Task/Box-the-compass/OCaml/box-the-compass.ocaml @@ -0,0 +1,31 @@ +let test_cases = [0.0; 16.87; 16.88; 33.75; 50.62; 50.63; 67.5; + 84.37; 84.38; 101.25; 118.12; 118.13; 135.0; + 151.87; 151.88; 168.75; 185.62; 185.63; 202.5; + 219.37; 219.38; 236.25; 253.12; 253.13; 270.0; + 286.87; 286.88; 303.75; 320.62; 320.63; 337.5; + 354.37; 354.38];; + +let directions = ["North"; "North by East"; "North-Northeast"; + "Northeast by North"; "Northeast"; + "Northeast by East"; "East-Northeast"; "East by North"; + "East"; "East by South"; "East-Southeast"; + "Southeast by East"; "Southeast"; "Southeast by South"; + "South-Southeast"; "South by East"; "South"; + "South by West"; "South-Southwest"; "Southwest by South"; + "Southwest"; "Southwest by West"; "West-Southwest"; + "West by South"; "West"; "West by North"; + "West-Northwest"; "Northwest by West"; "Northwest"; + "Northwest by North"; "North-Northwest"; "North by West";];; + +let get_direction_index input = + let shifted = (input +. 5.6201) in + let shifted = if shifted > 360. then shifted -. 360. else shifted in + int_of_float (shifted /. 11.25);; + +let print_direction input = + let index = get_direction_index input in + let direction = List.nth directions index in + let test = Printf.printf "%3d %-20s %.2f\n" (index + 1) direction in + test input;; + +List.iter (print_direction) test_cases;; diff --git a/Task/Box-the-compass/OoRexx/box-the-compass.rexx b/Task/Box-the-compass/OoRexx/box-the-compass.rexx new file mode 100644 index 0000000000..e6a76460fb --- /dev/null +++ b/Task/Box-the-compass/OoRexx/box-the-compass.rexx @@ -0,0 +1,259 @@ +/* Rexx */ + +Do + globs = '!DEG !MIN !SEC !FULL' + Drop !DEG !MIN !SEC !FULL + sign. = '' + sign.!DEG = 'c2b0'x -- degree sign : U+00B0 + sign.!MIN = 'e280b2'x -- prime : U+2032 + sign.!SEC = 'e280b3'x -- double prime : U+2033 + points. = '' + + Call display_compass_points + + Call display_sample + Say + + headings. = '' + headings.0 = 0 + Call make_headings + + Call flush_queue + Do h_ = 1 to headings.0 + Queue headings.h_ + End h_ + + Call display_sample + Say + + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +flush_queue: +Procedure +Do + Do q_ = 1 to queued() + Parse pull . + End q_ + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +display_sample: +Procedure Expose points. sign. (globs) +Do + + Do q_ = 1 to queued() + Parse pull heading + index = get_index(heading) + Parse Value get_point(index) with p_abbrev p_full + Say index~right(3), + p_abbrev~left(4) p_full~left(20), + heading~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(heading)')', + '' + End q_ + + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +display_compass_points: +Procedure Expose points. sign. (globs) +Do + + points = 32 + one_pt = 360 / points + + Do h_ = 0 to points - 1 + heading = h_ * 360 / points + hmin = heading - one_pt / 2 + hmax = heading + one_pt / 2 + + If hmin < 0 then Do + hmin = hmin + 360 + End + If hmax >= 360 then Do + hmax = hmax - 360 + End + + index = (h_ // points) + 1 + Parse Value get_point(index) with p_abbrev p_full + + Say index~right(3), + p_abbrev~left(4) p_full~left(20), + hmin~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(hmin)')', + heading~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(heading)')', + hmax~format(5, 3) || sign.!DEG '('format_degrees_minutes_seconds(hmax)')', + '' + End h_ + Say + + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +make_headings: +Procedure Expose headings. +Do + points = 32 + Do i_ = 0 to points + heading = i_ * 360 / 32 + + it = i_ // 3 + Select + When it = 1 then Do + heading_h = heading + 5.62 + End + + When it = 2 then Do + heading_h = heading - 5.62 + End + + Otherwise Do + heading_h = heading + End + End + + index = (i_ // points) + 1 + ix = headings.0 + 1; headings.0 = ix; headings.ix = heading_h + End i_ + + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +get_index: +Procedure +Do + Parse Arg heading . + + one_pt = 360 / 32 + hn = heading // 360 + hi = hn % one_pt + + If hn > hi * one_pt + one_pt / 2 then Do + hi = hi + 1 -- greater than max range for this point; bump to next point + End + + idx = hi // 32 + 1 -- add one to get index into points. stem + + Return idx +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +get_point: +Procedure Expose points. sign. (globs) +Do + Parse arg index . + + Call get_points + + Return points.index points.index.!FULL +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +get_points: +Procedure Expose points. sign. (globs) +Do + + Drop !FULL + + points. = '' + p_ = 0 + p_ = p_ + 1; points.0 = p_; points.p_ = 'N'; points.p_.!FULL = 'North' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NbE'; points.p_.!FULL = 'North by East' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NNE'; points.p_.!FULL = 'North-Northeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NEbn'; points.p_.!FULL = 'Northeast by North' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NE'; points.p_.!FULL = 'Northeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NEbE'; points.p_.!FULL = 'Northeast by East' + p_ = p_ + 1; points.0 = p_; points.p_ = 'ENE'; points.p_.!FULL = 'East-Northeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'EbN'; points.p_.!FULL = 'East by North' + p_ = p_ + 1; points.0 = p_; points.p_ = 'E'; points.p_.!FULL = 'East' + p_ = p_ + 1; points.0 = p_; points.p_ = 'EbS'; points.p_.!FULL = 'East by South' + p_ = p_ + 1; points.0 = p_; points.p_ = 'ESE'; points.p_.!FULL = 'East-Southeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SEbE'; points.p_.!FULL = 'Southeast by East' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SE'; points.p_.!FULL = 'Southeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SEbS'; points.p_.!FULL = 'Southeast by South' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SSE'; points.p_.!FULL = 'South-Southeast' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SbE'; points.p_.!FULL = 'South by East' + p_ = p_ + 1; points.0 = p_; points.p_ = 'S'; points.p_.!FULL = 'South' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SbW'; points.p_.!FULL = 'South by West' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SSW'; points.p_.!FULL = 'South-Southwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SWbS'; points.p_.!FULL = 'Southwest by South' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SW'; points.p_.!FULL = 'Southwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'SWbW'; points.p_.!FULL = 'Southwest by West' + p_ = p_ + 1; points.0 = p_; points.p_ = 'WSW'; points.p_.!FULL = 'Southwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'WbS'; points.p_.!FULL = 'West by South' + p_ = p_ + 1; points.0 = p_; points.p_ = 'W'; points.p_.!FULL = 'West' + p_ = p_ + 1; points.0 = p_; points.p_ = 'WbN'; points.p_.!FULL = 'West by North' + p_ = p_ + 1; points.0 = p_; points.p_ = 'WNW'; points.p_.!FULL = 'West-Northwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NWbW'; points.p_.!FULL = 'Northwest by West' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NW'; points.p_.!FULL = 'Northwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NWbN'; points.p_.!FULL = 'Northwest by North' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NNW'; points.p_.!FULL = 'North-Northwest' + p_ = p_ + 1; points.0 = p_; points.p_ = 'NbW'; points.p_.!FULL = 'North by West' + + Return +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +get_decimal_angle: +Procedure Expose sign. (globs) +Do + Parse Arg degrees ., minutes ., seconds . + + degrees = degrees * 10 % 10 + minutes = minutes * 10 % 10 + + angle = degrees + minutes / 60 + seconds / 60 / 60 + + Return angle +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +format_decimal_angle: +Procedure Expose sign. (globs) +Do + Parse Arg degrees ., minutes ., seconds . + + Return get_decimal_angle(degrees, minutes, seconds)~format(5, 3) || sign.!DEG +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +get_degrees_minutes_seconds: +Procedure Expose sign. (globs) +Do + Parse arg angle . + + degrees = angle * 100 % 100 + minutes = ((angle - degrees) * 60) * 100 % 100 + seconds = ((((angle - degrees) * 60) - minutes) * 60) * 100 % 100 + + Return degrees minutes seconds +End +Exit + +/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ +format_degrees_minutes_seconds: +Procedure Expose sign. (globs) +Do + Parse arg angle . + + Parse Value get_degrees_minutes_seconds(angle) with degrees minutes seconds . + + formatted = degrees~right(3) || sign.!DEG || minutes~right(2, 0) || sign.!MIN || seconds~right(2, 0) || sign.!SEC + + Return formatted +End +Exit diff --git a/Task/Break-OO-privacy/00DESCRIPTION b/Task/Break-OO-privacy/00DESCRIPTION index 751f03af42..b781e233e5 100644 --- a/Task/Break-OO-privacy/00DESCRIPTION +++ b/Task/Break-OO-privacy/00DESCRIPTION @@ -1,3 +1,19 @@ -Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. +{{omit from|AWK}} +{{omit from|BASIC}} +{{omit from|BBC BASIC}} +{{omit from|C}} +{{omit from|Déjà Vu}} +{{omit from|GUISS}} +{{omit from|Haskell}} +{{omit from|Locomotive Basic}} +{{omit from|Lotus 123 Macro Scripting}} +{{omit from|Mathematica}} +{{omit from|ZX Spectrum Basic}} -Note that cheating on your type system is almost universally regarded as unidiomatic at best, and poor programming practice at worst. Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off. +Show how to access private or protected members of a class in an object-oriented language from outside an instance of the class, without calling non-private or non-protected members of the class as a proxy. +The intent is to show how a debugger, serializer, or other meta-programming tool might access information that is barred by normal access methods to the object but can nevertheless be accessed from within the language by some provided escape hatch or reflection mechanism. +The intent is specifically not to demonstrate heroic measures such as peeking and poking raw memory. + +Note that cheating on your type system is almost universally regarded +as unidiomatic at best, and poor programming practice at worst. +Nonetheless, if your language intentionally maintains a double-standard for OO privacy, here's where you can show it off. diff --git a/Task/Break-OO-privacy/00META.yaml b/Task/Break-OO-privacy/00META.yaml new file mode 100644 index 0000000000..bf7ae2df8b --- /dev/null +++ b/Task/Break-OO-privacy/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Object oriented diff --git a/Task/Break-OO-privacy/Clojure/break-oo-privacy-1.clj b/Task/Break-OO-privacy/Clojure/break-oo-privacy-1.clj new file mode 100644 index 0000000000..684fd0c4ff --- /dev/null +++ b/Task/Break-OO-privacy/Clojure/break-oo-privacy-1.clj @@ -0,0 +1,7 @@ +(ns a) +(def ^:private priv :secret) + +; From REPL, in another namespace 'user': +user=> @a/priv ; fails with: IllegalStateException: var: a/priv is not public +user=> @#'a/priv ; succeeds +:secret diff --git a/Task/Break-OO-privacy/Clojure/break-oo-privacy-2.clj b/Task/Break-OO-privacy/Clojure/break-oo-privacy-2.clj new file mode 100644 index 0000000000..1c1811eac0 --- /dev/null +++ b/Task/Break-OO-privacy/Clojure/break-oo-privacy-2.clj @@ -0,0 +1,2 @@ +user=> (get-field Double "serialVersionUID" (Double/valueOf 1.0)) +-9172774392245257468 diff --git a/Task/Break-OO-privacy/Go/break-oo-privacy-1.go b/Task/Break-OO-privacy/Go/break-oo-privacy-1.go new file mode 100644 index 0000000000..3f9328b9dc --- /dev/null +++ b/Task/Break-OO-privacy/Go/break-oo-privacy-1.go @@ -0,0 +1,82 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "os" + "reflect" + "unsafe" +) + +type foobar struct { + Exported int // In Go identifiers that are capitalized are exported, + unexported int // while lowercase identifiers are not. +} + +func main() { + obj := foobar{12, 42} + fmt.Println("obj:", obj) + + examineAndModify(&obj) + fmt.Println("obj:", obj) + + anotherExample() +} + +// For simplicity this skips several checks. It assumes the thing in the +// interface is a pointer without checking (v.Kind()==reflect.Ptr), +// it then assumes it is a structure type with two int fields +// (v.Kind()==reflect.Struct, f.Type()==reflect.TypeOf(int(0))). +func examineAndModify(any interface{}) { + v := reflect.ValueOf(any) // get a reflect.Value + v = v.Elem() // dereference the pointer + fmt.Println(" v:", v, "=", v.Interface()) + t := v.Type() + // Loop through the struct fields + fmt.Printf(" %3s %-10s %-4s %s\n", "Idx", "Name", "Type", "CanSet") + for i := 0; i < v.NumField(); i++ { + f := v.Field(i) // reflect.Value of the field + fmt.Printf(" %2d: %-10s %-4s %t\n", i, + t.Field(i).Name, f.Type(), f.CanSet()) + } + + // "Exported", field 0, has CanSet==true so we can do: + v.Field(0).SetInt(16) + // "unexported", field 1, has CanSet==false so the following + // would fail at run-time with: + // panic: reflect: reflect.Value.SetInt using value obtained using unexported field + //v.Field(1).SetInt(43) + + // However, we can bypass this restriction with the unsafe + // package once we know what type it is (so we can use the + // correct pointer type, here *int): + vp := v.Field(1).Addr() // Take the fields's address + uip := vp.Pointer() // … get an int value of the address + up := unsafe.Pointer(uip) // … convert it "unsafely" + p := (*int)(up) // … and end up with what we want/need + fmt.Printf(" vp has type %-14T = %v\n", vp, vp) + fmt.Printf(" uip has type %-14T = %#0x\n", uip, uip) + fmt.Printf(" up has type %-14T = %#0x\n", up, up) + fmt.Printf(" p has type %-14T = %v pointing at %v\n", p, p, *p) + *p = 43 // effectively obj.unexported = 43 + // or an incr all on one ulgy line: + *(*int)(unsafe.Pointer(v.Field(1).Addr().Pointer()))++ +} + +// This time we'll use an external package to demonstrate that it's not +// restricted to things defined locally. We'll mess with bufio.Reader's +// interal workings by happening to know they have a non-exported +// "err error" field. Of course future versions of Go may not have this +// field or use it in the same way :). +func anotherExample() { + r := bufio.NewReader(os.Stdin) + + // Do the dirty stuff in one ugly and unsafe statement: + errp := (*error)(unsafe.Pointer( + reflect.ValueOf(r).Elem().FieldByName("err").Addr().Pointer())) + *errp = errors.New("unsafely injected error value into bufio inner workings") + + _, err := r.ReadByte() + fmt.Println("bufio.ReadByte returned error:", err) +} diff --git a/Task/Break-OO-privacy/Go/break-oo-privacy-2.go b/Task/Break-OO-privacy/Go/break-oo-privacy-2.go new file mode 100644 index 0000000000..1f5f38b3c2 --- /dev/null +++ b/Task/Break-OO-privacy/Go/break-oo-privacy-2.go @@ -0,0 +1,17 @@ +link printf + +procedure main() + (x := foo(1,2,3)).print() # create and show a foo + printf("Fieldnames of foo x : ") # show fieldnames + every printf(" %i",fieldnames(x)) # __s (self), __m (methods), vars + printf("\n") + printf("var 1 of foo x = %i\n", x.var1) # read var1 from outside x + x.var1 := -1 # change var1 from outside x + x.print() # show we changed it +end + +class foo(var1,var2,var3) # class with no set/read methods + method print() + printf("foo var1=%i, var2=%i, var3=%i\n",var1,var2,var3) + end +end diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m index 519c61fd95..962846293c 100644 --- a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-1.m @@ -4,14 +4,14 @@ @private NSString *_name; } -- (id)initWithName:(NSString *)name; +- (instancetype)initWithName:(NSString *)name; @end @implementation Example - (NSString *)description { return [NSString stringWithFormat:@"Hello, I am %@", _name]; } -- (id)initWithName:(NSString *)name { +- (instancetype)initWithName:(NSString *)name { if ((self = [super init])) { _name = [name copy]; } diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m index 0feb4058e9..6cf84f544b 100644 --- a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-2.m @@ -4,14 +4,14 @@ @private NSString *_name; } -- (id)initWithName:(NSString *)name; +- (instancetype)initWithName:(NSString *)name; @end @implementation Example - (NSString *)description { return [NSString stringWithFormat:@"Hello, I am %@", _name]; } -- (id)initWithName:(NSString *)name { +- (instancetype)initWithName:(NSString *)name { if ((self = [super init])) { _name = [name copy]; } diff --git a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m index 0e2840f7f7..340d42a828 100644 --- a/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m +++ b/Task/Break-OO-privacy/Objective-C/break-oo-privacy-3.m @@ -5,14 +5,14 @@ @private NSString *_name; } -- (id)initWithName:(NSString *)name; +- (instancetype)initWithName:(NSString *)name; @end @implementation Example - (NSString *)description { return [NSString stringWithFormat:@"Hello, I am %@", _name]; } -- (id)initWithName:(NSString *)name { +- (instancetype)initWithName:(NSString *)name { if ((self = [super init])) { _name = [name copy]; } diff --git a/Task/Break-OO-privacy/Scala/break-oo-privacy.scala b/Task/Break-OO-privacy/Scala/break-oo-privacy.scala new file mode 100644 index 0000000000..6fe708bd5f --- /dev/null +++ b/Task/Break-OO-privacy/Scala/break-oo-privacy.scala @@ -0,0 +1,22 @@ +class Example { + private var _name: String = null + + def this(name: String) { + this() + _name = name + } + + override def toString = "Hello, I am " + _name +} + +object BreakPrivacy extends App { + val foo: Example = new Example("Erik") + for (f <- classOf[Example].getDeclaredFields + if f.getName == "_name" + ) { + f.setAccessible(true) + println(f.get(foo)) + f.set(foo, "Edith") + println(foo) + } +} diff --git a/Task/Brownian-tree/D/brownian-tree.d b/Task/Brownian-tree/D/brownian-tree.d index d3e22b487f..85e9999bb9 100644 --- a/Task/Brownian-tree/D/brownian-tree.d +++ b/Task/Brownian-tree/D/brownian-tree.d @@ -1,12 +1,12 @@ -import core.stdc.stdio, std.random, grayscale_image; - -enum uint side = 600; // Square world side. -enum uint num_particles = 1_000; -static assert(side > 2 && num_particles < (side ^^ 2 * 0.7)); - void main() { - auto rng = Xorshift(unpredictableSeed); - ubyte[side][side] W; // World. + import core.stdc.stdio, std.random, grayscale_image; + + enum uint side = 600; // Square world side. + enum uint num_particles = 10_000; + static assert(side > 2 && num_particles < (side ^^ 2 * 0.7)); + + auto rng = unpredictableSeed.Xorshift; + ubyte[side][side] W; // World. W[side / 2][side / 2] = 1; // Set tree root. foreach (immutable _; 0 .. num_particles) { @@ -34,5 +34,5 @@ void main() { ubyte[] data = (&W[0][0])[0 .. side ^^ 2]; // Flat view. data[] += 255; - Image!ubyte.fromData(data, side,side).savePGM("brownian_tree.pgm"); + Image!ubyte.fromData(data, side, side).savePGM("brownian_tree.pgm"); } diff --git a/Task/Brownian-tree/Java/brownian-tree.java b/Task/Brownian-tree/Java/brownian-tree-1.java similarity index 100% rename from Task/Brownian-tree/Java/brownian-tree.java rename to Task/Brownian-tree/Java/brownian-tree-1.java diff --git a/Task/Brownian-tree/Java/brownian-tree-2.java b/Task/Brownian-tree/Java/brownian-tree-2.java new file mode 100644 index 0000000000..dcd5176e94 --- /dev/null +++ b/Task/Brownian-tree/Java/brownian-tree-2.java @@ -0,0 +1,90 @@ +import java.awt.Point; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; + +public class BasicBrownianTree { + + private int pixelsLost; + private Point p; + private Point nextP; + private int pixelCount; + private int width; + private int height; + private int color; + private BufferedImage img; + + public BasicBrownianTree( int argb, int size, double density ) { + pixelsLost = 0; + p = new Point(); + nextP = new Point(); + width = size; + height = size; + color = argb; + pixelCount = (int) ( width * height * density ); + img = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB ); + } + + public void generate() { + // print text to the console + System.out.println( "Drawing " + pixelCount + " pixels" ); + int background = img.getRGB( 0, 0 ); + img.setRGB( width / 2, height / 2, color ); + + for( int i = 0; i < pixelCount; i++ ) { + p.x = (int) ( Math.random() * width ); + p.y = (int) ( Math.random() * height ); + + while ( true ) { + int dx = (int) ( Math.random() * 3 ) - 1; + int dy = (int) ( Math.random() * 3 ) - 1; + nextP.setLocation( p.x + dx, p.y + dy ); + // handle out-of-bounds + if ( nextP.x < 0 || nextP.x >= width || nextP.y < 0 + || nextP.y >= height ) { + // increment the number of pixels lost and escape the loop + pixelsLost++; + break; + } + if ( img.getRGB( nextP.x, nextP.y ) != background ) { + img.setRGB( p.x, p.y, color ); + break; + } + p.setLocation( nextP ); + } + // Print a message every 2% + if ( i % ( pixelCount / 50 ) == 0 ) { + System.out.println( "Done with " + i + " pixels" ); + } + } + // We're done. Let the user know how many pixels were lost + System.out.println( "Finished. Pixels lost = " + pixelsLost ); + } + + public BufferedImage getImage() { + return img; + } + + public int getWidth() { + return width; + } + + public int getHeight() { + return height; + } + + public static void main( String[] args ) { + // create the new generator + BasicBrownianTree generator = new BasicBrownianTree( 0x664444ff, 400, 0.4 ); + // generate the image + generator.generate(); + try { + // save the image to the file "image.png" + ImageIO.write( generator.getImage(), "png", new File( "image.png" ) ); + } catch ( IOException e ) { + e.printStackTrace(); + } + } +} diff --git a/Task/Brownian-tree/REXX/brownian-tree.rexx b/Task/Brownian-tree/REXX/brownian-tree.rexx index 817748d5df..d0069c4493 100644 --- a/Task/Brownian-tree/REXX/brownian-tree.rexx +++ b/Task/Brownian-tree/REXX/brownian-tree.rexx @@ -1,38 +1,38 @@ -/*REXX program shows brownian motion of dust in a field with one seed. */ -parse arg height width motes . -if height=='' | height==',' then height=0 -if width=='' | width==',' then width=0 -if motes=='' then motes='10%' /*nn% Calculate # of dust motes.*/ - /* ... otherwise just the number.*/ -tree ='*' /*an affixed dust speck (tree). */ -mote ='fa'x /*char for a loose mote (of dust)*/ -empty=' ' /*char for an empty spot in field*/ -clearScr='CLS' /*(DOS?) command to clear screen.*/ -eons=1000000 /*time limit for browian movement*/ -snapshot=0 /*every n winks, show snapshot.*/ -snaptime=2 /*every n secs, show snapshot.*/ -seedPos=30 45 /*place seed in this field pos. */ -seedPos=0 /*if =0, use middle of the field.*/ - /*if -1, use random placement. */ +/*REXX program shows Brownian motion of dust in a field with one seed.*/ +parse arg height width motes randSeed . /*get args from the C.L. */ +if height=='' | height==',' then height=0 /*None? Use the default*/ +if width=='' | width==',' then width=0 /* " " " " */ +if motes=='' | motes==',' then motes='10%' /*% dust motes in field, */ + /* ··· otherwise just the number.*/ +tree = '*' /*an affixed dust speck (tree). */ +mote = '·' /*char for a loose mote (of dust)*/ +hole = ' ' /*char for an empty spot in field*/ +clearScr = 'CLS' /*(DOS?) command to clear screen.*/ +eons = 1000000 /* # cycles for Brownian movement*/ +snapshot = 0 /*every n winks, show snapshot.*/ +snaptime = 1 /*every n secs, show snapshot.*/ +seedPos = 30 45 /*place seed in this field pos. */ +seedPos = 0 /*if =0, use middle of the field.*/ + /*if -1, use a random placement. */ /*otherwise, place it at seedPos.*/ -randseed=0 /*set RANDSEED for repeatability.*/ -if randseed\==0 then call random ,,randseed /*set the 1st random num.*/ + /*set RANDSEED for repeatability.*/ +if datatype(randSeed,'W') then call random ,,randSeed /*if #, use it*/ + /* [↑] set the 1st random number*/ +if height==0 | width==0 then _=scrsize() /*not all REXXes have SCRSIZE.*/ +if height==0 then height=word(_,1)-3 /*adjust for border.*/ +if width==0 then width=word(_,2)-1 /* " " " */ -if height==0 | width==0 then _=scrsize() /*not all REXXes have SCRSIZE.*/ -if height==0 then height=word(_,1)-3 -if width==0 then width=word(_,2)-1 + seedAt=seedPos +if seedPos== 0 then seedAt=width%2 height%2 +if seedPos==-1 then seedAt=random(1,width) random(1,height) +parse var seedAt xs ys . /*obtain X & Y seed coördinates*/ + /* [↓] if right-most≡'%', use %.*/ +if right(motes,1)=='%' then motes=height * width * strip(motes,,'%') %100 +@.=hole /*create the field, all empty. */ - seedAt=seedPos -if seedPos== 0 then seedAt=width%2 height%2 -if seedPos==-1 then seedAt=random(1,width) random(1,height) -parse var seedAt xs ys . - -if right(motes,1)=='%' then motes=height*width*strip(motes,,'%')%100 -@.=empty /*create the field, all empty. */ - - do j=1 for motes /*sprinkle dust motes randomly. */ - rx=random(1, width); ry=random(1,height); @.rx.ry=mote - end /*j*/ + do j=1 for motes /*sprinkle # dust motes randomly.*/ + rx=random(1, width); ry=random(1,height); @.rx.ry=mote + end /*j*/ /* [↑] place a mote at random. */ /*plant the seed from which the */ /*tree will grow from dust motes */ @.xs.ys=tree /*that affixed themselves. */ @@ -41,16 +41,16 @@ tim=0 /*the time (in secs) of last show*/ loX=1; hiX= width /*used to optimize mote searching*/ loY=1; hiY=height /* " " " " " */ - /*═════════════════════════════soooo, this is brownian motion.*/ - do winks=1 for eons until \motion /*EONs is used just in case of ∞.*/ - motion=0 /*turn off brownian motion flag. */ - if snapshot \== 0 then if winks//snapshot==0 then call show - if snaptime \== 0 then do; t=time('S') - if t\==tim & t//snaptime==0 then do - tim=time('s') - call show - end - end + /*═════════════════════════════soooo, this is Brownian motion.*/ + do winks=1 for eons until \motion /*EONs is used instead of ∞. */ + motion=0 /*turn off Brownian motion flag. */ + if snapshot\==0 then if winks//snapshot==0 then call show + if snaptime\==0 then do; t=time('S') + if t\==tim & t//snaptime==0 then do + tim=time('s') + call show + end + end minX=loX; maxX=hiX /*as the tree grows, the search */ minY=loY; maxY=hiY /* for dust motes gets faster. */ loX= width; hiX=1 /*used to limit mote searching. */ @@ -58,8 +58,8 @@ loY=1; hiY=height /* " " " " " */ do x =minX to maxX; xm=x-1; xp=x+1 do y=minY to maxY; if @.x.y\==mote then iterate - if xhiX then hiX=x /*is faster than: hiX=max(X hiX) */ - if yhiY then hiY=y /*is faster than: hiY=max(y hiY) */ + if xhiX then hiX=x /*is faster than: hiX=max(X hiX) */ + if yhiY then hiY=y /*is faster than: hiY=max(y hiY) */ if @.xm.y ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ if @.xp.y ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ ym=y-1 @@ -70,39 +70,39 @@ loY=1; hiY=height /* " " " " " */ if @.x.yp ==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ if @.xm.yp==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ if @.xp.yp==tree then do; @.x.y=tree; iterate; end /*neighbor?*/ - motion=1 /*brownian motion is coming up. */ - xb=x+random(1,3)-2 /*apply brownian motion for X. */ - yb=y+random(1,3)-2 /*apply brownian motion for Y. */ - if @.xb.yb\==empty then iterate /*can the mote move there ? */ - @.x.y=empty /*"blank" out the old position. */ + motion=1 /* [↓] Brownian motion is coming.*/ + xb=x+random(1,3)-2 /* apply Brownian motion for X.*/ + yb=y+random(1,3)-2 /* " " " " Y.*/ + if @.xb.yb\==hole then iterate /*can mote actually move there ? */ + @.x.y=hole /*empty out the old mote position*/ @.xb.yb=mote /*move the mote (or possibly not)*/ - if xbhiX then hiX=min( width,xb) - if ybhiY then hiY=min(height,yb) - end /*y*/ + if xbhiX then hiX=min( width, xb) + if ybhiY then hiY=min(height, yb) + end /*y*/ /* [↑] limit the motes movement.*/ end /*x*/ - call crop + call crop /*crops/truncates the mote field.*/ end /*winks*/ call show exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────SHOW subroutine───────────────────────*/ -show: clearScr /*not necessary, but speeds it up*/ - do ys=height by -1 for height; aRow= - do xs=1 for width; aRow=aRow||@.xs.ys - end /*xs*/ - say aRow - end /*ys*/ -return /*────────────────────────────────CROP subroutine───────────────────────*/ -crop: if loX>1 & hiX1 & hiY1 & hiX1 & hiY [t[]]) - .filter!(a => a.sort().uniq.count == 4).array; + immutable d9 = "123456789"; + auto choices = cartesianProduct(d9, d9, d9, d9).map!(t => [t[]]) + .filter!(a => a.sort().uniq.count == 4).array; - do { - const ans = choices[uniform(0, $)]; - writef("My guess is %s. How many bulls and cows? ", ans); - immutable score = readln.filter!isDigit.map!q{ a - '0' }.array; - choices = choices.remove!(c => score != - [c.zip(ans).count!(p => p[0] == p[1]), - c.zip(ans).count!(p => p[0] != p[1] && ans.canFind(p[0]))]); - } while (choices.length > 1); + do { + const ans = choices[uniform(0, $)]; + writef("My guess is %s. How many bulls and cows? ", ans); + immutable score = readln.filter!isDigit.map!q{ a - '0' }.array; + choices = choices.remove!(c => score != + [c.zip(ans).count!(p => p[0] == p[1]), + c.zip(ans).count!(p => p[0] != p[1] && ans.canFind(p[0]))]); + } while (choices.length > 1); - if (choices.empty) - return "Nothing fits the scores you gave.".writeln; - writeln("Solution found: ", choices[0]); + if (choices.empty) + return "Nothing fits the scores you gave.".writeln; + writeln("Solution found: ", choices[0]); } diff --git a/Task/Bulls-and-cows-Player/MATLAB/bulls-and-cows-player.m b/Task/Bulls-and-cows-Player/MATLAB/bulls-and-cows-player.m new file mode 100644 index 0000000000..0684f5fdf8 --- /dev/null +++ b/Task/Bulls-and-cows-Player/MATLAB/bulls-and-cows-player.m @@ -0,0 +1,58 @@ +function BullsAndCowsPlayer +% Plays the game Bulls and Cows as the player + + % Generate list of all possible numbers + nDigits = 4; + lowVal = 1; + highVal = 9; + combs = nchoosek(lowVal:highVal, nDigits); + nCombs = size(combs, 1); + nPermsPerComb = factorial(nDigits); + gList = zeros(nCombs.*nPermsPerComb, nDigits); + for k = 1:nCombs + gList(nPermsPerComb*(k-1)+1:nPermsPerComb*k, :) = perms(combs(k, :)); + end + + % Prompt user + fprintf('Think of a number with:\n') + fprintf(' %d digits\n', nDigits) + fprintf(' Each digit between %d and %d inclusive\n', lowVal, highVal) + fprintf(' No repeated digits\n') + fprintf('I''ll try to guess that number and you score me:\n') + fprintf(' 1 Bull per correct digit in the correct place\n') + fprintf(' 1 Cow per correct digit in the wrong place\n') + fprintf('Think of your number and press Enter when ready\n') + pause + + % Play game until all digits are correct + nBulls = 0; + nGuesses = 0; + while nBulls < 4 && ~isempty(gList) + nList = size(gList, 1); + g = gList(randi(nList), :); % Random guess from list + fprintf('My guess: %s?\n', sprintf('%d', g)) + nBulls = input('How many bulls? '); + if nBulls < 4 + nCows = input('How many cows? '); + del = false(nList, 1); + for k = 1:nList + del(k) = any([nBulls nCows] ~= CountBullsCows(g, gList(k, :))); + end + gList(del, :) = []; + end + nGuesses = nGuesses+1; + end + if isempty(gList) + fprintf('That''s bull! You messed up your scoring.\n') + else + fprintf('Yay, I won! Only took %d guesses.\n', nGuesses) + end +end + +function score = CountBullsCows(guess, correct) +% Checks the guessed array of digits against the correct array to find the score +% Assumes arrays of same length and valid numbers + bulls = guess == correct; + cows = ismember(guess(~bulls), correct); + score = [sum(bulls) sum(cows)]; +end diff --git a/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx new file mode 100644 index 0000000000..65fcd8db72 --- /dev/null +++ b/Task/Bulls-and-cows-Player/REXX/bulls-and-cows-player.rexx @@ -0,0 +1,63 @@ +/*REXX pgm plays Bulls & Cows game with CBLFs (Carbon Based Life Forms).*/ +call gen@ /*generate all the possibilities.*/ +call # /*get the first guess for game. */ + + do tries=1 until #()<2 | bull==4; say + call prompter + do ?=L to H /*traipse through the whole list.*/ + if @.?==. then iterate /*was this already eliminated ? */ + call bull# ?,g /*obtain the bulls & cows count. */ + if bull\==bulls | cow\==cows then @.?=. /*eliminate it*/ + end /*?*/ + call # + end /*tries*/ + +if #==0 then do; call sayErr "At least one of your responses was invalid."; exit; end +pad=left('',9) +say; say pad " ┌─────────────────────────────────────────────────┐" + say pad " │ │" + say pad " │ Your secret Bulls and Cows number is: " g " │" + say pad " │ │" + say pad " └─────────────────────────────────────────────────┘"; say +say tries 'tries.' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines───────────────*/ +#: #=0; do k=L to H; if @.k==. then iterate; #=#+1; g=k; end; return # +gen@: @.=.; L=1234; H=9876; do j=L to H; if genOK() then @.j=j; end; return +genOK: if pos(0,j)\==0 then return 0; return \rep() +rep: do k=1 for 3; if pos(substr(j,k,1),j,k+1)\==0 then return 1; end; return 0 +sayErr: say; say pad '***error!*** ' em arg(1); return +/*──────────────────────────────────BULL# subroutine────────────────────*/ +bull#: parse arg n,q; L=length(n); bulls=0; cows=0 /*init. some vars*/ + + do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate + bulls=bulls+1 /*bump the bull count. */ + q=overlay(.,q,j) /*disallow this for a cow count. */ + end /*j*/ /* [↑] bull count───────────────*/ + + do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate + cows=cows+1 /*bump the cow count. */ + q=translate(q,,_) /*this allows for multiple digits*/ + end /*k*/ /* [↑] cow count───────────────*/ +return +/*──────────────────────────────────PROMPTER subroutine─────────────────*/ +prompter: pad='─────' /*define PAD chars for messages. */ + do forever; say + say pad "How many bulls and cows were guessed with " g '? [─── or QUIT]' + pull x 1 bull cow _ . /*PULL capitalizes the args.*/ + if abbrev('QUIT',x,1) then exit /*user wants to quit playing*/ + select + when bull=='' then em="no numbers were entered." + when cow =='' then em="not enough numbers were entered." + when _\=='' then em="too many numbers entered: " x + when \datatype(bull,'W') then em="1st number (bulls) not an integer: " bull + when \datatype(cow ,'W') then em="2nd number (cows) not an integer: " cow + when bull <0 | bull >4 then em="1st number (bulls) not 0──►4: " bull + when cow <0 | cow >4 then em="2nd number (cows) not 0──►4: " cow + when bull + cow > 4 then em="sum of bulls and cows can't be > 4: " x + otherwise em= + end /*select*/ + if em\=='' then do; call sayErr; iterate; end /*prompt user again.*/ + bull=bull/1; cow=cow/1 /*normalize the two answers. */ + return /*we've got two kosher numbers. */ + end /*forever*/ diff --git a/Task/Bulls-and-cows/D/bulls-and-cows.d b/Task/Bulls-and-cows/D/bulls-and-cows.d index 4aa2a16058..343f667819 100644 --- a/Task/Bulls-and-cows/D/bulls-and-cows.d +++ b/Task/Bulls-and-cows/D/bulls-and-cows.d @@ -1,17 +1,16 @@ void main() { import std.stdio, std.random, std.string, std.algorithm, - std.range, std.conv, std.ascii; + std.range, std.ascii; immutable hidden = "123456789"d.randomCover.take(4).array; while (true) { "Next guess: ".write; - immutable d = readln.strip.dtext; - if (d.count == 4 && d.all!isDigit && - d.dup.sort().uniq.count == 4) { - immutable bulls = d.zip(hidden).count!(p => p[0] == p[1]); + const d = readln.strip.array.sort().release; + if (d.count == 4 && d.all!isDigit && d.uniq.count == 4) { + immutable bulls = d.zip(hidden).count!q{ a[0] == a[1] }, + cows = d.count!(g => hidden.canFind(g)) - bulls; if (bulls == 4) return " You guessed it!".writeln; - immutable cows = d.count!(g => hidden.canFind(g)) - bulls; writefln("bulls %d, cows %d", bulls, cows); } " Bad guess! (4 unique digits, 1-9)".writeln; diff --git a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena index 92f8ca6b0d..db1e0f1436 100644 --- a/Task/Bulls-and-cows/Elena/bulls-and-cows.elena +++ b/Task/Bulls-and-cows/Elena/bulls-and-cows.elena @@ -5,6 +5,7 @@ #class GameMaster { #field theNumbers. + #field theAttempt. #constructor new [ @@ -12,11 +13,12 @@ #var aRandomNumbers := randomControl randomize:9 &array:(1,2,3,4,5,6,7,8,9). theNumbers := arrayControl Subarray:aRandomNumbers &from:0 &length:4. + theAttempt := Integer new:1. ] #method ask [ - #var aRow := consoleEx write:"Your Guess ?" readLine. + #var aRow := consoleEx write:"Your Guess #":theAttempt:" ?" readLine. ^ literalControl toArray:aRow. ] @@ -29,7 +31,7 @@ (aGuess length != 4) ? [ aBulls << -1. ] ! [ - control from:0 &to:3 &do: i + control forrange &int:0 &int:3 &do: (&int:i) [ #var ch := aGuess@i. #var aNumber := convertor toInt:(ch literal). @@ -39,7 +41,7 @@ ! [ #throw InvalidArgumentException new. ]. // check duplicates - #var duplicate := arrayControl seek:aGuess &until: x [ (x == ch)and:[ x equal &object:ch not ] ]. + #var duplicate := arrayControl seek:aGuess &until: x [ (x == ch)and:[ x equal &reference:ch not ] ]. nil != duplicate ? [ #throw InvalidArgumentException new. @@ -62,6 +64,8 @@ -1 ? [ consoleEx writeLine:"Not a valid guess.". ^ true. ] 4 ? [ consoleEx writeLine:"Congratulations! You have won!". ^ false. ] ! [ + theAttempt += 1. + consoleEx writeLine:"Your Score is " : aBulls : " bulls and " : aCows : " cows". ^ true. @@ -73,5 +77,5 @@ [ #var aGameMaster := GameMaster new. - control while:[ aGameMaster proceed:(aGameMaster ask). ]. + control while:[ aGameMaster proceed:(aGameMaster ask) ]. ]. diff --git a/Task/Bulls-and-cows/Go/bulls-and-cows.go b/Task/Bulls-and-cows/Go/bulls-and-cows.go new file mode 100644 index 0000000000..a4b59f82ad --- /dev/null +++ b/Task/Bulls-and-cows/Go/bulls-and-cows.go @@ -0,0 +1,68 @@ +package main + +import ( + "bufio" + "bytes" + "fmt" + "math/rand" + "os" + "strings" + "time" +) + +func main() { + fmt.Println(`Cows and Bulls +Guess four digit number of unique digits in the range 1 to 9. +A correct digit but not in the correct place is a cow. +A correct digit in the correct place is a bull.`) + // generate pattern + pat := make([]byte, 4) + rand.Seed(time.Now().Unix()) + r := rand.Perm(9) + for i := range pat { + pat[i] = '1' + byte(r[i]) + } + + // accept and score guesses + valid := []byte("123456789") +guess: + for in := bufio.NewReader(os.Stdin); ; { + fmt.Print("Guess: ") + guess, err := in.ReadString('\n') + if err != nil { + fmt.Println("\nSo, bye.") + return + } + guess = strings.TrimSpace(guess) + if len(guess) != 4 { + // malformed: not four characters + fmt.Println("Please guess a four digit number.") + continue + } + var cows, bulls int + for ig, cg := range guess { + if strings.IndexRune(guess[:ig], cg) >= 0 { + // malformed: repeated digit + fmt.Printf("Repeated digit: %c\n", cg) + continue guess + } + switch bytes.IndexByte(pat, byte(cg)) { + case -1: + if bytes.IndexByte(valid, byte(cg)) == -1 { + // malformed: not a digit + fmt.Printf("Invalid digit: %c\n", cg) + continue guess + } + default: // I just think cows should go first + cows++ + case ig: + bulls++ + } + } + fmt.Printf("Cows: %d, bulls: %d\n", cows, bulls) + if bulls == 4 { + fmt.Println("You got it.") + return + } + } +} diff --git a/Task/Bulls-and-cows/MATLAB/bulls-and-cows.m b/Task/Bulls-and-cows/MATLAB/bulls-and-cows.m new file mode 100644 index 0000000000..1b04574978 --- /dev/null +++ b/Task/Bulls-and-cows/MATLAB/bulls-and-cows.m @@ -0,0 +1,62 @@ +function BullsAndCows +% Plays the game Bulls and Cows as the "game master" + + % Create a secret number + nDigits = 4; + lowVal = 1; + highVal = 9; + digitList = lowVal:highVal; + secret = zeros(1, 4); + for k = 1:nDigits + idx = randi(length(digitList)); + secret(k) = digitList(idx); + digitList(idx) = []; + end + + % Give game information + fprintf('Welcome to Bulls and Cows!\n') + fprintf('Try to guess the %d-digit number (no repeated digits).\n', nDigits) + fprintf('Digits are between %d and %d (inclusive).\n', lowVal, highVal) + fprintf('Score: 1 Bull per correct digit in correct place.\n') + fprintf(' 1 Cow per correct digit in incorrect place.\n') + fprintf('The number has been chosen. Now it''s your moooooove!\n') + gs = input('Guess: ', 's'); + + % Loop until user guesses right or quits (no guess) + nGuesses = 1; + while gs + gn = str2double(gs); + if isnan(gn) || length(gn) > 1 % Not a scalar + fprintf('Malformed guess. Keep to valid scalars.\n') + gs = input('Try again: ', 's'); + else + g = sprintf('%d', gn) - '0'; + if length(g) ~= nDigits || any(g < lowVal) || any(g > highVal) || ... + length(unique(g)) ~= nDigits % Invalid number for game + fprintf('Malformed guess. Remember:\n') + fprintf(' %d digits\n', nDigits) + fprintf(' Between %d and %d inclusive\n', lowVal, highVal) + fprintf(' No repeated digits\n') + gs = input('Try again: ', 's'); + else + score = CountBullsCows(g, secret); + if score(1) == nDigits + fprintf('You win! Bully for you! Only %d guesses.\n', nGuesses) + gs = ''; + else + fprintf('Score: %d Bulls, %d Cows\n', score) + gs = input('Guess: ', 's'); + end + end + end + nGuesses = nGuesses+1; % Counts malformed guesses + end +end + +function score = CountBullsCows(guess, correct) +% Checks the guessed array of digits against the correct array to find the score +% Assumes arrays of same length and valid numbers + bulls = guess == correct; + cows = ismember(guess(~bulls), correct); + score = [sum(bulls) sum(cows)]; +end diff --git a/Task/Bulls-and-cows/MAXScript/bulls-and-cows-1.max b/Task/Bulls-and-cows/MAXScript/bulls-and-cows-1.max new file mode 100644 index 0000000000..694630b2c9 --- /dev/null +++ b/Task/Bulls-and-cows/MAXScript/bulls-and-cows-1.max @@ -0,0 +1,69 @@ +numCount = 4 -- number of digits to use + +digits = #(1, 2, 3, 4, 5, 6, 7, 8, 9) +num = "" +while num.count < numCount and digits.count > 0 do +( + local r = random 1 digits.count + append num (digits[r] as string) + deleteitem digits r +) +digits = undefined +numGuesses = 0 +inf = "Rules: \n1. Choose only % unique digits in any combination"+\ + " (0 can't be used).\n2. Only positive integers are allowed."+\ + "\n3. For each digit that is in it's place, you get a bull,\n"+\ + "\tand for each digit that is not in it's place, you get a cow."+\ + "\n4. The game is won when your number matches the number I chose."+\ + "\n\nPress [esc] to quit the game.\n\n" +clearlistener() +format inf num.count +while not keyboard.escpressed do +( + local userVal = getkbvalue prompt:"\nEnter your number: " + if (userVal as string) == num do + ( + format "\nCorrect! The number is %. It took you % moves.\n" num numGuesses + exit with OK + ) + local bulls = 0 + local cows = 0 + local badInput = false + case of + ( + (classof userVal != integer): + ( + format "\nThe number must be a positive integer.\n" + badInput = true + ) + ((userVal as string).count != num.count): + ( + format "\nThe number must have % digits.\n" num.count + badInput = true + ) + ((makeuniquearray (for i in 1 to (userVal as string).count \ + collect (userVal as string)[i])).count != (userVal as string).count): + ( + format "\nThe number can only have unique digits.\n" + badInput = true + ) + ) + if not badInput do + ( + userVal = userVal as string + i = 1 + while i <= userVal.count do + ( + for j = 1 to num.count do + ( + if userVal[i] == num[j] do + ( + if i == j then bulls += 1 else cows += 1 + ) + ) + i += 1 + ) + numGuesses += 1 + format "\nBulls: % Cows: %\n" bulls cows + ) +) diff --git a/Task/Bulls-and-cows/MAXScript/bulls-and-cows-2.max b/Task/Bulls-and-cows/MAXScript/bulls-and-cows-2.max new file mode 100644 index 0000000000..ffcbcbac87 --- /dev/null +++ b/Task/Bulls-and-cows/MAXScript/bulls-and-cows-2.max @@ -0,0 +1,20 @@ +OK +Rules: +1. Choose only 4 unique digits in any combination (0 can't be used). +2. Only positive integers are allowed. +3. For each digit that is in it's place, you get a bull, + and for each digit that is not in it's place, you get a cow. +4. The game is won when your number matches the number I chose. + +Press [esc] to quit the game. + +OK + +Enter your number: 2468 +Bulls: 0 Cows: 2 + +Enter your number: 2448 +The number can only have unique digits. + +Enter your number: 1357 +Bulls: 0 Cows: 1 diff --git a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx index e1a0c31dc1..54e65904ff 100644 --- a/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx +++ b/Task/Bulls-and-cows/REXX/bulls-and-cows-1.rexx @@ -1,43 +1,33 @@ -/*REXX pgm interactively plays a game of "Bulls & Cows" with CBLs. */ -/* [CBLs = Carbon Based Lifeforms.] */ -/* */ -/* This game is also known as: Cows and Bulls */ -/* Pigs and Bulls */ -/* Bulls and Cleots */ -/* MasterMind (or Master Mind) */ -/*══════════════════════════════════════════════════════════════════════*/ -?=''; do until length(?)==4 /*generate unique 4-digit number.*/ - r=random(1,9) /*change 1──►0 to allow a 0 dig*/ - if pos(r,?)\==0 then iterate /*don't allow a repeated digit. */ - ?=? || r - end /*until*/ +/*REXX pgm scores Bulls & Cows game with CBLFs (Carbon Based Life Forms)*/ +?=; do until length(?)==4 /*generate unique 4-digit number.*/ + r=random(1,9) /*change 1──►0 to allow a 0 dig*/ + if pos(r,?)\==0 then iterate /*don't allow a repeated digit. */ + ?=? || r /*add random dig by concatenation*/ + end /*until length··· */ /* [↑] builds a unique 4-digit #*/ -prompt='[Bulls & Cows game] ', /*build the prompt text string. */ - "Please enter a 4-digit guess (with no zeroes) [or Quit]:" + do until bulls==4; say /*play until guessed |enters QUIT*/ + say '───── [Bulls & Cows] Please enter a 4-digit guess (with no zeroes) [or Quit]:' + pull n; n=space(n,0); if abbrev('QUIT',n,1) then exit /*Quit ?*/ + q=?; L=length(n); bulls=0; cows=0 /*initialize some REXX variables.*/ - do until bulls==4 /*play until guessed |enters QUIT*/ - say prompt; pull n; n=space(n,0); if n=='' then iterate - if abbrev('QUIT',n,1) then exit /*Does the user want to quit now?*/ - g=?; L=length(n); bulls=0; cows=0 - /*bull count─────────────────────*/ - do j=1 for L; if substr(n,j,1)\==substr(g,j,1) then iterate - bulls=bulls+1 /*bump the bull count. */ - g=overlay(' ',g,j) /*disallow this for a cow count. */ - end /*j*/ - /*cow count─────────────────────*/ - do k=1 for L; x=substr(n,k,1); if pos(x,g)==0 then iterate - cows=cows+1 /*bump the cow count. */ - g=translate(g,,x) /*this allows for rule variants. */ - end /*k*/ + do j=1 for L; if substr(n,j,1)\==substr(q,j,1) then iterate + bulls=bulls+1 /*bump the bull count. */ + q=overlay(.,q,j) /*disallow this for a cow count. */ + end /*j*/ /* [↑] bull count───────────────*/ - if bulls\==4 then say "───── You got" bulls 'bull's(bulls) "and" cows 'cow's(cows)"." - end /*until bulls==4*/ + do k=1 for L; _=substr(n,k,1); if pos(_,q)==0 then iterate + cows=cows+1 /*bump the cow count. */ + q=translate(q,,_) /*this allows for multiple digits*/ + end /*k*/ /* [↑] cow count───────────────*/ + say + if L\==0 & bulls\==4 then say "───── You got" bulls 'bull's(bulls) "and" cows 'cow's(cows)"." + end /*until bulls···*/ say; say " ┌─────────────────────────────────────────┐" say " │ │" say " │ Congratulations, you've guessed it !! │" say " │ │" say " └─────────────────────────────────────────┘"; say -exit +exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)==1 then return ''; return 's' +s: if arg(1)==1 then return ''; return 's' /*handles plurals.*/ diff --git a/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb b/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb index 395b6185c8..94792331af 100644 --- a/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb +++ b/Task/Bulls-and-cows/Ruby/bulls-and-cows-2.rb @@ -1,32 +1,34 @@ -$size = 4 -$secret = [*'1' .. '9'].shuffle.first $size +size = 4 +secret = [*'1' .. '9'].sample(size) +guess = nil i=0 loop do i+=1 - loop do print "Guess #{i}: " - $guess = gets.chomp.chars.to_a - exit if $guess.empty? + guess = gets.chomp.chars + exit if guess.empty? - break if $guess.size == $size and - $guess.all? { |x| ('1'..'9').include? x } and - $guess.uniq.size == $size + 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" + puts "Problem, try again. You need to enter #{size} unique digits from 1 to 9" end - if $guess == $secret + 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] + size.times do |j| + if guess[j] == secret[j] + bulls += 1 + elsif secret.include? guess[j] + cows += 1 + end end puts "Bulls: #{bulls}; Cows: #{cows}" diff --git a/Task/Bulls-and-cows/Rust/bulls-and-cows.rust b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust index 50efff0678..8aafc2dab7 100644 --- a/Task/Bulls-and-cows/Rust/bulls-and-cows.rust +++ b/Task/Bulls-and-cows/Rust/bulls-and-cows.rust @@ -1,67 +1,45 @@ -use std::iter::range_inclusive; -use std::rand::{task_rng, Rng}; use std::io; -use std::str; -use std::option::collect; -use std::io::stdio::StdReader; -use std::str::from_char; -use std::iter::FromIterator; -use std::hashmap::HashSet; +use std::rand::{task_rng, Rng}; static NUMBER_OF_DIGITS: uint = 4; -static LOWEST_DIGIT: uint = 1; -static HIGHEST_DIGIT: uint = 9; -fn generate_digits() -> ~[uint] { - task_rng().sample(range_inclusive(LOWEST_DIGIT, HIGHEST_DIGIT), NUMBER_OF_DIGITS) +static DIGITS: [char, ..9] = ['1', '2', '3', '4', '5', '6', '7', '8', '9']; + +fn generate_digits() -> Vec { + let mut temp_digits = Vec::from_slice(DIGITS); + task_rng().shuffle(temp_digits.as_mut_slice()); + return temp_digits.iter().take(NUMBER_OF_DIGITS).map(|&a| a).collect(); } -fn read_input(reader: &mut StdReader) -> ~str { - let mut buf = [0u8, ..32]; - let num_bytes = reader.read(buf).unwrap(); - return str::from_utf8(buf).slice_to(num_bytes).trim().to_owned(); -} +fn parse_guess_string(guess: &String) -> Result, String> { + let chars: Vec = guess.as_slice().chars().collect(); -fn parse_guess_string(guess: &str) -> Option<~[uint]> { - let digit_chars = guess.chars(); - let digit_options = digit_chars.map(|c| from_str::(from_char(c))); - - // std::option::collect is a cool little function that goes through an iterator - // and returns a None if it hits a None. If not it will return a Some that - // contains a vector containing the unwrapped values of the iterator - let digits_maybe: Option<~[uint]> = collect(digit_options); - - match digits_maybe { - Some(ref digits) => { - if digits.len() != NUMBER_OF_DIGITS { - println!("you need to guess with {:u} digits", NUMBER_OF_DIGITS); - return None; - } - if digits.iter().any(|&digit| digit < LOWEST_DIGIT || digit > HIGHEST_DIGIT) { - println("digit out of range"); - return None; - } - let digits_set: HashSet<&uint> = FromIterator::from_iterator(&mut digits.iter()); - if digits_set.len() != NUMBER_OF_DIGITS { - println("no duplicates!"); - return None; - } - }, - None => println("non-numeric input, please try again") + if !chars.iter().all(|c| DIGITS.contains(c)) { + return Err("only digits, please".to_string()); } - return digits_maybe; + + if chars.len() != NUMBER_OF_DIGITS { + return Err(format!("you need to guess with {:u} digits", NUMBER_OF_DIGITS)); + } + + let mut uniques: Vec = chars.clone(); + uniques.dedup(); + if uniques.len() != chars.len() { + return Err("no duplicates, please".to_string()); + } + + return Ok(chars); } -fn calculate_score(digits: &[uint], guess: &[uint]) -> (uint, uint) { +fn calculate_score(given_digits: &Vec, guessed_digits: &Vec) -> (uint, uint) { let mut bulls = 0; let mut cows = 0; - for i in range(0, digits.len()) { - let mut j = guess.iter(); - let pos_maybe: Option = j.position(|&a| -> bool {a == digits[i]}); - match pos_maybe { - None => (), - Some(pos) if pos == i => bulls += 1, - Some(_) => cows += 1 + for i in range(0, NUMBER_OF_DIGITS) { + let pos: Option = guessed_digits.iter().position(|&a| -> bool {a == given_digits[i]}); + match pos { + None => (), + Some(p) if p == i => bulls += 1, + Some(_) => cows += 1 } } return (bulls, cows); @@ -71,20 +49,26 @@ fn main() { let mut reader = io::stdin(); loop { - let digits = generate_digits(); + let given_digits = generate_digits(); println!("I have chosen my {} digits. Please guess what they are", NUMBER_OF_DIGITS); + loop { - let guess_string = read_input(&mut reader); - let digits_maybe = parse_guess_string(guess_string); + + let guess_string = reader.read_line().unwrap().as_slice().trim().to_string(); + + let digits_maybe = parse_guess_string(&guess_string); match digits_maybe { - None => continue, - Some(guess_digits) => { - let (bulls, cows) = calculate_score(digits, guess_digits); - if bulls == NUMBER_OF_DIGITS { - println("you win!"); - break; - } else { - println!("bulls: {:u}, cows: {:u}", bulls, cows); + Err(msg) => { + println!("{}", msg); + continue; + }, + Ok(guess_digits) => { + match calculate_score(&given_digits, &guess_digits) { + (NUMBER_OF_DIGITS, _) => { + println!("you win!"); + break; + }, + (bulls, cows) => println!("bulls: {:u}, cows: {:u}", bulls, cows) } } } diff --git a/Task/Bulls-and-cows/Seed7/bulls-and-cows.seed7 b/Task/Bulls-and-cows/Seed7/bulls-and-cows.seed7 new file mode 100644 index 0000000000..f3f0b38c56 --- /dev/null +++ b/Task/Bulls-and-cows/Seed7/bulls-and-cows.seed7 @@ -0,0 +1,49 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + const integer: size is 4; + var set of char: digits is {'1' .. '9'}; + var string: chosen is " " mult size; + var integer: guesses is 0; + var string: guess is ""; + var integer: pos is 0; + var integer: bulls is 0; + var integer: cows is 0; + var boolean: okay is FALSE; + begin + for pos range 1 to 4 do + chosen @:= [pos] rand(digits); + excl(digits, chosen[pos]); + end for; + writeln("I have chosen a number from " <& size <& " unique digits from 1 to 9 arranged in a random order."); + writeln("You need to input a " <& size <& " digit, unique digit number as a guess at what I have chosen"); + repeat + incr(guesses); + repeat + write("Next guess [" <& guesses <& "]: "); + readln(guess); + okay := length(guess) = size; + for key pos range guess do + okay := okay and guess[pos] in {'1' .. '9'} and pos(guess[succ(pos) ..], guess[pos]) = 0; + end for; + if not okay then + writeln("Problem, try again. You need to enter " <& size <& " unique digits from 1 to 9"); + end if; + until okay; + if guess <> chosen then + bulls := 0; + cows := 0; + for key pos range chosen do + if guess[pos] = chosen[pos] then + incr(bulls); + elsif pos(chosen, guess[pos]) <> 0 then + incr(cows); + end if; + end for; + writeln(" " <& bulls <& " Bulls"); + writeln(" " <& cows <& " Cows"); + end if; + until guess = chosen; + writeln("Congratulations you guessed correctly in " <& guesses <& " attempts"); + end func; diff --git a/Task/CRC-32/00DESCRIPTION b/Task/CRC-32/00DESCRIPTION index 167bf56345..48d0bdd467 100644 --- a/Task/CRC-32/00DESCRIPTION +++ b/Task/CRC-32/00DESCRIPTION @@ -1,3 +1,10 @@ -Demonstrate a method of deriving the [[wp:Cyclic_Redundancy_Check|Cyclic Redundancy Check]] from within the language. The result should be in accordance with ISO 3309, [http://www.itu.int/rec/T-REC-V.42-200203-I/en ITU-T V.42], [http://tools.ietf.org/html/rfc1952 Gzip] and [http://www.w3.org/TR/2003/REC-PNG-20031110/ PNG]. Algorithms are described on [[wp:Computation of CRC|Computation of CRC]] in Wikipedia. This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. +{{omit from|GUISS}} +{{omit from|Lilypond}} +{{omit from|TPP}} + +Demonstrate a method of deriving the [[wp:Cyclic_Redundancy_Check|Cyclic Redundancy Check]] from within the language.
+The result should be in accordance with ISO 3309, [http://www.itu.int/rec/T-REC-V.42-200203-I/en ITU-T V.42], [http://tools.ietf.org/html/rfc1952 Gzip] and [http://www.w3.org/TR/2003/REC-PNG-20031110/ PNG].
+Algorithms are described on [[wp:Computation of CRC|Computation of CRC]] in Wikipedia. +This variant of CRC-32 uses LSB-first order, sets the initial CRC to FFFFFFFF16, and complements the final CRC. For the purpose of this task, generate a CRC-32 checksum for the ASCII encoded string "The quick brown fox jumps over the lazy dog" (without quotes). diff --git a/Task/CRC-32/00META.yaml b/Task/CRC-32/00META.yaml index 0b9ae97960..58add416f8 100644 --- a/Task/CRC-32/00META.yaml +++ b/Task/CRC-32/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Checksums note: Checksums diff --git a/Task/CRC-32/C++/crc-32-1.cpp b/Task/CRC-32/C++/crc-32-1.cpp index ada6e1de9d..943d8d7088 100644 --- a/Task/CRC-32/C++/crc-32-1.cpp +++ b/Task/CRC-32/C++/crc-32-1.cpp @@ -1,49 +1,61 @@ -#include -#include #include -#include #include #include +#include -class CRC32 +// These headers are only needed for main(), to demonstrate. +#include +#include +#include + +// Generates a lookup table for the checksums of all 8-bit values. +std::array generate_crc_lookup_table() noexcept { -public: - CRC32() + auto const reversed_polynomial = std::uint_fast32_t{0xEDB88320uL}; + + // This is a function object that calculates the checksum for a value, + // then increments the value, starting from zero. + struct byte_checksum + { + std::uint_fast32_t operator()() noexcept { - generateTable(); + auto checksum = static_cast(n++); + + for (auto i = 0; i < 8; ++i) + checksum = (checksum >> 1) ^ ((checksum & 0x1u) ? reversed_polynomial : 0); + + return checksum; } - 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]; } ); - } + unsigned n = 0; + }; -private: - void generateTable() - { - int nCount = 0; - // fill the table with 0..255 - std::generate( m_pTable.begin(), m_pTable.end(), [&nCount](){ return nCount++; } ); + auto table = std::array{}; + std::generate(table.begin(), table.end(), byte_checksum{}); - // 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); } ); - } - } + return table; +} -private: - std::array m_pTable; -}; +// Calculates the CRC for any sequence of values. (You could use type traits and a +// static assert to ensure the values can be converted to 8 bits.) +template +std::uint_fast32_t crc(InputIterator first, InputIterator last) +{ + // Generate lookup table only on first use then cache it - this is thread-safe. + static auto const table = generate_crc_lookup_table(); + + // Calculate the checksum - make sure to clip to 32 bits, for systems that don't + // have a true (fast) 32-bit type. + return std::uint_fast32_t{0xFFFFFFFFuL} & + ~std::accumulate(first, last, + ~std::uint_fast32_t{0} & std::uint_fast32_t{0xFFFFFFFFuL}, + [](std::uint_fast32_t checksum, std::uint_fast8_t value) + { return table[(checksum ^ value) & 0xFFu] ^ (checksum >> 8); }); +} 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; + auto const s = std::string{"The quick brown fox jumps over the lazy dog"}; + + std::cout << std::hex << std::setw(8) << std::setfill('0') << crc(s.begin(), s.end()) << '\n'; } diff --git a/Task/CRC-32/D/crc-32.d b/Task/CRC-32/D/crc-32.d index 90999818b3..b0e1402d1b 100644 --- a/Task/CRC-32/D/crc-32.d +++ b/Task/CRC-32/D/crc-32.d @@ -1,6 +1,6 @@ -import std.stdio, std.digest.crc; - void main() { + import std.stdio, std.digest.crc; + "The quick brown fox jumps over the lazy dog" - .crc32Of().crcHexString().writeln(); + .crc32Of.crcHexString.writeln; } diff --git a/Task/CRC-32/Oberon-2/crc-32.oberon-2 b/Task/CRC-32/Oberon-2/crc-32.oberon-2 new file mode 100644 index 0000000000..574c103ef7 --- /dev/null +++ b/Task/CRC-32/Oberon-2/crc-32.oberon-2 @@ -0,0 +1,11 @@ +MODULE CRC32; +IMPORT + NPCT:Zlib, + Strings, + Out; +VAR + s: ARRAY 128 OF CHAR; +BEGIN + COPY("The quick brown fox jumps over the lazy dog",s); + Out.Hex(Zlib.CRC32(0,s,0,Strings.Length(s)),0);Out.Ln +END CRC32. diff --git a/Task/CRC-32/PicoLisp/crc-32.l b/Task/CRC-32/PicoLisp/crc-32.l new file mode 100644 index 0000000000..01499650f3 --- /dev/null +++ b/Task/CRC-32/PicoLisp/crc-32.l @@ -0,0 +1,27 @@ +(setq *Table + (mapcar + '((N) + (do 8 + (setq N + (if (bit? 1 N) + (x| (>> 1 N) `(hex "EDB88320")) + (>> 1 N) ) ) ) ) + (range 0 255) ) ) + +(de crc32 (Lst) + (let Crc `(hex "FFFFFFFF") + (for I (chop Lst) + (setq Crc + (x| + (get + *Table + (inc (x| (& Crc 255) (char I))) ) + (>> 8 Crc) ) ) ) + (x| `(hex "FFFFFFFF") Crc) ) ) + +(let Str "The quick brown fox jumps over the lazy dog" + (println (hex (crc32 Str))) + (println + (hex (native "libz.so" "crc32" 'N 0 Str (length Str))) ) ) + +(bye) diff --git a/Task/CRC-32/REXX/crc-32.rexx b/Task/CRC-32/REXX/crc-32.rexx index f0ef5c2417..50da774811 100644 --- a/Task/CRC-32/REXX/crc-32.rexx +++ b/Task/CRC-32/REXX/crc-32.rexx @@ -1,34 +1,37 @@ /*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].*/ -call show "The quick brown fox jumps over the lazy dog" -call show 'Generate CRC32 Checksum For Byte Array Example' +/*──────────────────────────────────────────────────────────────────────*/ +call show 'The quick brown fox jumps over the lazy dog' /*1st str*/ +call show 'Generate CRC32 Checksum For Byte Array Example' /*2nd str*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SHOW subroutine─────────────────────*/ -show: procedure; parse arg Xstring; numeric digits 12; say; say -checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC*/ -say center(' input string [length of' length(Xstring) "bytes] ", 79, '─') -say Xstring /*show the string on its own line*/ -say -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*/ -return /*──────────────────────────────────CRC_32 subroutine───────────────────*/ -CRC_32: procedure; parse arg !,$ /*2nd arg is for multi-invokes. */ +CRC_32: procedure; parse arg !,$ /*2nd arg: repeated─invocations.*/ + /* [↓] build 8─bit indexed table*/ + do i=0 for 256; z=d2c(i) /* one byte at a time. */ + r=right(z, 4, '0'x) /*insure the "R" is 32 bits. */ - do i=0 for 256; 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*/ - !.z=r - end /*i*/ + 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 /*assign to an 8─bit index table.*/ + 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*/ + ?=bitxor(right($, 1), substr(!, k, 1)) + $=bitxor('0'x || left($, 3), !.?) + end /*k*/ return $ /*return with da money to invoker*/ +/*──────────────────────────────────SHOW subroutine─────────────────────*/ +show: procedure; parse arg Xstring; numeric digits 12; say; say +checksum=CRC_32(Xstring) /*invoke CRC_32 to create a CRC*/ +checksum=bitxor(checksum,'ffFFffFF'x) /*final convolution for checksum.*/ +say center(' input string [length of' length(Xstring) "bytes] ", 79, '═') +say Xstring /*show the string on its own line*/ +say /* ↓↓↓↓↓↓↓↓↓↓↓↓ is 15 blanks.*/ +say 'hex CRC-32 checksum =' c2x(checksum) left('', 15), + "dec CRC-32 checksum =" c2d(checksum) /*show CRC-32 in hex & dec.*/ +return diff --git a/Task/CSV-to-HTML-translation/00DESCRIPTION b/Task/CSV-to-HTML-translation/00DESCRIPTION index 309283211c..b8ec827980 100644 --- a/Task/CSV-to-HTML-translation/00DESCRIPTION +++ b/Task/CSV-to-HTML-translation/00DESCRIPTION @@ -1,12 +1,12 @@ -Consider a simplified CSV format where all rows are separated by a -newline and all columns are separated by commas. No commas are -allowed as field data, but the data may contain other characters -and character sequences that would normally be escaped when -converted to HTML +Consider a simplified CSV format where all rows are separated by a newline +and all columns are separated by commas. +No commas are allowed as field data, but the data may contain +other characters and character sequences that would +normally be escaped when converted to HTML The task is to create a function that takes a string representation of the CSV data -and returns a text string of an HTML table representing the CSV data. Use the following -data as the CSV text to convert, and show your output. +and returns a text string of an HTML table representing the CSV data. +Use the following data as the CSV text to convert, and show your output. :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! @@ -14,5 +14,6 @@ data as the CSV text to convert, and show your output. :Brians mother,I'm his mother; that's who! :The multitude,Behold his mother! Behold his mother! -For extra credit, ''optionally'' allow special formatting for the -first row of the table as if it is the tables header row (via preferably; CSS if you must). +For extra credit, ''optionally'' allow special formatting +for the first row of the table as if it is the tables header row +(via preferably; CSS if you must). diff --git a/Task/CSV-to-HTML-translation/D/csv-to-html-translation-1.d b/Task/CSV-to-HTML-translation/D/csv-to-html-translation-1.d index 34b41bff97..507f53bcd2 100644 --- a/Task/CSV-to-HTML-translation/D/csv-to-html-translation-1.d +++ b/Task/CSV-to-HTML-translation/D/csv-to-html-translation-1.d @@ -1,34 +1,37 @@ -import std.stdio; - -dstring input = - "Character,Speech\n" - "The multitude,The messiah! Show us the messiah!\n" - "Brians mother,Now you listen here! He's not the messiah; " - "he's a very naughty boy! Now go away!\n" - "The multitude,Who are you?\n" - "Brians mother,I'm his mother; that's who!\n" - "The multitude,Behold his mother! Behold his mother!"; - void main() { - bool theadDone; - write("\n\n\n\n"); - write("\n\n \n\n
"); - foreach (c; input) { + import std.stdio; + + immutable input = + "Character,Speech\n" ~ + "The multitude,The messiah! Show us the messiah!\n" ~ + "Brians mother,Now you listen here! He's not the messiah; " ~ + "he's a very naughty boy! Now go away!\n" ~ + "The multitude,Who are you?\n" ~ + "Brians mother,I'm his mother; that's who!\n" ~ + "The multitude,Behold his mother! Behold his mother!"; + + "\n\n\n\n".write; + "\n\n \n \n\n\n \n \n\n\n \n\n
".write; + + bool theadDone = false; + + foreach (immutable c; input) { switch(c) { case '\n': - if (theadDone) - write("
"); - else { - write("
"); + if (theadDone) { + "
".write; + } else { + "
".write; theadDone = true; } break; - case ',': write(""); break; - case '<': write("<"); break; - case '>': write(">"); break; - case '&': write("&"); break; - default: write(c); + case ',': "".write; break; + case '<': "<".write; break; + case '>': ">".write; break; + case '&': "&".write; break; + default: c.write; break; } } - write("
\n\n"); + + "
\n\n".write; } diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js index 48a36f60a0..216911471c 100644 --- a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-1.js @@ -5,26 +5,14 @@ var csv = "Character,Speech\n" + "Brians mother,I'm his mother; that's who!\n" + "The multitude,Behold his mother! Behold his mother!"; -csv = csv.replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); +var lines = csv.replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .split(/[\n\r]/) + .map(function(line) { return line.split(',')}) + .map(function(row) {return '\t\t' + row[0] + '' + row[1] + '';}); -var lines = csv.split(/[\n\r]+/g), - header = lines.shift().split(","), - line, - rows = "", - thead = ''+ - ''+header[0]+''+ - ''+header[1]+''+ - '\n'; - -for (var i=0, len=lines.length; i'+line[0]+''+ - ''+line[1]+''+ - '\n'; -} - -console.log('\n' + thead + '\n' + rows + '
' ); +console.log('\n\t\n' + lines[0] + + '\n\t\n\t\n' + lines.slice(1).join('\n') + + '\t\n
'); diff --git a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-2.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-2.js index 812deb6489..805ca24553 100644 --- a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-2.js +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-2.js @@ -1,9 +1,12 @@ - - - - - - - - -
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!
+ + + + + + + + + + + +
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/JavaScript/csv-to-html-translation-3.js b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-3.js index 2e07b4825f..8f29353460 100644 --- a/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-3.js +++ b/Task/CSV-to-HTML-translation/JavaScript/csv-to-html-translation-3.js @@ -1,20 +1,11 @@ -function csv_to_table(s) { - function ce(t) { return document.createElement(t); } - function ap(t) { document.body.appendChild(t); } - var t = ce('table'), f = 0; //1; - s.split('\n').map(function(l) { - var r = ce(f ? 'tr': 'thead'); - l.split(',').map(function (w) { - var c = ce(f ? 'td' : 'th'); - c.textContent = w; - r.appendChild(c); - }); - t.appendChild(r); - f = 1; //0; - }); - //return t.innerHTML; - return t.outerHTML; -} -/* -but also with this changes is very dependent by javascript engine and/or browser version (in: IE>=9, chrome ) -*/ + + + + + + + + + + +
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/Mathematica/csv-to-html-translation.math b/Task/CSV-to-HTML-translation/Mathematica/csv-to-html-translation.math index c8c23ec897..fa580fa292 100644 --- a/Task/CSV-to-HTML-translation/Mathematica/csv-to-html-translation.math +++ b/Task/CSV-to-HTML-translation/Mathematica/csv-to-html-translation.math @@ -14,23 +14,3 @@ StringSplit[StringReplace[a,{","->"","<"->"<",">"->">"}],"\n"]//F ,Map[StringJoin["",#,"\n"]&, StringSplit[StringReplace[a,{","->"","<"->"<",">"->">"}],"\n"]//Rest] ,""] - -Output: - - - - - - - - -
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!
- - - - - - - - -
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/Maxima/csv-to-html-translation-1.maxima b/Task/CSV-to-HTML-translation/Maxima/csv-to-html-translation-1.maxima index 05091247a1..66d3e9fa3e 100644 --- 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 @@ -5,19 +5,16 @@ outstream: openw(outfile); printf(outstream, "~%"); nr: 0; -unless (line: readline(instream), line=false) do ( +while (line: readline(instream))#false do ( nr: nr + 1, line: ssubst("<", "<", line), line: ssubst(">", ">", line), - q: map(lambda([f], strim(" ", f)), split(line, ",")), + value_list: 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]) - ), + for value in value_list do printf(outstream, "", value), printf(outstream, ""), - if nr=1 then printf(outstream, "~%") else printf(outstream, "~%") - ); + if nr=1 then printf(outstream, "~%") else printf(outstream, "~%")); printf(outstream, "
~a~a
~%"); close(instream); diff --git a/Task/CSV-to-HTML-translation/Oberon-2/csv-to-html-translation.oberon-2 b/Task/CSV-to-HTML-translation/Oberon-2/csv-to-html-translation.oberon-2 new file mode 100644 index 0000000000..c04966bc37 --- /dev/null +++ b/Task/CSV-to-HTML-translation/Oberon-2/csv-to-html-translation.oberon-2 @@ -0,0 +1,72 @@ +MODULE CSV2HTML; +IMPORT + Object, + IO, + IO:FileChannel, + IO:TextRider, + SB := ADT:StringBuffer, + NPCT:Tools, + NPCT:CGI:Utils, + Ex := Exception, + Out; +VAR + fileChannel: FileChannel.Channel; + rd: TextRider.Reader; + line: ARRAY 1024 OF CHAR; + table: SB.StringBuffer; + parts: ARRAY 2 OF STRING; + + PROCEDURE DoTableHeader(sb: SB.StringBuffer;parts: ARRAY OF STRING); + BEGIN + sb.Append(""+Utils.EscapeHTML(parts[0])+""+Utils.EscapeHTML(parts[1])+""); + sb.AppendLn + END DoTableHeader; + + PROCEDURE DoTableRow(sb: SB.StringBuffer;parts: ARRAY OF STRING); + BEGIN + sb.Append(""+Utils.EscapeHTML(parts[0])+""+Utils.EscapeHTML(parts[1])+""); + sb.AppendLn + END DoTableRow; + + PROCEDURE DoTable(sb: SB.StringBuffer): STRING; + VAR + aux: SB.StringBuffer; + BEGIN + aux := SB.New("");aux.AppendLn; + RETURN aux.ToString() + sb.ToString() + "
"; + END DoTable; + +BEGIN + TRY + fileChannel := FileChannel.OpenUnbuffered("script.csv",{FileChannel.read}); + CATCH Ex.Exception(ex): + Out.Object(ex.GetMessage());Out.Ln; + HALT(1) + END; + rd := TextRider.ConnectReader(fileChannel); + (* Extract headers *) + TRY + rd.ReadLine(line); + table := NEW(SB.StringBuffer,2048); + Tools.Split(Object.NewLatin1(line),",",parts); + DoTableHeader(table,parts); + CATCH IO.Error(ex): + Out.Object(ex.Name() + ": " + ex.GetMessage());Out.Ln; + HALT(2) + END; + + (* Extract data *) + LOOP + TRY + rd.ReadLine(line); + IF (line[0] # 0X)THEN (* skip empty lines *) + Tools.Split(Object.NewLatin1(line),",",parts); + DoTableRow(table,parts) + END + CATCH IO.Error(ex): + EXIT + END + END; + Out.Object(DoTable(table));Out.Ln; + fileChannel.Close() +END CSV2HTML. diff --git a/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx new file mode 100644 index 0000000000..718c9ae479 --- /dev/null +++ b/Task/CSV-to-HTML-translation/REXX/csv-to-html-translation.rexx @@ -0,0 +1,36 @@ +/*REXX program to convert CSV ───► HTML table representing the CSV data.*/ +arg header_ . /*see if the user wants a header.*/ +wantsHdr= (header_=='HEADER') /*arg (low/upp/mix case)=HEADER ?*/ + + iFID= 'CSV_HTML.TXT' /*the input fileID. */ +if wantsHdr then oFID= 'OUTPUTH.HTML' /*output fileID with header, */ + else oFID= 'OUTPUT.HTML' /* " " without header. */ + + do rows=0 while lines(iFID)\==0 /*read the rows from a (txt) file*/ + row.rows=strip(linein(iFID)) + end /*rows*/ + +convFrom= '& < > "' /*special characters to convert. */ +convTo = '& < > "' /*what they are converted into. */ + +call write , '' +call write , '' + + do j=0 for rows; call write 5, '' + tx='td' + if wantsHdr & j==0 then tx='th' + + do while row.j\==''; parse var row.j yyy ',' row.j + do k=1 for words(convFrom) + yyy=changestr(word(convFrom,k),yyy,word(convTo,k)) + end /*k*/ + call write 10, '<'tx">"yyy'" + end /*forever*/ + end /*j*/ + +call write 5, '' +call write , '
' +call write , '' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────WRITE subroutine────────────────────*/ +write: call lineout oFID, left('', 0 || arg(1))arg(2); return diff --git a/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-1.scala b/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-1.scala index 62e12d1c9c..78ab05a4f3 100644 --- a/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-1.scala +++ b/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-1.scala @@ -1,35 +1,42 @@ -import scala.xml.Utility - - val header = - """ - -Csv2Html - - - """ - -def csv2html(csv:String, withHead:Boolean) = { - - def processRow = "" ++ (_:String).split(',').flatMap("" + Utility.escape(_) + "") ++ "" - - val (first::rest) = csv.lines.toList - - val tableHead = if (withHead) s"${processRow(first)}\n" else processRow(first) - - val tableContent = tableHead + rest.map(processRow).mkString("\n") - - s"$header$tableContent
" -} - +object CsvToHTML extends App { + val header = + CsvToHTML + + val 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!""" + """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!""".stripMargin -csv2html(csv, true) + def csv2html(csv: String, withHead: Boolean) = { + + def processRow(text: String) = + {text.split(',').map(s => + {s} + )} + + + val (first :: rest) = csv.lines.toList // Separate the header and the rest + + def tableHead = if (withHead) + + {processRow(first)} + + else processRow(first) + + + {header} + + {tableHead}{rest.map(processRow)} +
+ + + } + + println(csv2html(csv, true)) +} diff --git a/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-2.scala b/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-2.scala index 24c8274147..7aac06da93 100644 --- a/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-2.scala +++ b/Task/CSV-to-HTML-translation/Scala/csv-to-html-translation-2.scala @@ -1,13 +1,50 @@ - -Csv2Html - - - - - - -
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!
+ + CsvToHTML + + + + + + + + + + + + + + + + + + +
+ Character + + Speech +
+ The multitude + + The 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 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/UNIX-Shell/csv-to-html-translation-1.sh b/Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-1.sh new file mode 100644 index 0000000000..8b47e49b57 --- /dev/null +++ b/Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-1.sh @@ -0,0 +1,42 @@ +csv2html() { + IFS=, + echo "" + + echo "" + read -r speaker text + htmlrow "$speaker" "$text" th + echo "" + + echo "" + while read -r speaker text; do + htmlrow "$speaker" "$text" + done + echo "" + echo "
" +} + +htmlrow() { + cell=${3:-td} + printf "<%s>%s<%s>%s\n" \ + "$cell" "$(escape_html "$1")" "$cell" \ + "$cell" "$(escape_html "$2")" "$cell" +} + +escape_html() { + str=${1//\&/&} + str=${str///>} + echo "$str" +} + +html=$( + csv2html <<-END + 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! + END +) +echo "$html" diff --git a/Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-2.sh b/Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-2.sh new file mode 100644 index 0000000000..509d30afe9 --- /dev/null +++ b/Task/CSV-to-HTML-translation/UNIX-Shell/csv-to-html-translation-2.sh @@ -0,0 +1,12 @@ + + + + + + + + + + + +
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/Caesar-cipher/00DESCRIPTION b/Task/Caesar-cipher/00DESCRIPTION index 2b245252fc..eba31cd869 100644 --- a/Task/Caesar-cipher/00DESCRIPTION +++ b/Task/Caesar-cipher/00DESCRIPTION @@ -1,3 +1,11 @@ -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. +Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding.
+The key is an integer from 1 to 25. -Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13. +This cipher rotates (either towards left or right) 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 a key of length 1.
+Also, [[Rot-13]] is identical to Caesar cipher with key 13. diff --git a/Task/Caesar-cipher/00META.yaml b/Task/Caesar-cipher/00META.yaml index fdbbfe89ad..380ea4e089 100644 --- a/Task/Caesar-cipher/00META.yaml +++ b/Task/Caesar-cipher/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- String manipulation note: Encryption diff --git a/Task/Caesar-cipher/Babel/caesar-cipher.pb b/Task/Caesar-cipher/Babel/caesar-cipher.pb new file mode 100644 index 0000000000..1652654876 --- /dev/null +++ b/Task/Caesar-cipher/Babel/caesar-cipher.pb @@ -0,0 +1,52 @@ +((main + {"The quick brown fox jumps over the lazy dog.\n" + dup << + + 17 caesar_enc ! + dup << + + 17 caesar_dec ! + <<}) + +(caesar_enc + { 2 take + { caesar_enc_loop ! } + nest }) + +(caesar_enc_loop { + give + <- str2ar + {({ dup is_upper ! } + { 0x40 - + -> dup <- + encrypt ! + 0x40 + } + { dup is_lower ! } + { 0x60 - + -> dup <- + encrypt ! + 0x60 + } + { 1 } + {fnord}) + cond} + eachar + collect ! + ls2lf ar2str}) + +(collect { -1 take }) + +(encrypt { + 1 - 26 % 1 + }) + +(caesar_dec { <- 26 -> - caesar_enc ! }) + +(is_upper + { dup + <- 0x40 cugt -> + 0x5b cult + cand }) + +(is_lower + { dup + <- 0x60 cugt -> + 0x7b cult + cand })) diff --git a/Task/Caesar-cipher/D/caesar-cipher-1.d b/Task/Caesar-cipher/D/caesar-cipher-1.d index 61f7ee8512..1d552650fd 100644 --- a/Task/Caesar-cipher/D/caesar-cipher-1.d +++ b/Task/Caesar-cipher/D/caesar-cipher-1.d @@ -1,8 +1,8 @@ import std.stdio, std.traits; -pure S rot(S)(in S s, in int key) pure /*nothrow*/ +S rot(S)(in S s, in int key) pure nothrow @safe if (isSomeString!S) { - auto res = s.dup; // Not nothrow. + auto res = s.dup; foreach (immutable i, ref c; res) { if ('a' <= c && c <= 'z') @@ -13,7 +13,7 @@ if (isSomeString!S) { return res; } -void main() { +void main() @safe { enum key = 3; immutable txt = "The five boxing wizards jump quickly"; writeln("Original: ", txt); diff --git a/Task/Caesar-cipher/D/caesar-cipher-3.d b/Task/Caesar-cipher/D/caesar-cipher-3.d index 5fcf4bf0a8..cb7d294fd9 100644 --- a/Task/Caesar-cipher/D/caesar-cipher-3.d +++ b/Task/Caesar-cipher/D/caesar-cipher-3.d @@ -1,11 +1,11 @@ import std.stdio, std.ascii, std.string, std.algorithm; -string rot(in string s, in int key) pure /*nothrow*/ { +string rot(in string s, in int key) pure nothrow @safe { auto uppr = uppercase.dup.representation; bringToFront(uppr[0 .. key], uppr[key .. $]); auto lowr = lowercase.dup.representation; bringToFront(lowr[0 .. key], lowr[key .. $]); - return s.translate(makeTrans(letters, cast(char[])(uppr ~ lowr))); + return s.translate(makeTrans(letters, assumeUTF(uppr ~ lowr))); } void main() { diff --git a/Task/Caesar-cipher/Eiffel/caesar-cipher.e b/Task/Caesar-cipher/Eiffel/caesar-cipher.e new file mode 100644 index 0000000000..05b947e03d --- /dev/null +++ b/Task/Caesar-cipher/Eiffel/caesar-cipher.e @@ -0,0 +1,53 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + s: STRING_32 + do + s := "The tiny tiger totally taunted the tall Till." + print ("%NString to encode: " + s) + print ("%NEncoded string: " + encode (s, 12)) + print ("%NDecoded string (after encoding and decoding): " + decode (encode (s, 12), 12)) + end + +feature -- Basic operations + + decode (to_be_decoded: STRING_32; offset: INTEGER): STRING_32 + -- Decode `to be decoded' according to `offset'. + do + Result := encode (to_be_decoded, 26 - offset) + end + + encode (to_be_encoded: STRING_32; offset: INTEGER): STRING_32 + -- Encode `to be encoded' according to `offset'. + local + l_offset: INTEGER + l_char_code: INTEGER + do + create Result.make_empty + l_offset := (offset \\ 26) + 26 + across to_be_encoded as tbe loop + if tbe.item.is_alpha then + if tbe.item.is_upper then + l_char_code := ('A').code + (tbe.item.code - ('A').code + l_offset) \\ 26 + Result.append_character (l_char_code.to_character_32) + else + l_char_code := ('a').code + (tbe.item.code - ('a').code + l_offset) \\ 26 + Result.append_character (l_char_code.to_character_32) + end + else + Result.append_character (tbe.item) + end + end + end +end diff --git a/Task/Caesar-cipher/Elena/caesar-cipher.elena b/Task/Caesar-cipher/Elena/caesar-cipher.elena index 6610015857..9df8aff7d5 100644 --- a/Task/Caesar-cipher/Elena/caesar-cipher.elena +++ b/Task/Caesar-cipher/Elena/caesar-cipher.elena @@ -1,7 +1,7 @@ #define system. #define system'routines. #define extensions. -#define extensions'math. +#define system'math. // --- Constants --- @@ -29,13 +29,13 @@ (-1 < anIndex) ? [ - theExtendee eval:(Letters @ (modulus:(theKey+anIndex):26)) + theExtendee eval:(Letters @ ((theKey+anIndex) int mod:26)) ] ! [ anIndex := BigLetters indexOf &index:0 &char:aChar. (-1 < anIndex) ? [ - theExtendee eval:(BigLetters @ (modulus:(theKey+anIndex):26)) + theExtendee eval:(BigLetters @ ((theKey+anIndex) int mod:26)) ] ! [ theExtendee eval:aChar. diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-1.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-1.groovy new file mode 100644 index 0000000000..ee8dc32212 --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-1.groovy @@ -0,0 +1,13 @@ +def caesarEncode(​cipherKey, text) { + def builder = new StringBuilder() + text.each { character -> + int ch = character[0] as char + switch(ch) { + case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break + case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break + } + builder << (ch as char) + } + builder as String +} +def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-2.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-2.groovy new file mode 100644 index 0000000000..fcc5a14c10 --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-2.groovy @@ -0,0 +1,7 @@ +def caesarEncode(cipherKey, text) { + text.chars.collect { c -> + int off = c.isUpperCase() ? 'A' : 'a' + c.isLetter() ? (((c as int) - off + cipherKey) % 26 + off) as char : c + }.join() +} +def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-3.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-3.groovy new file mode 100644 index 0000000000..ba7170cbc9 --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-3.groovy @@ -0,0 +1,4 @@ +def caesarEncode(k, text) { + (text as int[]).collect { it==' ' ? ' ' : (((it & 0x1f) + k - 1) % 26 + 1 | it & 0xe0) as char }.join() +} +def caesarDecode(k, text) { caesarEncode(26 - k, text) } diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-4.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-4.groovy new file mode 100644 index 0000000000..0f1759451b --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-4.groovy @@ -0,0 +1,4 @@ +def caesarEncode(k, text) { + text.tr('a-zA-Z', ((('a'..'z')*2)[k..(k+25)] + (('A'..'Z')*2)[k..(k+25)]).join()) +} +def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-5.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-5.groovy new file mode 100644 index 0000000000..70311e6fae --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-5.groovy @@ -0,0 +1,5 @@ +def caesarEncode(k, text) { + def c = { (it*2)[k..(k+25)].join() } + text.tr('a-zA-Z', c('a'..'z') + c('A'..'Z')) +} +def caesarDecode(cipherKey, text) { caesarEncode(26 - cipherKey, text) } diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher-6.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher-6.groovy new file mode 100644 index 0000000000..aa35bb934a --- /dev/null +++ b/Task/Caesar-cipher/Groovy/caesar-cipher-6.groovy @@ -0,0 +1,10 @@ +def plainText = "The Quick Brown Fox jumped over the lazy dog" +def cipherKey = 12 +def cipherText = caesarEncode(cipherKey, plainText) +def decodedText = caesarDecode(cipherKey, cipherText) + +println "plainText: $plainText" +println "cypherText($cipherKey): $cipherText" +println "decodedText($cipherKey): $decodedText" + +assert plainText == decodedText diff --git a/Task/Caesar-cipher/Groovy/caesar-cipher.groovy b/Task/Caesar-cipher/Groovy/caesar-cipher.groovy deleted file mode 100644 index d444b882b4..0000000000 --- a/Task/Caesar-cipher/Groovy/caesar-cipher.groovy +++ /dev/null @@ -1,24 +0,0 @@ -def caeserEncode(int ​cipherKey, String text) { - def builder = new StringBuilder() - text.each { character -> - int ch = character[0] as char - switch(ch) { - case 'a'..'z': ch = ((ch - 97 + cipherKey) % 26 + 97); break - case 'A'..'Z': ch = ((ch - 65 + cipherKey) % 26 + 65); break - } - builder.append(ch as char) - } - builder.toString() -} -def caeserDecode(int cipherKey, String text) { caeserEncode(26 - cipherKey, text) } - -def plainText = "The Quick Brown Fox jumped over the lazy dog" -def cipherKey = 12 -def cipherText = caeserEncode(cipherKey, plainText) -def decodedText = caeserDecode(cipherKey, cipherText) - -println "plainText: $plainText" -println "cypherText($cipherKey): $cipherText" -println "decodedText($cipherKey): $decodedText" - -assert plainText == decodedText​​ diff --git a/Task/Caesar-cipher/Java/caesar-cipher.java b/Task/Caesar-cipher/Java/caesar-cipher.java index dc6deb920e..f96c34474c 100644 --- a/Task/Caesar-cipher/Java/caesar-cipher.java +++ b/Task/Caesar-cipher/Java/caesar-cipher.java @@ -1,26 +1,30 @@ public class Cipher { - public static void main(String[] args) { - String enc = Cipher.encode( - "The quick brown fox Jumped over the lazy Dog", 12); - System.out.println(enc); - System.out.println(Cipher.decode(enc, 12)); - } + public static void main(String[] args) { - public static String decode(String enc, int offset) { - return encode(enc, -offset); - } + String str = "The quick brown fox Jumped over the lazy Dog"; - public static String encode(String enc, int offset) { - offset = offset % 26 + 26; - StringBuilder encoded = new StringBuilder(); - for (char i : enc.toLowerCase().toCharArray()) { - if (Character.isLetter(i)) { - int j = (i - 'a' + offset) % 26; - encoded.append((char) (j + 'a')); - } else { - encoded.append(i); - } - } - return encoded.toString(); - } + System.out.println( Cipher.encode( str, 12 )); + System.out.println( Cipher.decode( Cipher.encode( str, 12), 12 )); + } + + public static String decode(String enc, int offset) { + return encode(enc, 26-offset); + } + + public static String encode(String enc, int offset) { + offset = offset % 26 + 26; + StringBuilder encoded = new StringBuilder(); + for (char i : enc.toCharArray()) { + if (Character.isLetter(i)) { + if (Character.isUpperCase(i)) { + encoded.append((char) ('A' + (i - 'A' + offset) % 26 )); + } else { + encoded.append((char) ('a' + (i - 'a' + offset) % 26 )); + } + } else { + encoded.append(i); + } + } + return encoded.toString(); + } } diff --git a/Task/Caesar-cipher/Mathematica/caesar-cipher.math b/Task/Caesar-cipher/Mathematica/caesar-cipher.math index 14d801fb45..771888f37a 100644 --- a/Task/Caesar-cipher/Mathematica/caesar-cipher.math +++ b/Task/Caesar-cipher/Mathematica/caesar-cipher.math @@ -1 +1 @@ -cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,3]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]] +cypher[mesg_String,n_Integer]:=StringReplace[mesg,Flatten[Thread[Rule[#,RotateLeft[#,n]]]&/@CharacterRange@@@{{"a","z"},{"A","Z"}}]] diff --git a/Task/Caesar-cipher/OOC/caesar-cipher.ooc b/Task/Caesar-cipher/OOC/caesar-cipher.ooc new file mode 100644 index 0000000000..0a0c6f4d0e --- /dev/null +++ b/Task/Caesar-cipher/OOC/caesar-cipher.ooc @@ -0,0 +1,19 @@ +main: func (args: String[]) { + shift := args[1] toInt() + if (args length != 3) { + "Usage: #{args[0]} [number] [sentence]" println() + "Incorrect number of arguments." println() + } else if (!shift && args[1] != "0"){ + "Usage: #{args[0]} [number] [sentence]" println() + "Number is not a valid number." println() + } else { + str := "" + for (c in args[2]) { + if (c alpha?()) { + c = (c lower?() ? 'a' : 'A') + (26 + c toLower() - 'a' + shift) % 26 + } + str += c + } + str println() + } +} diff --git a/Task/Caesar-cipher/Oberon-2/caesar-cipher.oberon-2 b/Task/Caesar-cipher/Oberon-2/caesar-cipher.oberon-2 new file mode 100644 index 0000000000..5be3cf9924 --- /dev/null +++ b/Task/Caesar-cipher/Oberon-2/caesar-cipher.oberon-2 @@ -0,0 +1,59 @@ +MODULE Caesar; +IMPORT + Out; +CONST + encode* = 1; + decode* = -1; + +VAR + text,cipher: POINTER TO ARRAY OF CHAR; + + PROCEDURE Cipher*(txt: ARRAY OF CHAR; key: INTEGER; op: INTEGER; VAR cipher: ARRAY OF CHAR); + VAR + i: LONGINT; + BEGIN + i := 0; + WHILE i < LEN(txt) - 1 DO + IF (txt[i] >= 'A') & (txt[i] <= 'Z') THEN + cipher[i] := CHR(ORD('A') + ((ORD(txt[i]) - ORD('A') + (key * op))) MOD 26) + ELSIF (txt[i] >= 'a') & (txt[i] <= 'z') THEN + cipher[i] := CHR(ORD('a') + ((ORD(txt[i]) - ORD('a') + (key * op))) MOD 26) + ELSE + cipher[i] := txt[i] + END; + INC(i) + END; + cipher[i] := 0X + END Cipher; + +BEGIN + NEW(text,3);NEW(cipher,3); + COPY("HI",text^); + Out.String(text^);Out.String(" =e=> "); + Cipher(text^,2,encode,cipher^); + Out.String(cipher^); + + COPY(cipher^,text^); + Cipher(text^,2,decode,cipher^); + Out.String(" =d=> ");Out.String(cipher^);Out.Ln; + + COPY("ZA",text^); + Out.String(text^);Out.String(" =e=> "); + Cipher(text^,2,encode,cipher^); + Out.String(cipher^); + + COPY(cipher^,text^); + Cipher(text^,2,decode,cipher^); + Out.String(" =d=> ");Out.String(cipher^);Out.Ln; + + NEW(text,37);NEW(cipher,37); + COPY("The five boxing wizards jump quickly",text^); + Out.String(text^);Out.String(" =e=> "); + Cipher(text^,3,encode,cipher^); + Out.String(cipher^); + + COPY(cipher^,text^); + Cipher(text^,3,decode,cipher^); + Out.String(" =d=> ");Out.String(cipher^);Out.Ln; + +END Caesar. diff --git a/Task/Caesar-cipher/Perl/caesar-cipher.pl b/Task/Caesar-cipher/Perl/caesar-cipher.pl index 95d5e5a41e..86747526cb 100644 --- a/Task/Caesar-cipher/Perl/caesar-cipher.pl +++ b/Task/Caesar-cipher/Perl/caesar-cipher.pl @@ -1,11 +1,11 @@ -sub encipher { - my ($_, $k, $decode) = @_; - $k = 26 - $k if $decode; - join('', map(chr(((ord(uc $_) - 65 + $k) % 26) + 65), /([a-z])/gi)); +sub caesar { + my ($message, $key, $decode) = @_; + $key = 26 - $key if $decode; + $message =~ s/([A-Z])/chr(((ord(uc $1) - 65 + $key) % 26) + 65)/geir; } my $msg = 'THE FIVE BOXING WIZARDS JUMP QUICKLY'; -my $enc = encipher($msg, 10); -my $dec = encipher($enc, 10, 'decode'); +my $enc = caesar($msg, 10); +my $dec = caesar($enc, 10, 'decode'); print "msg: $msg\nenc: $enc\ndec: $dec\n"; diff --git a/Task/Caesar-cipher/PowerShell/caesar-cipher.psh b/Task/Caesar-cipher/PowerShell/caesar-cipher.psh new file mode 100644 index 0000000000..4eb37cd988 --- /dev/null +++ b/Task/Caesar-cipher/PowerShell/caesar-cipher.psh @@ -0,0 +1,75 @@ +# Author: M. McNabb +function Get-CaesarCipher +{ +Param +( +[Parameter( +Mandatory=$true,ValueFromPipeline=$true)] +[string] +$Text, + +[ValidateRange(1,25)] +[int] +$Key = 1, + +[switch] +$Decode +) + +begin +{ + $LowerAlpha = [char]'a'..[char]'z' + $UpperAlpha = [char]'A'..[char]'Z' +} + +process +{ + $Chars = $Text.ToCharArray() + + function encode + { + param + ( + $Char, + $Alpha = [char]'a'..[char]'z' + ) + $Index = $Alpha.IndexOf([int]$Char) + $NewIndex = ($Index + $Key) - $Alpha.Length + $Alpha[$NewIndex] + } + + function decode + { + param + ( + $Char, + $Alpha = [char]'a'..[char]'z' + ) + $Index = $Alpha.IndexOf([int]$Char) + $int = $Index - $Key + if ($int -lt 0) {$NewIndex = $int + $Alpha.Length} + else {$NewIndex = $int} + $Alpha[$NewIndex] + } + + foreach ($Char in $Chars) + { + if ([int]$Char -in $LowerAlpha) + { + if ($Decode) {$Char = decode $Char} + else {$Char = encode $Char} + } + elseif ([int]$Char -in $UpperAlpha) + { + if ($Decode) {$Char = decode $Char $UpperAlpha} + else {$Char = encode $Char $UpperAlpha} + } + + $Char = [char]$Char + [string]$OutText += $Char + } + + $OutText + $OutText = $null +} +} diff --git a/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx b/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx index 96107a60d0..77ba012c0e 100644 --- a/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx +++ b/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx @@ -4,19 +4,19 @@ arg key p /*get key and text to be cyphered*/ p=space(p,0) /*remove all blanks from text. */ say 'Caesar cypher key:' key say ' plain text:' p -y=caesar(p, key) ; say ' cyphered:' y -z=caesar(y,-key) ; say ' uncyphered:' z -if z\==p then say "plain text doesn't match uncyphered cyphered text." +y=caesar(p, key) ; say ' cyphered:' y +z=caesar(y,-key) ; say ' uncyphered:' z +if z\==p then say "plain text doesn't match uncyphered cyphered text." exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────CAESAR subroutine───────────────────*/ caesar: procedure; arg s,k; @='ABCDEFGHIJKLMNOPQRSTUVWXYZ'; L=length(@) ak=abs(k) -if ak > length(@)-1 | k==0 | k=='' then call err k 'key is invalid' +if ak>length(@)-1 | k==0 | k=='' then call err k 'key is invalid' _=verify(s,@) /*any illegal char specified ? */ -if _\==0 then call err 'unsupported character:' substr(s,_,1) +if _\==0 then call err 'unsupported character:' substr(s,_,1) /*now that error checks are done:*/ -if k>0 then ky=k+1 /*either cypher it, or ... */ - else ky=27-ak /* decypher it. */ +if k>0 then ky=k+1 /*either cypher it, or ··· */ + else ky=27-ak /* decypher it. */ return translate(s,substr(@||@,ky,L),@) /*──────────────────────────────────ERR subroutine──────────────────────*/ err: say; say '***error!***'; say; say arg(1); say; exit 13 diff --git a/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx b/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx index c2b2fa82fe..2e7b12a6d5 100644 --- a/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx +++ b/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx @@ -2,9 +2,9 @@ parse arg key p /*get key and text to be cyphered*/ say 'Caesar cypher key:' key say ' plain text:' p -y=caesar(p, key) ; say ' cyphered:' y -z=caesar(y,-key) ; say ' uncyphered:' z -if z\==p then say "plain text doesn't match uncyphered cyphered text." +y=caesar(p, key) ; say ' cyphered:' y +z=caesar(y,-key) ; say ' uncyphered:' z +if z\==p then say "plain text doesn't match uncyphered cyphered text." exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────CAESAR subroutine───────────────────*/ caesar: procedure; parse arg s,k; @='abcdefghijklmnopqrstuvwxyz' @@ -13,11 +13,10 @@ caesar: procedure; parse arg s,k; @='abcdefghijklmnopqrstuvwxyz' /*last char is doubled, REXX quoted syntax rules.*/ L=length(@) ak=abs(k) -if ak>length(@)-1 | k==0 then call err k 'key is invalid' +if ak>length(@)-1 | k==0 then call err k 'key is invalid' _=verify(s,@) /*any illegal char specified ? */ -if _\==0 then call err 'unsupported character:' substr(s,_,1) -if k>0 then ky=k+1 - else ky=L+1-ak +if _\==0 then call err 'unsupported character:' substr(s,_,1) +if k>0 then ky=k+1 + else ky=L+1-ak return translate(s,substr(@||@,ky,L),@) /*──────────────────────────────────ERR subroutine──────────────────────*/ -err: say; say '***error!***'; say; say arg(1); say; exit 13 diff --git a/Task/Caesar-cipher/UNIX-Shell/caesar-cipher.sh b/Task/Caesar-cipher/UNIX-Shell/caesar-cipher.sh new file mode 100644 index 0000000000..1986d3f297 --- /dev/null +++ b/Task/Caesar-cipher/UNIX-Shell/caesar-cipher.sh @@ -0,0 +1,56 @@ +caesar() { + local OPTIND + local encrypt n=0 + while getopts :edn: option; do + case $option in + e) encrypt=true ;; + d) encrypt=false ;; + n) n=$OPTARG ;; + :) echo "error: missing argument for -$OPTARG" >&2 + return 1 ;; + ?) echo "error: unknown option -$OPTARG" >&2 + return 1 ;; + esac + done + shift $((OPTIND-1)) + if [[ -z $encrypt ]]; then + echo "error: specify one of -e or -d" >&2 + return 1 + fi + + local upper=ABCDEFGHIJKLMNOPQRSTUVWXYZ + local lower=abcdefghijklmnopqrstuvwxyz + if $encrypt; then + tr "$upper$lower" "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" <<< "$1" + else + tr "${upper:n}${upper:0:n}${lower:n}${lower:0:n}" "$upper$lower" <<< "$1" + fi +} + +tr() { + local -A charmap + local i trans line char + for ((i=0; i<${#1}; i++)); do + charmap[${1:i:1}]=${2:i:1} + done + while IFS= read -r line; do + trans="" + for ((i=0; i<${#line}; i++)); do + char=${line:i:1} + if [[ -n ${charmap[$char]} ]]; then + trans+=${charmap[$char]} + else + trans+=$char + fi + done + echo "$trans" + done +} + +txt="The five boxing wizards jump quickly." +enc=$(caesar -e -n 5 "$txt") +dec=$(caesar -d -n 5 "$enc") + +echo "original: $txt" +echo "encrypted: $enc" +echo "decrypted: $dec" diff --git a/Task/Calendar/00DESCRIPTION b/Task/Calendar/00DESCRIPTION index f8c5456505..5dbca16812 100644 --- a/Task/Calendar/00DESCRIPTION +++ b/Task/Calendar/00DESCRIPTION @@ -1,4 +1,6 @@ -Create a routine that will generate a text calendar for any year. Test the calendar by generating a calendar for the year 1969, on a device of the time. Choose one of the following devices: +Create a routine that will generate a text calendar for any year. +Test the calendar by generating a calendar for the year 1969, on a device of the time. +Choose one of the following devices: * A line printer with a width of 132 characters. * An [[wp:IBM_3270#Displays|IBM 3278 model 4 terminal]] (80×43 display with accented characters). Target formatting the months of the year to fit nicely across the 80 character width screen. Restrict number of lines in test output to 43. @@ -13,3 +15,5 @@ This task is inspired by [http://www.ee.ryerson.ca/~elf/hack/realmen.html Real P For further Kudos see task [[Calendar - for "real" programmers|CALENDAR]], where all code is to be in UPPERCASE. For economy of size, do not actually include Snoopy generation in either the code or the output, instead just output a place-holder. + +For other calendar-related tasks, see [[Five weekends]]. diff --git a/Task/Calendar/D/calendar.d b/Task/Calendar/D/calendar.d index 0eb48091df..9cad721901 100644 --- a/Task/Calendar/D/calendar.d +++ b/Task/Calendar/D/calendar.d @@ -6,7 +6,7 @@ in { } body { immutable rows = 12 / nCols + (12 % nCols != 0); auto date = Date(year, 1, 1); - auto offs = cast(int)date.dayOfWeek; + int offs = date.dayOfWeek; const months = "January February March April May June July August September October November December".split; diff --git a/Task/Calendar/Haskell/calendar.hs b/Task/Calendar/Haskell/calendar.hs new file mode 100644 index 0000000000..23d896bd93 --- /dev/null +++ b/Task/Calendar/Haskell/calendar.hs @@ -0,0 +1,92 @@ +import qualified Data.Text as T +import Data.Time +import Data.Time.Calendar +import Data.Time.Calendar.WeekDate +import Data.List.Split (chunksOf) +import Data.List + +data Day = Su | Mo | Tu | We | Th | Fr | Sa + deriving (Show, Eq, Ord, Enum) + +data Month = January | February | March + | April | May | June + | July | August | September + | October | November | December + deriving (Show, Eq, Ord, Enum) + +monthToInt :: Month -> Int +monthToInt = (+ 1) . fromEnum + +dayFromDate :: Integer -> Month -> Int -> Int +dayFromDate year month day = day' `mod` 7 + where (_, _, day') = toWeekDate $ fromGregorian year (monthToInt month) day + +nSpaces :: Int -> T.Text +nSpaces n = T.replicate n (T.pack " ") + +space :: T.Text +space = nSpaces 1 + +calMarginWidth = 3 + +calMargin :: T.Text +calMargin = nSpaces calMarginWidth + +calWidth = 20 + +listMonth :: Integer -> Month -> [T.Text] +listMonth year month = [monthHeader, weekHeader] ++ weeks' + where + monthHeader = (T.center calWidth ' ') . T.pack $ show month + + weekHeader = (T.intercalate space) $ map (T.pack . show) [(Su)..] + + monthLength = toInteger $ + gregorianMonthLength year $ + monthToInt month + + firstDay = dayFromDate year month 1 + + days = replicate firstDay (nSpaces 2) ++ + map ((T.justifyRight 2 ' ') . T.pack . show) [1..monthLength] + + weeks = map (T.justifyLeft calWidth ' ') $ + map (T.intercalate space) $ + chunksOf 7 days + + weeks' = weeks ++ replicate (6 - length weeks) (nSpaces calWidth) + +listCalendar :: Integer -> Int -> [[[T.Text]]] +listCalendar year calColumns = (chunksOf calColumns) . (map (listMonth year)) $ + enumFrom January + +calColFromCol :: Int -> Int +calColFromCol columns = c + if r >= calWidth then 1 else 0 + where (c, r) = columns `divMod` (calWidth + calMarginWidth) + +colFromCalCol :: Int -> Int +colFromCalCol calCol = calCol * calWidth + ((calCol - 1) * calMarginWidth) + +center :: Int -> String -> String +center i a = T.unpack . (T.center i ' ') $ T.pack a + +printCal :: [[[T.Text]]] -> IO () +printCal [] = return () +printCal (c:cx) = do + mapM_ (putStrLn . T.unpack) rows + printCal cx + where rows = map (T.intercalate calMargin) $ transpose c + +printCalendar :: Integer -> Int -> IO () +printCalendar year columns = + if columns < 20 + then putStrLn $ "Cannot print less than 20 columns" + else do + putStrLn $ center columns' "[Maybe Snoopy]" + putStrLn $ center columns' $ show year + putStrLn "" + printCal $ listCalendar year calcol' + where + calcol' = calColFromCol columns + + columns' = colFromCalCol calcol' diff --git a/Task/Calendar/Java/calendar.java b/Task/Calendar/Java/calendar.java new file mode 100644 index 0000000000..2d06c4e5dd --- /dev/null +++ b/Task/Calendar/Java/calendar.java @@ -0,0 +1,57 @@ +import java.text.*; +import java.util.*; + +public class CalendarTask { + + public static void main(String[] args) { + printCalendar(1969, 3); + } + + static void printCalendar(int year, int nCols) { + if (nCols < 1 || nCols > 12) + throw new IllegalArgumentException("Illegal column width."); + + Calendar date = new GregorianCalendar(year, 0, 1); + + int nRows = (int) Math.ceil(12.0 / nCols); + int offs = date.get(Calendar.DAY_OF_WEEK) - 1; + int w = nCols * 24; + + String[] monthNames = new DateFormatSymbols(Locale.US).getMonths(); + + String[][] mons = new String[12][8]; + for (int m = 0; m < 12; m++) { + + String name = monthNames[m]; + int len = 11 + name.length() / 2; + String format = MessageFormat.format("%{0}s%{1}s", len, 21 - len); + + mons[m][0] = String.format(format, name, ""); + mons[m][1] = " Su Mo Tu We Th Fr Sa"; + int dim = date.getActualMaximum(Calendar.DAY_OF_MONTH); + + for (int d = 1; d < 43; d++) { + boolean isDay = d > offs && d <= offs + dim; + String entry = isDay ? String.format(" %2s", d - offs) : " "; + if (d % 7 == 1) + mons[m][2 + (d - 1) / 7] = entry; + else + mons[m][2 + (d - 1) / 7] += entry; + } + offs = (offs + dim) % 7; + date.add(Calendar.MONTH, 1); + } + + System.out.printf("%" + (w / 2 + 10) + "s%n", "[Snoopy Picture]"); + System.out.printf("%" + (w / 2 + 4) + "s%n%n", year); + + for (int r = 0; r < nRows; r++) { + for (int i = 0; i < 8; i++) { + for (int c = r * nCols; c < (r + 1) * nCols && c < 12; c++) + System.out.printf(" %s", mons[c][i]); + System.out.println(); + } + System.out.println(); + } + } +} diff --git a/Task/Calendar/Ruby/calendar.rb b/Task/Calendar/Ruby/calendar.rb index c6ac3140b3..8484c891a5 100644 --- a/Task/Calendar/Ruby/calendar.rb +++ b/Task/Calendar/Ruby/calendar.rb @@ -63,7 +63,7 @@ columns = begin Integer(ENV["COLUMNS"] || "") rescue begin require 'io/console'; IO.console.winsize[1] rescue LoadError - begin Integer(`tput co`) + begin Integer(`tput cols`) rescue 80; end; end; end diff --git a/Task/Call-a-foreign-language-function/Lua/call-a-foreign-language-function.lua b/Task/Call-a-foreign-language-function/Lua/call-a-foreign-language-function.lua new file mode 100644 index 0000000000..daf46d7500 --- /dev/null +++ b/Task/Call-a-foreign-language-function/Lua/call-a-foreign-language-function.lua @@ -0,0 +1,14 @@ +local ffi = require("ffi") +ffi.cdef[[ +char * strndup(const char * s, size_t n); +int strlen(const char *s); +]] + +local s1 = "Hello, world!" +print("Original: " .. s1) +local s_s1 = ffi.C.strlen(s1) +print("strlen: " .. s_s1) + +local s2 = ffi.string(ffi.C.strndup(s1, s_s1), s_s1) +print("Copy: " .. s2) +print("strlen: " .. ffi.C.strlen(s2)) diff --git a/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury index 18753cc116..bd079bd401 100644 --- a/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury +++ b/Task/Call-a-foreign-language-function/Mercury/call-a-foreign-language-function-1.mercury @@ -9,7 +9,7 @@ :- implementation. % The actual FFI code begins here. -:- pragma foreign_decl("C", "char *strdup(const char *s);"). +:- pragma foreign_decl("C", "#include "). :- func strdup(string::in) = (string::out) is det. :- pragma foreign_proc("C", strdup(S::in) = (SD::out), diff --git a/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-1.r b/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-1.r new file mode 100644 index 0000000000..4273fbb2b0 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-1.r @@ -0,0 +1,2 @@ +dyn.load("my/special/R/lib.so") +.Call("my_lib_fun", arg1, arg2) diff --git a/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-2.r b/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-2.r new file mode 100644 index 0000000000..ee55ff11cb --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/R/call-a-function-in-a-shared-library-2.r @@ -0,0 +1 @@ +.C("my_lib_fun", arg1, arg2, ret) diff --git a/Task/Call-a-function-in-a-shared-library/Scala/call-a-function-in-a-shared-library.scala b/Task/Call-a-function-in-a-shared-library/Scala/call-a-function-in-a-shared-library.scala new file mode 100644 index 0000000000..1135ef5d73 --- /dev/null +++ b/Task/Call-a-function-in-a-shared-library/Scala/call-a-function-in-a-shared-library.scala @@ -0,0 +1,26 @@ +import net.java.dev.sna.SNA +import com.sun.jna.ptr.IntByReference + +object GetDiskFreeSpace extends App with SNA { + + snaLibrary = "Kernel32" // Native library name +/* + * Important Note! + * + * The val holding the SNA-returned function must have the same name as the native function itself + * (see line following this comment). This is the only place you specify the native function name. + */ + val GetDiskFreeSpaceA = SNA[String, IntByReference, IntByReference, IntByReference, IntByReference, Boolean] + + // This Windows function is described here: + // http://msdn.microsoft.com/en-us/library/aa364935(v=vs.85).aspx + val (disk, spc, bps, fc, tc) = ("C:\\", + new IntByReference, // Sectors per cluster + new IntByReference, // Bytes per sector + new IntByReference, // Free clusters + new IntByReference) // Total clusters + + val ok = GetDiskFreeSpaceA(disk, spc, bps, fc, tc) // status + println(f"'$disk%s' ($ok%s): sectors/cluster: ${spc.getValue}%d, bytes/sector: ${bps.getValue}%d, " + + f" free-clusters: ${fc.getValue}%d, total/clusters: ${tc.getValue}%d%n") +}} diff --git a/Task/Call-a-function/00META.yaml b/Task/Call-a-function/00META.yaml index 2233b6b2e3..8c9a460d88 100644 --- a/Task/Call-a-function/00META.yaml +++ b/Task/Call-a-function/00META.yaml @@ -1,3 +1,4 @@ --- category: - Functions and subroutines +- Simple diff --git a/Task/Call-a-function/ALGOL-68/call-a-function.alg b/Task/Call-a-function/ALGOL-68/call-a-function.alg new file mode 100644 index 0000000000..7792840557 --- /dev/null +++ b/Task/Call-a-function/ALGOL-68/call-a-function.alg @@ -0,0 +1,28 @@ +# A function without arguments: # +f(); +# or # +f; + +# A function with a fixed number of arguments: # +f(1, x); + +# ALGOL 68 does not support optional arguments, variable numbers of arguments, or named +arguments. +However, some functions may take an argument "0" as an instruction to use the default value +(sort of a pseudo-optional argument). # + +# In "Talk:Call a function" a statement context is explained as +"The function is used as an instruction (with a void context), +rather than used within an expression." Based on that, +both ALGOL examples above are already in a statement context. +For full ALGOL compatibility, though, they should be in the form "VOID (f ());" # + +# A function's return value being used: # +x := f(y); + +# There is no distinction between built-in functions and user-defined functions. # + +# A subroutine is simply a function that returns VOID. # + +# If the function is declared with argument(s) of mode REF MODE, +then those arguments are being passed by reference. # diff --git a/Task/Call-a-function/D/call-a-function.d b/Task/Call-a-function/D/call-a-function.d new file mode 100644 index 0000000000..18eeed8df2 --- /dev/null +++ b/Task/Call-a-function/D/call-a-function.d @@ -0,0 +1,103 @@ +import std.traits; + +enum isSubroutine(alias F) = is(ReturnType!F == void); + +void main() { + void foo1() {} + + // Calling a function that requires no arguments: + foo1(); + foo1; // Alternative syntax. + + + void foo2(int x, int y) {} + + immutable lambda = function int(int x) => x ^^ 2; + + // Calling a function with a fixed number of arguments: + foo2(1, 2); + foo2(1, 2); + cast(void)lambda(1); + + + void foo3(int x, int y=2) {} + + // Calling a function with optional arguments: + foo3(1); + foo3(1, 3); + + int sum(int[] arr...) { + int tot = 0; + foreach (immutable x; arr) + tot += x; + return tot; + } + + real sum2(Args...)(Args arr) { + typeof(return) tot = 0; + foreach (immutable x; arr) + tot += x; + return tot; + } + + // Calling a function with a variable number of arguments: + assert(sum(1, 2, 3) == 6); + assert(sum(1, 2, 3, 4) == 10); + assert(sum2(1, 2.5, 3.5) == 7); + + // Calling a function with named arguments: + // Various struct or tuple-based tricks can be used for this, + // but currently D doesn't have named arguments. + + + // Using a function in statement context (?): + if (1) + foo1; + + // Using a function in first-class context within an expression: + assert(sum(1) == 1); + + + auto foo4() { return 1; } + + // Obtaining the return value of a function: + immutable x = foo4; + + + // Distinguishing built-in functions and user-defined functions: + // There are no built-in functions, beside the operators, and + // pseudo-functions like assert(). + + + int myFynction(int x) { return x; } + void mySubroutine(int x) {} + + // Distinguishing subroutines and functions: + // (A subroutine is merely a function that has no explicit + // return statement and will return void). + pragma(msg, isSubroutine!mySubroutine); // Prints: true + pragma(msg, isSubroutine!myFynction); // Prints: false + + + void foo5(int a, in int b, ref int c, out int d, lazy int e, scope int f) {} + + // Stating whether arguments are passed by value, by reference, etc: + alias STC = ParameterStorageClass; + alias psct = ParameterStorageClassTuple!foo5; + static assert(psct.length == 6); // Six parameters. + static assert(psct[0] == STC.none); + static assert(psct[1] == STC.none); + static assert(psct[2] == STC.ref_); + static assert(psct[3] == STC.out_); + static assert(psct[4] == STC.lazy_); + static assert(psct[5] == STC.scope_); + // There are also inout and auto ref. + + + int foo6(int a, int b) { return a + b; } + + // Is partial application possible and how: + import std.functional; + alias foo6b = partial!(foo6, 5); + assert(foo6b(6) == 11); +} diff --git a/Task/Call-a-function/Forth/call-a-function.fth b/Task/Call-a-function/Forth/call-a-function.fth new file mode 100644 index 0000000000..47308b9dde --- /dev/null +++ b/Task/Call-a-function/Forth/call-a-function.fth @@ -0,0 +1,25 @@ +a-function \ requiring no arguments +a-function \ with a fixed number of arguents +a-function \ having optional arguments +a-function \ having a variable number of arguments +a-function \ having such named arguments as we have in Forth +' a-function var ! \ using a function in a first-class context (here: storing it in a variable) +a-function \ in which we obtain a function's return value + + \ forth lacks 'statement contenxt' + \ forth doesn't distinguish between built-in and user-defined functions + \ forth doesn't distinguish between functions and subroutines + \ forth doesn't care about by-value or by-reference + +\ partial application is achieved by creating functions and manipulating stacks +: curried 0 a-function ; +: only-want-third-argument 1 2 rot a-function ; + +\ Realistic example: +: move ( delta-x delta-y -- ) + y +! x +! ; + +: down ( n -- ) 0 swap move ; +: up ( n -- ) negate down ; +: right ( n -- ) 0 move ; +: left ( n -- ) negate right ; diff --git a/Task/Call-a-function/Fortran/call-a-function.f b/Task/Call-a-function/Fortran/call-a-function.f new file mode 100644 index 0000000000..f114936f6c --- /dev/null +++ b/Task/Call-a-function/Fortran/call-a-function.f @@ -0,0 +1,70 @@ +program main +implicit none +integer :: a +integer :: f, g +logical :: lresult +interface + integer function h(a,b,c) + integer :: a, b + integer, optional :: c + end function +end interface +write(*,*) 'no arguments: ', f() +write(*,*) '-----------------' +write(*,*) 'fixed arguments: ', g(5,8,lresult) +write(*,*) '-----------------' +write(*,*) 'optional arguments: ', h(5,8), h(5,8,4) +write(*,*) '-----------------' +write(*,*) 'function with variable arguments: Does not apply!' +write(*,*) 'An option is to pass arrays of variable lengths.' +write(*,*) '-----------------' +write(*,*) 'named arguments: ', h(c=4,b=8,a=5) +write(*,*) '-----------------' +write(*,*) 'function in statement context: Does not apply!' +write(*,*) '-----------------' +write(*,*) 'Fortran passes memorty location of variables as arguments.' +write(*,*) 'So an argument can hold the return value.' +write(*,*) 'function result: ', g(5,8,lresult) , ' function successful? ', lresult +write(*,*) '-----------------' +write(*,*) 'Distinguish between built-in and user-defined functions: Does not apply!' +write(*,*) '-----------------' +write(*,*) 'Calling a subroutine: ' +a = 30 +call sub(a) +write(*,*) 'Function call: ', f() +write(*,*) '-----------------' +write(*,*) 'All variables are passed as pointers.' +write(*,*) 'Problems can arise if instead of sub(a), one uses sub(10).' +write(*,*) '-----------------' +end program + +!no argument +integer function f() +f = 10 +end function + +!fixed number of arguments +integer function g(a, b, lresult) +integer :: a, b +logical :: lresult +g = a+b +lresult = .TRUE. +end function + +!optional arguments +integer function h(a, b, c) +integer :: a, b +integer, optional :: c + +h = a+b +if(present(c)) then + h = h+10*c +end if +end function + +!subroutine +subroutine sub(a) +integer :: a +a = a*100 +write(*,*) 'Output of subroutine: ', a +end subroutine diff --git a/Task/Call-a-function/Go/call-a-function-1.go b/Task/Call-a-function/Go/call-a-function-1.go new file mode 100644 index 0000000000..a3bf3e6a7b --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-1.go @@ -0,0 +1,11 @@ +import ( + "image" + "image/gif" + "io/ioutil" + "strings" + "unicode" +) + +func f() (int, float64) { return 0, 0 } +func g(int, float64) int { return 0 } +func h(string, ...int) {} diff --git a/Task/Call-a-function/Go/call-a-function-2.go b/Task/Call-a-function/Go/call-a-function-2.go new file mode 100644 index 0000000000..0aab9b6c94 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-2.go @@ -0,0 +1,9 @@ + f() + g(1, 2.0) + // If f() is defined to return exactly the number and type of + // arguments that g() accepts than they can be used in place: + g(f()) + // But only without other arguments, this won't compile: + //h("fail", f()) + // But this will: + g(g(1, 2.0), 3.0) diff --git a/Task/Call-a-function/Go/call-a-function-3.go b/Task/Call-a-function/Go/call-a-function-3.go new file mode 100644 index 0000000000..397ec49970 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-3.go @@ -0,0 +1,8 @@ + h("ex1") + h("ex2", 1, 2) + h("ex3", 1, 2, 3, 4) + // such functions can also be called by expanding a slice: + list := []int{1,2,3,4} + h("ex4", list...) + // but again, not mixed with other arguments, this won't compile: + //h("fail", 2, list...) diff --git a/Task/Call-a-function/Go/call-a-function-4.go b/Task/Call-a-function/Go/call-a-function-4.go new file mode 100644 index 0000000000..d523fae22c --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-4.go @@ -0,0 +1 @@ + gif.Encode(ioutil.Discard, image.Black, &gif.Options{NumColors: 16}) diff --git a/Task/Call-a-function/Go/call-a-function-5.go b/Task/Call-a-function/Go/call-a-function-5.go new file mode 100644 index 0000000000..05a1bb6830 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-5.go @@ -0,0 +1 @@ + if 2*g(1, 3.0)+4 > 0 {} diff --git a/Task/Call-a-function/Go/call-a-function-6.go b/Task/Call-a-function/Go/call-a-function-6.go new file mode 100644 index 0000000000..5f61e283c2 --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-6.go @@ -0,0 +1,9 @@ + fn := func(r rune) rune { + if unicode.IsSpace(r) { + return -1 + } + return r + } + strings.Map(fn, "Spaces removed") + strings.Map(unicode.ToLower, "Test") + strings.Map(func(r rune) rune { return r + 1 }, "shift") diff --git a/Task/Call-a-function/Go/call-a-function-7.go b/Task/Call-a-function/Go/call-a-function-7.go new file mode 100644 index 0000000000..eade45e08c --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-7.go @@ -0,0 +1,4 @@ + a, b := f() // multivalue return + _, c := f() // only some of a multivalue return + d := g(a, c) // single return value + e, i := g(d, b), g(d, 2) // multiple assignment diff --git a/Task/Call-a-function/Go/call-a-function-8.go b/Task/Call-a-function/Go/call-a-function-8.go new file mode 100644 index 0000000000..64c134f5dd --- /dev/null +++ b/Task/Call-a-function/Go/call-a-function-8.go @@ -0,0 +1,2 @@ + list = append(list, a, d, e, i) + i = len(list) diff --git a/Task/Call-a-function/Maple/call-a-function-1.maple b/Task/Call-a-function/Maple/call-a-function-1.maple new file mode 100644 index 0000000000..315fc787e6 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-1.maple @@ -0,0 +1 @@ + f() diff --git a/Task/Call-a-function/Maple/call-a-function-2.maple b/Task/Call-a-function/Maple/call-a-function-2.maple new file mode 100644 index 0000000000..b41269168e --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-2.maple @@ -0,0 +1 @@ +f(1,sin(x), g -> int(g(t),t=0..1) diff --git a/Task/Call-a-function/Maple/call-a-function-3.maple b/Task/Call-a-function/Maple/call-a-function-3.maple new file mode 100644 index 0000000000..d1b9874ad6 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-3.maple @@ -0,0 +1 @@ +f(1, sin(x), g -> int(g(t),t=0..1) diff --git a/Task/Call-a-function/Maple/call-a-function-4.maple b/Task/Call-a-function/Maple/call-a-function-4.maple new file mode 100644 index 0000000000..d1b9874ad6 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-4.maple @@ -0,0 +1 @@ +f(1, sin(x), g -> int(g(t),t=0..1) diff --git a/Task/Call-a-function/Maple/call-a-function-5.maple b/Task/Call-a-function/Maple/call-a-function-5.maple new file mode 100644 index 0000000000..9e1db0e3e7 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-5.maple @@ -0,0 +1 @@ +f(a,b,method = foo) diff --git a/Task/Call-a-function/Maple/call-a-function-6.maple b/Task/Call-a-function/Maple/call-a-function-6.maple new file mode 100644 index 0000000000..cae76f42e1 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-6.maple @@ -0,0 +1 @@ +f(a); f(b); diff --git a/Task/Call-a-function/Maple/call-a-function-7.maple b/Task/Call-a-function/Maple/call-a-function-7.maple new file mode 100644 index 0000000000..fa2b62e127 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-7.maple @@ -0,0 +1 @@ +f(a) + g(b) diff --git a/Task/Call-a-function/Maple/call-a-function-8.maple b/Task/Call-a-function/Maple/call-a-function-8.maple new file mode 100644 index 0000000000..25bbdb2928 --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-8.maple @@ -0,0 +1 @@ + x := f(1) diff --git a/Task/Call-a-function/Maple/call-a-function-9.maple b/Task/Call-a-function/Maple/call-a-function-9.maple new file mode 100644 index 0000000000..013c29820e --- /dev/null +++ b/Task/Call-a-function/Maple/call-a-function-9.maple @@ -0,0 +1,2 @@ +> type( op, 'builtin' ); + true diff --git a/Task/Call-a-function/Perl/call-a-function-1.pl b/Task/Call-a-function/Perl/call-a-function-1.pl new file mode 100644 index 0000000000..efd8f2416b --- /dev/null +++ b/Task/Call-a-function/Perl/call-a-function-1.pl @@ -0,0 +1,4 @@ +foo(); # Call foo on the null list +&foo(); # Ditto +foo($arg1, $arg2); # Call foo on $arg1 and $arg2 +&foo($arg1, $arg2); # Ditto; ignores prototypes diff --git a/Task/Call-a-function/Perl/call-a-function-2.pl b/Task/Call-a-function/Perl/call-a-function-2.pl new file mode 100644 index 0000000000..e901f01b48 --- /dev/null +++ b/Task/Call-a-function/Perl/call-a-function-2.pl @@ -0,0 +1 @@ +foo; diff --git a/Task/Call-a-function/Perl/call-a-function-3.pl b/Task/Call-a-function/Perl/call-a-function-3.pl new file mode 100644 index 0000000000..142d7d873b --- /dev/null +++ b/Task/Call-a-function/Perl/call-a-function-3.pl @@ -0,0 +1 @@ +&foo; diff --git a/Task/Call-a-function/Perl/call-a-function-4.pl b/Task/Call-a-function/Perl/call-a-function-4.pl new file mode 100644 index 0000000000..bd3a06ed57 --- /dev/null +++ b/Task/Call-a-function/Perl/call-a-function-4.pl @@ -0,0 +1 @@ +goto &foo; diff --git a/Task/Call-a-function/Perl/call-a-function-5.pl b/Task/Call-a-function/Perl/call-a-function-5.pl new file mode 100644 index 0000000000..abf755e809 --- /dev/null +++ b/Task/Call-a-function/Perl/call-a-function-5.pl @@ -0,0 +1,3 @@ +&$fooref('foo', 'bar'); +&{$fooref}('foo', 'bar'); +$fooref->('foo', 'bar'); diff --git a/Task/Call-a-function/Python/call-a-function.py b/Task/Call-a-function/Python/call-a-function.py index 2906bd6592..ea1dbd2efd 100644 --- a/Task/Call-a-function/Python/call-a-function.py +++ b/Task/Call-a-function/Python/call-a-function.py @@ -8,6 +8,13 @@ def fixed_args(x, y): # call fixed_args(1, 2) # x=1, y=2 +## Can also called them using the parameter names, in either order: +fixed_args(y=2, x=1) + +## Can also "apply" fixed_args() to a sequence: +myargs=(1,2) # tuple +fixed_args(*myargs) + def opt_args(x=1): print(x) # calls @@ -41,6 +48,18 @@ def is_builtin(x): is_builtin(pow) # True is_builtin(is_builtin) # False +# Very liberal function definition + +def takes_anything(*args, **kwargs): + for each in args: + print(each) + for key, value in sorted(kwargs.items()): + print("%s:%s" % (key, value)) + # Passing those to another, wrapped, function: + wrapped_fn(*args, **kwargs) + # (Function being wrapped can have any parameter list + # ... that doesn't have to match this prototype) + ## A subroutine is merely a function that has no explicit ## return statement and will return None. diff --git a/Task/Call-a-function/R/call-a-function.r b/Task/Call-a-function/R/call-a-function.r new file mode 100644 index 0000000000..28266b4161 --- /dev/null +++ b/Task/Call-a-function/R/call-a-function.r @@ -0,0 +1,58 @@ +### Calling a function that requires no arguments +no_args <- function() NULL +no_args() + + +### Calling a function with a fixed number of arguments +fixed_args <- function(x, y) print(paste("x=", x, ", y=", y, sep="")) +fixed_args(1, 2) # x=1, y=2 +fixed_args(y=2, x=1) # y=1, x=2 + + +### Calling a function with optional arguments +opt_args <- function(x=1) x +opt_args() # x=1 +opt_args(3.141) # x=3.141 + + +### Calling a function with a variable number of arguments +var_args <- function(...) print(list(...)) +var_args(1, 2, 3) +var_args(1, c(2,3)) +var_args() + + +### Calling a function with named arguments +fixed_args(y=2, x=1) # x=1, y=2 + + +### Using a function in statement context +if (TRUE) no_args() + + +### Using a function in first-class context within an expression +print(no_args) + + +### Obtaining the return value of a function +return_something <- function() 1 +x <- return_something() +x + + +### Distinguishing built-in functions and user-defined functions +# Not easily possible. See +# http://cran.r-project.org/doc/manuals/R-ints.html#g_t_002eInternal-vs-_002ePrimitive +# for details. + + +### Distinguishing subroutines and functions +# No such distinction. + + +### Stating whether arguments are passed by value or by reference +# Pass by value. + + +### Is partial application possible and how +# Yes, see http://rosettacode.org/wiki/Partial_function_application#R diff --git a/Task/Call-a-function/Scala/call-a-function.scala b/Task/Call-a-function/Scala/call-a-function.scala new file mode 100644 index 0000000000..cd7a3f17a6 --- /dev/null +++ b/Task/Call-a-function/Scala/call-a-function.scala @@ -0,0 +1,65 @@ +def ??? = throw new NotImplementedError // placeholder for implementation of hypothetical methods +def myFunction0() = ??? +myFunction0() // function invoked with empty parameter list +myFunction0 // function invoked with empty parameter list omitted + +def myFunction = ??? +myFunction // function invoked with no arguments or empty arg list +/* myFunction() */ // error: does not take parameters + +def myFunction1(x: String) = ??? +myFunction1("foobar") // function invoked with single argument +myFunction1 { "foobar" } // function invoked with single argument provided by a block + // (a block of code within {}'s' evaluates to the result of its last expression) + +def myFunction2(first: Int, second: String) = ??? +val b = "foobar" +myFunction2(6, b) // function with two arguments + +def multipleArgLists(first: Int)(second: Int, third: String) = ??? +multipleArgLists(42)(17, "foobar") // function with three arguments in two argument lists + +def myOptionalParam(required: Int, optional: Int = 42) = ??? +myOptionalParam(1) // function with optional param +myOptionalParam(1, 2) // function with optional param provided + +def allParamsOptional(firstOpt: Int = 42, secondOpt: String = "foobar") = ??? +allParamsOptional() // function with all optional args +/* allParamsOptional */ // error: missing arguments for method allParamsOptional; + // follow with `_' if you want to treat it as a partially applied function + +def sum[Int](values: Int*) = values.foldLeft(0)((a, b) => a + b) +sum(1, 2, 3) // function accepting variable arguments as literal + +val values = List(1, 2, 3) +sum(values: _*) // function acception variable arguments from collection +sum() // function accepting empty variable arguments + +def mult(firstValue: Int, otherValues: Int*) = otherValues.foldLeft(firstValue)((a, b) => a * b) +mult(1, 2, 3) // function with non-empty variable arguments +myOptionalParam(required = 1) // function called with named arguments (all functions have named arguments) +myFunction2(second = "foo", first = 1) // function with re-ordered named arguments +mult(firstValue = 1, otherValues = 2, 3) // function with named variable argument as literal + +val otherValues = Seq(2, 3) +mult(1, otherValues = otherValues: _*) // function with named variable argument from collection +val result = myFunction0() // function called in an expression context +myFunction0() // function called in statement context +/* myOptionalParam(optional = 1, 2) */ // error: positional after named argument. + +def transform[In, Out](initial: In)(transformation: In => Out) = transformation(initial) +val result = transform(42)(x => x * x) // function in first-class context within an expression + +def divide(top: Double, bottom: Double) = top / bottom +val div = (divide _) // partial application -- defer application of entire arg list +val halve = divide(_: Double, 2) // partial application -- defer application of some arguments + +class Foo(var value: Int) +def incFoo(foo: Foo) = foo.value += 1 // function showing AnyRef's are passed by reference +/* def incInt(i: Int) = i += 1 */ // error: += is not a member of Int + // (All arguments are passed by reference, but reassignment + // or setter must be defined on a type or a field + // (respectively) in order to modify its value.) + +// No distinction between built-in functions and user-defined functions +// No distinction between subroutines and functions diff --git a/Task/Call-a-function/XSLT/call-a-function.xslt b/Task/Call-a-function/XSLT/call-a-function.xslt new file mode 100644 index 0000000000..a027e5d2eb --- /dev/null +++ b/Task/Call-a-function/XSLT/call-a-function.xslt @@ -0,0 +1,277 @@ + + + + + + + + + + + + + + + + + This test is NOT OK. + + + + 'haystack' does NOT start with 'hay'. + + + + '' = 'hay' + '' = 'stack' + + + + '' = 'abcdefgh' + '' = 'ijklmnop' + + The number of root elements in the input document is (should be 1). + + + + + + + + + + + + + + See attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 3 + + + + + + + 3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No parameters needed here! + + + + + + The context element here is named "" + + + + + + + + + ( * ) + = + + + + + + + + ( * ) + = + + + + + + + + + + + + + + + diff --git a/Task/Call-an-object-method/Clojure/call-an-object-method.clj b/Task/Call-an-object-method/Clojure/call-an-object-method.clj new file mode 100644 index 0000000000..81d2ded984 --- /dev/null +++ b/Task/Call-an-object-method/Clojure/call-an-object-method.clj @@ -0,0 +1,5 @@ +(Long/toHexString 15) ; use forward slash for static methods +(System/currentTimeMillis) + +(.equals 1 2) ; use dot operator to call instance methods +(. 1 (equals 2)) ; alternative style diff --git a/Task/Call-an-object-method/Maple/call-an-object-method-1.maple b/Task/Call-an-object-method/Maple/call-an-object-method-1.maple new file mode 100644 index 0000000000..fbf9acc61b --- /dev/null +++ b/Task/Call-an-object-method/Maple/call-an-object-method-1.maple @@ -0,0 +1,2 @@ +# Static +Method( obj, other, arg ); diff --git a/Task/Call-an-object-method/Maple/call-an-object-method-2.maple b/Task/Call-an-object-method/Maple/call-an-object-method-2.maple new file mode 100644 index 0000000000..4a39891f11 --- /dev/null +++ b/Task/Call-an-object-method/Maple/call-an-object-method-2.maple @@ -0,0 +1,2 @@ +# Instance +Method( obj, other, arg ); diff --git a/Task/Call-an-object-method/Rust/call-an-object-method.rust b/Task/Call-an-object-method/Rust/call-an-object-method.rust new file mode 100644 index 0000000000..cce613c684 --- /dev/null +++ b/Task/Call-an-object-method/Rust/call-an-object-method.rust @@ -0,0 +1,26 @@ +struct Foo; + +impl Foo { + // implementation of an instance method for struct Foo + // returning the answer to life + fn get_the_answer_to_life(&self) -> i32 { + 42 + } + + // implementation of a static method for struct Foo + // returning a new instance object + fn new() -> Foo { + println!("Hello, world!"); + Foo // returning the new Foo object + } +} + +fn main() { + // create the instance object foo, + // by calling the static method new of struct Foo + let foo = Foo::new(); + + // get the answer to life + // by calling the instance method of object foo + println!("The answer to life is {}.", foo.get_the_answer_to_life()); +} diff --git a/Task/Canny-edge-detector/00META.yaml b/Task/Canny-edge-detector/00META.yaml new file mode 100644 index 0000000000..58807afa1b --- /dev/null +++ b/Task/Canny-edge-detector/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Image processing diff --git a/Task/Canny-edge-detector/D/canny-edge-detector.d b/Task/Canny-edge-detector/D/canny-edge-detector.d index 0e3ec61fd7..dad2d10a2d 100644 --- a/Task/Canny-edge-detector/D/canny-edge-detector.d +++ b/Task/Canny-edge-detector/D/canny-edge-detector.d @@ -1,22 +1,23 @@ -import core.stdc.stdio, std.math, std.typecons, std.string, +import core.stdc.stdio, std.math, std.typecons, std.string, std.conv, std.algorithm, std.ascii, std.array, bitmap, grayscale_image; enum maxBrightness = 255; alias Pixel = short; +alias IntT = typeof(size_t.init.signed); // If normalize is true, map pixels to range 0...maxBrightness. void convolution(bool normalize)(in Pixel[] inp, Pixel[] outp, in float[] kernel, - in int nx, in int ny, in int kn) -pure nothrow in { + in IntT nx, in IntT ny, in IntT kn) +pure nothrow @nogc in { assert(kernel.length == kn ^^ 2); assert(kn % 2 == 1); assert(nx > kn && ny > kn); assert(inp.length == outp.length); } body { - //immutable int kn = sqrti(kernel.length); - immutable int khalf = kn / 2; + //immutable IntT kn = sqrti(kernel.length); + immutable IntT khalf = kn / 2; static if (normalize) { float pMin = float.max, pMax = -float.max; @@ -58,11 +59,11 @@ pure nothrow in { void gaussianFilter(in Pixel[] inp, Pixel[] outp, - in int nx, in int ny, in float sigma) + in IntT nx, in IntT ny, in float sigma) pure nothrow in { assert(inp.length == outp.length); } body { - immutable int n = 2 * cast(int)(2 * sigma) + 3; + immutable IntT n = 2 * cast(IntT)(2 * sigma) + 3; immutable float mean = floor(n / 2.0); auto kernel = new float[n * n]; @@ -85,13 +86,13 @@ pure nothrow in { Image!Pixel cannyEdgeDetection(in Image!Pixel inp, - in int tMin, in int tMax, + in IntT tMin, in IntT tMax, in float sigma) pure nothrow in { assert(inp !is null); } body { - immutable int nx = inp.nx; - immutable int ny = inp.ny; + immutable IntT nx = inp.nx.signed; + immutable IntT ny = inp.ny.signed; auto outp = new Pixel[nx * ny]; gaussianFilter(inp.image, outp, nx, ny, sigma); @@ -119,15 +120,15 @@ pure nothrow in { auto nms = new Pixel[nx * ny]; foreach (immutable i; 1 .. nx - 1) foreach (immutable j; 1 .. ny - 1) { - immutable int c = i + nx * j, - nn = c - nx, - ss = c + nx, - ww = c + 1, - ee = c - 1, - nw = nn + 1, - ne = nn - 1, - sw = ss + 1, - se = ss - 1; + immutable IntT c = i + nx * j, + nn = c - nx, + ss = c + nx, + ww = c + 1, + ee = c - 1, + nw = nn + 1, + ne = nn - 1, + sw = ss + 1, + se = ss - 1; immutable aux = atan2(double(after_Gy[c]), double(after_Gx[c])) + PI; @@ -147,7 +148,7 @@ pure nothrow in { } // Reuse array used as a stack. nx*ny/2 elements should be enough. - int[] edges = (cast(int*)after_Gy.ptr)[0 .. after_Gy.length / 2]; + IntT[] edges = (cast(IntT*)after_Gy.ptr)[0 .. after_Gy.length / 2]; outp[] = Pixel.init; edges[] = 0; @@ -157,14 +158,14 @@ pure nothrow in { foreach (immutable i; 1 .. nx - 1) { if (nms[c] >= tMax && outp[c] == 0) { // Trace edges. outp[c] = maxBrightness; - int nedges = 1; + IntT nedges = 1; edges[0] = c; do { nedges--; - immutable int t = edges[nedges]; + immutable IntT t = edges[nedges]; - immutable int[8] neighbours = [ + immutable IntT[8] neighbours = [ t - nx, // nn t + nx, // ss t + 1, // ww diff --git a/Task/Carmichael-3-strong-pseudoprimes/C/carmichael-3-strong-pseudoprimes.c b/Task/Carmichael-3-strong-pseudoprimes/C/carmichael-3-strong-pseudoprimes.c new file mode 100644 index 0000000000..caba7a088f --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/C/carmichael-3-strong-pseudoprimes.c @@ -0,0 +1,48 @@ +#include + +/* C's % operator actually calculates the remainder of a / b so we need a + * small adjustment so it works as expected for negative values */ +#define mod(n,m) ((((n) % (m)) + (m)) % (m)) + +int is_prime(unsigned int n) +{ + if (n <= 3) { + return n > 1; + } + else if (!(n % 2) || !(n % 3)) { + return 0; + } + else { + unsigned int i; + for (i = 5; i*i <= n; i += 6) + if (!(n % i) || !(n % (i + 2))) + return 0; + return 1; + } +} + +void carmichael3(int p1) +{ + if (!is_prime(p1)) return; + + int h3, d, p2, p3; + for (h3 = 1; h3 < p1; ++h3) { + for (d = 1; d < h3 + p1; ++d) { + if ((h3 + p1)*(p1 - 1) % d == 0 && mod(-p1 * p1, h3) == d % h3) { + p2 = 1 + ((p1 - 1) * (h3 + p1)/d); + if (!is_prime(p2)) continue; + p3 = 1 + (p1 * p2 / h3); + if (!is_prime(p3) || (p2 * p3) % (p1 - 1) != 1) continue; + printf("%d %d %d\n", p1, p2, p3); + } + } + } +} + +int main(void) +{ + int p1; + for (p1 = 2; p1 < 62; ++p1) + carmichael3(p1); + return 0; +} diff --git a/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d b/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d index bdd37cc892..0d38aedce5 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d +++ b/Task/Carmichael-3-strong-pseudoprimes/D/carmichael-3-strong-pseudoprimes.d @@ -1,6 +1,6 @@ -enum mod = (in int n, in int m) pure nothrow => ((n % m) + m) % m; +enum mod = (in int n, in int m) pure nothrow @nogc=> ((n % m) + m) % m; -bool isPrime(in uint n) pure nothrow { +bool isPrime(in uint n) pure nothrow @nogc { if (n == 2 || n == 3) return true; else if (n < 2 || n % 2 == 0 || n % 3 == 0) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Icon/carmichael-3-strong-pseudoprimes.icon b/Task/Carmichael-3-strong-pseudoprimes/Icon/carmichael-3-strong-pseudoprimes.icon new file mode 100644 index 0000000000..1e1f9da4e5 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Icon/carmichael-3-strong-pseudoprimes.icon @@ -0,0 +1,24 @@ +link "factors" + +procedure main(A) + n := integer(!A) | 61 + every write(carmichael3(!n)) +end + +procedure carmichael3(p1) + every (isprime(p1), (h := 1+!(p1-1)), (d := !(h+p1-1))) do + if (mod(((h+p1)*(p1-1)),d) = 0, mod((-p1*p1),h) = mod(d,h)) then { + p2 := 1 + (p1-1)*(h+p1)/d + p3 := 1 + p1*p2/h + if (isprime(p2), isprime(p3), mod((p2*p3),(p1-1)) = 1) then + suspend format(p1,p2,p3) + } +end + +procedure mod(n,d) + return (d+n%d)%d +end + +procedure format(p1,p2,p3) + return left(p1||" * "||p2||" * "||p3,20)||" = "||(p1*p2*p3) +end diff --git a/Task/Carmichael-3-strong-pseudoprimes/Perl/carmichael-3-strong-pseudoprimes.pl b/Task/Carmichael-3-strong-pseudoprimes/Perl/carmichael-3-strong-pseudoprimes.pl new file mode 100644 index 0000000000..43a88ae865 --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/Perl/carmichael-3-strong-pseudoprimes.pl @@ -0,0 +1,17 @@ +use ntheory qw/forprimes is_prime vecprod/; + +forprimes { my $p = $_; + for my $h3 (2 .. $p-1) { + my $ph3 = $p + $h3; + for my $d (1 .. $ph3-1) { # Jameseon procedure page 6 + next if ((-$p*$p) % $h3) != ($d % $h3); + next if (($p-1)*$ph3) % $d; + my $q = 1 + ($p-1)*$ph3 / $d; # Jameson eq 7 + next unless is_prime($q); + my $r = 1 + ($p*$q-1) / $h3; # Jameson eq 6 + next unless is_prime($r); + next unless ($q*$r) % ($p-1) == 1; + printf "%2d x %5d x %5d = %s\n",$p,$q,$r,vecprod($p,$q,$r); + } + } +} 3,61; diff --git a/Task/Carmichael-3-strong-pseudoprimes/PicoLisp/carmichael-3-strong-pseudoprimes.l b/Task/Carmichael-3-strong-pseudoprimes/PicoLisp/carmichael-3-strong-pseudoprimes.l new file mode 100644 index 0000000000..156778176b --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/PicoLisp/carmichael-3-strong-pseudoprimes.l @@ -0,0 +1,40 @@ +(de modulo (X Y) + (% (+ Y (% X Y)) Y) ) + +(de prime? (N) + (let D 0 + (or + (= N 2) + (and + (> N 1) + (bit? 1 N) + (for (D 3 T (+ D 2)) + (T (> D (sqrt N)) T) + (T (=0 (% N D)) NIL) ) ) ) ) ) + +(for P1 61 + (when (prime? P1) + (for (H3 2 (> P1 H3) (inc H3)) + (let G (+ H3 P1) + (for (D 1 (> G D) (inc D)) + (when + (and + (=0 + (% (* G (dec P1)) D) ) + (= + (modulo (* (- P1) P1) H3) + (% D H3)) ) + (let + (P2 + (inc + (/ (* (dec P1) G) D) ) + P3 (inc (/ (* P1 P2) H3)) ) + (when + (and + (prime? P2) + (prime? P3) + (= 1 (modulo (* P2 P3) (dec P1))) ) + (print (list P1 P2 P3)) ) ) ) ) ) ) ) ) +(prinl) + +(bye) diff --git a/Task/Carmichael-3-strong-pseudoprimes/Python/carmichael-3-strong-pseudoprimes.py b/Task/Carmichael-3-strong-pseudoprimes/Python/carmichael-3-strong-pseudoprimes.py index 66cc034699..aee7f5722f 100644 --- a/Task/Carmichael-3-strong-pseudoprimes/Python/carmichael-3-strong-pseudoprimes.py +++ b/Task/Carmichael-3-strong-pseudoprimes/Python/carmichael-3-strong-pseudoprimes.py @@ -1,6 +1,6 @@ class Isprime(): ''' - Extensible sieve of Erastosthenes + Extensible sieve of Eratosthenes >>> isprime.check(11) True diff --git a/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx new file mode 100644 index 0000000000..7e7194592e --- /dev/null +++ b/Task/Carmichael-3-strong-pseudoprimes/REXX/carmichael-3-strong-pseudoprimes.rexx @@ -0,0 +1,44 @@ +/*REXX program calculates Carmichael 3-strong pseudoprimes (up to N).*/ +numeric digits 30 /*in case user wants bigger nums.*/ +parse arg N .; if N=='' then N=61 /*allow user to specify the limit*/ +if 7=='f7'x then times='af'x /*if EBCDIC machine, use a bullet*/ + else times='f9'x /* " ASCII " " " " */ +carms=0 /*number of Carmichael #s so far.*/ +!.=0; !.2=1; !.3=1; !.5=1; !.7=1; !.11=1; !.13=1; !.17=1; !.19=1; !.23=1 + /*[↓] prime # memoization array.*/ + do p=3 to N by 2; if \isPrime(p) then iterate /*Not prime? Skip*/ + pm=p-1; nps=-p*p; bot=0; top=0 /*some handy-dandy REXX variables*/ + @.=0 /*[↑] Carmichael numbers are odd*/ + do h3=2 to pm; g=h3+p /*find Carmichael #s for this P. */ + gPM=g*pm; npsH3=((nps//h3)+h3)//h3 /*shortcuts.*/ + + do d=1 for g-1 + if gPM//d \== 0 then iterate + if npsH3 \== d//h3 then iterate + q=1+gPM%d; if \isPrime(q) then iterate + r=1+p*q%h3; if q*r//pm\==1 then iterate + if \isPrime(r) then iterate + carms=carms+1; @.q=r /*bump Carmichael #; add to array*/ + if bot==0 then bot=q; bot=min(bot,q); top=max(top,q) + /*find the maximum. */ + end /*d*/ /* [↑] find minimum and maximum.*/ + end /*h3*/ + $=0 /*display a list of some Carm #s.*/ + do j=bot to top by 2; if @.j==0 then iterate; $=1 + say '──────── a Carmichael number: ' p times j times @.j + end /*j*/ + if $ then say /*show beautification blank line.*/ + end /*p*/ + +say; say carms ' Carmichael numbers found.' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPRIME subroutine──────────────────*/ +isPrime: procedure expose !.; parse arg x; if !.x then return 1 +if x<23 then return 0; if x//2==0 then return 0; if x// 3==0 then return 0 +if right(x,1)==5 then return 0; if x// 7==0 then return 0 +if x//11==0 then return 0; if x//13==0 then return 0 +if x//17==0 then return 0; if x//19==0 then return 0 + do i=23 by 6 until i*i>x; if x// i ==0 then return 0 + if x//(i+2)==0 then return 0 + end /*i*/ +!.x=1; return 1 diff --git a/Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir b/Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir new file mode 100644 index 0000000000..7e62379bf9 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Elixir/case-sensitivity-of-identifiers.elixir @@ -0,0 +1,4 @@ +dog = "Benjamin" +doG = "Samba" +dOG = "Bernie" +IO.puts "The three dogs are named #{dog}, #{doG} and #{dOG}." diff --git a/Task/Case-sensitivity-of-identifiers/Oberon-2/case-sensitivity-of-identifiers.oberon-2 b/Task/Case-sensitivity-of-identifiers/Oberon-2/case-sensitivity-of-identifiers.oberon-2 new file mode 100644 index 0000000000..2b48ed5480 --- /dev/null +++ b/Task/Case-sensitivity-of-identifiers/Oberon-2/case-sensitivity-of-identifiers.oberon-2 @@ -0,0 +1,12 @@ +MODULE CaseSensitivity; +IMPORT + Out; +VAR + dog, Dog, DOG: STRING; +BEGIN + dog := "Benjamin"; + Dog := "Samba"; + DOG := "Bernie"; + Out.Object("The three dogs are named " + dog + ", " + Dog + " and " + DOG); + Out.Ln +END CaseSensitivity. diff --git a/Task/Catalan-numbers/00DESCRIPTION b/Task/Catalan-numbers/00DESCRIPTION index cd1bef3d6a..e085125e09 100644 --- a/Task/Catalan-numbers/00DESCRIPTION +++ b/Task/Catalan-numbers/00DESCRIPTION @@ -6,3 +6,7 @@ Or alternatively (also recursive): :C_0 = 1 \quad \mbox{and} \quad C_n=\frac{2(2n-1)}{n+1}C_{n-1}, Implement at least one of these algorithms and print out the first 15 Catalan numbers with each. [[Memoization]] is not required, but may be worth the effort when using the second method above. + +Related tasks: +*[[Catalan numbers/Pascal's triangle]] +*[[Evaluate binomial coefficients]] diff --git a/Task/Catalan-numbers/Bracmat/catalan-numbers-1.bracmat b/Task/Catalan-numbers/Bracmat/catalan-numbers-1.bracmat index 8429e0891c..72b612213f 100644 --- a/Task/Catalan-numbers/Bracmat/catalan-numbers-1.bracmat +++ b/Task/Catalan-numbers/Bracmat/catalan-numbers-1.bracmat @@ -51,5 +51,7 @@ ' ( 1+!n:~>15:?n & out$(str$(C !n " = " C$!n)) ) -& +& out$"Using taylor expansion of sqrt(1-4X). (See http://bababadalgharaghtakamminarronnkonnbro.blogspot.in/2012/10/algebraic-type-systems-combinatorial.html)" +& out$(1+(1+-1*tay$((1+-4*X)^1/2,X,16))*(2*X)^-1+-1) +& out$ ); diff --git a/Task/Catalan-numbers/Bracmat/catalan-numbers-2.bracmat b/Task/Catalan-numbers/Bracmat/catalan-numbers-2.bracmat index 1644a8a1e4..4bae6082b1 100644 --- a/Task/Catalan-numbers/Bracmat/catalan-numbers-2.bracmat +++ b/Task/Catalan-numbers/Bracmat/catalan-numbers-2.bracmat @@ -49,3 +49,20 @@ C12 = 208012 C13 = 742900 C14 = 2674440 C15 = 9694845 +Using taylor expansion of sqrt(1-4X). (See http://bababadalgharaghtakamminarronnkonnbro.blogspot.in/2012/10/algebraic-type-systems-combinatorial.html) + 1 ++ X ++ 2*X^2 ++ 5*X^3 ++ 14*X^4 ++ 42*X^5 ++ 132*X^6 ++ 429*X^7 ++ 1430*X^8 ++ 4862*X^9 ++ 16796*X^10 ++ 58786*X^11 ++ 208012*X^12 ++ 742900*X^13 ++ 2674440*X^14 ++ 9694845*X^15 diff --git a/Task/Catalan-numbers/D/catalan-numbers.d b/Task/Catalan-numbers/D/catalan-numbers.d index 02a02575c3..0bbae65cb1 100644 --- a/Task/Catalan-numbers/D/catalan-numbers.d +++ b/Task/Catalan-numbers/D/catalan-numbers.d @@ -1,29 +1,20 @@ -import std.stdio, std.bigint, std.functional; +import std.stdio, std.algorithm, std.bigint, std.functional, std.range; -BigInt factorial(in uint n) { - alias mfact = memoize!factorial; - return n ? mfact(n - 1) * n : 1.BigInt; -} +auto product(R)(R r) { return reduce!q{a * b}(1.BigInt, r); } -auto cats1(in uint n) { - return factorial(2 * n) / (factorial(n + 1) * n.factorial); -} +const cats1 = sequence!((a, n) => iota(n+2, 2*n+1).product / iota(1, n+1).product)(1); -BigInt cats2(in uint n) { - alias mcats2 = memoize!cats2; +BigInt cats2a(in uint n) { + alias mcats2a = memoize!cats2a; if (n == 0) return 1.BigInt; - BigInt sum = 0; - foreach (immutable i; 0 .. n) - sum += mcats2(i) * mcats2(n - 1 - i); - return sum; + return n.iota.map!(i => mcats2a(i) * mcats2a(n - 1 - i)).sum; } -BigInt cats3(in uint n) { - alias mcats3 = memoize!cats3; - return n ? (4*n - 2) * mcats3(n - 1) / (n + 1) : 1.BigInt; -} +const cats2 = sequence!((a, n) => n.cats2a); + +const cats3 = recurrence!q{ (4*n - 2) * a[n - 1] / (n + 1) }(1.BigInt); void main() { - foreach (immutable i; 0 .. 15) - writefln("%2d => %s %s %s", i, i.cats1, i.cats2, i.cats3); + foreach (cats; TypeTuple!(cats1, cats2, cats3)) + cats.take(15).writeln; } diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e b/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e new file mode 100644 index 0000000000..7715dd1ae4 --- /dev/null +++ b/Task/Catalan-numbers/Eiffel/catalan-numbers-1.e @@ -0,0 +1,19 @@ +class + CATALAN_NUMBERS +feature + + cat_num(n:INTEGER): DOUBLE + require + n_not_negative:n>= 0 + local + s,t: DOUBLE + do + if n=0 then + Result:= 1.0 + else + t:= 4*n.to_double-2 + s:= n.to_double+1 + Result:= t/s*cat_num(n-1) + end + end +end diff --git a/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e b/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e new file mode 100644 index 0000000000..3a7e4bbfed --- /dev/null +++ b/Task/Catalan-numbers/Eiffel/catalan-numbers-2.e @@ -0,0 +1,24 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + make + local + s: STRING + do + create cat + from + i:=0 + until + i>14 + loop + io.put_double (cat.cat_num (i)) + io.put_string ("%N") + i:= i+1 + end + end + cat: CATALAN_NUMBERS +end diff --git a/Task/Catalan-numbers/GAP/catalan-numbers.gap b/Task/Catalan-numbers/GAP/catalan-numbers.gap index 1f582283c5..3ae0146804 100644 --- a/Task/Catalan-numbers/GAP/catalan-numbers.gap +++ b/Task/Catalan-numbers/GAP/catalan-numbers.gap @@ -23,9 +23,9 @@ end; # The first fifteen: 0 to 14 ! -List([0 .. 14], n -> Catalan1(n)); -List([0 .. 14], n -> Catalan2(n)); -List([0 .. 14], n -> Catalan3(n)); -List([0 .. 14], n -> Catalan4(n)); +List([0 .. 14], Catalan1); +List([0 .. 14], Catalan2); +List([0 .. 14], Catalan3); +List([0 .. 14], Catalan4); # Same output for all four: # [ 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440 ] diff --git a/Task/Catalan-numbers/Maple/catalan-numbers.maple b/Task/Catalan-numbers/Maple/catalan-numbers.maple new file mode 100644 index 0000000000..b3cc9b5d74 --- /dev/null +++ b/Task/Catalan-numbers/Maple/catalan-numbers.maple @@ -0,0 +1,4 @@ +CatalanNumbers := proc( n::posint ) + return seq( (2*i)!/((i + 1)!*i!), i = 0 .. n - 1 ); +end proc: +CatalanNumbers(15); diff --git a/Task/Catalan-numbers/PARI-GP/catalan-numbers-1.pari b/Task/Catalan-numbers/PARI-GP/catalan-numbers-1.pari index 146c37dddd..5b12665de7 100644 --- a/Task/Catalan-numbers/PARI-GP/catalan-numbers-1.pari +++ b/Task/Catalan-numbers/PARI-GP/catalan-numbers-1.pari @@ -1 +1 @@ -Catalan(n)=binomial(2*n,n+1)/n +catalan(n)=binomial(2*n,n+1)/n diff --git a/Task/Catalan-numbers/PARI-GP/catalan-numbers-2.pari b/Task/Catalan-numbers/PARI-GP/catalan-numbers-2.pari index 4b55d02750..f05f62a145 100644 --- a/Task/Catalan-numbers/PARI-GP/catalan-numbers-2.pari +++ b/Task/Catalan-numbers/PARI-GP/catalan-numbers-2.pari @@ -1 +1 @@ -Catalan(n)=(2*n)!/(n+1)!/n! +catalan(n)=(2*n)!/(n+1)!/n! diff --git a/Task/Catalan-numbers/PARI-GP/catalan-numbers-3.pari b/Task/Catalan-numbers/PARI-GP/catalan-numbers-3.pari index a5f3f8e4fb..7796e21e38 100644 --- a/Task/Catalan-numbers/PARI-GP/catalan-numbers-3.pari +++ b/Task/Catalan-numbers/PARI-GP/catalan-numbers-3.pari @@ -1 +1 @@ -Catalan(n)=prod(k=n+2,2*n,k)/prod(k=2,n,k) +catalan(n)=prod(k=n+2,2*n,k)/prod(k=2,n,k) diff --git a/Task/Catalan-numbers/PARI-GP/catalan-numbers-4.pari b/Task/Catalan-numbers/PARI-GP/catalan-numbers-4.pari index d6cb360be0..861144eb68 100644 --- a/Task/Catalan-numbers/PARI-GP/catalan-numbers-4.pari +++ b/Task/Catalan-numbers/PARI-GP/catalan-numbers-4.pari @@ -1,4 +1,4 @@ -Catalan(n)={ +catalan(n)={ my(t=1); for(k=n+2,2*n,t*=k); for(k=2,n,t/=k); diff --git a/Task/Catalan-numbers/PARI-GP/catalan-numbers-5.pari b/Task/Catalan-numbers/PARI-GP/catalan-numbers-5.pari index 43202f8b66..93223d6eca 100644 --- a/Task/Catalan-numbers/PARI-GP/catalan-numbers-5.pari +++ b/Task/Catalan-numbers/PARI-GP/catalan-numbers-5.pari @@ -1 +1 @@ -vector(15,n,Catalan(n)) +vector(15,n,catalan(n)) diff --git a/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 b/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 index 0c31652ae7..ee095b566f 100644 --- a/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 +++ b/Task/Catalan-numbers/Perl-6/catalan-numbers.pl6 @@ -1,3 +1,3 @@ -my @catalan := 1, { (state $n)++; 2*(2*$n-1)/($n+1) * $_ } ... *; +constant Catalan = 1, [\*] (2, 6 ... *) Z/ 2 .. *; -.say for @catalan[^15]; +.say for Catalan[^15]; diff --git a/Task/Catalan-numbers/Perl/catalan-numbers-1.pl b/Task/Catalan-numbers/Perl/catalan-numbers-1.pl index 696d643fa4..218907b76f 100644 --- a/Task/Catalan-numbers/Perl/catalan-numbers-1.pl +++ b/Task/Catalan-numbers/Perl/catalan-numbers-1.pl @@ -1,4 +1,7 @@ -sub f { $_[0] ? $_[0] * f($_[0]-1) : 1 } -sub catalan { f(2 * $_[0]) / f($_[0]) / f($_[0]+1) } +sub factorial { my $f = 1; $f *= $_ for 2 .. $_[0]; $f; } +sub catalan { + my $n = shift; + factorial(2*$n) / factorial($n+1) / factorial($n); +} print "$_\t@{[ catalan($_) ]}\n" for 0 .. 20; diff --git a/Task/Catalan-numbers/Perl/catalan-numbers-3.pl b/Task/Catalan-numbers/Perl/catalan-numbers-3.pl new file mode 100644 index 0000000000..718ac8805c --- /dev/null +++ b/Task/Catalan-numbers/Perl/catalan-numbers-3.pl @@ -0,0 +1,6 @@ +use ntheory qw/binomial/; +sub catalan { + my $n = shift; + binomial(2*$n,$n)/($n+1); +} +print "$_\t", catalan($_), "\n" for 0 .. 10000; diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx new file mode 100644 index 0000000000..9d649a5d70 --- /dev/null +++ b/Task/Catalan-numbers/REXX/catalan-numbers-1.rexx @@ -0,0 +1,31 @@ +/*REXX program calculates Catalan numbers using four different methods.*/ +parse arg bot top . /*get optional args from the C.L.*/ +if bot=='' then do; top=15; bot=0; end /*No args? Use a range of 0──►15.*/ +if top=='' then top=bot /*No top? Use the bottom for it.*/ +numeric digits max(20, 5*top) /*allows gihugic Catalan numbers.*/ +call hdr '1a'; do j=bot to top; say $cat() catalan1a(j); end +call hdr '1b'; do j=bot to top; say $cat() catalan1b(j); end +call hdr 2 ; do j=bot to top; say $cat() catalan2(j) ; end +call hdr 3 ; do j=bot to top; say $cat() catalan3(j) ; end +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines───────────────*/ +$cat: return ' Catalan' right(j,length(top))": " +catalan1a: procedure expose !.; parse arg n; return comb(n+n,n)%(n+1) +catalan1b: procedure expose !.; parse arg n; return !(n+n)%((n+1)*!(n)**2) +comb: procedure; parse arg x,y; return pFact(x-y+1,x) % pFact(2,y) +pFact: procedure; !=1; do k=arg(1) to arg(2); !=!*k; end; return ! +/*──────────────────────────────────! (factorial) function──────────────*/ +!: procedure expose !.; parse arg x; if !.x\==. then return !.x +!=1; do k=1 for x; !=!*k; end /*k*/; !.x=!; return ! +/*──────────────────────────────────catalan method 2────────────────────*/ +catalan2: procedure expose c.; parse arg n; if c.n\==. then return c.n +s=0; do k=0 to n-1 + s=s + catalan2(k) * catalan2(n-k-1) /*recursive invokes*/ + end /*k*/ +c.n=s; return s /*use REXX memoization technique.*/ +/*──────────────────────────────────catalan method 3────────────────────*/ +catalan3: procedure expose c.; parse arg n; if c.n\==. then return c.n +c.n=(4*n-2) * catalan3(n-1) % (n+1); return c.n /*use memoization.*/ +/*──────────────────────────────────HDR subroutine──────────────────────*/ +hdr: !.=.; c.=.; c.0=1; say /*set some variables; blank line.*/ +say center(' Catalan numbers, method' left(arg(1),3), 79, '─'); return diff --git a/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx b/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx new file mode 100644 index 0000000000..b523782cf9 --- /dev/null +++ b/Task/Catalan-numbers/REXX/catalan-numbers-2.rexx @@ -0,0 +1,51 @@ +/* REXX --------------------------------------------------------------- +* 01.07.2014 Walter Pachl +*--------------------------------------------------------------------*/ +Numeric Digits 1000 +Parse Arg m . +If m='' Then m=20 +Do i=0 To m + c1.i=c1(i) + End +c2.=1 +Do i=1 To m + c2.i=c2(i) + End +c3.=1 +Do i=1 To m + im1=i-1 + c3.i=2*(2*i-1)*c3.im1/(i+1) + End +l=length(c3.m) +hdr=' n' right('c1.n',l), + right('c2.n',l), + right('c3.n',l) +Say hdr +Do i=0 To m + Say right(i,2) format(c1.i,l), + format(c2.i,l), + format(c3.i,l) + End +Say hdr +Exit + +c1: Procedure +Parse Arg n +return fact(2*n)/(fact(n)*fact(n+1)) + +c2: Procedure Expose c2. +Parse Arg n +res=0 +Do i=0 To n-1 + nmi=n-i-1 + res=res+c2.i*c2.nmi + End +Return res + +fact: Procedure +Parse Arg n +f=1 +Do i=1 To n + f=f*i + End +Return f diff --git a/Task/Catalan-numbers/REXX/catalan-numbers.rexx b/Task/Catalan-numbers/REXX/catalan-numbers.rexx deleted file mode 100644 index e3fb084f46..0000000000 --- a/Task/Catalan-numbers/REXX/catalan-numbers.rexx +++ /dev/null @@ -1,47 +0,0 @@ -/*REXX program calculates Catalan numbers using three different methods.*/ -parse arg bot top . /*get args from the command line.*/ -if bot=='' then do; top=15; bot=0; end /*No args? Use a range of 0 ─► 15*/ -if top=='' then top=bot /*No top? Use the bottom for it.*/ -numeric digits max(20,5*top) /*no limit on big Catalan numbers*/ -w=length(top) /*use W to align Catalan index.*/ - -say; say center(' Catalan numbers, method 1 ' , 79, '-'); !.=0 - do m1=bot to top - say right(m1,w) '=' catalan1(m1) - end /*m1*/ - -say; say center(' Catalan numbers, method 2 ' , 79, '-'); c.=0; c.0=1 - do m2=bot to top - say right(m2,w) '=' catalan2(m2) - end /*m2*/ - -say; say center(' Catalan numbers, method 3 ' , 79, '-'); c.=0; c.0=1 - do m3=bot to top - say right(m3,w) '=' catalan3(m3) - end /*m3*/ -exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────catalan method 1────────────────────*/ -catalan1: procedure expose !.; parse arg n /*n+n is faster than 2*n */ -return !(n+n) % ( (n+1) * !(n)**2 ) /*using COMB would be faster*/ - -/*──────────────────────────────────catalan method 2────────────────────*/ -catalan2: procedure expose c.; parse arg n; if c.n\==0 then return c.n -s=0; do j=0 to n-1 - s=s + catalan2(j) * catalan2(n-j-1) /*recursive invokes.*/ - end /*j*/ -c.n=s /*use REXX memoization technique.*/ -return s - -/*──────────────────────────────────catalan method 3────────────────────*/ -catalan3: procedure expose c.; parse arg n; if c.n\==0 then return c.n -c.n=(4*n-2) * catalan3(n-1) % (n+1) /*use REXX memoization technique.*/ -return c.n - -/*──────────────────────────────────! (factorial) function──────────────*/ -!: procedure expose !.; parse arg x; if !.x\==0 then return !.x; !=1 - do k=1 for x - !=!*k - end /*k*/ -!.x=! /*use REXX memoization technique.*/ -return ! diff --git a/Task/Catalan-numbers/Run-BASIC/catalan-numbers.run b/Task/Catalan-numbers/Run-BASIC/catalan-numbers.run index 5f93ddb672..282f182115 100644 --- a/Task/Catalan-numbers/Run-BASIC/catalan-numbers.run +++ b/Task/Catalan-numbers/Run-BASIC/catalan-numbers.run @@ -3,9 +3,6 @@ FOR i = 1 TO 15 NEXT FUNCTION catalan(n) - IF n = 0 THEN - catalan = 1 - ELSE - catalan = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1) - END IF + catalan = 1 + if n <> 0 then catalan = ((2 * ((2 * n) - 1)) / (n + 1)) * catalan(n - 1) END FUNCTION diff --git a/Task/Catalan-numbers/Rust/catalan-numbers.rust b/Task/Catalan-numbers/Rust/catalan-numbers.rust new file mode 100644 index 0000000000..d601e28cc7 --- /dev/null +++ b/Task/Catalan-numbers/Rust/catalan-numbers.rust @@ -0,0 +1,13 @@ +fn factorial(n: u64) -> u64 { + range(1u64, n + 1).fold(1u64, |a, b| a * b) +} + +fn c_n(n: u64) -> u64 { + factorial(n * 2) / (factorial(n + 1) * factorial(n)) +} + +fn main() { + for i in range(1u64, 11u64) { + println!("c_n({}) = {}", i, c_n(i)) + } +} diff --git a/Task/Character-codes/00DESCRIPTION b/Task/Character-codes/00DESCRIPTION index 8f49990e6e..a6c684424b 100644 --- a/Task/Character-codes/00DESCRIPTION +++ b/Task/Character-codes/00DESCRIPTION @@ -1 +1,5 @@ -Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses). For example, the character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode). Conversely, given a code, print out the corresponding character. +Given a character value in your language, print its code (could be ASCII code, Unicode code, or whatever your language uses). + +For example, the character 'a' (lowercase letter A) has a code of 97 in ASCII (as well as Unicode, as ASCII forms the beginning of Unicode). + +Conversely, given a code, print out the corresponding character. diff --git a/Task/Character-codes/00META.yaml b/Task/Character-codes/00META.yaml index f13cf9d6db..13ebd3c3d4 100644 --- a/Task/Character-codes/00META.yaml +++ b/Task/Character-codes/00META.yaml @@ -2,4 +2,5 @@ category: - Basic language learning - String manipulation +- Simple note: Text processing diff --git a/Task/Character-codes/Babel/character-codes-1.pb b/Task/Character-codes/Babel/character-codes-1.pb new file mode 100644 index 0000000000..eab8588542 --- /dev/null +++ b/Task/Character-codes/Babel/character-codes-1.pb @@ -0,0 +1,2 @@ +'abcdefg' str2ar +{%d nl <<} eachar diff --git a/Task/Character-codes/Babel/character-codes-2.pb b/Task/Character-codes/Babel/character-codes-2.pb new file mode 100644 index 0000000000..9d53da64b9 --- /dev/null +++ b/Task/Character-codes/Babel/character-codes-2.pb @@ -0,0 +1 @@ +(98 97 98 101 108) ls2lf ar2str nl << diff --git a/Task/Character-codes/D/character-codes.d b/Task/Character-codes/D/character-codes.d index 3a902cddce..7be33740e4 100644 --- a/Task/Character-codes/D/character-codes.d +++ b/Task/Character-codes/D/character-codes.d @@ -1,13 +1,12 @@ -import std.stdio, std.utf; - void main() { + import std.stdio, std.utf; + string test = "a"; size_t index = 0; - // Get four-byte utf32 value for index 0 - // this returns dchar, so cast it to numeric. - writeln(cast(uint)test.decode(index)); + // Get four-byte utf32 value for index 0. + writefln("%d", test.decode(index)); - // 'index' has moved to next character position in input. + // 'index' has moved to next character input position. assert(index == 1); } diff --git a/Task/Character-codes/Eiffel/character-codes.e b/Task/Character-codes/Eiffel/character-codes.e new file mode 100644 index 0000000000..fcf7645eb5 --- /dev/null +++ b/Task/Character-codes/Eiffel/character-codes.e @@ -0,0 +1,28 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + c8: CHARACTER_8 + c32: CHARACTER_32 + do + c8 := '%/97/' -- using code value notation + c8 := '%/0x61/' -- same as above, but using hexadecimal literal + print(c8.natural_32_code) -- prints "97" + print(c8) -- prints the character "a" + + c32 := 'a' -- using character literal + print(c32.natural_32_code) -- prints "97" + print(c32) -- prints "U+00000061" + + --c8 := 'π' -- compile-time error (c8 does not have enough range) + c32 := 'π' -- assigns Unicode value 960 + end +end diff --git a/Task/Character-codes/Elena/character-codes.elena b/Task/Character-codes/Elena/character-codes.elena index cda8416be0..32e8bc8032 100644 --- a/Task/Character-codes/Elena/character-codes.elena +++ b/Task/Character-codes/Elena/character-codes.elena @@ -3,5 +3,5 @@ #symbol Program => [ console write:("a" getAt:0 Number). - console write:(CharValue new:97). + console write:(CharValue new &short:97). ]. diff --git a/Task/Character-codes/Frink/character-codes.frink b/Task/Character-codes/Frink/character-codes.frink index 449dd3f3ea..986e111e5f 100644 --- a/Task/Character-codes/Frink/character-codes.frink +++ b/Task/Character-codes/Frink/character-codes.frink @@ -1,4 +1,5 @@ println[char["a"]] // prints 97 +println[chars["a"]] // prints [97] (an array) println[char[97]] // prints a println[char["Frink rules!"]] // prints [70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33] println[[70, 114, 105, 110, 107, 32, 114, 117, 108, 101, 115, 33]] // prints "Frink rules!" diff --git a/Task/Character-codes/Go/character-codes-2.go b/Task/Character-codes/Go/character-codes-2.go index 3653ecac18..bfba538651 100644 --- a/Task/Character-codes/Go/character-codes-2.go +++ b/Task/Character-codes/Go/character-codes-2.go @@ -3,14 +3,19 @@ package main import "fmt" func main() { - // yes, there is more concise syntax, but this makes - // the data types very clear. - var b byte = 'a' - var r rune = 'π' - var s string = "aπ" + // yes, there is more concise syntax, but this makes + // the data types very clear. + var b byte = 'a' + var r rune = 'π' + var s string = "aπ" - fmt.Println(b, r, s) - for _, c := range s { // this gives c the type rune - fmt.Println(c) - } + fmt.Println(b, r, s) + fmt.Println("string cast to []rune:", []rune(s)) + // A range loop over a string gives runes, not bytes + fmt.Print(" string range loop: ") + for _, c := range s { + fmt.Print(c, " ") // c is type rune + } + // We can also print the bytes of a string without an explicit loop + fmt.Printf("\n string bytes: % #x\n", s) } diff --git a/Task/Character-codes/JavaScript/character-codes.js b/Task/Character-codes/JavaScript/character-codes.js index 7f6c2629b9..0553536fe1 100644 --- a/Task/Character-codes/JavaScript/character-codes.js +++ b/Task/Character-codes/JavaScript/character-codes.js @@ -1,2 +1,2 @@ -document.write('a'.charCodeAt(0)); // prints "97" -document.write(String.fromCharCode(97)); // prints "a" +console.log('a'.charCodeAt(0)); // prints "97" +console.log(String.fromCharCode(97)); // prints "a" diff --git a/Task/Character-codes/Vim-Script/character-codes.vim b/Task/Character-codes/Vim-Script/character-codes.vim new file mode 100644 index 0000000000..d37835b48a --- /dev/null +++ b/Task/Character-codes/Vim-Script/character-codes.vim @@ -0,0 +1,6 @@ +"encoding is set to utf-8 +echo char2nr("a") +"Prints 97 + +echo nr2char(97) +"Prints a diff --git a/Task/Chat-server/Go/chat-server.go b/Task/Chat-server/Go/chat-server.go index 103fa0edcf..6031671c19 100644 --- a/Task/Chat-server/Go/chat-server.go +++ b/Task/Chat-server/Go/chat-server.go @@ -1,148 +1,181 @@ package main import ( - "os" - "fmt" - "net" - "flag" "bufio" - "bytes" + "flag" + "fmt" + "log" + "net" + "strings" + "time" ) -// Quick and dirty error handling. -func error_(err error, r int) { - fmt.Printf("Error: %v\n", err) +func main() { + log.SetPrefix("chat: ") + addr := flag.String("addr", "localhost:4000", "listen address") + flag.Parse() + log.Fatal(ListenAndServe(*addr)) +} - if r >= 0 { - os.Exit(r) +// A Server represents a chat server that accepts incoming connections. +type Server struct { + add chan *conn // To add a connection + rem chan string // To remove a connection by name + msg chan string // To send a message to all connections + stop chan bool // To stop early +} + +// ListenAndServe listens on the TCP network address addr for +// new chat client connections. +func ListenAndServe(addr string) error { + ln, err := net.Listen("tcp", addr) + if err != nil { + return err + } + log.Println("Listening for connections on", addr) + defer ln.Close() + s := &Server{stop: make(chan bool)} + go s.handleConns() + for { + // TODO use AcceptTCP() so that we can get a TCPConn on which + // we can call SetKeepAlive() and SetKeepAlivePeriod() + rwc, err := ln.Accept() + if err != nil { + // TODO Could handle err.(net.Error).Temporary() + // here by adding a backoff delay. + close(s.stop) + return err + } + log.Println("New connection from", rwc.RemoteAddr()) + go newConn(s, rwc).welcome() } } -// A type for storing the connections. -type clientMap map[string]net.Conn +// handleConns is run as a go routine to handle adding and removal of +// chat client connections as well as broadcasting messages to them. +func (s *Server) handleConns() { + s.add = make(chan *conn) + s.rem = make(chan string) + s.msg = make(chan string) -// A method that makes clientMap compatible with io.Writer, allowing it to be -// used with fmt.Fprintf(). -func (cm clientMap) Write(buf []byte) (n int, err error) { - for _, c := range cm { - // Write to each client in a seperate goroutine. - go c.Write(buf) - } + // We define the `conns` map here rather than within Server, + // and we use local function literals rather than methods to be + // extra sure that the only place that touches this map is this + // method. In this way we forgo any explicit locking needed as + // we're the only go routine that can see or modify this. + conns := make(map[string]*conn) - n = len(buf) - - return -} - -// Check if a name exists; if it doesn't, add it. -func (cm clientMap) Add(name string, c net.Conn) bool { - for k := range cm { - if name == k { - return false + var dropConn func(string) + writeAll := func(str string) { + log.Printf("Broadcast: %q", str) + // TODO handle blocked connections + for name, c := range conns { + c.SetWriteDeadline(time.Now().Add(500 * time.Millisecond)) + _, err := c.Write([]byte(str)) + if err != nil { + log.Printf("Error writing to %q: %v", name, err) + c.Close() + delete(conns, name) + // Defer all the disconnect messages until after + // we've closed all currently problematic conns. + defer dropConn(name) + } } } - cm[name] = c - - return true -} - -// A clientMap variable. -var clients clientMap - -func init() { - // Initialize the map. - clients = make(clientMap) -} - -func client(c net.Conn) { - // Close the connection when this function returns. - defer c.Close() - - br := bufio.NewReader(c) - - fmt.Fprintf(c, "Please enter your name: ") - - buf, err := br.ReadBytes('\n') - if err != nil { - error_(err, -1) - return - } - name := string(bytes.Trim(buf, " \t\n\r\x00")) - - if name == "" { - fmt.Fprintf(c, "!!! %v is invalid !!!\n", name) + dropConn = func(name string) { + if c, ok := conns[name]; ok { + log.Printf("Closing connection with %q from %v", + name, c.RemoteAddr()) + c.Close() + delete(conns, name) + } else { + log.Printf("Dropped connection with %q", name) + } + str := fmt.Sprintf("--- %q disconnected ---\n", name) + writeAll(str) } - // Try to add the connection to the map. - if !clients.Add(name, c) { - fmt.Fprintf(c, "!!! %v is not available !!!\n", name) - return - } - - // Send a message telling the clients who connected. - fmt.Fprintf(clients, "+++ %v connected +++\n", name) - // Send a disconnected message when the function returns. - defer fmt.Fprintf(clients, "--- %v disconnected ---\n", name) - // Remove the client from the list. - defer delete(clients, name) + defer func() { + writeAll("Server stopping!\n") + for _, c := range conns { + c.Close() + } + }() for { - buf, err = br.ReadBytes('\n') + select { + case c := <-s.add: + if _, exists := conns[c.name]; exists { + fmt.Fprintf(c, "Name %q is not available\n", c.name) + go c.welcome() + continue + } + str := fmt.Sprintf("+++ %q connected +++\n", c.name) + writeAll(str) + conns[c.name] = c + go c.readloop() + case str := <-s.msg: + writeAll(str) + case name := <-s.rem: + dropConn(name) + case <-s.stop: + return + } + } +} + +// A conn represents the server side of a single chat connection. +// Note we embed the bufio.Reader and net.Conn (and specifically in +// that order) so that a conn gets the appropriate methods from each +// to be a full io.ReadWriteCloser. +type conn struct { + *bufio.Reader // buffered input + net.Conn // raw connection + server *Server // the Server on which the connection arrived + name string +} + +func newConn(s *Server, rwc net.Conn) *conn { + return &conn{ + Reader: bufio.NewReader(rwc), + Conn: rwc, + server: s, + } +} + +// welcome requests a name from the client before attempting to add the +// named connect to the set handled by the server. +func (c *conn) welcome() { + var err error + for c.name = ""; c.name == ""; { + fmt.Fprint(c, "Enter your name: ") + c.name, err = c.ReadString('\n') + if err != nil { + log.Printf("Reading name from %v: %v", c.RemoteAddr(), err) + c.Close() + return + } + c.name = strings.TrimSpace(c.name) + } + // The server will take this *conn and do a final check + // on the name, possibly starting c.welcome() again. + c.server.add <- c +} + +// readloop is started as a go routine by the server once the initial +// welcome phase has completed successfully. It reads single lines from +// the client and passes them to the server for broadcast to all chat +// clients (including us). +// Once done, we ask the server to remove our (and close) our connection. +func (c *conn) readloop() { + for { + msg, err := c.ReadString('\n') if err != nil { break } - buf = bytes.Trim(buf, " \t\n\r\x00") - - // Ignore empty messages. - if len(buf) == 0 { - continue - } - - switch { - // Support for '/me' type messages. - case string(buf[0:3]) == "/me": - buf = append([]byte(name), buf[3:]...) - default: - // Prepend the user-name and '> '. - buf = append([]byte(name+"> "), buf...) - } - - // Send the message to all the clients. - fmt.Fprintf(clients, "%v\n", string(buf)) - } -} - -func main() { - // Flags. Use -help for usage info. - var ( - port int - help bool - ) - flag.IntVar(&port, "port", 23, "Port to listen on") - flag.BoolVar(&help, "help", false, "Display this") - flag.Parse() - - if help { - flag.Usage() - return - } - - // Initialize a new listener. - lis, err := net.Listen("tcp", fmt.Sprintf(":%v", port)) - if err != nil { - error_(err, 1) - } - - // Begin the main loop. - for { - c, err := lis.Accept() - if err != nil { - error_(err, -1) - continue - } - - // Launch a new goroutine to handle the connection. - go client(c) + //msg = strings.TrimSpace(msg) + c.server.msg <- c.name + "> " + msg } + c.server.rem <- c.name } diff --git a/Task/Chat-server/Haskell/chat-server.hs b/Task/Chat-server/Haskell/chat-server-1.hs similarity index 100% rename from Task/Chat-server/Haskell/chat-server.hs rename to Task/Chat-server/Haskell/chat-server-1.hs diff --git a/Task/Chat-server/Haskell/chat-server-2.hs b/Task/Chat-server/Haskell/chat-server-2.hs new file mode 100644 index 0000000000..0d14e5d3d4 --- /dev/null +++ b/Task/Chat-server/Haskell/chat-server-2.hs @@ -0,0 +1,27 @@ +global mlck, nCons, cons + +procedure main() + mlck := mutex() + nCons := 0 + cons := mutex(set()) + while f := open(":12321","na") do { + handle_client(f) + critical mlck: if nCons <= 0 then close(f) + } +end + +procedure handle_client(f) + critical mlck: nCons +:= 1 + thread { + select(f,1000) & { + writes(f, "Name? ") + nick := (read(f) ? tab(upto('\n\r'))) + every write(!cons, nick," has joined.") + insert(cons, f) + while s := read(f) do every write(!cons, nick,": ",s) + } + delete(cons, f) + every write(!cons, nick," has left.") + critical mlck: nCons -:= 1 + } +end diff --git a/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d b/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d index 8eb0585fc8..be5b0e070d 100644 --- a/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d +++ b/Task/Check-Machin-like-formulas/D/check-machin-like-formulas.d @@ -9,7 +9,7 @@ Pair[][] parseEquations(in string text) /*pure nothrow*/ { Pair[][] machins; foreach (const line; text.splitLines) { Pair[] formula; - foreach (/*const*/ part; line.split("=")[1].matchAll(r)) { + foreach (part; line.split("=")[1].matchAll(r)) { immutable mul = part["mul"], num = part["num"], denom = part["denom"]; @@ -24,9 +24,9 @@ Pair[][] parseEquations(in string text) /*pure nothrow*/ { } -Rational tans(in Pair[] xs) pure /*nothrow*/ { +Rational tans(in Pair[] xs) pure nothrow { static Rational tanEval(in int coef, in Rational f) - pure /*nothrow*/ { + pure nothrow { if (coef == 1) return f; if (coef < 0) diff --git a/Task/Check-Machin-like-formulas/PARI-GP/check-machin-like-formulas.pari b/Task/Check-Machin-like-formulas/PARI-GP/check-machin-like-formulas.pari new file mode 100644 index 0000000000..76ea53305e --- /dev/null +++ b/Task/Check-Machin-like-formulas/PARI-GP/check-machin-like-formulas.pari @@ -0,0 +1,31 @@ +tanEval(coef, f)={ + if (coef <= 1, return(if(coef<1,-tanEval(-coef, f),f))); + my(a=tanEval(coef\2, f), b=tanEval(coef-coef\2, f)); + (a + b)/(1 - a*b) +}; +tans(xs)={ + if (#xs == 1, return(tanEval(xs[1][1], xs[1][2]))); + my(a=tans(xs[1..#xs\2]),b=tans(xs[#xs\2+1..#xs])); + (a + b)/(1 - a*b) +}; +test(v)={ + my(t=tans(v)); + if(t==1,print("OK"),print("Error: "v)) +}; +test([[1,1/2],[1,1/3]]); +test([[2,1/3],[1,1/7]]); +test([[4,1/5],[-1,1/239]]); +test([[5,1/7],[2,3/79]]); +test([[5,29/278],[7,3/79]]); +test([[1,1/2],[1,1/5],[1,1/8]]); +test([[4,1/5],[-1,1/70],[1,1/99]]); +test([[5,1/7],[4,1/53],[2,1/4443]]); +test([[6,1/8],[2,1/57],[1,1/239]]); +test([[8,1/10],[-1,1/239],[-4,1/515]]); +test([[12,1/18],[8,1/57],[-5,1/239]]); +test([[16,1/21],[3,1/239],[4,3/1042]]); +test([[22,1/28],[2,1/443],[-5,1/1393],[-10,1/11018]]); +test([[22,1/38],[17,7/601],[10,7/8149]]); +test([[44,1/57],[7,1/239],[-12,1/682],[24,1/12943]]); +test([[88,1/172],[51,1/239],[32,1/682],[44,1/5357],[68,1/12943]]); +test([[88,1/172],[51,1/239],[32,1/682],[44,1/5357],[68,1/12944]]); diff --git a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx index 2be4ecb356..f025634e0b 100644 --- a/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx +++ b/Task/Check-Machin-like-formulas/REXX/check-machin-like-formulas.rexx @@ -1,27 +1,27 @@ /*REXX program evaluates some expressions and verifies their veracity.*/ parse arg digs .; if digs=='' then digs=100 /*use default for digs?*/ -numeric digits digs+10; numeric fuzz 3; pi=pi(); !.= - !.1 = 'pi/4 = atan(1/2) + atan(1/3)' - !.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' - !.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' - !.4 = 'pi/4 = 5*atan(1/7) + 2*atan(3/79)' - !.5 = 'pi/4 = 5*atan(29/278) + 7*atan(3/79)' - !.6 = 'pi/4 = atan(1/2) + atan(1/5) + atan(1/8)' - !.7 = 'pi/4 = 4*atan(1/5) - atan(1/70) + atan(1/99)' - !.8 = 'pi/4 = 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443)' - !.9 = 'pi/4 = 6*atan(1/8) + 2*atan(1/57) + atan(1/239)' -!.10 = 'pi/4 = 8*atan(1/10) - atan(1/239) - 4*atan(1/515)' -!.11 = 'pi/4 = 12*atan(1/18) + 8*atan(1/57) - 5*atan(1/239)' -!.12 = 'pi/4 = 16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042)' -!.13 = 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)' -!.14 = 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)' -!.15 = 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)' -!.16 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943)' -!.17 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944)' +numeric digits digs+10; numeric fuzz 3; pi=pi(); @.= + @.1 = 'pi/4 = atan(1/2) + atan(1/3)' + @.2 = 'pi/4 = 2*atan(1/3) + atan(1/7)' + @.3 = 'pi/4 = 4*atan(1/5) - atan(1/239)' + @.4 = 'pi/4 = 5*atan(1/7) + 2*atan(3/79)' + @.5 = 'pi/4 = 5*atan(29/278) + 7*atan(3/79)' + @.6 = 'pi/4 = atan(1/2) + atan(1/5) + atan(1/8)' + @.7 = 'pi/4 = 4*atan(1/5) - atan(1/70) + atan(1/99)' + @.8 = 'pi/4 = 5*atan(1/7) + 4*atan(1/53) + 2*atan(1/4443)' + @.9 = 'pi/4 = 6*atan(1/8) + 2*atan(1/57) + atan(1/239)' +@.10 = 'pi/4 = 8*atan(1/10) - atan(1/239) - 4*atan(1/515)' +@.11 = 'pi/4 = 12*atan(1/18) + 8*atan(1/57) - 5*atan(1/239)' +@.12 = 'pi/4 = 16*atan(1/21) + 3*atan(1/239) + 4*atan(3/1042)' +@.13 = 'pi/4 = 22*atan(1/28) + 2*atan(1/443) - 5*atan(1/1393) - 10*atan(1/11018)' +@.14 = 'pi/4 = 22*atan(1/38) + 17*atan(7/601) + 10*atan(7/8149)' +@.15 = 'pi/4 = 44*atan(1/57) + 7*atan(1/239) - 12*atan(1/682) + 24*atan(1/12943)' +@.16 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12943)' +@.17 = 'pi/4 = 88*atan(1/172) + 51*atan(1/239) + 32*atan(1/682) + 44*atan(1/5357) + 68*atan(1/12944)' - do j=1 while !.j\=='' /*evaluate each of the formulas. */ - interpret 'answer=' "(" !.j ")" /*the heavy lifting.*/ - say right(word('bad OK',answer+1),3)": " space(!.j,0) + do j=1 while @.j\=='' /*evaluate each of the formulas. */ + interpret 'answer=' "(" @.j ")" /*the heavy lifting.*/ + say right(word('bad OK',answer+1),3)": " space(@.j,0) end /*j*/ /* [↑] show OK | bad, formula. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines─────────────────────────*/ @@ -29,9 +29,9 @@ Acos: procedure; parse arg x; if x<-1 | x>1 then call AcosErr return .5*pi()-Asin(x) Asin: procedure; parse arg x; if x<-1 | x>1 then call AsinErr; s=x*x - if abs(x)>=.7 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z - do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end - return z +if abs(x)>=sqrt(2)*.5 then return sign(x)*Acos(sqrt(1-s)); z=x; o=x; p=z + do j=2 by 2; o=o*s*(j-1)/j; z=z+o/(j+1); if z=p then leave; p=z; end +return z Atan: procedure; parse arg x; if abs(x)=1 then return pi()/4*sign(x) return Asin(x/sqrt(1+x**2)) diff --git a/Task/Check-that-file-exists/00DESCRIPTION b/Task/Check-that-file-exists/00DESCRIPTION index ccf27b821e..76ae248e94 100644 --- a/Task/Check-that-file-exists/00DESCRIPTION +++ b/Task/Check-that-file-exists/00DESCRIPTION @@ -1 +1,2 @@ -In this task, the job is to verify that a file called "input.txt" and the directory called "docs" exist. This should be done twice: once for the current working directory and once for a file and a directory in the filesystem root. +In this task, the job is to verify that a file called "input.txt" and the directory called "docs" exist. +This should be done twice: once for the current working directory and once for a file and a directory in the filesystem root. diff --git a/Task/Check-that-file-exists/00META.yaml b/Task/Check-that-file-exists/00META.yaml index 40458d9f21..308143aadb 100644 --- a/Task/Check-that-file-exists/00META.yaml +++ b/Task/Check-that-file-exists/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: File System Operations diff --git a/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.l b/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.l new file mode 100644 index 0000000000..93c74c0e76 --- /dev/null +++ b/Task/Check-that-file-exists/Emacs-Lisp/check-that-file-exists.l @@ -0,0 +1,4 @@ +(file-exists-p "input.txt") +(file-directory-p "docs") +(file-exists-p "/input.txt") +(file-directory-p "/docs") diff --git a/Task/Check-that-file-exists/NewLISP/check-that-file-exists.newlisp b/Task/Check-that-file-exists/NewLISP/check-that-file-exists.newlisp new file mode 100644 index 0000000000..54ae8c0fad --- /dev/null +++ b/Task/Check-that-file-exists/NewLISP/check-that-file-exists.newlisp @@ -0,0 +1,7 @@ +(dolist (file '("input.txt" "/input.txt")) + (if (file? file true) + (println "file " file " exists"))) + +(dolist (dir '("docs" "/docs")) + (if (directory? dir) + (println "directory " dir " exists"))) diff --git a/Task/Check-that-file-exists/Prolog/check-that-file-exists.pro b/Task/Check-that-file-exists/Prolog/check-that-file-exists.pro new file mode 100644 index 0000000000..2af16f4a8a --- /dev/null +++ b/Task/Check-that-file-exists/Prolog/check-that-file-exists.pro @@ -0,0 +1,5 @@ +exists_file('input.txt'), +exists_directory('docs'). + +exits_file('/input.txt'), +exists_directory('/docs'). 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 index a78119794e..6061493813 100644 --- a/Task/Check-that-file-exists/Scala/check-that-file-exists.scala +++ b/Task/Check-that-file-exists/Scala/check-that-file-exists.scala @@ -1,5 +1,17 @@ -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) +import java.nio.file.{ Files, FileSystems } + +object FileExistsTest extends App { + + val defaultFS = FileSystems.getDefault() + val separator = defaultFS.getSeparator() + + def test(filename: String) { + val path = defaultFS.getPath(filename) + + println(s"The following ${if (Files.isDirectory(path)) "directory" else "file"} called $filename" + + (if (Files.exists(path)) " exists." else " not exists.")) + } + + // main + List("output.txt", separator + "output.txt", "docs", separator + "docs" + separator).foreach(test) +} diff --git a/Task/Cholesky-decomposition/00DESCRIPTION b/Task/Cholesky-decomposition/00DESCRIPTION index 0e849c9368..6648b11250 100644 --- a/Task/Cholesky-decomposition/00DESCRIPTION +++ b/Task/Cholesky-decomposition/00DESCRIPTION @@ -16,7 +16,7 @@ A &= & = \begin{pmatrix} l_{11} & 0 & 0 \\ - l_{21} & l_{22} & 0 \\f + l_{21} & l_{22} & 0 \\ l_{31} & l_{32} & l_{33}\\ \end{pmatrix} \begin{pmatrix} diff --git a/Task/Cholesky-decomposition/D/cholesky-decomposition.d b/Task/Cholesky-decomposition/D/cholesky-decomposition.d index e8c8e0c295..46dbc056c1 100644 --- a/Task/Cholesky-decomposition/D/cholesky-decomposition.d +++ b/Task/Cholesky-decomposition/D/cholesky-decomposition.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.numeric; -T[][] cholesky(T)(in T[][] A) pure nothrow { +T[][] cholesky(T)(in T[][] A) pure nothrow /*@safe*/ { auto L = new T[][](A.length, A.length); foreach (immutable r, row; L) row[r + 1 .. $] = 0; @@ -14,14 +14,14 @@ T[][] cholesky(T)(in T[][] A) pure nothrow { } void main() { - double[][] m1 = [[25, 15, -5], - [15, 18, 0], - [-5, 0, 11]]; - writefln("%(%(%2.0f %)\n%)\n", cholesky(m1)); + immutable double[][] m1 = [[25, 15, -5], + [15, 18, 0], + [-5, 0, 11]]; + writefln("%(%(%2.0f %)\n%)\n", m1.cholesky); - double[][] m2 = [[18, 22, 54, 42], - [22, 70, 86, 62], - [54, 86, 174, 134], - [42, 62, 134, 106]]; - writefln("%(%(%2.3f %)\n%)\n", m2.cholesky); + immutable double[][] m2 = [[18, 22, 54, 42], + [22, 70, 86, 62], + [54, 86, 174, 134], + [42, 62, 134, 106]]; + writefln("%(%(%2.3f %)\n%)", m2.cholesky); } diff --git a/Task/Cholesky-decomposition/J/cholesky-decomposition-1.j b/Task/Cholesky-decomposition/J/cholesky-decomposition-1.j index 9d58d5f3cf..8a5069e642 100644 --- a/Task/Cholesky-decomposition/J/cholesky-decomposition-1.j +++ b/Task/Cholesky-decomposition/J/cholesky-decomposition-1.j @@ -7,8 +7,7 @@ cholesky=: 3 : 0 assert. (A=|A)>0=A NB. check for positive definite %:A else. - p=. >.n%2 [ q=. <.n%2 - X=. (p,p) {.A [ Y=. (p,-q){.A [ Z=. (-q,q){.A + 'X Y t Z'=. , (;~n$(>.-:n){.1) <;.1 A L0=. cholesky X L1=. cholesky Z-(T=.(h Y) mp %.X) mp Y L0,(T mp L0),.L1 diff --git a/Task/Cholesky-decomposition/Smalltalk/cholesky-decomposition.st b/Task/Cholesky-decomposition/Smalltalk/cholesky-decomposition.st new file mode 100644 index 0000000000..2cf713301e --- /dev/null +++ b/Task/Cholesky-decomposition/Smalltalk/cholesky-decomposition.st @@ -0,0 +1,22 @@ +FloatMatrix>>#cholesky + | l | + l := FloatMatrix zero: numRows. + 1 to: numRows do: [:i | + 1 to: i do: [:k | | rowSum lkk factor aki partialSum | + i = k + ifTrue: [ + rowSum := (1 to: k - 1) sum: [:j | | lkj | + lkj := l at: j @ k. + lkj squared]. + lkk := (self at: k @ k) - rowSum. + lkk := lkk sqrt. + l at: k @ k put: lkk] + ifFalse: [ + factor := l at: k @ k. + aki := self at: k @ i. + partialSum := (1 to: k - 1) sum: [:j | | ljk lji | + lji := l at: j @ i. + ljk := l at: j @ k. + lji * ljk]. + l at: k @ i put: aki - partialSum * factor reciprocal]]]. + ^l diff --git a/Task/Classes/00DESCRIPTION b/Task/Classes/00DESCRIPTION index 916fffc8da..e30b50e311 100644 --- a/Task/Classes/00DESCRIPTION +++ b/Task/Classes/00DESCRIPTION @@ -1,14 +1,28 @@ -In [[object-oriented programming]] '''class''' is a set (a [[wp:Transitive_closure|transitive closure]]) of types bound by the relation of [[inheritance]]. It is said that all types derived from some base type T and the type T itself form a class T. The first type T from the class T sometimes is called the '''root type''' of the class. +In [[object-oriented programming]] '''class''' is a set (a [[wp:Transitive_closure|transitive closure]]) of types bound by the relation of [[inheritance]]. It is said that all types derived from some base type T and the type T itself form a class T. +The first type T from the class T sometimes is called the '''root type''' of the class. -A class of types itself, as a type, has the values and operations of its own. The operations of are usually called '''methods''' of the root type. Both operations and values are called [[polymorphism | polymorphic]]. +A class of types itself, as a type, has the values and operations of its own. +The operations of are usually called '''methods''' of the root type. +Both operations and values are called [[polymorphism | polymorphic]]. -A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. The action of choice the type-specific implementation of a polymorphic operation is called '''dispatch'''. Correspondingly, polymorphic operations are often called '''dispatching''' or '''virtual'''. Operations with multiple arguments and/or the results of the class are called '''multi-methods'''. A further generalization of is the operation with arguments and/or results from different classes. +A polymorphic operation (method) selects an implementation depending on the actual specific type of the polymorphic argument. +The action of choice the type-specific implementation of a polymorphic operation is called '''dispatch'''. Correspondingly, polymorphic operations are often called '''dispatching''' or '''virtual'''. +Operations with multiple arguments and/or the results of the class are called '''multi-methods'''. +A further generalization of is the operation with arguments and/or results from different classes. * single-dispatch languages are those that allow only one argument or result to control the dispatch. Usually it is the first parameter, often hidden, so that a prefix notation ''x''.''f''() is used instead of mathematical ''f''(''x''). * multiple-dispatch languages allow many arguments and/or results to control the dispatch. -A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. This type is sometimes called '''the most specific type''' of a [polymorphic] value. The type tag of the value is used in order to resolve the dispatch. The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. +A polymorphic value has a type tag indicating its specific type from the class and the corresponding specific value of that type. +This type is sometimes called '''the most specific type''' of a [polymorphic] value. +The type tag of the value is used in order to resolve the dispatch. +The set of polymorphic values of a class is a transitive closure of the sets of values of all types from that class. -In many [[object-oriented programming | OO]] languages the type of the class of T and T itself are considered equivalent. In some languages they are distinct (like in [[Ada]]). When class T and T are equivalent, there is no way to distinguish polymorphic and specific values. +In many [[object-oriented programming | OO]] languages +the type of the class of T and T itself are considered equivalent. +In some languages they are distinct (like in [[Ada]]). +When class T and T are equivalent, there is no way to distinguish +polymorphic and specific values. -The purpose of this task is to create a basic class with a method, a constructor, an instance variable and how to instantiate it. +The purpose of this task is to create a basic class with a method, +a constructor, an instance variable and how to instantiate it. diff --git a/Task/Classes/Clojure/classes.clj b/Task/Classes/Clojure/classes.clj new file mode 100644 index 0000000000..1da45ba20b --- /dev/null +++ b/Task/Classes/Clojure/classes.clj @@ -0,0 +1,9 @@ +; You can think of this as an interface +(defprotocol Foo (getFoo [this])) + +; Generates Example1 Class with foo as field, with method that returns foo. +(defrecord Example1 [foo] Foo (getFoo [this] foo)) + +; Create instance and invoke our method to return field value +(-> (Example1. "Hi") .getFoo) +"Hi" diff --git a/Task/Classes/Java/classes.java b/Task/Classes/Java/classes-1.java similarity index 74% rename from Task/Classes/Java/classes.java rename to Task/Classes/Java/classes-1.java index 62456424fc..1be8b1fa3f 100644 --- a/Task/Classes/Java/classes.java +++ b/Task/Classes/Java/classes-1.java @@ -1,4 +1,4 @@ -public class MyClass { +public class MyClass{ // instance variable private int variable; // Note: instance variables are usually "private" @@ -6,14 +6,14 @@ public class MyClass { /** * The constructor */ - public MyClass() { + public MyClass(){ // creates a new instance } /** * A method */ - public void someMethod() { + public void someMethod(){ this.variable = 1; } } diff --git a/Task/Classes/Java/classes-2.java b/Task/Classes/Java/classes-2.java new file mode 100644 index 0000000000..956a0f6ee8 --- /dev/null +++ b/Task/Classes/Java/classes-2.java @@ -0,0 +1 @@ +new MyClass(); diff --git a/Task/Classes/Objective-C/classes-2.m b/Task/Classes/Objective-C/classes-2.m index e49eb8e20e..88ef8459a1 100644 --- a/Task/Classes/Objective-C/classes-2.m +++ b/Task/Classes/Objective-C/classes-2.m @@ -1,10 +1,11 @@ @implementation MyClass // Was not declared because init is defined in NSObject -- (id)init +- (instancetype)init { - if (self = [super init]) - variable = 0; + if (self = [super init]) { + variable = 0; // not strictly necessary as all instance variables are initialized to zero + } return self; } diff --git a/Task/Classes/REALbasic/classes-1.realbasic b/Task/Classes/REALbasic/classes-1.realbasic new file mode 100644 index 0000000000..5b09f50b35 --- /dev/null +++ b/Task/Classes/REALbasic/classes-1.realbasic @@ -0,0 +1,14 @@ +Class NumberContainer + Private TheNumber As Integer + Sub Constructor(InitialNumber As Integer) + TheNumber = InitialNumber + End Sub + + Function Number() As Integer + Return TheNumber + End Function + + Sub Number(Assigns NewNumber As Integer) + TheNumber = NewNumber + End Sub +End Class diff --git a/Task/Classes/REALbasic/classes-2.realbasic b/Task/Classes/REALbasic/classes-2.realbasic new file mode 100644 index 0000000000..717b398a66 --- /dev/null +++ b/Task/Classes/REALbasic/classes-2.realbasic @@ -0,0 +1,2 @@ +Dim num As New NumberContainer(1) ' call the constructor +num.Number = num.Number + 5 ' call both Number methods diff --git a/Task/Classes/Ruby/classes.rb b/Task/Classes/Ruby/classes.rb index 92ca5d16ef..9f3b8613ef 100644 --- a/Task/Classes/Ruby/classes.rb +++ b/Task/Classes/Ruby/classes.rb @@ -1,26 +1,13 @@ class MyClass - @@class_var = [] def initialize - # 'initialize' is the constructor method invoked during 'MyClass.new' @instance_var = 0 end - def some_method - @instance_var = 1 - @@class_var << Time.now + def add_1 + @instance_var += 1 end - def self.class_method - # ... - end - - # another way to define class methods: define an instance method in this class object's singleton class - class << self - def another_class_method - # ... - end - end end -myclass = MyClass.new +my_class = MyClass.new #allocates an object and calls it's initialize method, then returns it. diff --git a/Task/Classes/UNIX-Shell/classes.sh b/Task/Classes/UNIX-Shell/classes.sh new file mode 100644 index 0000000000..b7794b95ed --- /dev/null +++ b/Task/Classes/UNIX-Shell/classes.sh @@ -0,0 +1,19 @@ +typeset -T Summation_t=( + integer sum + + # the constructor + function create { + _.sum=0 + } + + # a method + function add { + (( _.sum += $1 )) + } +) + +Summation_t s +for i in 1 2 3 4 5; do + s.add $i +done +print ${s.sum} diff --git a/Task/Closest-pair-problem/00DESCRIPTION b/Task/Closest-pair-problem/00DESCRIPTION index 7dbc003b14..162b19eaf2 100644 --- a/Task/Closest-pair-problem/00DESCRIPTION +++ b/Task/Closest-pair-problem/00DESCRIPTION @@ -1,7 +1,9 @@ {{Wikipedia|Closest pair of points problem}} The aim of this task is to provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the [[wp:Closest pair of points problem|Closest pair of points problem]] in the ''planar'' case. -The straightforward solution is a O(n2) algorithm (which we can call ''brute-force algorithm''); the pseudocode (using indexes) could be simply: +The straightforward solution is a O(n2) algorithm +(which we can call ''brute-force algorithm''); +the pseudocode (using indexes) could be simply: '''bruteForceClosestPair''' of P(1), P(2), ... P(N) '''if''' N < 2 '''then''' @@ -20,7 +22,9 @@ The straightforward solution is a O(n2) algorithm (which we can call '''return''' minDistance, minPoints '''endif''' -A better algorithm is based on the recursive divide&conquer approach, as explained also at [[wp:Closest pair of points problem#Planar_case|Wikipedia]], which is O(''n'' log ''n''); a pseudocode could be: +A better algorithm is based on the recursive divide&conquer approach, +as explained also at [[wp:Closest pair of points problem#Planar_case|Wikipedia]], +which is O(''n'' log ''n''); a pseudocode could be: '''closestPair''' of (xP, yP) where xP is P(1) .. P(N) sorted by x coordinate, and diff --git a/Task/Closest-pair-problem/C++/closest-pair-problem.cpp b/Task/Closest-pair-problem/C++/closest-pair-problem.cpp new file mode 100644 index 0000000000..c855813fed --- /dev/null +++ b/Task/Closest-pair-problem/C++/closest-pair-problem.cpp @@ -0,0 +1,115 @@ +/* + Author: Kevin Bacon + Date: 04/03/2014 + Task: Closest-pair problem +*/ + +#include +#include +#include +#include +#include +#include +#include +#include + +typedef std::pair point_t; +typedef std::pair points_t; + +double distance_between(const point_t& a, const point_t& b) { + return std::sqrt(std::pow(b.first - a.first, 2) + + std::pow(b.second - a.second, 2)); +} + +std::pair find_closest_brute(const std::vector& points) { + if (points.size() < 2) { + return { -1, { { 0, 0 }, { 0, 0 } } }; + } + auto minDistance = std::abs(distance_between(points.at(0), points.at(1))); + points_t minPoints = { points.at(0), points.at(1) }; + for (auto i = std::begin(points); i != (std::end(points) - 1); ++i) { + for (auto j = i + 1; j < std::end(points); ++j) { + auto newDistance = std::abs(distance_between(*i, *j)); + if (newDistance < minDistance) { + minDistance = newDistance; + minPoints.first = *i; + minPoints.second = *j; + } + } + } + return { minDistance, minPoints }; +} + +std::pair find_closest_optimized(const std::vector& xP, + const std::vector& yP) { + if (xP.size() <= 3) { + return find_closest_brute(xP); + } + auto N = xP.size(); + auto xL = std::vector(); + auto xR = std::vector(); + std::copy(std::begin(xP), std::begin(xP) + (N / 2), std::back_inserter(xL)); + std::copy(std::begin(xP) + (N / 2), std::end(xP), std::back_inserter(xR)); + auto xM = xP.at(N / 2).first; + auto yL = std::vector(); + auto yR = std::vector(); + std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yL), [&xM](const point_t& p) { + return p.first <= xM; + }); + std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yR), [&xM](const point_t& p) { + return p.first > xM; + }); + auto p1 = find_closest_optimized(xL, yL); + auto p2 = find_closest_optimized(xR, yR); + auto minPair = (p1.first <= p2.first) ? p1 : p2; + auto yS = std::vector(); + std::copy_if(std::begin(yP), std::end(yP), std::back_inserter(yS), [&minPair, &xM](const point_t& p) { + return std::abs(xM - p.first) < minPair.first; + }); + auto result = minPair; + for (auto i = std::begin(yS); i != (std::end(yS) - 1); ++i) { + for (auto k = i + 1; k != std::end(yS) && + ((k->second - i->second) < minPair.first); ++k) { + auto newDistance = std::abs(distance_between(*k, *i)); + if (newDistance < result.first) { + result = { newDistance, { *k, *i } }; + } + } + } + return result; +} + +void print_point(const point_t& point) { + std::cout << "(" << point.first + << ", " << point.second + << ")"; +} + +int main(int argc, char * argv[]) { + std::default_random_engine re(std::chrono::system_clock::to_time_t( + std::chrono::system_clock::now())); + std::uniform_real_distribution urd(-500.0, 500.0); + std::vector points(100); + std::generate(std::begin(points), std::end(points), [&urd, &re]() { + return point_t { 1000 + urd(re), 1000 + urd(re) }; + }); + auto answer = find_closest_brute(points); + std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { + return a.first < b.first; + }); + auto xP = points; + std::sort(std::begin(points), std::end(points), [](const point_t& a, const point_t& b) { + return a.second < b.second; + }); + auto yP = points; + std::cout << "Min distance (brute): " << answer.first << " "; + print_point(answer.second.first); + std::cout << ", "; + print_point(answer.second.second); + answer = find_closest_optimized(xP, yP); + std::cout << "\nMin distance (optimized): " << answer.first << " "; + print_point(answer.second.first); + std::cout << ", "; + print_point(answer.second.second); + return 0; +} diff --git a/Task/Closest-pair-problem/D/closest-pair-problem-1.d b/Task/Closest-pair-problem/D/closest-pair-problem-1.d index 326e8143cb..2c2bf9b689 100644 --- a/Task/Closest-pair-problem/D/closest-pair-problem-1.d +++ b/Task/Closest-pair-problem/D/closest-pair-problem-1.d @@ -1,12 +1,9 @@ import std.stdio, std.typecons, std.math, std.algorithm, std.random, std.traits, std.range, std.complex; -//auto bfClosestPair(T)(in T[] points) pure nothrow { +auto bruteForceClosestPair(T)(in T[] points) pure nothrow @nogc { // return pairwise(points.length.iota, points.length.iota) // .reduce!(min!((i, j) => abs(points[i] - points[j]))); -//} - -auto bruteForceClosestPair(T)(in T[] points) pure nothrow { auto minD = Unqual!(typeof(T.re)).infinity; T minI, minJ; foreach (immutable i, const p1; points.dropBackOne) @@ -21,7 +18,7 @@ auto bruteForceClosestPair(T)(in T[] points) pure nothrow { return tuple(minD, minI, minJ); } -auto closestPair(T)(T[] points) /*pure nothrow*/ { +auto closestPair(T)(T[] points) pure nothrow { static Tuple!(typeof(T.re), T, T) inner(in T[] xP, /*in*/ T[] yP) pure nothrow { if (xP.length <= 3) diff --git a/Task/Closest-pair-problem/D/closest-pair-problem-2.d b/Task/Closest-pair-problem/D/closest-pair-problem-2.d index 7b0d6f5ac9..6d5cdc9ae2 100644 --- a/Task/Closest-pair-problem/D/closest-pair-problem-2.d +++ b/Task/Closest-pair-problem/D/closest-pair-problem-2.d @@ -2,7 +2,7 @@ import std.stdio, std.random, std.math, std.typecons, std.complex, std.traits; Nullable!(Tuple!(size_t, size_t)) -bfClosestPair2(T)(in Complex!T[] points) pure nothrow { +bfClosestPair2(T)(in Complex!T[] points) pure nothrow @nogc { auto minD = Unqual!(typeof(points[0].re)).infinity; if (points.length < 2) return typeof(return)(); diff --git a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx index f929ac6413..72295d045e 100644 --- a/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx +++ b/Task/Closest-pair-problem/REXX/closest-pair-problem.rexx @@ -1,37 +1,32 @@ -/*REXX program to solve the closest pair problem. */ -parse arg N low high seed .; if n=='' then n=100 -if seed\=='' then call random ,,seed /*use seed, makes rand repeatable*/ -if low=='' | low==',' then low=0 -if high=='' | high==',' then high=20000 -w=length(high); w=w + (w//2==0) - do j=1 for N /*gen random points*/ - @.j.xx=random(low,high) - @.j.yy=random(low,high) +/*REXX program solves the closest pair of points problem in 2 dimensions*/ +parse arg N low high seed . /*get optional arguments from CL.*/ +if N=='' | N==',' then N=100 /*N not specified? Use default.*/ +if low=='' | low==',' then low=0 +if high=='' | high==',' then high=20000 +if seed\==''& seed\==',' then call random ,,seed /*seed for repeatable.*/ +w=length(high); w=w + (w//2==0) + /*╔══════════════════════╗*/ do j=1 for N /*gen N random pts.*/ + /*║ generate N points. ║*/ @x.j=random(low,high) /*random X.*/ + /*╚══════════════════════╝*/ @y.j=random(low,high) /* " Y.*/ end /*j*/ -nearA=1 -nearB=2 -minDD=(@.nearA.xx-@.nearB.xx)**2 + (@.nearA.yy-@.nearB.yy)**2 + A=1; B=2 +minDD=(@x.A-@x.B)**2 + (@y.A-@y.B)**2 /*distance between 1st two points*/ - do j=1 for N-1 - do k=j+1 to N - dd=(@.j.xx-@.k.xx)**2 + (@.j.yy-@.k.yy)**2 - if dd\=0 then if dd9; 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 -.sqrtG: numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 +/*──────────────────────────────────SQRT subroutine───────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric form +numeric digits 11;p=d+d%4+2;parse value format(x,2,1,,0) 'E0' with g 'E' _ . +g=g*.5'E'_%2; m.=11; 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 diff --git a/Task/Closest-pair-problem/Ruby/closest-pair-problem.rb b/Task/Closest-pair-problem/Ruby/closest-pair-problem.rb index 8dbd92a3e7..834459f7b4 100644 --- a/Task/Closest-pair-problem/Ruby/closest-pair-problem.rb +++ b/Task/Closest-pair-problem/Ruby/closest-pair-problem.rb @@ -6,36 +6,26 @@ end def closest_bruteforce(points) mindist, minpts = Float::MAX, [] - points.length.times do |i| - (i+1).upto(points.length - 1) do |j| - dist = distance(points[i], points[j]) - if dist < mindist - mindist = dist - minpts = [points[i], points[j]] - end + points.combination(2) do |pi,pj| + dist = distance(pi, pj) + if dist < mindist + mindist = dist + minpts = [pi, pj] end end [mindist, minpts] end def closest_recursive(points) - if points.length <= 3 - return closest_bruteforce(points) - end - xP = points.sort_by {|p| p.x} - mid = (points.length / 2.0).ceil - pL = xP[0,mid] - pR = xP[mid..-1] - dL, pairL = closest_recursive(pL) - dR, pairR = closest_recursive(pR) - if dL < dR - dmin, dpair = dL, pairL - else - dmin, dpair = dR, pairR - end - yP = xP.find_all {|p| (pL[-1].x - p.x).abs < dmin}.sort_by {|p| p.y} - closest = Float::MAX - closestPair = [] + return closest_bruteforce(points) if points.length <= 3 + xP = points.sort_by(&:x) + mid = points.length / 2 + xm = xP[mid].x + dL, pairL = closest_recursive(xP[0,mid]) + dR, pairR = closest_recursive(xP[mid..-1]) + dmin, dpair = dL= dmin @@ -46,14 +36,9 @@ def closest_recursive(points) end end end - if closest < dmin - [closest, closestPair] - else - [dmin, dpair] - end + [closest, closestPair] end - points = Array.new(100) {Point.new(rand, rand)} p ans1 = closest_bruteforce(points) p ans2 = closest_recursive(points) diff --git a/Task/Closest-pair-problem/Scala/closest-pair-problem.scala b/Task/Closest-pair-problem/Scala/closest-pair-problem.scala index 75776ad259..202ad3068d 100644 --- a/Task/Closest-pair-problem/Scala/closest-pair-problem.scala +++ b/Task/Closest-pair-problem/Scala/closest-pair-problem.scala @@ -1,24 +1,133 @@ -import scala.util._ +import scala.collection.mutable.ListBuffer +import scala.util.Random -object ClosestPair{ - class Point(x:Double, y:Double) extends Pair(x,y){ - def distance(p:Point)=math.hypot(_1-p._1, _2-p._2) - } +object ClosestPair { + case class Point(x: Double, y: Double){ + def distance(p: Point) = math.hypot(x-p.x, y-p.y) - def closestPairBF(a:Array[Point])={ - var minDist=a(0) distance a(1) - var minPoints=(a(0), a(1)) + override def toString = "(" + x + ", " + y + ")" + } - for(p1<-a; p2<-a if p1.ne(p2); dist=p1 distance p2 if(dist point.x) + } + + def sortByY(points: List[Point]) = { + points.sortBy(point => point.y) + } + + def divideAndConquer(points: List[Point]): Pair = { + val pointsSortedByX = sortByX(points) + val pointsSortedByY = sortByY(points) + + divideAndConquer(pointsSortedByX, pointsSortedByY) + } + + def bruteForce(points: List[Point]): Pair = { + val numPoints = points.size + if (numPoints < 2) + return null + var pair = Pair(points(0), points(1)) + if (numPoints > 2) { + for (i <- 0 until numPoints - 1) { + val point1 = points(i) + for (j <- i + 1 until numPoints) { + val point2 = points(j) + val distance = point1 distance point2 + if (distance < pair.distance) + pair = Pair(point1, point2) + } } - (minPoints, minDist) - } + } + return pair + } - def main(args: Array[String]): Unit = { - val a=Array.fill(1000)(new Point(Random.nextDouble, Random.nextDouble)) - val (points, dist)=closestPairBF(a) - println("min: "+points._1+" - "+points._2+" ->"+dist) - } + + private def divideAndConquer(pointsSortedByX: List[Point], pointsSortedByY: List[Point]): Pair = { + val numPoints = pointsSortedByX.size + if(numPoints <= 3) { + return bruteForce(pointsSortedByX) + } + + val dividingIndex = numPoints >>> 1 + val leftOfCenter = pointsSortedByX.slice(0, dividingIndex) + val rightOfCenter = pointsSortedByX.slice(dividingIndex, numPoints) + + var tempList = leftOfCenter.map(x => x) + //println(tempList) + tempList = sortByY(tempList) + var closestPair = divideAndConquer(leftOfCenter, tempList) + + tempList = rightOfCenter.map(x => x) + tempList = sortByY(tempList) + + val closestPairRight = divideAndConquer(rightOfCenter, tempList) + + if (closestPairRight.distance < closestPair.distance) + closestPair = closestPairRight + + tempList = List[Point]() + val shortestDistance = closestPair.distance + val centerX = rightOfCenter(0).x + + for (point <- pointsSortedByY) { + if (Math.abs(centerX - point.x) < shortestDistance) + tempList = tempList :+ point + } + + closestPair = shortestDistanceF(tempList, shortestDistance, closestPair) + closestPair + } + + private def shortestDistanceF(tempList: List[Point], shortestDistance: Double, closestPair: Pair ): Pair = { + var shortest = shortestDistance + var bestResult = closestPair + for (i <- 0 until tempList.size) { + val point1 = tempList(i) + for (j <- i + 1 until tempList.size) { + val point2 = tempList(j) + if ((point2.y - point1.y) >= shortestDistance) + return closestPair + val distance = point1 distance point2 + if (distance < closestPair.distance) + { + bestResult = Pair(point1, point2) + shortest = distance + } + } + } + + closestPair + } + + def main(args: Array[String]) { + val numPoints = if(args.length == 0) 1000 else args(0).toInt + + val points = ListBuffer[Point]() + val r = new Random() + for (i <- 0 until numPoints) { + points.+=:(new Point(r.nextDouble(), r.nextDouble())) + } + println("Generated " + numPoints + " random points") + + var startTime = System.currentTimeMillis() + val bruteForceClosestPair = bruteForce(points.toList) + var elapsedTime = System.currentTimeMillis() - startTime + println("Brute force (" + elapsedTime + " ms): " + bruteForceClosestPair) + + startTime = System.currentTimeMillis() + val dqClosestPair = divideAndConquer(points.toList) + elapsedTime = System.currentTimeMillis() - startTime + println("Divide and conquer (" + elapsedTime + " ms): " + dqClosestPair) + if (bruteForceClosestPair.distance != dqClosestPair.distance) + println("MISMATCH") + } } diff --git a/Task/Collections/00DESCRIPTION b/Task/Collections/00DESCRIPTION index d21cb98ad5..e7b4598947 100644 --- a/Task/Collections/00DESCRIPTION +++ b/Task/Collections/00DESCRIPTION @@ -1,4 +1,6 @@ -{{clarified-review}}Collections are abstractions to represent sets of values. In statically-typed languages, the values are typically of a common data type. +{{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. diff --git a/Task/Collections/00META.yaml b/Task/Collections/00META.yaml index 659c8686af..cf16804e6f 100644 --- a/Task/Collections/00META.yaml +++ b/Task/Collections/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Data Structures note: Basic language learning diff --git a/Task/Collections/Java/collections-5.java b/Task/Collections/Java/collections-5.java index 60ad707e5c..f0279f3395 100644 --- a/Task/Collections/Java/collections-5.java +++ b/Task/Collections/Java/collections-5.java @@ -4,7 +4,7 @@ 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); @@ -13,9 +13,6 @@ public class Collections { 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++) diff --git a/Task/Collections/Maple/collections-1.maple b/Task/Collections/Maple/collections-1.maple new file mode 100644 index 0000000000..b83400ba87 --- /dev/null +++ b/Task/Collections/Maple/collections-1.maple @@ -0,0 +1,5 @@ +L1 := [3, 4, 5, 6]; + L1 := [3, 4, 5, 6] + +L2 := [7, 8, 9]; + L2 := [7, 8, 9] diff --git a/Task/Collections/Maple/collections-2.maple b/Task/Collections/Maple/collections-2.maple new file mode 100644 index 0000000000..5229036122 --- /dev/null +++ b/Task/Collections/Maple/collections-2.maple @@ -0,0 +1,2 @@ +[op(L1), op(L2)] + [3, 4, 5, 6, 7, 8, 9] diff --git a/Task/Collections/Maple/collections-3.maple b/Task/Collections/Maple/collections-3.maple new file mode 100644 index 0000000000..f04cc94c1b --- /dev/null +++ b/Task/Collections/Maple/collections-3.maple @@ -0,0 +1,2 @@ +A1 := Array([3, 4, 5, 6]); + A1 := [3, 4, 5, 6] diff --git a/Task/Collections/Maple/collections-4.maple b/Task/Collections/Maple/collections-4.maple new file mode 100644 index 0000000000..e6918e31c9 --- /dev/null +++ b/Task/Collections/Maple/collections-4.maple @@ -0,0 +1,2 @@ +ArrayTools:-Append(A1, 7); + A1 := [3, 4, 5, 6, 7] diff --git a/Task/Collections/Ruby/collections-1.rb b/Task/Collections/Ruby/collections-1.rb index 10ae7d056f..fe277abb50 100644 --- a/Task/Collections/Ruby/collections-1.rb +++ b/Task/Collections/Ruby/collections-1.rb @@ -1,5 +1,4 @@ # creating an empty array and adding values - a = [] #=> [] a[0] = 1 #=> [1] a[3] = "abc" #=> [1, nil, nil, "abc"] diff --git a/Task/Collections/Ruby/collections-2.rb b/Task/Collections/Ruby/collections-2.rb index 6f15f724dc..8408fc1ed8 100644 --- a/Task/Collections/Ruby/collections-2.rb +++ b/Task/Collections/Ruby/collections-2.rb @@ -1,5 +1,4 @@ # creating an empty hash - h = {} #=> {} h["a"] = 1 #=> {"a"=>1} h["test"] = 2.4 #=> {"a"=>1, "test"=>2.4} diff --git a/Task/Collections/Ruby/collections-4.rb b/Task/Collections/Ruby/collections-4.rb new file mode 100644 index 0000000000..9aa71fc18d --- /dev/null +++ b/Task/Collections/Ruby/collections-4.rb @@ -0,0 +1,21 @@ +require 'set' + +# different ways of creating a set +p s1 = Set[1, 2, 3, 4] #=> # +p s2 = [8, 6, 4, 2].to_set #=> # +p s3 = Set.new(1..4) {|x| x*2} #=> # + +# Union +p s1 | s2 #=> # +# Intersection +p s1 & s2 #=> # +# Difference +p s1 - s2 #=> # + +p s1 ^ s2 #=> # + +p s2 == s3 #=> true + +p s1.add(5) #=> # +p s1 << 0 #=> # +p s1.delete(3) #=> # diff --git a/Task/Collections/Ruby/collections-5.rb b/Task/Collections/Ruby/collections-5.rb new file mode 100644 index 0000000000..a610172437 --- /dev/null +++ b/Task/Collections/Ruby/collections-5.rb @@ -0,0 +1,24 @@ +require 'matrix' + +# creating a matrix +p m0 = Matrix.zero(3) #=> Matrix[[0, 0, 0], [0, 0, 0], [0, 0, 0]] +p m1 = Matrix.identity(3) #=> Matrix[[1, 0, 0], [0, 1, 0], [0, 0, 1]] +p m2 = Matrix[[11, 12], [21, 22]] + #=> Matrix[[11, 12], [21, 22]] +p m3 = Matrix.build(3) {|row, col| row - col} + #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]] + +p m2[0,0] #=> 11 +p m1 * 5 #=> Matrix[[5, 0, 0], [0, 5, 0], [0, 0, 5]] +p m1 + m3 #=> Matrix[[1, -1, -2], [1, 1, -1], [2, 1, 1]] +p m1 * m3 #=> Matrix[[0, -1, -2], [1, 0, -1], [2, 1, 0]] + +# creating a Vector +p v1 = Vector[1,3,5] #=> Vector[1, 3, 5] +p v2 = Vector[0,1,2] #=> Vector[0, 1, 2] +p v1[1] #=> 3 +p v1 * 2 #=> Vector[2, 6, 10] +p v1 + v2 #=> Vector[1, 4, 7] + +p m1 * v1 #=> Vector[1, 3, 5] +p m3 * v1 #=> Vector[-13, -4, 5] diff --git a/Task/Collections/Ruby/collections-6.rb b/Task/Collections/Ruby/collections-6.rb new file mode 100644 index 0000000000..b09739baab --- /dev/null +++ b/Task/Collections/Ruby/collections-6.rb @@ -0,0 +1,23 @@ +require 'ostruct' + +# creating a OpenStruct +ab = OpenStruct.new +p ab #=> # +ab.foo = 25 +p ab.foo #=> 25 +ab[:bar] = 2 +p ab["bar"] #=> 2 +p ab #=> # +ab.delete_field("foo") +p ab.foo #=> nil +p ab #=> # + +p son = OpenStruct.new({ :name => "Thomas", :age => 3 }) + #=> # +p son.name #=> "Thomas" +p son[:age] #=> 3 +son.age += 1 +p son.age #=> 4 +son.items = ["candy","toy"] +p son.items #=> ["candy","toy"] +p son #=> # "Netherlands", + "New York" -> "USA", + "Heemstede" -> "Netherlands") + + map("Laussanne") = "Switzerland" // 2 Ways of updating + map += ("Tokio" -> "Japan") + + assert(map("New York") == "USA") + assert(!map.isDefinedAt("Gent")) // isDefinedAt is false + assert(map.isDefinedAt("Laussanne")) // true + + val hash = new TrieMap[Int, Int] + hash(1) = 2 + hash += (1 -> 2) // same as hash(1) = 2 + hash += (3 -> 4, 5 -> 6, 44 -> 99) + hash(44) // 99 + hash.contains(33) // false + hash.isDefinedAt(33) // same as contains + hash.contains(44) // true + // iterate over key/value + // hash.foreach { case (key, val) => println( "key " + e._1 + " value " + e._2) } // e is a 2 element Tuple + // same with for syntax + for ((k, v) <- hash) println("key " + k + " value " + v) + // // items in map where the key is greater than 3 + map.filter { k => k._1 > 3 } // Map(5 -> 6, 44 -> 99) + // // same with for syntax + for ((k, v) <- map; if k > 3) yield (k, v) diff --git a/Task/Collections/Scheme/collections-3.ss b/Task/Collections/Scheme/collections-3.ss index 6ca29fc6e0..081b053898 100644 --- a/Task/Collections/Scheme/collections-3.ss +++ b/Task/Collections/Scheme/collections-3.ss @@ -1,2 +1 @@ -(1 2 3) -() +(cons obj lst) diff --git a/Task/Collections/Scheme/collections-4.ss b/Task/Collections/Scheme/collections-4.ss index 081b053898..8447867de2 100644 --- a/Task/Collections/Scheme/collections-4.ss +++ b/Task/Collections/Scheme/collections-4.ss @@ -1 +1,2 @@ -(cons obj lst) +(display (cons 0 (list 1 2 3))) +(newline) diff --git a/Task/Collections/Scheme/collections-5.ss b/Task/Collections/Scheme/collections-5.ss index 8447867de2..51b630f818 100644 --- a/Task/Collections/Scheme/collections-5.ss +++ b/Task/Collections/Scheme/collections-5.ss @@ -1,2 +1 @@ -(display (cons 0 (list 1 2 3))) -(newline) +(append lst ...) diff --git a/Task/Collections/Scheme/collections-6.ss b/Task/Collections/Scheme/collections-6.ss index 78efe5d71b..420c173fcc 100644 --- a/Task/Collections/Scheme/collections-6.ss +++ b/Task/Collections/Scheme/collections-6.ss @@ -1 +1,2 @@ -(0 1 2 3) +(display (append (list 1 2 3) (list 4 5 6))) +(newline) diff --git a/Task/Collections/UNIX-Shell/collections-1.sh b/Task/Collections/UNIX-Shell/collections-1.sh new file mode 100644 index 0000000000..976dc01d29 --- /dev/null +++ b/Task/Collections/UNIX-Shell/collections-1.sh @@ -0,0 +1,9 @@ +a_index=(one two three) # create an array with a few elements +a_index+=(four five) # append some elements +a_index[9]=ten # add a specific index +for elem in "${a_index[@]}"; do # interate over the elements + echo "$elem" +done +for idx in "${!a_index[@]}"; do # interate over the array indices + printf "%d\t%s\n" $idx "${a_index[idx]}" +done diff --git a/Task/Collections/UNIX-Shell/collections-2.sh b/Task/Collections/UNIX-Shell/collections-2.sh new file mode 100644 index 0000000000..22f68cf202 --- /dev/null +++ b/Task/Collections/UNIX-Shell/collections-2.sh @@ -0,0 +1,9 @@ +declare -A a_assoc=([one]=1 [two]=2 [three]=3) # create an array with a few elements +a_assoc+=([four]=4 [five]=5) # add some elements +a_assoc[ten]=10 +for value in "${a_assoc[@]}"; do # interate over the values + echo "$value" +done +for key in "${!a_assoc[@]}"; do # interate over the array indices + printf "%s\t%s\n" "$key" "${a_assoc[$key]}" +done diff --git a/Task/Collections/UNIX-Shell/collections-3.sh b/Task/Collections/UNIX-Shell/collections-3.sh new file mode 100644 index 0000000000..372d491956 --- /dev/null +++ b/Task/Collections/UNIX-Shell/collections-3.sh @@ -0,0 +1 @@ +declare -A diff --git a/Task/Collections/UNIX-Shell/collections-4.sh b/Task/Collections/UNIX-Shell/collections-4.sh new file mode 100644 index 0000000000..59cc6ebec8 --- /dev/null +++ b/Task/Collections/UNIX-Shell/collections-4.sh @@ -0,0 +1 @@ +typeset -A diff --git a/Task/Color-of-a-screen-pixel/Ruby/color-of-a-screen-pixel.rb b/Task/Color-of-a-screen-pixel/Ruby/color-of-a-screen-pixel.rb new file mode 100644 index 0000000000..6aff58f157 --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Ruby/color-of-a-screen-pixel.rb @@ -0,0 +1,12 @@ +module Screen + IMPORT_COMMAND = '/usr/bin/import' + + # Returns an array with RGB values for the pixel at the given coords + def self.pixel(x, y) + if m = `#{IMPORT_COMMAND} -silent -window root -crop 1x1+#{x.to_i}+#{y.to_i} -depth 8 txt:-`.match(/\((\d+),(\d+),(\d+)\)/) + m[1..3].map(&:to_i) + else + false + end + end +end diff --git a/Task/Color-of-a-screen-pixel/Scala/color-of-a-screen-pixel.scala b/Task/Color-of-a-screen-pixel/Scala/color-of-a-screen-pixel.scala new file mode 100644 index 0000000000..3641c5bafd --- /dev/null +++ b/Task/Color-of-a-screen-pixel/Scala/color-of-a-screen-pixel.scala @@ -0,0 +1 @@ +def getColorAt(x: Int, y: Int): Color = new Robot().getPixelColor(x, y) diff --git a/Task/Color-quantization/D/color-quantization.d b/Task/Color-quantization/D/color-quantization-1.d similarity index 73% rename from Task/Color-quantization/D/color-quantization.d rename to Task/Color-quantization/D/color-quantization-1.d index d83b3b0368..01366e124a 100644 --- a/Task/Color-quantization/D/color-quantization.d +++ b/Task/Color-quantization/D/color-quantization-1.d @@ -5,34 +5,35 @@ struct Col { float r, g, b; } alias Cluster = Tuple!(Col, float, Col, Col[]); enum Axis { R, G, B } -enum round = (in float x) pure nothrow => cast(int)floor(x + 0.5); +enum round = (in float x) pure nothrow @safe @nogc => cast(int)floor(x + 0.5); -enum roundRGB = (in Col c) pure nothrow => RGB(cast(ubyte)round(c.r), - cast(ubyte)round(c.g), - cast(ubyte)round(c.b)); +enum roundRGB = (in Col c) pure nothrow @safe @nogc => + RGB(cast(ubyte)round(c.r), + cast(ubyte)round(c.g), + cast(ubyte)round(c.b)); -enum addRGB = (in Col c1, in Col c2) pure nothrow => +enum addRGB = (in Col c1, in Col c2) pure nothrow @safe @nogc => Col(c1.r + c2.r, c1.g + c2.g, c1.b + c2.b); -Col meanRGB(in Col[] pxList) pure nothrow { +Col meanRGB(in Col[] pxList) pure nothrow @safe @nogc { immutable tot = reduce!addRGB(Col(0, 0, 0), pxList); immutable n = pxList.length; return Col(tot.r / n, tot.g / n, tot.b / n); } -enum minC = (in Col c1, in Col c2) pure nothrow => +enum minC = (in Col c1, in Col c2) pure nothrow @safe @nogc => 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 => +enum maxC = (in Col c1, in Col c2) pure nothrow @safe @nogc => 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 { +Tuple!(Col, Col) extrems(in Col[] lst) pure nothrow @safe @nogc { 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 { +Tuple!(float, Col) volumeAndDims(in Col[] lst) pure nothrow @safe @nogc { immutable e = lst.extrems; immutable r = Col(e[1].r - e[0].r, e[1].g - e[0].g, @@ -40,7 +41,7 @@ Tuple!(float, Col) volumeAndDims(in Col[] lst) pure nothrow { return typeof(return)(r.r * r.g * r.b, r); } -Cluster makeCluster(Col[] pixelList) pure nothrow { +Cluster makeCluster(Col[] pixelList) pure nothrow @safe @nogc { immutable vol_dims = pixelList.volumeAndDims; immutable int len = pixelList.length; return typeof(return)(pixelList.meanRGB, @@ -49,10 +50,10 @@ Cluster makeCluster(Col[] pixelList) pure nothrow { pixelList); } -enum fCmp = (in float a, in float b) pure nothrow => +enum fCmp = (in float a, in float b) pure nothrow @safe @nogc => (a > b) ? 1 : (a < b ? -1 : 0); -Axis largestAxis(in Col c) pure nothrow { +Axis largestAxis(in Col c) pure nothrow @safe @nogc { immutable int r1 = fCmp(c.r, c.g); immutable int r2 = fCmp(c.r, c.b); if (r1 == 1 && r2 == 1) return Axis.R; @@ -63,26 +64,25 @@ Axis largestAxis(in Col c) pure nothrow { Tuple!(Cluster, Cluster) subdivide(in Col c, in float nVolProd, in Col vol, Col[] pixels) -pure nothrow { - bool delegate(immutable Col) pure nothrow partFunc; +pure nothrow @safe @nogc { + Col[] px2; 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; + case Axis.R: px2 = pixels.partition!(c1 => c1.r < c.r); break; + case Axis.G: px2 = pixels.partition!(c1 => c1.g < c.g); break; + case Axis.B: px2 = pixels.partition!(c1 => c1.b < c.b); break; } - auto px2 = pixels.partition!partFunc; auto px1 = pixels[0 .. $ - px2.length]; return typeof(return)(px1.makeCluster, px2.makeCluster); } -uint RGB2uint(in RGB c) pure nothrow { +uint RGB2uint(in RGB c) pure nothrow @safe @nogc { return c.r | (c.g << 8) | (c.b << 16); } -enum uintToRGB = (in uint c) pure nothrow => +enum uintToRGB = (in uint c) pure nothrow @safe @nogc => RGB(c & 0xFF, (c >> 8) & 0xFF, (c >> 16) & 0xFF); -Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow { +Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow /*@safe*/ { immutable width = img.nx; immutable height = img.ny; @@ -91,7 +91,7 @@ Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow { cols[i] = Col(c.tupleof); immutable dumb = Col(0, 0, 0); - Cluster unused= Cluster(dumb, -float.infinity, dumb, (Col[]).init); + Cluster unused = Cluster(dumb, -float.infinity, dumb, (Col[]).init); auto clusters = [cols.makeCluster]; while (clusters.length < n) { @@ -99,7 +99,7 @@ Image!RGB colorQuantize(in Image!RGB img, in int n) pure nothrow { Cluster cl = reduce!((c1, c2) => c1[1] > c2[1] ? c1 : c2) (unused, clusters); clusters = [cl[].subdivide[]] ~ - clusters.remove!(c => c == cl, SwapStrategy.unstable); + clusters.remove!(c => c == cl, SwapStrategy.unstable); //** } uint[uint] pixMap; // Faster than RGB[RGB]. diff --git a/Task/Color-quantization/D/color-quantization-2.d b/Task/Color-quantization/D/color-quantization-2.d new file mode 100644 index 0000000000..9f52369b96 --- /dev/null +++ b/Task/Color-quantization/D/color-quantization-2.d @@ -0,0 +1,447 @@ +import core.stdc.stdlib: malloc, calloc, realloc, free, abort; +import std.stdio: stderr, File; +import std.ascii: isWhite; +import std.math: abs; +import std.conv: to; +import std.string: split, strip; +import std.exception: enforce; +import std.array: empty; +import std.typetuple: TypeTuple; + +enum ON_INHEAP = 1; + +struct Image { + uint w, h; + ubyte[0] pix; +} + +Image* imageNew(in uint w, in uint h) nothrow @nogc +in { + assert(w > 0 && h > 0); +} out(result) { + assert(result != null); +} body { + auto im = cast(Image*)malloc(Image.sizeof + w * h * 3); + im.w = w; + im.h = h; + return im; +} + +Image* readPPM6(in string fileName) +in { + assert(!fileName.empty); +} out(result) { + assert(result != null); +} body { + auto fIn = File(fileName, "rb"); + enforce(fIn.readln.strip == "P6"); + + // Skip comments. + string line; + do { + line = fIn.readln; + } while (line.length && line[0] == '#'); + + const size = line.split.to!(uint[]); + enforce(size.length == 2); + //immutable size = line.split.to!(uint[2]); + auto img = imageNew(size[0], size[1]); + enforce(fIn.readln.strip == "255"); + fIn.rawRead(img.pix.ptr[0 .. img.w * img.h * 3]); + return img; +} + +void writePPM6(in Image* img, in string fileName) +in { + assert(!fileName.empty); + assert(img != null); +} body { + auto fOut = File(fileName, "wb"); + fOut.writefln("P6\n%d %d\n255", img.w, img.h); + fOut.rawWrite(img.pix.ptr[0 .. img.w * img.h * 3]); + fOut.close; +} + +struct OctreeNode { + long r, g, b; // Sum of all child node colors. + uint count, heapIdx; + ubyte nKids, kidIdx, flags, depth; + OctreeNode*[8] kids; + OctreeNode* parent; +} + +struct HeapNode { + uint alloc, n; + OctreeNode** buf; +} + +int cmpOctreeNode(in OctreeNode* a, in OctreeNode* b) +pure nothrow @safe @nogc +in { + assert(a != null); + assert(b != null); +} out(result) { + assert(result == -1 || result == 0 || result == 1); +} body { + if (a.nKids < b.nKids) + return -1; + if (a.nKids > b.nKids) + return 1; + + immutable uint ac = a.count >> a.depth; + immutable uint bc = b.count >> b.depth; + return (ac < bc) ? -1 : (ac > bc); +} + +void downHeap(HeapNode* h, OctreeNode* p) pure nothrow @nogc +in { + assert(h != null); + assert(p != null); +} body { + auto n = p.heapIdx; + + while (true) { + uint m = n * 2; + if (m >= h.n) + break; + if (m + 1 < h.n && cmpOctreeNode(h.buf[m], h.buf[m + 1]) > 0) + m++; + + if (cmpOctreeNode(p, h.buf[m]) <= 0) + break; + + h.buf[n] = h.buf[m]; + h.buf[n].heapIdx = n; + n = m; + } + + h.buf[n] = p; + p.heapIdx = n; +} + +void upHeap(HeapNode* h, OctreeNode* p) pure nothrow @nogc +in { + assert(h != null); + assert(p != null); +} body { + auto n = p.heapIdx; + + while (n > 1) { + auto prev = h.buf[n / 2]; + if (cmpOctreeNode(p, prev) >= 0) + break; + + h.buf[n] = prev; + prev.heapIdx = n; + n /= 2; + } + + h.buf[n] = p; + p.heapIdx = n; +} + +void addHeap(HeapNode* h, OctreeNode* p) nothrow @nogc +in { + assert(h != null); + assert(p != null); +} body { + if ((p.flags & ON_INHEAP)) { + downHeap(h, p); + upHeap(h, p); + return; + } + + p.flags |= ON_INHEAP; + if (!h.n) + h.n = 1; + if (h.n >= h.alloc) { + while (h.n >= h.alloc) + h.alloc += 1024; + h.buf = cast(OctreeNode**)realloc(h.buf, (OctreeNode*).sizeof * h.alloc); + assert(h.buf != null); + } + + p.heapIdx = h.n; + h.buf[h.n++] = p; + upHeap(h, p); +} + +OctreeNode* popHeap(HeapNode* h) pure nothrow @nogc +in { + assert(h != null); +} out(result) { + assert(result != null); +} body { + if (h.n <= 1) + return null; + + auto ret = h.buf[1]; + h.buf[1] = h.buf[--h.n]; + + h.buf[h.n] = null; + + h.buf[1].heapIdx = 1; + downHeap(h, h.buf[1]); + + return ret; +} + +OctreeNode* octreeNodeNew(in ubyte idx, in ubyte depth, OctreeNode* p, + ref OctreeNode[] pool) nothrow @nogc +out(result) { + assert(result != null); +} body { + __gshared static uint len = 0; + + if (len <= 1) { + OctreeNode* p2 = cast(OctreeNode*)calloc(OctreeNode.sizeof, 2048); + assert(p2 != null); + p2.parent = pool.ptr; + pool = p2[0 .. 2048]; + len = 2047; + } + + OctreeNode* x = pool.ptr + len--; + x.kidIdx = idx; + x.depth = depth; + x.parent = p; + if (p) + p.nKids++; + return x; +} + +void octreeNodeFree(ref OctreeNode[] pool) nothrow @nogc +out { + assert(pool.empty); +} body { + auto poolPtr = pool.ptr; + + while (poolPtr) { + auto p = poolPtr.parent; + free(poolPtr); + poolPtr = p; + } + + pool = null; +} + +OctreeNode* octreeNodeInsert(OctreeNode* root, in ubyte* pix, ref OctreeNode[] pool) +nothrow @nogc +in { + assert(root != null); + assert(pix != null); + assert(!pool.empty); +} out(result) { + assert(result != null); +} body { + ubyte depth = 0; + + for (ubyte bit = (1 << 7); ++depth < 8; bit >>= 1) { + immutable ubyte i = !!(pix[1] & bit) * 4 + + !!(pix[0] & bit) * 2 + + !!(pix[2] & bit); + if (!root.kids[i]) + root.kids[i] = octreeNodeNew(i, depth, root, pool); + + root = root.kids[i]; + } + + root.r += pix[0]; + root.g += pix[1]; + root.b += pix[2]; + root.count++; + return root; +} + +OctreeNode* octreeNodeFold(OctreeNode* p) nothrow @nogc +in { + assert(p != null); +} out(result) { + assert(result != null); +} body { + if (p.nKids) + abort(); + auto q = p.parent; + q.count += p.count; + + q.r += p.r; + q.g += p.g; + q.b += p.b; + q.nKids--; + q.kids[p.kidIdx] = null; + return q; +} + +void colorReplace(OctreeNode* root, ubyte* pix) pure nothrow @nogc +in { + assert(root != null); + assert(pix != null); +} body { + for (ubyte bit = (1 << 7); bit; bit >>= 1) { + immutable i = !!(pix[1] & bit) * 4 + + !!(pix[0] & bit) * 2 + + !!(pix[2] & bit); + if (!root.kids[i]) + break; + root = root.kids[i]; + } + + pix[0] = cast(ubyte)root.r; + pix[1] = cast(ubyte)root.g; + pix[2] = cast(ubyte)root.b; +} + +void errorDiffuse(Image* im, HeapNode* h) nothrow @nogc +in { + assert(im != null); + assert(h != null); +} body { + OctreeNode* nearestColor(in int* v) nothrow @nogc + in { + assert(v != null); + } out(result) { + assert(result != null); + } body { + auto max = long.max; + typeof(return) on = null; + + foreach (immutable uint i; 1 .. h.n) { + immutable diff = 3 * abs(h.buf[i].r - v[0]) + + 5 * abs(h.buf[i].g - v[1]) + + 2 * abs(h.buf[i].b - v[2]); + if (diff < max) { + max = diff; + on = h.buf[i]; + } + } + + return on; + } + + uint pos(in uint i, in uint j) nothrow @safe @nogc { + return 3 * (i * im.w + j); + } + + enum C10 = 7; + enum C01 = 5; + enum C11 = 2; + enum C00 = 1; + enum CTOTAL = C00 + C11 + C10 + C01; + + auto npx = cast(int*)calloc(int.sizeof, im.h * im.w * 3); + assert(npx != null); + auto pix = im.pix.ptr; + alias triple = TypeTuple!(0, 1, 2); + + for (auto px = npx, i = 0u; i < im.h; i++) { + for (uint j = 0; j < im.w; j++, pix += 3, px += 3) { + /*static*/ foreach (immutable k; triple) + px[k] = cast(int)pix[k] * CTOTAL; + } + } + + static void clamp(ref int x) pure nothrow @safe @nogc { + if (x > 255) x = 255; + if (x < 0) x = 0; + } + + pix = im.pix.ptr; + + for (auto px = npx, i = 0u; i < im.h; i++) { + for (uint j = 0; j < im.w; j++, pix += 3, px += 3) { + /*static*/ foreach (immutable k; triple) + px[k] /= CTOTAL; + /*static*/ foreach (immutable k; triple) + clamp(px[k]); + + const nd = nearestColor(px); + uint[3] v = void; + v[0] = cast(uint)(px[0] - nd.r); + v[1] = cast(uint)(px[1] - nd.g); + v[2] = cast(uint)(px[2] - nd.b); + + pix[0] = cast(ubyte)nd.r; + pix[1] = cast(ubyte)nd.g; + pix[2] = cast(ubyte)nd.b; + + if (j < im.w - 1) { + /*static*/ foreach (immutable k; triple) + npx[pos(i, j + 1) + k] += v[k] * C10; + } + + if (i >= im.h - 1) + continue; + + /*static*/ foreach (immutable k; triple) + npx[pos(i + 1, j) + k] += v[k] * C01; + + if (j < im.w - 1) { + /*static*/ foreach (immutable k; triple) + npx[pos(i + 1, j + 1) + k] += v[k] * C11; + } + + if (j) { + /*static*/ foreach (immutable k; triple) + npx[pos(i + 1, j - 1) + k] += v[k] * C00; + } + } + } + + free(npx); +} + +void colorQuant(Image* im, in uint nColors, in bool dither) nothrow @nogc +in { + assert(im != null); + assert(nColors > 1); +} body { + auto pix = im.pix.ptr; + HeapNode heap = { 0, 0, null }; + OctreeNode[] pool; + + auto root = octreeNodeNew(0, 0, null, pool); + for (uint i = 0; i < im.w * im.h; i++, pix += 3) + addHeap(&heap, octreeNodeInsert(root, pix, pool)); + + while (heap.n > nColors + 1) + addHeap(&heap, octreeNodeFold(popHeap(&heap))); + + foreach (immutable i; 1 .. heap.n) { + auto got = heap.buf[i]; + immutable double c = got.count; + got.r = cast(long)(got.r / c + 0.5); + got.g = cast(long)(got.g / c + 0.5); + got.b = cast(long)(got.b / c + 0.5); + } + + if (dither) + errorDiffuse(im, &heap); + else { + uint i; + for (i = 0, pix = im.pix.ptr; i < im.w * im.h; i++, pix += 3) + colorReplace(root, pix); + } + + pool.octreeNodeFree; + heap.buf.free; +} + +int main(in string[] args) { + if (args.length < 3 || args.length > 4) { + stderr.writeln("Usage: quant ppmFile nColors [dith]"); + return 1; + } + + immutable nColors = args[2].to!uint; + assert(nColors > 1); + + auto im = readPPM6(args[1]); + immutable useDithering = (args.length == 4) ? (args[3] == "dith") : false; + immutable fileNameOut = useDithering ? "outd.ppm" : "out.ppm"; + + colorQuant(im, nColors, useDithering); + writePPM6(im, fileNameOut); + + im.free; + return 0; +} diff --git a/Task/Color-quantization/Haskell/color-quantization.hs b/Task/Color-quantization/Haskell/color-quantization.hs new file mode 100644 index 0000000000..c1a362dfe9 --- /dev/null +++ b/Task/Color-quantization/Haskell/color-quantization.hs @@ -0,0 +1,128 @@ +import qualified Data.ByteString.Lazy as BS +import qualified Data.Foldable as Fold +import qualified Data.List as List +import Data.Ord +import qualified Data.Sequence as Seq +import Data.Word +import System.Environment + +import Codec.Picture +import Codec.Picture.Types + +type Accessor = PixelRGB8 -> Pixel8 + +-- Getters for pixel components, as the constructor does not +-- provide any public ones. +red, blue, green :: Accessor +red (PixelRGB8 r _ _) = r +green (PixelRGB8 _ g _) = g +blue (PixelRGB8 _ _ b) = b + +-- Get all of the pixels in the image in list form. +getPixels :: Pixel a => Image a -> [a] +getPixels image = + [pixelAt image x y + | x <- [0..(imageWidth image - 1)] + , y <- [0..(imageHeight image - 1)]] + +-- Compute the color-space extents of a list of pixels. +extents :: [PixelRGB8] -> (PixelRGB8, PixelRGB8) +extents pixels = (extent minimum, extent maximum) + where + bound f g = f $ map g pixels + extent f = PixelRGB8 (bound f red) (bound f green) (bound f blue) + +-- Compute the average value of a list of pixels. +average :: [PixelRGB8] -> PixelRGB8 +average pixels = PixelRGB8 (avg red) (avg green) (avg blue) + where + len = toInteger $ length pixels + avg c = fromIntegral $ (sum $ map (toInteger . c) pixels) `div` len + +-- Perform a componentwise pixel operation. +compwise :: (Word8 -> Word8 -> Word8) -> PixelRGB8 -> PixelRGB8 -> PixelRGB8 +compwise f (PixelRGB8 ra ga ba) (PixelRGB8 rb gb bb) = + PixelRGB8 (f ra rb) (f ga gb) (f ba bb) + +-- Compute the absolute difference of two pixels. +diffPixel :: PixelRGB8 -> PixelRGB8 -> PixelRGB8 +diffPixel = compwise (\x y -> max x y - min x y) + +-- Compute the Euclidean distance squared between two pixels. +distPixel :: PixelRGB8 -> PixelRGB8 -> Integer +distPixel x y = (rr ^ 2) + (gg ^ 2) + (bb ^ 2) + where + PixelRGB8 r g b = diffPixel x y + rr = toInteger r + gg = toInteger g + bb = toInteger b + +-- Determine the dimension of the longest axis of the extents. +longestAccessor :: (PixelRGB8, PixelRGB8) -> Accessor +longestAccessor (l, h) = + snd $ Fold.maximumBy (comparing fst) $ zip [r, g, b] [red, green, blue] + where + PixelRGB8 r g b = diffPixel h l + +-- Find the index of a pixel to its respective palette. +nearestIdx :: PixelRGB8 -> [PixelRGB8] -> Int +nearestIdx pixel px = ans + where + Just ans = List.findIndex (== near) px + near = List.foldl1 comp px + comp a b = if distPixel a pixel <= distPixel b pixel then a else b + +-- Sort a list of pixels on its longest axis and then split by the mean. +-- It is intentional that the mean is chosen by all dimensions +-- instead of the given one. +meanSplit :: [PixelRGB8] -> Accessor -> ([PixelRGB8], [PixelRGB8]) +meanSplit l f = List.splitAt index sorted + where + sorted = List.sortBy (comparing f) l + index = nearestIdx (average l) sorted + +-- Perform the Median Cut algorithm on an image producing +-- an index map image and its respective palette. +meanCutQuant :: Image PixelRGB8 -> Int -> (Image Pixel8, Palette) +meanCutQuant image numRegions = (indexmap, palette) + where + extentsP p = (p, extents p) + regions = map (\(p, e) -> (average p, e)) + $ search $ Seq.singleton $ extentsP $ getPixels image + palette = snd $ generateFoldImage (\(x:xs) _ _ -> (xs, x)) + (map fst regions) numRegions 1 + indexmap = pixelMap + (\pixel -> fromIntegral $ nearestIdx pixel $ map fst regions) + image + search queue = + case Seq.viewl queue of + (pixels, extent) Seq.:< queueB -> + let (left, right) = meanSplit pixels $ longestAccessor extent + queueC = Fold.foldl (Seq.|>) queueB $ map extentsP [left, right] + in if Seq.length queueC >= numRegions + then List.take numRegions $ Fold.toList queueC + else search queueC + Seq.EmptyL -> error "Queue should never be empty." + +quantizeIO :: FilePath -> FilePath -> Int -> IO () +quantizeIO path outpath numRegions = do + dynimage <- readImage path + case dynimage of + Left err -> putStrLn err + Right (ImageRGB8 image) -> doImage image + Right (ImageRGBA8 image) -> doImage (pixelMap dropTransparency image) + _ -> putStrLn "Expecting RGB8 or RGBA8 image" + where + doImage image = do + let (indexmap, palette) = meanCutQuant image numRegions + case encodePalettedPng palette indexmap of + Left err -> putStrLn err + Right bstring -> BS.writeFile outpath bstring + +main :: IO () +main = do + args <- getArgs + prog <- getProgName + case args of + [path, outpath] -> quantizeIO path outpath 16 + _ -> putStrLn $ "Usage: " ++ prog ++ " " diff --git a/Task/Colour-bars-Display/Factor/colour-bars-display.factor b/Task/Colour-bars-Display/Factor/colour-bars-display.factor new file mode 100644 index 0000000000..cd367b5e93 --- /dev/null +++ b/Task/Colour-bars-Display/Factor/colour-bars-display.factor @@ -0,0 +1,23 @@ +USING: accessors colors.constants kernel math sequences ui +ui.gadgets ui.gadgets.tracks ui.pens.solid ; +IN: rosetta-code.colour-bars-display + +: colors ( -- ) [ +horizontal +{ + COLOR: black + COLOR: red + COLOR: green + COLOR: blue + COLOR: magenta + COLOR: cyan + COLOR: yellow + COLOR: white +} +[ gadget new swap >>interior ] map +dup length recip +[ track-add ] curry each +{ 640 480 } >>pref-dim +"bars" open-window +] with-ui ; +MAIN: colors diff --git a/Task/Colour-bars-Display/REXX/colour-bars-display.rexx b/Task/Colour-bars-Display/REXX/colour-bars-display.rexx new file mode 100644 index 0000000000..270ccbb31c --- /dev/null +++ b/Task/Colour-bars-Display/REXX/colour-bars-display.rexx @@ -0,0 +1,26 @@ +/*REXX program displays eight colored vertical bars on the full screen. */ +parse value scrsize() with sd sw . /*screen depth,width.*/ +barWidth=sw%8 /*calculate bar width*/ +_.=copies('db'x,barWidth) /*the bar, full width*/ +_.8=left(_.,barWidth-1) /*last bar width. */ + $ = x2c('1b5b73') || x2c('1b5b313b33376d') /* preamble, header. */ +hdr.1 = x2c('1b5b303b33306d') /* the color black. */ +hdr.2 = x2c('1b5b313b33316d') /* the color red. */ +hdr.3 = x2c('1b5b313b33326d') /* the color green. */ +hdr.4 = x2c('1b5b313b33346d') /* the color blue. */ +hdr.5 = x2c('1b5b313b33356d') /* the color magenta.*/ +hdr.6 = x2c('1b5b313b33366d') /* the color cyan. */ +hdr.7 = x2c('1b5b313b33336d') /* the color yellow. */ +hdr.8 = x2c('1b5b313b33376d') /* the color white. */ + tail = x2c('1b5b751b5b303b313b33363b34303b306d') /* epilogue, trailer.*/ + /* [↓] last bar width is shrunk.*/ + do j=1 for 8 /*build the line, color by color.*/ + $=$ || hdr.j || _.j /*append the color header + bar. */ + end /*j*/ /* [↑] color order is the list. */ + /* [↓] the tail is overkill. */ +$=$ || tail /*append the epilogue (trailer). */ + /* [↓] show full screen of bars.*/ + do k=1 for sd /*SD = screen depth (from above).*/ + say $ /*have REXX display line of bars.*/ + end /*k*/ /* [↑] Note: SD could be zero.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Colour-pinstripe-Display/00DESCRIPTION b/Task/Colour-pinstripe-Display/00DESCRIPTION index d0d69d6bf9..c7345869f6 100644 --- a/Task/Colour-pinstripe-Display/00DESCRIPTION +++ b/Task/Colour-pinstripe-Display/00DESCRIPTION @@ -1,3 +1,5 @@ The task is to create 1 pixel wide coloured vertical pinstripes with a sufficient number of pinstripes to span the entire width of the graphics display. The pinstripes should either follow the system palette sequence or a sequence that includes Black, Red, Green, Blue, Magenta, Cyan, Yellow, White. After filling the top quarter of the display, we switch to a wider 2 pixel wide vertical pinstripe pattern. Halfway down the display we switch to 3 pixel wide vertical pinstripe and then finally to a 4 pixels wide vertical pinstripe for the last quarter of the display. + +c.f. [[Pinstripe/Display]] diff --git a/Task/Colour-pinstripe-Display/Java/colour-pinstripe-display.java b/Task/Colour-pinstripe-Display/Java/colour-pinstripe-display.java new file mode 100644 index 0000000000..67dc977e1c --- /dev/null +++ b/Task/Colour-pinstripe-Display/Java/colour-pinstripe-display.java @@ -0,0 +1,38 @@ +import java.awt.*; +import static java.awt.Color.*; +import javax.swing.*; + +public class ColourPinstripeDisplay extends JPanel { + final static Color[] palette = {black, red, green, blue, magenta,cyan, + yellow, white}; + + final int bands = 4; + + public ColourPinstripeDisplay() { + setPreferredSize(new Dimension(900, 600)); + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + int h = getHeight(); + for (int b = 1; b <= bands; b++) { + for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) { + g.setColor(palette[colIndex % palette.length]); + g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands)); + } + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(() -> { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setTitle("ColourPinstripeDisplay"); + f.add(new ColourPinstripeDisplay(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + } +} diff --git a/Task/Combinations-with-repetitions/00DESCRIPTION b/Task/Combinations-with-repetitions/00DESCRIPTION index fc50ae4a19..a8c9e97660 100644 --- a/Task/Combinations-with-repetitions/00DESCRIPTION +++ b/Task/Combinations-with-repetitions/00DESCRIPTION @@ -1,4 +1,6 @@ -The set of combinations with repetitions is computed from a set, S (of cardinality n), and a size of resulting selection, k, by reporting the sets of cardinality k where each member of those sets is chosen from S. In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. For example: +The set of combinations with repetitions is computed from a set, S (of cardinality n), and a size of resulting selection, k, by reporting the sets of cardinality k where each member of those sets is chosen from S. +In the real world, it is about choosing sets where there is a “large” supply of each type of element and where the order of choice does not matter. +For example: :Q: How many ways can a person choose two doughnuts from a store selling three types of doughnut: iced, jam, and plain? (i.e., S is \{\mathrm{iced}, \mathrm{jam}, \mathrm{plain}\}, |S| = 3, and k = 2.) :A: 6: {iced, iced}; {iced, jam}; {iced, plain}; {jam, jam}; {jam, plain}; {plain, plain}. diff --git a/Task/Combinations-with-repetitions/AWK/combinations-with-repetitions.awk b/Task/Combinations-with-repetitions/AWK/combinations-with-repetitions.awk new file mode 100644 index 0000000000..1d4462f96e --- /dev/null +++ b/Task/Combinations-with-repetitions/AWK/combinations-with-repetitions.awk @@ -0,0 +1,23 @@ +# syntax: GAWK -f COMBINATIONS_WITH_REPETITIONS.AWK +BEGIN { + n = split("iced,jam,plain",donuts,",") + for (i=1; i<=n; i++) { + for (j=1; j<=n; j++) { + if (donuts[i] < donuts[j]) { + key = sprintf("%s %s",donuts[i],donuts[j]) + } + else { + key = sprintf("%s %s",donuts[j],donuts[i]) + } + arr[key]++ + } + } + cmd = "SORT" + for (i in arr) { + printf("%s\n",i) | cmd + choices++ + } + close(cmd) + printf("choices = %d\n",choices) + exit(0) +} diff --git a/Task/Combinations-with-repetitions/Bracmat/combinations-with-repetitions.bracmat b/Task/Combinations-with-repetitions/Bracmat/combinations-with-repetitions.bracmat new file mode 100644 index 0000000000..fa2631110c --- /dev/null +++ b/Task/Combinations-with-repetitions/Bracmat/combinations-with-repetitions.bracmat @@ -0,0 +1,19 @@ +( ( choices + = n things thing result + . !arg:(?n.?things) + & ( !n:0&1 + | 0:?result + & ( !things + : ? + ( %?`thing ?:?things + & !thing*choices$(!n+-1.!things)+!result + : ?result + & ~ + ) + | !result + ) + ) + ) +& out$(choices$(2.iced jam plain)) +& out$(choices$(3.iced jam plain butter marmite tahin fish salad onion grass):?+[?N&!N) +); diff --git a/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions.clj b/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions.clj new file mode 100644 index 0000000000..34a0638d73 --- /dev/null +++ b/Task/Combinations-with-repetitions/Clojure/combinations-with-repetitions.clj @@ -0,0 +1,6 @@ +(defn combinations [coll k] + (when-let [[x & xs] coll] + (if (= k 1) + (map list coll) + (concat (map (partial cons x) (combinations coll (dec k))) + (combinations xs k))))) diff --git a/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions.coffee b/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions.coffee new file mode 100644 index 0000000000..4ba3f5440a --- /dev/null +++ b/Task/Combinations-with-repetitions/CoffeeScript/combinations-with-repetitions.coffee @@ -0,0 +1,12 @@ +combos = (arr, k) -> + return [ [] ] if k == 0 + return [] if arr.length == 0 + + combos_with_head = ([arr[0]].concat combo for combo in combos arr, k-1) + combos_sans_head = combos arr[1...], k + combos_with_head.concat combos_sans_head + +arr = ['iced', 'jam', 'plain'] +console.log "valid pairs from #{arr.join ','}:" +console.log combos arr, 2 +console.log "#{combos([1..10], 3).length} ways to order 3 donuts given 10 types" diff --git a/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d index cf2a77c929..8819e25782 100644 --- a/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d +++ b/Task/Combinations-with-repetitions/D/combinations-with-repetitions-1.d @@ -4,7 +4,7 @@ const struct CombRep { immutable uint nt, nc; private const ulong[] combVal; - this(in uint numType, in uint numChoice) pure nothrow + this(in uint numType, in uint numChoice) pure nothrow @safe in { assert(0 < numType && numType + numChoice <= 64, "Valid only for nt + nc <= 64 (ulong bit size)"); @@ -34,15 +34,16 @@ const struct CombRep { this.combVal = localCombVal; } - uint length() @property const pure nothrow { + uint length() @property const pure nothrow @safe { return combVal.length; } - uint[] opIndex(in uint idx) const pure nothrow { + uint[] opIndex(in uint idx) const pure nothrow @safe { return val2set(combVal[idx]); } - int opApply(immutable int delegate(in ref uint[]) dg) { + int opApply(immutable int delegate(in ref uint[]) pure nothrow @safe dg) + pure nothrow @safe { foreach (immutable v; combVal) { auto set = val2set(v); if (dg(set)) @@ -51,7 +52,7 @@ const struct CombRep { return 1; } - private uint[] val2set(in ulong v) const pure nothrow { + private uint[] val2set(in ulong v) const pure nothrow @safe { // Convert bit pattern to selection set immutable uint bitLimit = nt + nc - 1; uint typeIdx = 0; @@ -66,7 +67,7 @@ const struct CombRep { } // For finite Random Access Range. -auto combRep(R)(R types, in uint numChoice) /*pure nothrow*/ +auto combRep(R)(R types, in uint numChoice) /*pure*/ nothrow @safe if (hasLength!R && isRandomAccessRange!R) { ElementType!R[][] result; @@ -80,7 +81,7 @@ if (hasLength!R && isRandomAccessRange!R) { return result; } -void main() { +void main() @safe { foreach (const e; combRep(["iced", "jam", "plain"], 2)) writefln("%-(%5s %)", e); writeln("Ways to select 3 from 10 types is ", diff --git a/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions.erl b/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions.erl new file mode 100644 index 0000000000..8a6ffeb70e --- /dev/null +++ b/Task/Combinations-with-repetitions/Erlang/combinations-with-repetitions.erl @@ -0,0 +1,9 @@ +-module(comb). +-compile(export_all). + +comb_rep(0,_) -> + [[]]; +comb_rep(_,[]) -> + []; +comb_rep(N,[H|T]=S) -> + [[H|L] || L <- comb_rep(N-1,S)]++comb_rep(N,T). diff --git a/Task/Combinations-with-repetitions/Go/combinations-with-repetitions-3.go b/Task/Combinations-with-repetitions/Go/combinations-with-repetitions-3.go index 18d243368a..b1f5e11c0b 100644 --- a/Task/Combinations-with-repetitions/Go/combinations-with-repetitions-3.go +++ b/Task/Combinations-with-repetitions/Go/combinations-with-repetitions-3.go @@ -7,12 +7,12 @@ import ( ) // Go maps are an easy representation for sets as long as the element type -// of the set is valid as a key type for maps. Strings are easy. We follow -// the convention of always storing true for the value. +// of the set is valid as a key type for maps. Strings are easy. +// We follow the convention of always storing true for the value. type set map[string]bool -// Multisets of strings are easy in the same way. We store the multiplicity -// of the element as the value. +// Multisets of strings are easy in the same way. +// We store the multiplicity of the element as the value. type multiset map[string]int // But multisets are not valid as a map key type so we must do something diff --git a/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions.js b/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions.js new file mode 100644 index 0000000000..97d6e9602a --- /dev/null +++ b/Task/Combinations-with-repetitions/JavaScript/combinations-with-repetitions.js @@ -0,0 +1,24 @@ +Donuts +

diff --git a/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia b/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia
new file mode 100644
index 0000000000..0189960c13
--- /dev/null
+++ b/Task/Combinations-with-repetitions/Julia/combinations-with-repetitions.julia
@@ -0,0 +1,4 @@
+function combos_with_replacement(list, k)
+    n = length(list)
+    [[list[c[i]-i+1] for i=1:length(c)] for c in combinations([1:(n+k-1)],k)]
+end
diff --git a/Task/Combinations-with-repetitions/Lua/combinations-with-repetitions.lua b/Task/Combinations-with-repetitions/Lua/combinations-with-repetitions.lua
new file mode 100644
index 0000000000..bf59860a03
--- /dev/null
+++ b/Task/Combinations-with-repetitions/Lua/combinations-with-repetitions.lua
@@ -0,0 +1,46 @@
+function GenerateCombinations(tList, nMaxElements, tOutput, nStartIndex, nChosen, tCurrentCombination)
+	if not nStartIndex then
+		nStartIndex = 1
+	end
+	if not nChosen then
+		nChosen = 0
+	end
+	if not tOutput then
+		tOutput = {}
+	end
+	if not tCurrentCombination then
+		tCurrentCombination = {}
+	end
+	
+	if nChosen == nMaxElements then
+		-- Must copy the table to avoid all elements referring to a single reference
+		local tCombination = {}
+		for k,v in pairs(tCurrentCombination) do
+			tCombination[k] = v
+		end
+		
+		table.insert(tOutput, tCombination)
+		return
+	end
+
+ 	local nIndex = 1
+	for k,v in pairs(tList) do
+		if nIndex >= nStartIndex then
+			tCurrentCombination[nChosen + 1] = tList[nIndex]
+			GenerateCombinations(tList, nMaxElements, tOutput, nIndex, nChosen + 1, tCurrentCombination)
+		end
+		
+		nIndex = nIndex + 1
+	end
+	
+	return tOutput
+end
+
+tDonuts = {"iced", "jam", "plain"}
+tCombinations = GenerateCombinations(tDonuts, #tDonuts)
+for nCombination,tCombination in ipairs(tCombinations) do
+	print("Combination " .. tostring(nCombination))
+	for nIndex,strFlavor in ipairs(tCombination) do
+		print("+" .. strFlavor)
+	end
+end
diff --git a/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions.php b/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions.php
new file mode 100644
index 0000000000..c75762744b
--- /dev/null
+++ b/Task/Combinations-with-repetitions/PHP/combinations-with-repetitions.php
@@ -0,0 +1,32 @@
+";
+  }
+  $donuts = range(1, 10);
+  $num_donut_combos = count(combos($donuts, 3));
+  echo "$num_donut_combos ways to order 3 donuts given 10 types";
+?>
diff --git a/Task/Combinations-with-repetitions/Perl/combinations-with-repetitions.pl b/Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-1.pl
similarity index 100%
rename from Task/Combinations-with-repetitions/Perl/combinations-with-repetitions.pl
rename to Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-1.pl
diff --git a/Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-2.pl b/Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-2.pl
new file mode 100644
index 0000000000..4a20c023fe
--- /dev/null
+++ b/Task/Combinations-with-repetitions/Perl/combinations-with-repetitions-2.pl
@@ -0,0 +1,8 @@
+use Algorithm::Combinatorics qw/combinations_with_repetition/;
+my $iter = combinations_with_repetition([qw/iced jam plain/], 2);
+while (my $p = $iter->next) {
+  print "@$p\n";
+}
+# Not an efficient way: generates them all in an array!
+my $count =()= combinations_with_repetition([1..10],7);
+print "There are $count ways to pick 7 out of 10\n";
diff --git a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx
index 2d987cf675..b43e62ed79 100644
--- a/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx
+++ b/Task/Combinations-with-repetitions/REXX/combinations-with-repetitions.rexx
@@ -1,30 +1,29 @@
 /*REXX program shows combination sets for  X  things taken  Y  at a time*/
-parse arg x y symbols .;  if x=='' | x==',' then x=3
-                          if y=='' | y==',' then y=2
-if symbols=='' then symbols='iced jam plain'       /*symbol table words.*/
-
-say "────────────" abs(x) 'doughnut selection taken' y "at a time:"
-say "────────────" RcombN(x,y) 'combinations.';      if x\=='' then exit #
-say
-    x= -10          /*indicate that the combinations aren't to be shown.*/
-    y=   3
-say "────────────" abs(x) 'doughnut selection choose' y "at a time:"
-say "────────────" RcombN(x,y) 'combinations.'
+parse arg x y symbols x2 y2 symbols2 . /*get optional arguments from CL.*/
+if  x=='' |  x==','   then  x=  3      /*X  not specified?  Use default.*/
+if  y=='' |  y==','   then  y=  2      /*Y   "     "         "      "   */
+if x2=='' | x2==','   then x2=-10      /*X2  "     "         "      "   */
+if y2=='' | y2==','   then y2=  3      /*Y2  "     "         "      "   */
+if symbols ==''  then symbols ='iced jam plain'   /*symbol  table words.*/
+if symbols2==''  then symbols2=symbols            /*symbol2   "     "   */
+call  RcombN  x,  y,  symbols          /*1st part of Rosetta Code task. */
+call  RcombN  x2, y2, symbols2         /*2nd   "   "    "      "    "   */
 exit                                   /*stick a fork in it, we're done.*/
 /*─────────────────────────────────────RCOMBN subroutine────────────────*/
-RcombN: procedure expose # symbols; parse arg x 1 ox,y;  x=abs(x);  base=x
-!.=1
-           do #=1;  if ox>0 then do;  L=;     do d=1 for y while ox>0
-                                              L=L word(symbols,!.d)
-                                              end   /*d*/ ;          say L
-                                 end
-           !.y=!.y+1;    if !.y==base then if .RcombN(y-1) then leave
-           end    /*#*/
+RcombN: procedure;  parse arg x,y,syms;  tell=x>0;    x=abs(x);   base=x+1
+syms=translate(syms,,',')              /*separate the symbols from list.*/
+say "────────────"  abs(x)   'doughnut selection taken'   y   "at a time:"
+           do i=1  for words(syms);  $.i=word(syms,i);  end
+@.=1                                   /* [↓]   maybe show combinations.*/
+           do #=1;  if tell  then do;  L=;     do d=1  for y   /*a comb.*/
+                                               _=@.d;          L=L  $._
+                                               end   /*d*/ ;        say L
+                                  end
+           @.y=@.y+1;    if @.y==base  then  if .RcombN(y-1)  then leave
+           end   /*#*/
+say "────────────"  #  'combinations.';             say;  say;  say
 return #
-/*─────────────────────────────────────.RCOMBN subroutine───────────────*/
-.RcombN: procedure expose !. y base;   parse arg d;  if d==0 then return 1
-p=!.d+1;   if p==base then return .RcombN(d-1)
-                do u=d to y
-                !.u=p
-                end     /*u*/
+.RcombN: procedure expose @. y base;  parse arg d;  if d==0  then return 1
+p=@.d+1;   if p==base  then return .RcombN(d-1);    do u=d  to y;    @.u=p
+                                                    end   /*u*/
 return 0
diff --git a/Task/Combinations-with-repetitions/Ruby/combinations-with-repetitions.rb b/Task/Combinations-with-repetitions/Ruby/combinations-with-repetitions.rb
index beea310dd0..3621bb5c41 100644
--- a/Task/Combinations-with-repetitions/Ruby/combinations-with-repetitions.rb
+++ b/Task/Combinations-with-repetitions/Ruby/combinations-with-repetitions.rb
@@ -1,3 +1,7 @@
 possible_doughnuts = ['iced', 'jam', 'plain'].repeated_combination(2)
 puts "There are #{possible_doughnuts.count} possible doughnuts:"
 possible_doughnuts.each{|doughnut_combi| puts doughnut_combi.join(' and ')}
+
+# Extra credit
+possible_doughnuts = [*1..10].repeated_combination(3)
+puts "", "#{possible_doughnuts.count} ways to order 3 donuts given 10 types"
diff --git a/Task/Combinations/00DESCRIPTION b/Task/Combinations/00DESCRIPTION
index bccf71426b..efdc832627 100644
--- a/Task/Combinations/00DESCRIPTION
+++ b/Task/Combinations/00DESCRIPTION
@@ -1,4 +1,5 @@
 Given non-negative integers m and n, generate all size m [http://mathworld.wolfram.com/Combination.html combinations] of the integers from 0 to n-1 in sorted order (each combination is sorted and the entire table is sorted).
+
 For example, 3 comb 5 is
  0 1 2
  0 1 3
diff --git a/Task/Combinations/AppleScript/combinations.applescript b/Task/Combinations/AppleScript/combinations.applescript
new file mode 100644
index 0000000000..2b69cea1bc
--- /dev/null
+++ b/Task/Combinations/AppleScript/combinations.applescript
@@ -0,0 +1,27 @@
+on comb(n, k)
+	set c to {}
+	repeat with i from 1 to k
+		set end of c to i's contents
+	end repeat
+	set r to {c's contents}
+	repeat while my next_comb(c, k, n)
+		set end of r to c's contents
+	end repeat
+	return r
+end comb
+
+on next_comb(c, k, n)
+	set i to k
+	set c's item i to (c's item i) + 1
+	repeat while (i > 1 and c's item i ≥ n - k + 1 + i)
+		set i to i - 1
+		set c's item i to (c's item i) + 1
+	end repeat
+	if (c's item 1 > n - k + 1) then return false	
+	repeat with i from i + 1 to k
+		set c's item i to (c's item (i - 1)) + 1
+	end repeat
+	return true
+end next_comb
+
+return comb(5, 3)
diff --git a/Task/Combinations/CoffeeScript/combinations.coffee b/Task/Combinations/CoffeeScript/combinations.coffee
new file mode 100644
index 0000000000..93cacf3d1b
--- /dev/null
+++ b/Task/Combinations/CoffeeScript/combinations.coffee
@@ -0,0 +1,25 @@
+combinations = (n, p) ->
+  return [ [] ] if p == 0
+  i = 0
+  combos = []
+  combo = []
+  while combo.length < p
+    if i < n
+      combo.push i
+      i += 1
+    else
+      break if combo.length == 0
+      i = combo.pop() + 1
+
+    if combo.length == p
+      combos.push clone combo
+      i = combo.pop() + 1
+  combos
+
+clone = (arr) -> (n for n in arr)
+
+N = 5
+for i in [0..N]
+  console.log "------ #{N} #{i}"
+  for combo in combinations N, i
+    console.log combo
diff --git a/Task/Combinations/D/combinations-2.d b/Task/Combinations/D/combinations-2.d
index 3cd4a44f4e..7d68fd6cf8 100644
--- a/Task/Combinations/D/combinations-2.d
+++ b/Task/Combinations/D/combinations-2.d
@@ -1,10 +1,9 @@
 import std.stdio, std.algorithm, std.range;
 
-T[][] comb(T)(in T[] s, in int m) /*pure*/ nothrow {
+immutable(int)[][] comb(immutable int[] s, in int m) pure nothrow @safe {
   if (!m) return [[]];
   if (s.empty) return [];
-  return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x).array ~
-         s[1 .. $].comb(m);
+  return s[1 .. $].comb(m - 1).map!(x => s[0] ~ x).array ~ s[1 .. $].comb(m);
 }
 
 void main() {
diff --git a/Task/Combinations/D/combinations-3.d b/Task/Combinations/D/combinations-3.d
index c3ef2247cc..bc897500dd 100644
--- a/Task/Combinations/D/combinations-3.d
+++ b/Task/Combinations/D/combinations-3.d
@@ -1,126 +1,94 @@
 module combinations3;
 
-ulong binomial(long n, long k) pure nothrow
-in {
-    assert(n > 0, "binomial: n must be > 0.");
-} body {
-    if (k < 0 || k > n)
-        return 0;
-    if (k > (n / 2))
-        k = n - k;
-    ulong result = 1;
-    foreach (ulong d; 1 .. k + 1) {
-        result *= n;
-        n--;
-        result /= d;
-    }
-    return result;
-}
-
+import std.traits: Unqual;
 
 struct Combinations(T, bool copy=true) {
-    // Algorithm by Knuth, Pre-fascicle 3A, draft of
-    // section 7.2.1.3: "Generating all partitions".
-    T[] items;
-    int k;
-    size_t len = -1; // computed lazily
+    Unqual!T[] pool, front;
+    size_t r, n;
+    bool empty = false;
+    size_t[] indices;
+    size_t len;
+    bool lenComputed = false;
 
-    this(in T[] items, in int k)
-    in {
-        assert(items.length, "combinations: items can't be empty.");
-    } body {
-        this.items = items.dup;
-        this.k = k;
+    this(T[] pool_, in size_t r_) pure nothrow @safe {
+        this.pool = pool_.dup;
+        this.r = r_;
+        this.n = pool.length;
+        if (r > n)
+            empty = true;
+        indices.length = r;
+        foreach (immutable i, ref ini; indices)
+            ini = i;
+        front.length = r;
+        foreach (immutable i, immutable idx; indices)
+            front[i] = pool[idx];
     }
 
-    @property size_t length() /*logic_const*/ {
-        if (len == -1) // set cache
-            len = cast(size_t)binomial(items.length, k);
+    @property size_t length() /*logic_const*/ pure nothrow @nogc {
+        static size_t binomial(size_t n, size_t k) pure nothrow @safe @nogc
+        in {
+            assert(n > 0, "binomial: n must be > 0.");
+        } body {
+            if (k < 0 || k > n)
+                return 0;
+            if (k > (n / 2))
+                k = n - k;
+            size_t result = 1;
+            foreach (size_t d; 1 .. k + 1) {
+                result *= n;
+                n--;
+                result /= d;
+            }
+            return result;
+        }
+
+        if (!lenComputed) {
+            // Set cache.
+            len = binomial(n, r);
+            lenComputed = true;
+        }
         return len;
     }
 
-    int opApply(int delegate(ref T[]) dg) {
-        if (k == items.length)
-            return dg(items);         // yield items
-
-        auto outarr = new T[k];
-        if (k == 0)
-            return dg(outarr);        // yield []
-
-        if (k < 0 || k > items.length)
-            return 0;                 // yield nothing
-
-        int result, x;
-        immutable n = items.length;
-        auto c = new uint[k + 3]; // c[0] isn'k used
-
-        foreach (j; 1 .. k + 1)
-            c[j] = j - 1;
-        c[k + 1] = n;
-        c[k + 2] = 0;
-        int j = k;
-
-        while (true) {
-            // The following lines equal to:
-            //int pos;
-            //foreach (i; 1 .. k +1)
-            //    outarr[pos++] = items[c[i]];
-            auto outarr_ptr = outarr.ptr;
-            auto c_ptr = &(c[1]);
-            auto c_ptrkp1 = &(c[k + 1]);
-            while (c_ptr != c_ptrkp1)
-                *outarr_ptr++ = items[*c_ptr++];
-
-
-            static if (copy) {
-                auto outarr2 = outarr.dup;
-                result = dg(outarr2); // yield outarr2
-            } else {
-                result = dg(outarr); // yield outarr
-            }
-
-            if (j > 0) {
-                x = j;
-                c[j] = x;
-                j--;
-                continue;
-            }
-
-            if ((c[1] + 1) < c[2]) {
-                c[1]++;
-                continue;
-            } else
-                j = 2;
-
-            while (true) {
-                c[j - 1] = j - 2;
-                x = c[j] + 1;
-                if (x == c[j + 1])
-                    j++;
-                else
+    void popFront() pure nothrow @safe {
+        if (!empty) {
+            bool broken = false;
+            size_t pos = 0;
+            foreach_reverse (immutable i; 0 .. r) {
+                pos = i;
+                if (indices[i] != i + n - r) {
+                    broken = true;
                     break;
+                }
             }
-
-            if (j > k)
-                return result; // End
-
-            c[j] = x;
-            j--;
+            if (!broken) {
+                empty = true;
+                return;
+            }
+            indices[pos]++;
+            foreach (immutable j; pos + 1 .. r)
+                indices[j] = indices[j - 1] + 1;
+            static if (copy)
+                front = new Unqual!T[front.length];
+            foreach (immutable i, immutable idx; indices)
+                front[i] = pool[idx];
         }
     }
 }
 
-Combinations!(T,copy) combinations(bool copy=true, T)
-                                  (in T[] items, in int k)
+Combinations!(T, copy) combinations(bool copy=true, T)
+                                   (T[] items, in size_t k)
 in {
     assert(items.length, "combinations: items can't be empty.");
 } body {
-    return Combinations!(T, copy)(items, k);
+    return typeof(return)(items, k);
 }
 
-
-// compile with -version=combinations3_main to run main
-version(combinations3_main) void main() {
-    import std.stdio, std.array;
-    writeln(array(combinations([1, 2, 3, 4], 2)));
+// Compile with -version=combinations3_main to run main.
+version(combinations3_main)
+void main() {
+    import std.stdio, std.array, std.algorithm;
+    [1, 2, 3, 4].combinations!false(2).array.writeln;
+    [1, 2, 3, 4].combinations!true(2).array.writeln;
+    [1, 2, 3, 4].combinations(2).map!(x => x).writeln;
 }
diff --git a/Task/Combinations/Eiffel/combinations-1.e b/Task/Combinations/Eiffel/combinations-1.e
new file mode 100644
index 0000000000..652e772e5e
--- /dev/null
+++ b/Task/Combinations/Eiffel/combinations-1.e
@@ -0,0 +1,96 @@
+class
+	COMBINATIONS
+create
+	make
+feature
+	make(n, k:INTEGER)
+		require
+			n_positive: n>0
+			k_positive: k>0
+			k_smaller_equal: k<=n
+		do
+			create set.make
+			set.extend ("")
+			create sol.make
+			sol:=solve(set,k,n-k)
+			sol:= conv_sol(n, sol)
+		ensure
+			correct_num_of_sol: num_of_comb(n,k)= sol.count
+		end
+	set: LINKED_LIST[STRING]
+	sol: LINKED_LIST[STRING]
+
+	conv_sol(n: INTEGER; solution: LINKED_LIST[STRING]):LINKED_LIST[STRING]
+	local
+		i,j: INTEGER
+		temp: STRING
+	do
+		create temp.make (n)
+		from
+			i:=1
+		until
+			i>solution.count
+		loop
+			from
+				j:= 1
+			until
+				j> n
+			loop
+				if solution[i].at (j)= '1' then
+					temp.append (j.out)
+				end
+				j:= j+1
+			end
+			solution[i].deep_copy( temp)
+			temp.wipe_out
+			i:= i+1
+		end
+		Result:= solution
+	end
+
+	solve(seta: LINKED_LIST[STRING];one,zero: INTEGER): LINKED_LIST[STRING]
+		local
+			new_P1,  new_P0: LINKED_LIST[STRING]
+		do
+			create new_P1.make
+			create new_P0.make
+			if  one > 0  then
+				new_P1.deep_copy(seta)
+				across new_P1 as P1  loop new_P1.item.append ("1")  end
+			     new_P1:=solve(new_P1, one-1, zero)
+		 	end
+			if zero > 0 then
+				new_P0.deep_copy(seta)
+				across new_P0 as P0  loop new_P0.item.append ("0")  end
+				new_P0:=solve(new_P0, one, zero-1)
+			end
+			if one=0 and zero= 0 then
+				Result:= seta
+			else
+				create Result.make
+				Result.fill (new_p0)
+				Result.fill (new_p1)
+			end
+		end
+
+	num_of_comb (n,k:INTEGER):INTEGER
+	--- used for contracts
+		local
+			upper, lower, m, l: INTEGER
+		do
+			upper:= 1
+			lower:= 1
+			m:= n
+			l:= k
+			from
+			until
+				m
+    lists:last(all_combinations(K, List)).
+
+all_combinations(K, List) ->
+    lists:foldr(
+      fun(X, Next) ->
+              Sub = lists:sublist(Next, length(Next) - 1),
+              Step = [[]] ++ [[[X|S] || S <- L] || L <- Sub],
+              lists:zipwith(fun lists:append/2, Step, Next)
+      end, [[[]]] ++ lists:duplicate(K, []), List).
diff --git a/Task/Combinations/Lua/combinations.lua b/Task/Combinations/Lua/combinations.lua
index f392d78a24..354fb82e00 100644
--- a/Task/Combinations/Lua/combinations.lua
+++ b/Task/Combinations/Lua/combinations.lua
@@ -1,4 +1,3 @@
--- Recursive version
 function map(f, a, ...) if a then return f(a), map(f, ...) end end
 function incr(k) return function(a) return k > a and a or a+1 end end
 function combs(m, n)
@@ -11,35 +10,3 @@ function combs(m, n)
 end
 
 for k, v in ipairs(combs(3, 5)) do print(unpack(v)) end
-
--- Iterative version
-function icombs(a,b)
-    if a==0 then return end
-    local taken = {} local slots = {}
-    for i=1,a do slots[i]=0 end
-    for i=1,b do taken[i]=false end
-    local index = 1
-    while index > 0 do repeat
-        repeat slots[index] = slots[index] + 1
-        until slots[index] > b or not taken[slots[index]]
-        if slots[index] > b then
-            slots[index] = 0
-            index = index - 1
-            if index > 0 then
-                taken[slots[index]] = false
-            end
-            break
-        else
-            taken[slots[index]] = true
-        end
-        if index == a then
-            for i=1,a do io.write(slots[i]) io.write(" ") end
-            io.write("\n")
-            taken[slots[index]] = false
-            break
-        end
-        index = index + 1
-    until true end
-end
-
-icombs(3, 5)
diff --git a/Task/Combinations/Maple/combinations.maple b/Task/Combinations/Maple/combinations.maple
new file mode 100644
index 0000000000..d0d7cfe6b8
--- /dev/null
+++ b/Task/Combinations/Maple/combinations.maple
@@ -0,0 +1,4 @@
+> combinat:-choose( 5, 3 );
+[[1, 2, 3], [1, 2, 4], [1, 2, 5], [1, 3, 4], [1, 3, 5], [1, 4, 5], [2, 3, 4], [2, 3, 5],
+
+    [2, 4, 5], [3, 4, 5]]
diff --git a/Task/Combinations/Perl-6/combinations-2.pl6 b/Task/Combinations/Perl-6/combinations-2.pl6
index a5fd07dc76..759bb0f5ad 100644
--- a/Task/Combinations/Perl-6/combinations-2.pl6
+++ b/Task/Combinations/Perl-6/combinations-2.pl6
@@ -1,10 +1,15 @@
 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  );
+    return ([],) unless $k;
+    return if $k > $n || $n <= 0;
+    my @c = ^$k;
+    gather loop {
+      take [@c];
+      next if @c[$k-1]++ < $n-1;
+      my $i = $k-2;
+      $i-- while $i >= 0 && @c[$i] >= $n-($k-$i);
+      last if $i < 0;
+      @c[$i]++;
+      while ++$i < $k { @c[$i] = @c[$i-1] + 1; }
     }
 }
-
-.say for combinations(5, 3);
+.say for combinations(5,3);
diff --git a/Task/Combinations/Perl-6/combinations-3.pl6 b/Task/Combinations/Perl-6/combinations-3.pl6
new file mode 100644
index 0000000000..a5fd07dc76
--- /dev/null
+++ b/Task/Combinations/Perl-6/combinations-3.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/Perl/combinations-1.pl b/Task/Combinations/Perl/combinations-1.pl
new file mode 100644
index 0000000000..04c0525afa
--- /dev/null
+++ b/Task/Combinations/Perl/combinations-1.pl
@@ -0,0 +1,2 @@
+use ntheory qw/forcomb/;
+forcomb { print "@_\n" } 5,3
diff --git a/Task/Combinations/Perl/combinations-2.pl b/Task/Combinations/Perl/combinations-2.pl
new file mode 100644
index 0000000000..76d81dc54a
--- /dev/null
+++ b/Task/Combinations/Perl/combinations-2.pl
@@ -0,0 +1,3 @@
+use Algorithm::Combinatorics qw/combinations/;
+my @c = combinations( [0..4], 3 );
+print "@$_\n" for @c;
diff --git a/Task/Combinations/Perl/combinations-3.pl b/Task/Combinations/Perl/combinations-3.pl
new file mode 100644
index 0000000000..d6bfa6443c
--- /dev/null
+++ b/Task/Combinations/Perl/combinations-3.pl
@@ -0,0 +1,5 @@
+use Algorithm::Combinatorics qw/combinations/;
+my $iter = combinations([0..4],3);
+while (my $c = $iter->next) {
+  print "@$c\n";
+}
diff --git a/Task/Combinations/Perl/combinations.pl b/Task/Combinations/Perl/combinations.pl
deleted file mode 100644
index 1bbad0ffa8..0000000000
--- a/Task/Combinations/Perl/combinations.pl
+++ /dev/null
@@ -1,4 +0,0 @@
-use Math::Combinatorics;
-
-@n = (0 .. 4);
-print join("\n", map { join(" ", @{$_}) } combine(3, @n)), "\n";
diff --git a/Task/Combinations/Prolog/combinations-2.pro b/Task/Combinations/Prolog/combinations-2.pro
index 4ec7ae3ad2..97b95cfcc7 100644
--- a/Task/Combinations/Prolog/combinations-2.pro
+++ b/Task/Combinations/Prolog/combinations-2.pro
@@ -1,12 +1,10 @@
- ?- comb_clpfd(L, 3, 5), writeln(L), fail.
-[1,2,3]
-[1,2,4]
-[1,2,5]
-[1,3,4]
-[1,3,5]
-[1,4,5]
-[2,3,4]
-[2,3,5]
-[2,4,5]
-[3,4,5]
-false.
+comb_Prolog(L, M, N) :-
+    length(L, M),
+    fill(L, 1, N).
+
+fill([], _, _).
+
+fill([H | T], Min, Max) :-
+    between(Min, Max, H),
+    H1 is H + 1,
+    fill(T, H1, Max).
diff --git a/Task/Combinations/Prolog/combinations-3.pro b/Task/Combinations/Prolog/combinations-3.pro
index 97b95cfcc7..dd41062347 100644
--- a/Task/Combinations/Prolog/combinations-3.pro
+++ b/Task/Combinations/Prolog/combinations-3.pro
@@ -1,10 +1,3 @@
-comb_Prolog(L, M, N) :-
-    length(L, M),
-    fill(L, 1, N).
-
-fill([], _, _).
-
-fill([H | T], Min, Max) :-
-    between(Min, Max, H),
-    H1 is H + 1,
-    fill(T, H1, Max).
+:- use_module(library(clpfd)).
+comb_lstcomp(N, M, V) :-
+	V <- {L	& length(L, N), L ins 1..M & all_distinct(L), chain(L, #<), label(L)}.
diff --git a/Task/Combinations/REXX/combinations.rexx b/Task/Combinations/REXX/combinations.rexx
index 95c66adb6d..0e25e9288e 100644
--- a/Task/Combinations/REXX/combinations.rexx
+++ b/Task/Combinations/REXX/combinations.rexx
@@ -1,27 +1,28 @@
 /*REXX program shows combination sets for  X  things taken  Y  at a time*/
-@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU; @digs=123456789
-parse arg x y symbols .;  if x=='' | x==',' then x=5
-                          if y=='' | y==',' then y=3
-if symbols=='' then symbols=@digs||@abc||@abcU    /*symbol table string.*/
-say "────────────" x 'things taken' y "at a time:"
-say "────────────" combN(x,y) 'combinations.'
+parse arg x y $ .                      /*get optional args from the C.L.*/
+if x=='' | x==','  then x=5            /*X  specified?  No, use default.*/
+if y=='' | y==','  then y=3            /*Y  specified?  No, use default.*/
+@abc='abcdefghijklmnopqrstuvwxyz';   @abcU=@abc;   upper @abcU
+if $=='' then $=123456789||@abc||@abcU /*chars for symbol table string. */
+say "────────────"        x      ' things taken '      y     " at a time:"
+say "────────────"  combN(x,y)   ' combinations.'
 exit                                   /*stick a fork in it, we're done.*/
 /*──────────────────────────────────COMBN subroutine────────────────────*/
-combN: procedure expose symbols;  parse arg x,y;   base=x+1;  bbase=base-y
-!.=0;           do i=1 for y;    !.i=i
+combN: procedure expose $;    parse arg x,y;     base=x+1;    bbase=base-y
+!.=0;           do i=1  for y;    !.i=i
                 end   /*i*/
 
-          do j=1;  L=;           do d=1 for y
-                                 L=L   word(substr(symbols,!.d,1)   !.d,1)
-                                 end   /*d*/
+          do j=1;   L=;           do d=1  for y
+                                  L=L  word(substr($,!.d,1)   !.d,1)
+                                  end   /*d*/
           say L
-          !.y=!.y+1;   if !.y==base   then   if .combUp(y-1)   then leave
+          !.y=!.y+1;    if !.y==base   then   if .combUp(y-1)   then leave
           end         /*j*/
 return j
 
 .combUp: procedure expose !. y bbase;  parse arg d;  if d==0 then return 1
-p=!.d;        do u=d to y;     !.u=p+1
-              if !.u==bbase+u then return .combUp(u-1)
+p=!.d;        do u=d  to y;         !.u=p+1
+              if !.u==bbase+u  then return .combUp(u-1)
               p=!.u
               end     /*u*/
 return 0
diff --git a/Task/Combinations/Scala/combinations-2.scala b/Task/Combinations/Scala/combinations-2.scala
index 10bc260850..18206c9ab1 100644
--- a/Task/Combinations/Scala/combinations-2.scala
+++ b/Task/Combinations/Scala/combinations-2.scala
@@ -1,2 +1,8 @@
-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))
+  def combs[A](n: Int, l: List[A]): Iterator[List[A]] = n match {
+    case _ if n < 0 || l.lengthCompare(n) < 0 => Iterator.empty
+    case 0 => Iterator(List.empty)
+    case n => l.tails.flatMap({
+      case Nil => Nil
+      case x :: xs => combs(n - 1, xs).map(x :: _)
+    })
+  }
diff --git a/Task/Combinations/Scala/combinations-3.scala b/Task/Combinations/Scala/combinations-3.scala
new file mode 100644
index 0000000000..7a77696f4a
--- /dev/null
+++ b/Task/Combinations/Scala/combinations-3.scala
@@ -0,0 +1,16 @@
+  def combs[A](n: Int, xs: List[A]): Stream[List[A]] =
+    combsBySize(xs)(n)
+
+  def combsBySize[A](xs: List[A]): Stream[Stream[List[A]]] = {
+    val z: Stream[Stream[List[A]]] = Stream(Stream(List())) ++ Stream.continually(Stream.empty)
+    xs.toStream.foldRight(z)((a, b) => zipWith[Stream[List[A]]](_ ++ _, f(a, b), b))
+  }
+
+  def zipWith[A](f: (A, A) => A, as: Stream[A], bs: Stream[A]): Stream[A] = (as, bs) match {
+    case (Stream.Empty, _) => Stream.Empty
+    case (_, Stream.Empty) => Stream.Empty
+    case (a #:: as, b #:: bs) => f(a, b) #:: zipWith(f, as, bs)
+  }
+
+  def f[A](x: A, xsss: Stream[Stream[List[A]]]): Stream[Stream[List[A]]] =
+    Stream.empty #:: xsss.map(_.map(x :: _))
diff --git a/Task/Combinations/Scala/combinations-4.scala b/Task/Combinations/Scala/combinations-4.scala
new file mode 100644
index 0000000000..10bc260850
--- /dev/null
+++ b/Task/Combinations/Scala/combinations-4.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/Combinations/Smalltalk/combinations.st b/Task/Combinations/Smalltalk/combinations.st
index 90a781294a..8da7afde3d 100644
--- a/Task/Combinations/Smalltalk/combinations.st
+++ b/Task/Combinations/Smalltalk/combinations.st
@@ -1,6 +1,4 @@
-(0 to: 4)
-    combinations: 3 atATimeDo: [ :x |
-        ':-)' logCr: x ].
+(0 to: 4) combinations: 3 atATimeDo: [ :x | Transcript cr; show: x printString].
 
 "output on Transcript:
 #(0 1 2)
diff --git a/Task/Command-line-arguments/PHP/command-line-arguments.php b/Task/Command-line-arguments/PHP/command-line-arguments.php
index 1c2fbf66f7..4f994577d8 100644
--- a/Task/Command-line-arguments/PHP/command-line-arguments.php
+++ b/Task/Command-line-arguments/PHP/command-line-arguments.php
@@ -1,4 +1,4 @@
 
+$all_args_without_program_name = array_shift($argv);
diff --git a/Task/Command-line-arguments/Scala/command-line-arguments-1.scala b/Task/Command-line-arguments/Scala/command-line-arguments-1.scala
index f92aab43c8..3deaf2307b 100644
--- a/Task/Command-line-arguments/Scala/command-line-arguments-1.scala
+++ b/Task/Command-line-arguments/Scala/command-line-arguments-1.scala
@@ -1,5 +1,3 @@
-object T {
-  def main(args: Array[String]) {
-    println("Received the following arguments": + args.mkString("", ", ", "."))
-  }
+object CommandLineArguments extends App {
+    println(s"Received the following arguments: + ${args.mkString("", ", ", ".")}")
 }
diff --git a/Task/Command-line-arguments/Scala/command-line-arguments-2.scala b/Task/Command-line-arguments/Scala/command-line-arguments-2.scala
index e547819eec..3c43b9dea9 100644
--- a/Task/Command-line-arguments/Scala/command-line-arguments-2.scala
+++ b/Task/Command-line-arguments/Scala/command-line-arguments-2.scala
@@ -1 +1 @@
-println("My arguments are: "+argv.mkString("", ", ", "."))
+println(s"Received the following arguments: + ${argv.mkString("", ", ", ".")}")
diff --git a/Task/Command-line-arguments/TXR/command-line-arguments.txr b/Task/Command-line-arguments/TXR/command-line-arguments-1.txr
similarity index 100%
rename from Task/Command-line-arguments/TXR/command-line-arguments.txr
rename to Task/Command-line-arguments/TXR/command-line-arguments-1.txr
diff --git a/Task/Command-line-arguments/TXR/command-line-arguments-2.txr b/Task/Command-line-arguments/TXR/command-line-arguments-2.txr
new file mode 100644
index 0000000000..d7865d6dd1
--- /dev/null
+++ b/Task/Command-line-arguments/TXR/command-line-arguments-2.txr
@@ -0,0 +1,4 @@
+@(do
+   (tree-case *args*
+     ((a b c) (put-line "got three args, thanks!"))
+     (else (put-line `usage: @(ldiff *full-args* *args*)   `))))
diff --git a/Task/Comments/00DESCRIPTION b/Task/Comments/00DESCRIPTION
index 20f1705be8..17a2680322 100644
--- a/Task/Comments/00DESCRIPTION
+++ b/Task/Comments/00DESCRIPTION
@@ -1,4 +1,5 @@
-All ways to include text in a language source file that's completely ignored by the compiler or interpreter.
+All ways to include text in a language source file
+that's completely ignored by the compiler or interpreter.
 
 '''See Also:'''
* Related Task: [[Documentation]] diff --git a/Task/Comments/00META.yaml b/Task/Comments/00META.yaml index 659c8686af..88792fbb77 100644 --- a/Task/Comments/00META.yaml +++ b/Task/Comments/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Initialization note: Basic language learning diff --git a/Task/Comments/360-Assembly/comments.360 b/Task/Comments/360-Assembly/comments.360 index f8b5009c23..0daa9f3f1a 100644 --- a/Task/Comments/360-Assembly/comments.360 +++ b/Task/Comments/360-Assembly/comments.360 @@ -1,5 +1,6 @@ * An asterisk in column one denotes a comment line * Comments may also follow any syntactically complete instruction: - NOP This is a comment (after a NOP instruction) + LA 1,0 Comment + NOP Comment (after a NOP instruction) * Comments after instructions with omitted operands require a comma "," - END , Comment (without comma, "Comment" assumed an operand of "END") + END , Comment (without comma, "Comment" assumed an operand of "END") diff --git a/Task/Comments/ALGOL-60/comments.alg b/Task/Comments/ALGOL-60/comments.alg new file mode 100644 index 0000000000..e50fb4e2e9 --- /dev/null +++ b/Task/Comments/ALGOL-60/comments.alg @@ -0,0 +1,4 @@ +'COMMENT' this is a first comment; +'COMMENT' +****** this is a second comment ****** +; diff --git a/Task/Comments/ALGOL-W/comments.alg b/Task/Comments/ALGOL-W/comments.alg new file mode 100644 index 0000000000..b87deec489 --- /dev/null +++ b/Task/Comments/ALGOL-W/comments.alg @@ -0,0 +1,8 @@ +begin + comment a comment; + % another comment + ; + % and + another + % +end this_word_is_also_a_comment. diff --git a/Task/Comments/BASIC/comments-1.basic b/Task/Comments/BASIC/comments-1.basic index e9aabc5db8..de95f49486 100644 --- a/Task/Comments/BASIC/comments-1.basic +++ b/Task/Comments/BASIC/comments-1.basic @@ -1,2 +1,2 @@ -100 ' Standard BASIC comments begin with "REM" (remark) and extend to the end of the line +100 REM 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/Elixir/comments.elixir b/Task/Comments/Elixir/comments.elixir new file mode 100644 index 0000000000..be697a0aa5 --- /dev/null +++ b/Task/Comments/Elixir/comments.elixir @@ -0,0 +1 @@ +# single line comment diff --git a/Task/Comments/JCL/comments.jcl b/Task/Comments/JCL/comments-1.jcl similarity index 100% rename from Task/Comments/JCL/comments.jcl rename to Task/Comments/JCL/comments-1.jcl diff --git a/Task/Comments/JCL/comments-2.jcl b/Task/Comments/JCL/comments-2.jcl new file mode 100644 index 0000000000..2cd96d6878 --- /dev/null +++ b/Task/Comments/JCL/comments-2.jcl @@ -0,0 +1 @@ +/* This is also a comment line (/* in columns 1-3) diff --git a/Task/Comments/Oberon-2/comments.oberon-2 b/Task/Comments/Oberon-2/comments.oberon-2 new file mode 100644 index 0000000000..0af8c335d3 --- /dev/null +++ b/Task/Comments/Oberon-2/comments.oberon-2 @@ -0,0 +1,6 @@ +(* this is a comment *) +(* + and this is a + multiline comment + (* with a nested comment *) +*) diff --git a/Task/Comments/PL-I/comments.pli b/Task/Comments/PL-I/comments-1.pli similarity index 100% rename from Task/Comments/PL-I/comments.pli rename to Task/Comments/PL-I/comments-1.pli diff --git a/Task/Comments/PL-I/comments-2.pli b/Task/Comments/PL-I/comments-2.pli new file mode 100644 index 0000000000..b6b13b979c --- /dev/null +++ b/Task/Comments/PL-I/comments-2.pli @@ -0,0 +1,3 @@ +/* +This is a multiline comment. +*/ diff --git a/Task/Comments/SQL/comments-1.sql b/Task/Comments/SQL/comments-1.sql new file mode 100644 index 0000000000..fe31b01c8a --- /dev/null +++ b/Task/Comments/SQL/comments-1.sql @@ -0,0 +1 @@ +SELECT * FROM mytable -- Selects all columns and rows diff --git a/Task/Comments/SQL/comments-2.sql b/Task/Comments/SQL/comments-2.sql new file mode 100644 index 0000000000..65e1c56867 --- /dev/null +++ b/Task/Comments/SQL/comments-2.sql @@ -0,0 +1,2 @@ +-- Selects all columns and rows +SELECT * FROM mytable diff --git a/Task/Comments/SQL/comments-3.sql b/Task/Comments/SQL/comments-3.sql new file mode 100644 index 0000000000..028aa80173 --- /dev/null +++ b/Task/Comments/SQL/comments-3.sql @@ -0,0 +1,2 @@ +SELECT * FROM mytable +-- Selects all columns and rows diff --git a/Task/Comments/Scilab/comments.scilab b/Task/Comments/Scilab/comments.scilab new file mode 100644 index 0000000000..e799136c07 --- /dev/null +++ b/Task/Comments/Scilab/comments.scilab @@ -0,0 +1,2 @@ +// this is a comment +i=i+1 // this is a comment diff --git a/Task/Comments/Simula/comments.simula b/Task/Comments/Simula/comments.simula new file mode 100644 index 0000000000..895e669841 --- /dev/null +++ b/Task/Comments/Simula/comments.simula @@ -0,0 +1 @@ +COMMENT This is a comment for Simula 67; diff --git a/Task/Comments/TorqueScript/comments.torque b/Task/Comments/TorqueScript/comments.torque new file mode 100644 index 0000000000..ab26873461 --- /dev/null +++ b/Task/Comments/TorqueScript/comments.torque @@ -0,0 +1 @@ +//This is a one line comment. There are no other commenting options in TorqueScript. diff --git a/Task/Comments/VBA/comments.vba b/Task/Comments/VBA/comments.vba new file mode 100644 index 0000000000..7d8fb39e54 --- /dev/null +++ b/Task/Comments/VBA/comments.vba @@ -0,0 +1 @@ +' This is a VBA comment diff --git a/Task/Comments/VBScript/comments.vb b/Task/Comments/VBScript/comments.vb new file mode 100644 index 0000000000..9ac187e3ec --- /dev/null +++ b/Task/Comments/VBScript/comments.vb @@ -0,0 +1 @@ +' This is a VBScript comment diff --git a/Task/Comments/Vim-Script/comments.vim b/Task/Comments/Vim-Script/comments.vim new file mode 100644 index 0000000000..a3d761313a --- /dev/null +++ b/Task/Comments/Vim-Script/comments.vim @@ -0,0 +1,2 @@ +let a = 4 " A valid comment +echo "foo" " Not a comment but an argument that misses the closing quote diff --git a/Task/Compile-time-calculation/D/compile-time-calculation-1.d b/Task/Compile-time-calculation/D/compile-time-calculation-1.d index 3dfc2e4640..4668d16ea6 100644 --- a/Task/Compile-time-calculation/D/compile-time-calculation-1.d +++ b/Task/Compile-time-calculation/D/compile-time-calculation-1.d @@ -1,8 +1,6 @@ -import core.stdc.stdio; - -long fact(long x) { +long fact(in long x) pure nothrow @nogc { long result = 1; - foreach (i; 2 .. x + 1) + foreach (immutable i; 2 .. x + 1) result *= i; return result; } @@ -11,5 +9,7 @@ void main() { // enum means "compile-time constant", it forces CTFE. enum fact10 = fact(10); + import core.stdc.stdio; + printf("%ld\n", fact10); } diff --git a/Task/Compile-time-calculation/Oberon-2/compile-time-calculation.oberon-2 b/Task/Compile-time-calculation/Oberon-2/compile-time-calculation.oberon-2 new file mode 100644 index 0000000000..d69a67a104 --- /dev/null +++ b/Task/Compile-time-calculation/Oberon-2/compile-time-calculation.oberon-2 @@ -0,0 +1,8 @@ +MODULE CompileTime; +IMPORT + Out; +CONST + tenfac = 10*9*8*7*6*5*4*3*2; +BEGIN + Out.String("10! =");Out.LongInt(tenfac,0);Out.Ln +END CompileTime. diff --git a/Task/Compound-data-type/00DESCRIPTION b/Task/Compound-data-type/00DESCRIPTION index 741bcb4eb0..f8a1b48e0a 100644 --- a/Task/Compound-data-type/00DESCRIPTION +++ b/Task/Compound-data-type/00DESCRIPTION @@ -1,6 +1,7 @@ {{Data structure}} Create a compound data type Point(x,y). -A compound data type is one that holds multiple independent values. See also [[Enumeration]]. +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/AWK/compound-data-type.awk b/Task/Compound-data-type/AWK/compound-data-type.awk index eb884beef8..62fb86ac54 100644 --- a/Task/Compound-data-type/AWK/compound-data-type.awk +++ b/Task/Compound-data-type/AWK/compound-data-type.awk @@ -1,2 +1,11 @@ -p["x"]=10 -p["y"]=42 +BEGIN { + p["x"]=10 + p["y"]=42 + + z = "ZZ" + p[ z ]=999 + + p[ 4 ]=5 + + for (i in p) print( i, ":", p[i] ) +} diff --git a/Task/Compound-data-type/Euphoria/compound-data-type.euphoria b/Task/Compound-data-type/Euphoria/compound-data-type.euphoria new file mode 100644 index 0000000000..6fa7f10f12 --- /dev/null +++ b/Task/Compound-data-type/Euphoria/compound-data-type.euphoria @@ -0,0 +1,11 @@ +enum x, y + +sequence point = {0,0} + +printf(1,"x = %d, y = %3.3f\n",point) + +point[x] = 'A' +point[y] = 53.42 + +printf(1,"x = %d, y = %3.3f\n",point) +printf(1,"x = %s, y = %3.3f\n",point) diff --git a/Task/Compound-data-type/UNIX-Shell/compound-data-type-1.sh b/Task/Compound-data-type/UNIX-Shell/compound-data-type-1.sh new file mode 100644 index 0000000000..3b11cd26d1 --- /dev/null +++ b/Task/Compound-data-type/UNIX-Shell/compound-data-type-1.sh @@ -0,0 +1,11 @@ +typeset -T Point=( + typeset x + typeset y +) +Point p +p.x=1 +p.y=2 +echo $p +echo ${p.x} ${p.y} +Point q=(x=3 y=4) +echo ${q.x} ${q.y} diff --git a/Task/Compound-data-type/UNIX-Shell/compound-data-type-2.sh b/Task/Compound-data-type/UNIX-Shell/compound-data-type-2.sh new file mode 100644 index 0000000000..61291fc42c --- /dev/null +++ b/Task/Compound-data-type/UNIX-Shell/compound-data-type-2.sh @@ -0,0 +1,5 @@ +point=() +point.x=5 +point.y=6 +echo $point +echo ${point.x} ${point.y} diff --git a/Task/Compound-data-type/Vim-Script/compound-data-type.vim b/Task/Compound-data-type/Vim-Script/compound-data-type.vim new file mode 100644 index 0000000000..f5b509fb6e --- /dev/null +++ b/Task/Compound-data-type/Vim-Script/compound-data-type.vim @@ -0,0 +1,9 @@ +function MakePoint(x, y) " 'Constructor' + return {"x": a:x, "y": a:y} +endfunction + +let p1 = MakePoint(3, 2) +let p2 = MakePoint(-1, -4) + +echon "Point 1: x = " p1.x ", y = " p1.y "\n" +echon "Point 2: x = " p2.x ", y = " p2.y "\n" diff --git a/Task/Concurrent-computing/PowerShell/concurrent-computing-1.psh b/Task/Concurrent-computing/PowerShell/concurrent-computing-1.psh new file mode 100644 index 0000000000..e6673ae63d --- /dev/null +++ b/Task/Concurrent-computing/PowerShell/concurrent-computing-1.psh @@ -0,0 +1,10 @@ +$Strings = "Enjoy","Rosetta","Code" + +$SB = {param($String)Write-Output $String} + +foreach($String in $Strings) { + Start-Job -ScriptBlock $SB -ArgumentList $String | Out-Null + } + +Get-Job | Wait-Job | Receive-Job +Get-Job | Remove-Job diff --git a/Task/Concurrent-computing/PowerShell/concurrent-computing-2.psh b/Task/Concurrent-computing/PowerShell/concurrent-computing-2.psh new file mode 100644 index 0000000000..b408fe5dd7 --- /dev/null +++ b/Task/Concurrent-computing/PowerShell/concurrent-computing-2.psh @@ -0,0 +1,16 @@ +$Strings = "Enjoy","Rosetta","Code" + +$SB = {param($String)Write-Output $String} + +$Pool = [RunspaceFactory]::CreateRunspacePool(1, 3) +$Pool.ApartmentState = "STA" +$Pool.Open() +foreach ($String in $Strings) { + $Pipeline = [System.Management.Automation.PowerShell]::create() + $Pipeline.RunspacePool = $Pool + [void]$Pipeline.AddScript($SB).AddArgument($String) + $AsyncHandle = $Pipeline.BeginInvoke() + $Pipeline.EndInvoke($AsyncHandle) + $Pipeline.Dispose() + } +$Pool.Close() diff --git a/Task/Concurrent-computing/Prolog/concurrent-computing.pro b/Task/Concurrent-computing/Prolog/concurrent-computing.pro new file mode 100644 index 0000000000..3e66bf1c26 --- /dev/null +++ b/Task/Concurrent-computing/Prolog/concurrent-computing.pro @@ -0,0 +1,12 @@ +main :- + thread_create(say("Enjoy"),A,[]), + thread_create(say("Rosetta"),B,[]), + thread_create(say("Code"),C,[]), + thread_join(A,_), + thread_join(B,_), + thread_join(C,_). + +say(Message) :- + Delay is random_float, + sleep(Delay), + writeln(Message). diff --git a/Task/Concurrent-computing/Rust/concurrent-computing.rust b/Task/Concurrent-computing/Rust/concurrent-computing.rust index 2b357f2a7f..26e4980e70 100644 --- a/Task/Concurrent-computing/Rust/concurrent-computing.rust +++ b/Task/Concurrent-computing/Rust/concurrent-computing.rust @@ -1,11 +1,11 @@ use std::io::timer::sleep; -use std::rand::{rng, Rng}; +use std::rand::{task_rng, Rng}; fn main() { - let mut random = rng(); + let mut rng = task_rng(); for word in "Enjoy Rosetta Code".words() { - let local_word = word.to_owned(); - let snooze_time = random.gen_range::(0, 1000); + let local_word = word.to_string(); + let snooze_time = rng.gen_range::(0, 1000); spawn(proc() { sleep(snooze_time); diff --git a/Task/Conditional-structures/00DESCRIPTION b/Task/Conditional-structures/00DESCRIPTION index c8481e1e63..a24865feb3 100644 --- a/Task/Conditional-structures/00DESCRIPTION +++ b/Task/Conditional-structures/00DESCRIPTION @@ -1 +1,3 @@ -{{Control Structures}}This page lists the conditional structures offered by different programming languages. Common conditional structures are '''if-then-else''' and '''switch'''. +{{Control Structures}} [[Category:Simple]] +This page lists the conditional structures offered by different programming languages. +Common conditional structures are '''if-then-else''' and '''switch'''. diff --git a/Task/Conditional-structures/360-Assembly/conditional-structures.360 b/Task/Conditional-structures/360-Assembly/conditional-structures.360 new file mode 100644 index 0000000000..5e2d51d428 --- /dev/null +++ b/Task/Conditional-structures/360-Assembly/conditional-structures.360 @@ -0,0 +1,48 @@ +* Unconditional Branch or No Branch: + B label Unconditional + BR Rx " + NOP label No Operation + NOPR Rx " +* After Compare Instructions + BH label Branch on High + BHR Rx " + BL label Branch on Low + BLR Rx " + BE label Branch on Equal + BER Rx " + BNH label Branch on Not High + BNHR Rx " + BNL label Branch on Not Low + BNLR Rx " + BNE label Branch on Not Equal + BNER Rx " +* After Arithmetic Instructions: + BP label Branch on Plus + BPR Rx " + BM label Branch on Minus + BMR Rx " + BZ label Branch on Zero + BZR Rx " + BO label Branch on Overflow + BOR Rx " + BNP label Branch on Not Plus + BNPR Rx " + BNM label Branch on Not Minus + BNMR Rx " + BNZ label Branch on Not Zero + BNZR Rx " + BNO label Branch on No Overflow + BNOR Rx " +* After Test Under Mask Instructions: + BO label Branch if Ones + BOR Rx " + BM label Branch if Mixed + BMR Rx " + BZ label Branch if Zero + BZR Rx " + BNO label Branch if Not Ones + BNOR Rx " + BNM label Branch if Not Mixed + BNMR Rx " + BNZ label Branch if Not Zero + BNZR Rx " diff --git a/Task/Conditional-structures/AWK/conditional-structures-2.awk b/Task/Conditional-structures/AWK/conditional-structures-2.awk index c2a697b232..1a2198b415 100644 --- a/Task/Conditional-structures/AWK/conditional-structures-2.awk +++ b/Task/Conditional-structures/AWK/conditional-structures-2.awk @@ -1 +1,5 @@ -i=(i<0? 0: 42) +if(i<0) { + i=0; j=1 + } else { + i=42; j=2 + } diff --git a/Task/Conditional-structures/AWK/conditional-structures-3.awk b/Task/Conditional-structures/AWK/conditional-structures-3.awk new file mode 100644 index 0000000000..c2a697b232 --- /dev/null +++ b/Task/Conditional-structures/AWK/conditional-structures-3.awk @@ -0,0 +1 @@ +i=(i<0? 0: 42) diff --git a/Task/Conditional-structures/Babel/conditional-structures-1.pb b/Task/Conditional-structures/Babel/conditional-structures-1.pb new file mode 100644 index 0000000000..cd9388f052 --- /dev/null +++ b/Task/Conditional-structures/Babel/conditional-structures-1.pb @@ -0,0 +1 @@ +"foo" "bar" 3 4 > sel << diff --git a/Task/Conditional-structures/Babel/conditional-structures-2.pb b/Task/Conditional-structures/Babel/conditional-structures-2.pb new file mode 100644 index 0000000000..759d2a859c --- /dev/null +++ b/Task/Conditional-structures/Babel/conditional-structures-2.pb @@ -0,0 +1,5 @@ + {3 4 >} + {"foo"} + {"bar"} + ifte + << diff --git a/Task/Conditional-structures/Babel/conditional-structures-3.pb b/Task/Conditional-structures/Babel/conditional-structures-3.pb new file mode 100644 index 0000000000..6b91e0f8df --- /dev/null +++ b/Task/Conditional-structures/Babel/conditional-structures-3.pb @@ -0,0 +1,6 @@ + ({3 4 >} {"Three is greater than four" } + {3 3 >} {"Three is greater than three"} + {3 2 >} {"Three is greater than two" } + {3 1 >} {"Three is greater than one" }) + cond + << diff --git a/Task/Conditional-structures/Batch-File/conditional-structures-1.bat b/Task/Conditional-structures/Batch-File/conditional-structures-1.bat new file mode 100644 index 0000000000..3969f943b4 --- /dev/null +++ b/Task/Conditional-structures/Batch-File/conditional-structures-1.bat @@ -0,0 +1,14 @@ +IF [NOT] ERRORLEVEL number command +IF [NOT] string1==string2 command +IF [NOT] EXIST filename command +IF CMDEXTVERSION number command +IF DEFINED variable command +IF [/I] string1 compare-op string2 command + where compare-op is: + EQU - equal + NEQ - not equal + LSS - less than + LEQ - less than or equal + GTR - greater than + GEQ - greater than or equal + /I case insensitive string compares diff --git a/Task/Conditional-structures/Batch-File/conditional-structures-2.bat b/Task/Conditional-structures/Batch-File/conditional-structures-2.bat new file mode 100644 index 0000000000..cce8ea48cd --- /dev/null +++ b/Task/Conditional-structures/Batch-File/conditional-structures-2.bat @@ -0,0 +1,5 @@ +IF EXIST %filename% ( + del %filename% +) ELSE ( + echo %filename% not found +) diff --git a/Task/Conditional-structures/Dao/conditional-structures-1.dao b/Task/Conditional-structures/Dao/conditional-structures-1.dao index 949f73cc61..eb8cb96a59 100644 --- a/Task/Conditional-structures/Dao/conditional-structures-1.dao +++ b/Task/Conditional-structures/Dao/conditional-structures-1.dao @@ -1,7 +1,7 @@ a = 3 if( a == 1 ){ io.writeln( 'a == 1' ) -}elif( a== 3 ){ +}else if( a== 3 ){ io.writeln( 'a == 3' ) }else{ io.writeln( 'a is neither 1 nor 3' ) diff --git a/Task/Conditional-structures/Dao/conditional-structures-2.dao b/Task/Conditional-structures/Dao/conditional-structures-2.dao index 1874434903..73d282642e 100644 --- a/Task/Conditional-structures/Dao/conditional-structures-2.dao +++ b/Task/Conditional-structures/Dao/conditional-structures-2.dao @@ -2,6 +2,6 @@ a = 3 switch( a ){ case 0: io.writeln( 'case 0' ) case 1, 2: io.writeln( 'case 1,2' ) -case 3 ... 5: io.writeln( 'case 3...5' ) +case 3, 4, 5: io.writeln( 'case 3,4,5' ) default: io.writeln( 'default' ) } diff --git a/Task/Conditional-structures/PL-I/conditional-structures-1.pli b/Task/Conditional-structures/PL-I/conditional-structures-1.pli index baa8844565..a5c71a8de6 100644 --- a/Task/Conditional-structures/PL-I/conditional-structures-1.pli +++ b/Task/Conditional-structures/PL-I/conditional-structures-1.pli @@ -1,14 +1,14 @@ -if condition then - statement; -else - statement; +if condition_exp then unique_statement; else unique_statement; -if condition then - do; - statement-1; - . - . - statement-n; - end; +if condition_exp then + unique_statement; else - statement; + unique_statement; + +if condition_exp +then do; + list_of_statements; +end; +else do; + list_of_statements; +end; diff --git a/Task/Conditional-structures/PL-I/conditional-structures-2.pli b/Task/Conditional-structures/PL-I/conditional-structures-2.pli index af670d4a9e..1931e49b67 100644 --- a/Task/Conditional-structures/PL-I/conditional-structures-2.pli +++ b/Task/Conditional-structures/PL-I/conditional-structures-2.pli @@ -1,16 +1,21 @@ -select (i); /* select on value of variable */ - when (1,4,9) - do; - statement(s) - end; +if condition_exp1 then + statement_1; +else if condition_exp2 then + statement_2; +else if condition_expN then + statement_N; +else + statement_E; - when (11, 42) - do; - statement(s) - end; - - other /* everything else */ - do; - statement(s) - end; +if condition_exp1 then do; + list_of_statements; +end; +else if condition_exp2 then do; + list_of_statements; +end; +else if condition_expN then do; + list_of_statements; +end; +else do; + list_of_statements; end; diff --git a/Task/Conditional-structures/PL-I/conditional-structures-3.pli b/Task/Conditional-structures/PL-I/conditional-structures-3.pli index a5a9418e2a..8b61d1ed00 100644 --- a/Task/Conditional-structures/PL-I/conditional-structures-3.pli +++ b/Task/Conditional-structures/PL-I/conditional-structures-3.pli @@ -1,21 +1,16 @@ -select; /* select first matching condition */ - when (i = 4); +select (i); /* select on value of variable */ + when (1,4,9) do; - statement(s) + statement_s; end; - when (this = that) + when (11, 42) do; - statement(s) + statement_s; end; - when (string = 'ABCDE') + other /* everything else */ do; - statement(s) - end; - - other - do; - statement(s) + statement_s; end; end; diff --git a/Task/Conditional-structures/PL-I/conditional-structures-4.pli b/Task/Conditional-structures/PL-I/conditional-structures-4.pli new file mode 100644 index 0000000000..95f424c624 --- /dev/null +++ b/Task/Conditional-structures/PL-I/conditional-structures-4.pli @@ -0,0 +1,21 @@ +select; /* select first matching condition */ + when (i = 4) + do; + statement_s; + end; + + when (this = that) + do; + statement_s; + end; + + when (mystring = 'ABCDE') + do; + statement_s; + end; + + other + do; + statement_s; + end; +end; diff --git a/Task/Conditional-structures/Pascal/conditional-structures-1.pascal b/Task/Conditional-structures/Pascal/conditional-structures-1.pascal index 64d9a3dc91..01a5dc87b0 100644 --- a/Task/Conditional-structures/Pascal/conditional-structures-1.pascal +++ b/Task/Conditional-structures/Pascal/conditional-structures-1.pascal @@ -6,18 +6,18 @@ ELSE IF condition1 THEN BEGIN procedure1; - procedure2; + procedure2 END ELSE procedure3; -IF condition 1 THEN +IF condition1 THEN BEGIN procedure1; - procedure2; + procedure2 END ELSE BEGIN procedure3; - procedure4; + procedure4 END; diff --git a/Task/Conditional-structures/REXX/conditional-structures-1.rexx b/Task/Conditional-structures/REXX/conditional-structures-1.rexx index 5a1d105c5c..b7356e0f3f 100644 --- a/Task/Conditional-structures/REXX/conditional-structures-1.rexx +++ b/Task/Conditional-structures/REXX/conditional-structures-1.rexx @@ -1,22 +1,18 @@ -if y then x=6 /* Y must be either 0 or 1 */ +if y then @=6 /* Y must be either 0 or 1 */ +if t**2>u then x=y /*simple IF with THEN & ELSE. */ + else x=-y -if t**2>u then x= y - else x=-y +if t**2>u then do j=1 for 10; say prime(j); end /*THEN DO loop.*/ + else x=-y /*simple ELSE. */ +if z>w+4 then do /*THEN DO group.*/ + z=abs(z) + say 'z='z + end + else do; z=0; say 'failed.'; end /*ELSE DO group.*/ -if t**2>u then do j=1 to 10; say prime(j); end - else x=-y - - -if z>w+4 then do - z=abs(z) - say 'z='z - end - else do; z=0; say 'failed.'; end - - -if x>y & c*dy & c*d0 then do + /*the WHEN conditional operators are the same as*/ + /*the IF conditional operators. */ + select + when t<0 then z=abs(u) + when t=0 & y=0 then z=0 + when t>0 then do y=sqrt(z) z=u**2 end - /*if control reaches this point and none of the WHENs */ - /*were satisfied, a SYNTAX condition is raised (error).*/ - end /*select*/ + /*if control reaches here & none of the WHENs were*/ + /*satisfiied, a SYNTAX (error) condition is raised*/ + end /*1st select*/ + + select + when a=='angel' then many='host' + when a=='ass' | a=='donkey' then many='pace' + when a=='crocodile' then many='bask' + when a=='crow' then many='murder' + when a=='lark' then many='ascension' + when a=='quail' then many='bevy' + when a=='wolf' then many='pack' + otherwise many='?' + end /*2nd select*/ /* [↑] uses OTHERWISE as a catch-all.*/ diff --git a/Task/Conditional-structures/REXX/conditional-structures-3.rexx b/Task/Conditional-structures/REXX/conditional-structures-3.rexx index 94df904106..5e1f60c999 100644 --- a/Task/Conditional-structures/REXX/conditional-structures-3.rexx +++ b/Task/Conditional-structures/REXX/conditional-structures-3.rexx @@ -8,7 +8,7 @@ when g=='wolf' then many='pack' otherwise say say '*** error! ***' - say g "isn't one of the known thingys." + say g "isn't one of the known thingys." say exit 13 end /*select*/ diff --git a/Task/Conditional-structures/Scala/conditional-structures.scala b/Task/Conditional-structures/Scala/conditional-structures.scala new file mode 100644 index 0000000000..f4ad0af20a --- /dev/null +++ b/Task/Conditional-structures/Scala/conditional-structures.scala @@ -0,0 +1,11 @@ + if (n == 12) "twelve" else "not twelve" + + today match { + case Monday => + Compute_Starting_Balance; + case Friday => + Compute_Ending_Balance; + case Tuesday => + Accumulate_Sales + case _ => {} + } diff --git a/Task/Conditional-structures/Scheme/conditional-structures-4.ss b/Task/Conditional-structures/Scheme/conditional-structures-4.ss index 586ef2350a..fe5913139b 100644 --- a/Task/Conditional-structures/Scheme/conditional-structures-4.ss +++ b/Task/Conditional-structures/Scheme/conditional-structures-4.ss @@ -1,2 +1 @@ -no -# +(cond ...) diff --git a/Task/Conditional-structures/Scheme/conditional-structures-5.ss b/Task/Conditional-structures/Scheme/conditional-structures-5.ss index fe5913139b..dcc72e04dd 100644 --- a/Task/Conditional-structures/Scheme/conditional-structures-5.ss +++ b/Task/Conditional-structures/Scheme/conditional-structures-5.ss @@ -1 +1,9 @@ -(cond ...) +(display + (cond ((> 1 2) "greater") + ((< 1 2) "less"))) +(newline) +(display + (cond ((> 1 1) "greater") + ((< 1 1) "less") + (else "equal"))) +(newline) diff --git a/Task/Conditional-structures/Scheme/conditional-structures-6.ss b/Task/Conditional-structures/Scheme/conditional-structures-6.ss index dcc72e04dd..ae39fe7209 100644 --- a/Task/Conditional-structures/Scheme/conditional-structures-6.ss +++ b/Task/Conditional-structures/Scheme/conditional-structures-6.ss @@ -1,9 +1 @@ -(display - (cond ((> 1 2) "greater") - ((< 1 2) "less"))) -(newline) -(display - (cond ((> 1 1) "greater") - ((< 1 1) "less") - (else "equal"))) -(newline) +(case ...) diff --git a/Task/Conditional-structures/Scheme/conditional-structures-7.ss b/Task/Conditional-structures/Scheme/conditional-structures-7.ss index a5b3cc688c..affbd16181 100644 --- a/Task/Conditional-structures/Scheme/conditional-structures-7.ss +++ b/Task/Conditional-structures/Scheme/conditional-structures-7.ss @@ -1,2 +1,11 @@ -less -equal +(display + (case (* 2 3) + ((2 3 5 7) "prime") + ((1 4 6 8 9) "composite"))) +(newline) +(display + (case (car (list c d)) + ((a e i o u) "vowel") + ((w y) "semivowel") + (else "consonant"))) +(newline) diff --git a/Task/Conditional-structures/TI-83-BASIC/conditional-structures-1.ti-83 b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-1.ti-83 new file mode 100644 index 0000000000..5192bda849 --- /dev/null +++ b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-1.ti-83 @@ -0,0 +1,2 @@ +If condition +statement diff --git a/Task/Conditional-structures/TI-83-BASIC/conditional-structures-2.ti-83 b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-2.ti-83 new file mode 100644 index 0000000000..595ca4c5bf --- /dev/null +++ b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-2.ti-83 @@ -0,0 +1 @@ +If condition : statement diff --git a/Task/Conditional-structures/TI-83-BASIC/conditional-structures-3.ti-83 b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-3.ti-83 new file mode 100644 index 0000000000..cbbe1fd576 --- /dev/null +++ b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-3.ti-83 @@ -0,0 +1,4 @@ +If condition +Then +statements +End diff --git a/Task/Conditional-structures/TI-83-BASIC/conditional-structures-4.ti-83 b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-4.ti-83 new file mode 100644 index 0000000000..fd9e8ec4c5 --- /dev/null +++ b/Task/Conditional-structures/TI-83-BASIC/conditional-structures-4.ti-83 @@ -0,0 +1,6 @@ +If condition +Then +statements +Else +statements +End diff --git a/Task/Conditional-structures/VBScript/conditional-structures-1.vb b/Task/Conditional-structures/VBScript/conditional-structures-1.vb new file mode 100644 index 0000000000..913ac77f84 --- /dev/null +++ b/Task/Conditional-structures/VBScript/conditional-structures-1.vb @@ -0,0 +1,14 @@ +If condition1 Then + statement +End If + +If condition1 Then + statement +ElseIf condition2 Then + statement +... +ElseIf conditionN Then + statement +Else + statement +End If diff --git a/Task/Conditional-structures/VBScript/conditional-structures-2.vb b/Task/Conditional-structures/VBScript/conditional-structures-2.vb new file mode 100644 index 0000000000..c7bec70a71 --- /dev/null +++ b/Task/Conditional-structures/VBScript/conditional-structures-2.vb @@ -0,0 +1,3 @@ +If condition Then statement + +If condition Then statement Else statement diff --git a/Task/Conditional-structures/VBScript/conditional-structures-3.vb b/Task/Conditional-structures/VBScript/conditional-structures-3.vb new file mode 100644 index 0000000000..2460e4f1a5 --- /dev/null +++ b/Task/Conditional-structures/VBScript/conditional-structures-3.vb @@ -0,0 +1,19 @@ +Select Case Expression + Case Value1: statement + Case Value2: statement + ... + Case ValueN: statement + Case Else: statement +End Select + +Select Case Expression + Case Value1 + statements + Case Value2 + statements + ... + Case ValueN + statements + Case Else + statements +End Select diff --git a/Task/Conditional-structures/VBScript/conditional-structures.vb b/Task/Conditional-structures/VBScript/conditional-structures.vb deleted file mode 100644 index d0dce66648..0000000000 --- a/Task/Conditional-structures/VBScript/conditional-structures.vb +++ /dev/null @@ -1,5 +0,0 @@ -if (condition) then - result = "met" -else - Result = "not met" -end if diff --git a/Task/Constrained-genericity/00DESCRIPTION b/Task/Constrained-genericity/00DESCRIPTION index 95d1118000..c9c5810506 100644 --- a/Task/Constrained-genericity/00DESCRIPTION +++ b/Task/Constrained-genericity/00DESCRIPTION @@ -1,4 +1,14 @@ -{{omit from|BBC BASIC}} -'''Constrained genericity''' or '''bounded quantification''' means that a parametrized type or function (see [[parametric polymorphism]]) can only be instantiated on types fulfilling some conditions, even if those conditions are not used in that function. +'''Constrained genericity''' or '''bounded quantification''' means +that a parametrized type or function (see [[parametric polymorphism]]) +can only be instantiated on types fulfilling some conditions, +even if those conditions are not used in that function. -Say a type is called "eatable" if you can call the function eat on it. Write a generic type FoodBox which contains a collection of objects of a type given as parameter, but can only be instantiated on eatable types. The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). The specification of a type being eatable should be as generic as possible in your language (i.e. the restrictions on the implementation of eatable types should be as minimal as possible). Also explain the restrictions, if any, on the implementation of eatable types, and show at least one example of an eatable type. +Say a type is called "eatable" if you can call the function eat on it. +Write a generic type FoodBox which contains a collection of objects of +a type given as parameter, but can only be instantiated on eatable types. +The FoodBox shall not use the function eat in any way (i.e. without the explicit restriction, it could be instantiated on any type). +The specification of a type being eatable should be as generic as possible +in your language (i.e. the restrictions on the implementation of eatable types +should be as minimal as possible). +Also explain the restrictions, if any, on the implementation of eatable types, +and show at least one example of an eatable type. diff --git a/Task/Constrained-genericity/Racket/constrained-genericity.rkt b/Task/Constrained-genericity/Racket/constrained-genericity.rkt new file mode 100644 index 0000000000..6826fef3b3 --- /dev/null +++ b/Task/Constrained-genericity/Racket/constrained-genericity.rkt @@ -0,0 +1,86 @@ +#lang racket +(module+ test (require tests/eli-tester)) + +;; This is all that an object should need to properly implement. +(define edible<%> + (interface () [eat (->m void?)])) + +(define (generic-container<%> containee/c) + (interface () + [contents (->m (listof containee/c))] + [insert (->m containee/c void?)] + [remove-at (->m exact-nonnegative-integer? containee/c)] + [count (->m exact-nonnegative-integer?)])) + +(define ((generic-box-mixin containee/c) %) + (->i ([containee/c contract?]) + (rv (containee/c) (implementation?/c (generic-container<%> containee/c)))) + (class* % ((generic-container<%> containee/c)) + (super-new) + (define l empty) + (define/public (contents) l) + (define/public (insert o) (set! l (cons o l))) + (define/public (remove-at i) + (begin0 (list-ref l i) + (append (take l i) (drop l (add1 i))))) + (define/public (count) (length l)))) + +;; As I understand it, a "Food Box" from the task is still a generic... i.e. +;; you will specify it down ;; to an "apple-box%" so: food-box%-generic is still +;; generic. food-box% will take any kind of food. +(define/contract (food-box-mixin T%) + (-> (or/c (λ (i) (eq? edible<%> i)) (implementation?/c edible<%>)) + (make-mixin-contract)) + (generic-box-mixin (and/c (is-a?/c edible<%>) (is-a?/c T%)))) + +(module+ test + + (define integer-box% ((generic-box-mixin integer?) object%)) + (define integer-box (new integer-box%)) + + (define apple% + (class* object% (edible<%>) + (super-new) + (define/public (eat) + (displayln "nom!")))) + + (define banana% + (class* object% (edible<%>) + (super-new) + (define/public (eat) + (displayln "peel.. peel... nom... nom!")))) + + (define semolina% + (class* object% () ; <-- empty interfaces clause + (super-new) + ;; you can call eat on it... but it's not explicitly (or even vaguely) + ;; edible<%> + (define/public (eat) (displayln "blech!")))) + + ;; this will take any object that is edible<%> and edible<%> (therefore all + ;; edible<%> objects) + (define any-food-box (new ((food-box-mixin edible<%>) object%))) + + ;; this will take any object that is edible and an apple<%> + ;; (therefore only apple<%>s) + (define apple-food-box (new ((food-box-mixin apple%) object%))) + + (test + ;; Test generic boxes + (send integer-box insert 22) + (send integer-box insert "a string") =error> exn:fail:contract? + + ;; Test the food box that takes any edible<%> + (send any-food-box insert (new apple%)) + (send any-food-box insert (new banana%)) + (send any-food-box insert (new semolina%)) =error> exn:fail:contract? + + ;; Test the food box that takes any apple% + (send apple-food-box insert (new apple%)) + (send apple-food-box insert (new banana%)) =error> exn:fail:contract? + (send apple-food-box insert (new semolina%)) =error> exn:fail:contract? + (send apple-food-box count) => 1 + + ;; Show that you cannot make a food-box from the non-edible<%> semolina cannot + (implementation? semolina% edible<%>) => #f + (new ((food-box-mixin semolina%) object%)) =error> exn:fail:contract?)) diff --git a/Task/Constrained-random-points-on-a-circle/Clojure/constrained-random-points-on-a-circle.clj b/Task/Constrained-random-points-on-a-circle/Clojure/constrained-random-points-on-a-circle.clj index 8145624ccf..0f711620da 100644 --- a/Task/Constrained-random-points-on-a-circle/Clojure/constrained-random-points-on-a-circle.clj +++ b/Task/Constrained-random-points-on-a-circle/Clojure/constrained-random-points-on-a-circle.clj @@ -1,17 +1,17 @@ -(import '[java.awt Color Graphics Dimension] - '[javax.swing JFrame JPanel]) +(ns rosettacode.circle-random-points + (:import [java.awt Color Graphics Dimension] + [javax.swing JFrame JPanel])) -(let [points (->> (for [x (range -15 16) - y (range -15 16) - :when (<= 10 (Math/sqrt (+ (* x x) (* y y))) 15)] +(let [points (->> (for [x (range -15 16), y (range -15 16) + :when (<= 10 (Math/hypot x y) 15)] [(+ x 15) (+ y 15)]) shuffle - (take 100 ,))] + (take 100))] (doto (JFrame.) (.add (doto (proxy [JPanel] [] (paint [^Graphics g] - (doseq [[x y] points] - (.fillRect g (* 10 x) (* 10 y) 10 10)))) + (doseq [[x y] points] + (.fillRect g (* 10 x) (* 10 y) 10 10)))) (.setPreferredSize (Dimension. 310 310)))) (.setResizable false) (.setDefaultCloseOperation JFrame/DISPOSE_ON_CLOSE) diff --git a/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir new file mode 100644 index 0000000000..b484c918c5 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Elixir/constrained-random-points-on-a-circle.elixir @@ -0,0 +1,30 @@ +defmodule Random do + def init() do + :random.seed(:erlang.now()) + end + def generate_point() do + x = :random.uniform(31) - 16 + y = :random.uniform(31) - 16 + if 10*10 <= x*x + y*y and x*x + y*y <= 15*15 do + {x, y} + else + generate_point() + end + end + def circle() do + points = for _ <- 1..100, do: generate_point() + for x <- -15..15 do + for y <- -15..15 do + if Enum.member?(points, {x, y}) do + IO.write "x" + else + IO.write " " + end + end + IO.puts "" + end + end +end + +Random.init() +Random.circle() diff --git a/Task/Constrained-random-points-on-a-circle/Falcon/constrained-random-points-on-a-circle.falcon b/Task/Constrained-random-points-on-a-circle/Falcon/constrained-random-points-on-a-circle.falcon new file mode 100644 index 0000000000..aead6b5b3c --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Falcon/constrained-random-points-on-a-circle.falcon @@ -0,0 +1,17 @@ +// Generate points in [min,max]^2 with constraint +function random_point (min, max, constraint) + [x, y] = [random(min, max), random(min, max)] + return constraint(x, y) ? [x, y] : random_point(min, max, constraint) +end + +// Generate point list +in_circle = { x, y => 10**2 <= x**2 + y**2 and x**2 + y**2 <= 15**2 } +points = [].comp([0:100], {__ => random_point(-15, 15, in_circle)}) + +// Show points +for i in [-15:16] + for j in [-15:16] + >> [i, j] in points ? "x" : " " + end + > +end diff --git a/Task/Constrained-random-points-on-a-circle/Maple/constrained-random-points-on-a-circle.maple b/Task/Constrained-random-points-on-a-circle/Maple/constrained-random-points-on-a-circle.maple new file mode 100644 index 0000000000..abb321854b --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Maple/constrained-random-points-on-a-circle.maple @@ -0,0 +1,12 @@ + a := table(): + i := 1: + while i < 100 do + ba := (rand(-15 .. 15))(): + bb := (rand(-15 .. 15))(): + b := evalf(sqrt(ba^2+bb^2)): + if b <= 15 and b >= 10 + then a[i] := [ba, bb]: + i := i+1: + end if: + end do: + plots:-pointplot(convert(a,list)); diff --git a/Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle.pli b/Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-1.pli similarity index 100% rename from Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle.pli rename to Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-1.pli diff --git a/Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-2.pli b/Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-2.pli new file mode 100644 index 0000000000..ac45c7e668 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/PL-I/constrained-random-points-on-a-circle-2.pli @@ -0,0 +1,43 @@ +*process source attributed xref or(!); + annulus: procedure options (main); + /* version 1 does not handle (0/15) etc. this does. */ + /* we show 1000 points here */ + declare 1 point(10000), + 2 x fixed binary, + 2 y fixed binary; + declare (i, j, a, b, a2, b2, c) fixed binary(31); + j = 0; + do i = 1 to 1000; + r=rand(31); a=r-16; + r=rand(31); b=r-16; + a2=a*a; + b2=b*b; + c2=a2+b2; + if c2>= 100 & c2 <= 225 then + do; j = j + 1; x(j) = a; y(j) = b; + /* put Edit(a,b,c)(3(F(3))); */ end; + end; + /* PLOT */ + declare table(-15:15, -15:15) character (2); + table = ' '; + do i = 1 to j; + table(x(i), y(i)) = '*'; + end; + do i = -15 to 15; + put skip; + do j = -15 to 15; + put edit (table(i,j)) (a); + end; + end; + + rand: Proc(n) Returns(Bin Fixed(31)); + /*-------------------------------------------------------------------- + * Return a random integer between 1 and n + *-------------------------------------------------------------------*/ + Dcl r Bin Float(31); + Dcl (n,d) Bin Fixed(31); + r=random(); + d=r*n+1; + Return(d); + End; + End annulus; diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx index 55d127d94d..c5463160fc 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-1.rexx @@ -1,25 +1,28 @@ -/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ -arg points low high .; $= /*allow args from command line. */ -if points=='' then points=100 -if low=='' then low=10; low2= low**2 -if high=='' then high=15; high2=high**2 - - do x=-high; x2=x*x /*gen all possible annulus points*/ - if x<0 & x2>high2 then iterate - if x>0 & x2>high2 then leave - do y=-high; y2=y*y; s=x2+y2 - if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y +/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²+y²) ≤ 15 */ +parse arg points low high . /*allow parms from command line. */ +if points=='' then points=100 +if low=='' then low=10; low2= low**2 /*define a square shortcut.*/ +if high=='' then high=15; high2=high**2 /* " " " " */ +$= + do x=-high; x2=x*x /*gen all possible annulus points*/ + if x<0 & x2>high2 then iterate + if x>0 & x2>high2 then leave + do y=-high; y2=y*y; s=x2+y2 + if (y<0 & s>high2) | s0 & s>high2 then leave + $=$ x','y /*add a point-set to the $ list. */ end /*y*/ end /*x*/ -field.=; plotChar='O'; minY=high2; maxY=-minY; ap=words($) +plotChar='O'; minY=high2; maxY=-minY; ap=words($); field.= - do j=1 for points /*"draw" the x,y points [char O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ + do j=1 for points /*"draw" the x,y points [char O].*/ + parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ field.y=overlay(plotChar, field.y, x+high+1) /*"draw: the point. */ minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ end /*j*/ - do y=minY to maxY; if field.y=='' then iterate; say field.y; end /*plot*/ + do y=minY to maxY /*display the annulus to screen. */ + if field\=='' then say field.y /*Not blank? Then display it. */ + end /*y*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx index 55d127d94d..daa5938b87 100644 --- a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-2.rexx @@ -1,25 +1,28 @@ -/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²≤y²) ≤ 15 */ -arg points low high .; $= /*allow args from command line. */ -if points=='' then points=100 -if low=='' then low=10; low2= low**2 -if high=='' then high=15; high2=high**2 - - do x=-high; x2=x*x /*gen all possible annulus points*/ - if x<0 & x2>high2 then iterate - if x>0 & x2>high2 then leave - do y=-high; y2=y*y; s=x2+y2 - if (y<0 & s>high2) | s0 & s>high2 then leave - $=$ x','y +/*REXX program gens 100 random points in an annulus: 10 ≤ √(x²+y²) ≤ 15 */ +parse arg points low high . /*allow parms from command line. */ +if points=='' then points=100 +if low=='' then low=10; low2= low**2 /*define a square shortcut.*/ +if high=='' then high=15; high2=high**2 /* " " " " */ +$= + do x=-high; x2=x*x /*gen all possible annulus points*/ + if x<0 & x2>high2 then iterate + if x>0 & x2>high2 then leave + do y=-high; y2=y*y; s=x2+y2 + if (y<0 & s>high2) | s0 & s>high2 then leave + $=$ x','y /*add a point-set to the $ list. */ end /*y*/ end /*x*/ -field.=; plotChar='O'; minY=high2; maxY=-minY; ap=words($) +plotChar='O'; minY=high2; maxY=-minY; ap=words($); field.= - do j=1 for points /*"draw" the x,y points [char O].*/ - parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ - field.y=overlay(plotChar, field.y, x+high+1) /*"draw: the point. */ + do j=1 for points /*"draw" the x,y points [char O].*/ + parse value word($,random(1,ap)) with x ',' y /*pick random point.*/ + field.y=overlay(plotChar, field.y, 2*x+2*high+1) /*"draw: the point. */ minY=min(minY,y); maxY=max(maxY,y) /*plot restricting. */ end /*j*/ - do y=minY to maxY; if field.y=='' then iterate; say field.y; end /*plot*/ + do y=minY to maxY /*display the annulus to screen. */ + if field\=='' then say field.y /*Not blank? Then display it. */ + end /*y*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx new file mode 100644 index 0000000000..5ea3c710fd --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-3.rexx @@ -0,0 +1,40 @@ +/* REXX --------------------------------------------------------------- +* show 100 random points of an annulus with radius 10 to 15 +* 18.06.2014 Walter Pachl 'derived/simplified' from REXX version 1 +*--------------------------------------------------------------------*/ + Parse Arg points low high scale . /* allow parms from command line.*/ + If points=='' Then points=100 /* number of points */ + If low=='' Then low=10 /* inner radius */ + If high=='' Then high=15 /* outer radius */ + If scale=='' Then scale=2 /* horizontal scaling */ + low2=low**2 + high2=high**2 + /* first compute all possible points */ + point.=0 + Do x=-high To high + x2=x*x + Do y=-high To high + y2=y*y + s=x2+y2 + If s>=low2 &s<=high2 Then Do + z=point.0+1 + point.z=x y + point.0=z + End + End + End + plotchar='O' + line.='' + np=point.0 /* available points */ + Do j=1 To points /* pick the needed points */ + r=random(1,np) + Parse Var point.r x y /* coordinates */ + line.y=overlay(plotchar,line.y,scale*(x+high)+1) /* put into line*/ + point.r=point.np /* replace taken point by last*/ + np=np-1 /* reduce available points */ + If np=0 Then Leave /* all possible points taken */ + End +/* now draw the picture */ + Do y=-high To high + Say line.y + End diff --git a/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-4.rexx b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-4.rexx new file mode 100644 index 0000000000..d129063063 --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/REXX/constrained-random-points-on-a-circle-4.rexx @@ -0,0 +1,78 @@ +/* REXX --------------------------------------------------------------- +* 19.06.2014 Walter Pachl alternate algorithm +* the idea: yl is a list of y coordinates which may have unused points +* one of the y's is picked at random +* Then we look for unused x coordinates in this line +* we pick one at random or drop the y from yl if none is found +* When yl becomes empty, all points are used and we stop +*--------------------------------------------------------------------*/ +Parse Arg n r rr scale +If r='' Then r=10 +If rr='' Then rr=15 +If n='' Then n=100 +If scale='' Then scale=2 +r2=r*r +rr2=rr*rr +ymin=0 +ymax=rr*2 +ol='' +pp.=0 +used.=0 +yl='' /* list of available y values */ +Do y=-rr To rr + yl=yl y + End +Do Until pp.0=n /*look for the required points*/ + If yl='' Then Do /* no more points available */ + Say 'all points filled' + Leave + End + yi=random(1,words(yl)) /* pick a y */ + y=word(yl,yi) + y2=y*y + p.=0 + Do x=0 To rr /* Loop through possible x's */ + x2=x*x + xy2=x2+y2 + If xy2>=r2&xy2<=rr2 Then Do /* within the annulus */ + Call take x y + Call take (-x) y + End + End + If p.0>0 Then Do /* some x's found (or just 1) */ + xi=random(1,p.0) /* pick an x */ + z=pp.0+1 + pp.z=p.xi + pp.0=z + Parse Var pp.z xa ya + used.xa.ya=1 /* remember it's taken */ + End + Else Do /* no x for this y */ + yi=wordpos(y,yl) /* remove y from yl */ + Select + When yi=1 Then yl=subword(yl,yi+1) + When yi=words(yl) Then yl=subword(yl,1,yi-1) + Otherwise yl=subword(yl,1,yi-1) subword(yl,yi+1) + End + End + End +line.='' /* empty the raster */ +Do i=1 To pp.0 /* place the points */ + Parse Var pp.i x y + line.y=overlay('+',line.y,scale*(rr+x)+1) + End +Do y=-rr To rr /* show the result */ + Say line.y + End +say pp.0 'points filled' +Exit +Return + +take: Procedure Expose p. used. /* add x to p. if its not used*/ + Parse Arg x y + If used.x.y=0 Then Do + z=p.0+1 + p.z=x y + p.0=z + End + Return diff --git a/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle.rb b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-1.rb similarity index 51% rename from Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle.rb rename to Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-1.rb index b418a9b773..82ab2a26bd 100644 --- a/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle.rb +++ b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-1.rb @@ -1,13 +1,13 @@ -points = (1...100).map { - # choose a random radius and angle - angle = rand * 2.0 * Math::PI - rad = rand * 5.0 + 10.0 - # convert back from polar to cartesian coordinates - [rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round) - } +points = (1..100).map do + # choose a random radius and angle + angle = rand * 2.0 * Math::PI + rad = rand * 5.0 + 10.0 + # convert back from polar to cartesian coordinates + [rad * Math::cos(angle), rad * Math::sin(angle)].map(&:round) +end (-15..15).each do |row| - puts((-15..15).map { |col| points.include?([row, col]) ? "X" : " " }.join) + puts (-15..15).map { |col| points.include?([row, col]) ? "X" : " " }.join end load 'raster_graphics.rb' diff --git a/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb new file mode 100644 index 0000000000..85d31e089c --- /dev/null +++ b/Task/Constrained-random-points-on-a-circle/Ruby/constrained-random-points-on-a-circle-2.rb @@ -0,0 +1,10 @@ +r2 = 10*10..15*15 +range = (-15..15).to_a +points = range.product(range).each_with_object([]) do |(i,j), pt| + pt << [i,j] if r2.cover?(i*i + j*j) +end + +puts "Precalculate: #{points.size}" +pt = Hash.new(" ") +points.sample(100).each{|i,j| pt[[i,j]] = " o"} +puts range.map{|i| range.map{|j| pt[[i,j]]}.join} diff --git a/Task/Constrained-random-points-on-a-circle/Scala/constrained-random-points-on-a-circle.scala b/Task/Constrained-random-points-on-a-circle/Scala/constrained-random-points-on-a-circle.scala index 896ec4ab78..5b5d8cbc6b 100644 --- a/Task/Constrained-random-points-on-a-circle/Scala/constrained-random-points-on-a-circle.scala +++ b/Task/Constrained-random-points-on-a-circle/Scala/constrained-random-points-on-a-circle.scala @@ -1,73 +1,77 @@ -object CRP extends SimpleSwingApplication { - 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.util.Random - import scala.math._ +import java.awt.{ Color, geom,Graphics2D ,Rectangle} +import scala.math.hypot +import scala.swing.{MainFrame,Panel,SimpleSwingApplication} +import scala.swing.Swing.pair2Dimension +import scala.util.Random +object CirculairConstrainedRandomPoints extends SimpleSwingApplication { //min/max of display-x resp. y - val dx0,dy0 = 30 - val dxm,dym = 430 + val dx0, dy0 = 30; val dxm, dym = 430 + val prefSizeX, prefSizeY = 480 - val prefSizeX,prefSizeY = 480 + val palet = 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 color + val xmax, ymax = 20; val xmin, ymin = -xmax - lazy val ui = new Panel { + class Coord(x: Double, y: Double) { + def dx = (((dxm - dx0) / 2 + x.toDouble / xmax * (dxm - dx0) / 2) + dx0).toInt + def dy = (((dym - dy0) / 2 - y.toDouble / ymax * (dym - dy0) / 2) + dy0).toInt + } + + object Coord { + def apply(x: Double, y: Double) = new Coord(x, y) + } + + //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).toSeq. + map { case (x, y, r) => new Rectangle(Coord(x, y).dx - 2, Coord(x, y).dy - 2, 4, 4) } + + private def ui = new Panel { background = Color.white preferredSize = (prefSizeX, prefSizeY) - val xmax,ymax = 20; val xmin,ymin = -20 - - case class Coord(x: Double, y: Double) { - val dx = (((dxm-dx0)/2+x.toDouble/xmax*(dxm-dx0)/2)+dx0).toInt - val dy = (((dym-dy0)/2-y.toDouble/ymax*(dym-dy0)/2)+dy0).toInt + class Circle(center: Coord, r: Double, val color: Color) { + val dr = (Coord(r, 0).dx - pcentre.dx) * 2 + val dx = center.dx - dr / 2 + val dy = center.dy - dr / 2 } - case class Circle(x: Double, y: Double, r: Double, c: java.awt.Color) { - val mdp = Coord(x,y) - val dr = (Coord(r,0).dx-pcentre.dx)*2 - val dx = mdp.dx-dr/2 - val dy = mdp.dy-dr/2 + object Circle { + def apply(x: Double, y: Double, r: Double, color: Color) = + new Circle(Coord(x, y), r, color) } - val pcentre = Coord(0,0) - val pxmax = Coord(xmax,0); val pxmin = Coord(xmin,0) - val pymax = Coord(0,ymax); val pymin = Coord(0,ymin) + val pcentre = Coord(0, 0) + val pxmax = Coord(xmax, 0); val pxmin = Coord(xmin, 0) + val pymax = Coord(0, ymax); val pymin = Coord(0, ymin) //axes: - var a_path = new geom.GeneralPath + val a_path = new geom.GeneralPath a_path.moveTo(pxmin.dx, pxmin.dy); a_path.lineTo(pxmax.dx, pxmax.dy) //x-axis a_path.moveTo(pymin.dx, pymin.dy); a_path.lineTo(pymax.dx, pymax.dy) //y-axis //labeling: - val labels = List(-20,-15,-10,-5,5,10,15,20) - labels.foreach{x=>{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)}) + val labels = List(-20, -15, -10, -5, 5, 10, 15, 20) + labels.foreach { x => { 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)} + val circles = cs.map { case (x, y, r, c) => Circle(x, y, r, palet(c)) } 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)} + circles.foreach { c => { g.setColor(c.color); g.drawOval(c.dx, c.dy, c.dr, c.dr) } } + g.setColor(palet("r")); points.foreach(g.draw(_)) + g.setColor(palet("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 ui def top = new MainFrame { title = "Rosetta Code >>> Task: Constrained random points on a circle | Language: Scala" diff --git a/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Perl/continued-fraction-arithmetic-construct-from-rational-number.pl b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Perl/continued-fraction-arithmetic-construct-from-rational-number.pl new file mode 100644 index 0000000000..9091ea166a --- /dev/null +++ b/Task/Continued-fraction-Arithmetic-Construct-from-rational-number/Perl/continued-fraction-arithmetic-construct-from-rational-number.pl @@ -0,0 +1,26 @@ +$|=1; + +sub rc2f { + my($num, $den) = @_; + return sub { return unless $den; + my $q = int($num/$den); + ($num, $den) = ($den, $num - $q*$den); + $q; }; +} + +sub rcshow { + my $sub = shift; + print "["; + my $n = $sub->(); + print "$n" if defined $n; + print "; $n" while defined($n = $sub->()); + print "]\n"; +} + +rcshow(rc2f(@$_)) + for ([1,2],[3,1],[23,8],[13,11],[22,7],[-151,77]); +print "\n"; +rcshow(rc2f(@$_)) + for ([14142,10000],[141421,100000],[1414214,1000000],[14142136,10000000]); +print "\n"; +rcshow(rc2f(314285714,100000000)); diff --git a/Task/Continued-fraction/ATS/continued-fraction.ats b/Task/Continued-fraction/ATS/continued-fraction.ats index 47914d457d..15ded774d2 100644 --- a/Task/Continued-fraction/ATS/continued-fraction.ats +++ b/Task/Continued-fraction/ATS/continued-fraction.ats @@ -1,37 +1,70 @@ -(* a coefficient function creates double values from in paramters *) +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) +// +(* +** a coefficient function creates double values from in paramters +*) typedef coeff_f = int -> double - -(* a continued fraction is described by a record of two coefficent functions a and b *) +// +(* +** a continued fraction is described by a record of two coefficent +** functions a and b +*) typedef frac = @{a= coeff_f, b= coeff_f} +// +(* ****** ****** *) -(* recursive definition of the approximation *) -fun calc_rec(f: frac, n: int, r: double): double = - if n = 0 then - f.a(0) + r // base case - else let // recursive case - val a: double = f.a(n) // record access - val b: double = f.b(n) - val s: double = b / (a + r) - //val () = printf("r%d = %f, a = %f, b = %f, r%d = %f\n", @(n, r, a, b, (n-1), s)) - in calc_rec(f, n - 1, s) end +fun calc +( + f: frac, n: int +) : double = let +// +(* +** recursive definition of the approximation +*) +fun loop +( + n: int, r: double +) : double = +( +if n = 0 + then f.a(0) + r + else loop (n - 1, f.b(n) / (f.a(n) + r)) +// end of [if] +) +// +in + loop (n, 0.0) +end // end of [calc] -fun calc(f: frac, n: int): double = - calc_rec(f, n, 0.0) +(* ****** ****** *) -(* anonymous coefficient functions created with lam (short for lambda) *) -val sqrt2 = @{ a= lam (n: int): double => if n = 0 then 1.0 else 2.0, - b= lam (n: int): double => 1.0 } +val sqrt2 = @{ + a= lam (n: int): double => if n = 0 then 1.0 else 2.0 +, + b= lam (n: int): double => 1.0 +} (* end of [val] *) -val napier = @{ a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * (n), - b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0 } +val napier = @{ + a= lam (n: int): double => if n = 0 then 2.0 else 1.0 * n +, + b= lam (n: int): double => if n = 1 then 1.0 else n - 1.0 +} (* end of [val] *) -fun square(x: double): double = x * x +val pi = @{ + a= lam (n: int): double => if n = 0 then 3.0 else 6.0 +, + b= lam (n: int): double => let val x = 2.0 * n - 1 in x * x end +} -val pi = @{ a= lam (n: int): double => if n = 0 then 3.0 else 6.0, - b= lam (n: int): double => square (2.0 * n - 1) } +(* ****** ****** *) -implement main () = begin - printf ("sqrt2 = %f\n", @(calc(sqrt2, 100))); - printf ("napier = %f\n", @(calc(napier, 100))); - printf (" pi = %f\n", @(calc( pi , 100))); -end +implement +main0 () = +( + println! ("sqrt2 = ", calc(sqrt2, 100)); + println! ("napier = ", calc(napier, 100)); + println! (" pi = ", calc( pi , 100)); +) (* end of [main0] *) diff --git a/Task/Continued-fraction/AutoHotkey/continued-fraction-1.ahk b/Task/Continued-fraction/AutoHotkey/continued-fraction-1.ahk new file mode 100644 index 0000000000..91eed9147f --- /dev/null +++ b/Task/Continued-fraction/AutoHotkey/continued-fraction-1.ahk @@ -0,0 +1,47 @@ +sqrt2_a(n) ; function definition is as simple as that +{ +return n?2.0:1.0 +} + +sqrt2_b(n) +{ +return 1.0 +} + +navier_a(n) +{ +return n?n:2.0 +} + +navier_b(n) +{ +return n>1.0?n-1.0:1.0 +} + +pi_a(n) +{ +return n?6.0:3.0 +} + +pi_b(n) +{ +return (2.0*n-1.0)**2.0 ; exponentiation operator +} + +calc(f,expansions) +{ +r:=0,i:=expansions +; A nasty trick: the names of the two coefficient functions are generated dynamically +; a dot surrounded by spaces means string concatenation +f_a:=f . "_a",f_b:=f . "_b" + +while i>0 { +; You can see two dynamic function calls here +r:=%f_b%(i)/(%f_a%(i)+r) +i-- +} + +return %f_a%(0)+r +} + +Msgbox, % "sqrt 2 = " . calc("sqrt2", 1000) . "`ne = " . calc("navier", 1000) . "`npi = " . calc("pi", 1000) diff --git a/Task/Continued-fraction/AutoHotkey/continued-fraction-2.ahk b/Task/Continued-fraction/AutoHotkey/continued-fraction-2.ahk new file mode 100644 index 0000000000..9ee7d2345a --- /dev/null +++ b/Task/Continued-fraction/AutoHotkey/continued-fraction-2.ahk @@ -0,0 +1,3 @@ +sqrt 2 = 1.414214 +e = 2.718282 +pi = 3.141593 diff --git a/Task/Continued-fraction/AutoHotkey/continued-fraction-3.ahk b/Task/Continued-fraction/AutoHotkey/continued-fraction-3.ahk new file mode 100644 index 0000000000..e5cad81238 --- /dev/null +++ b/Task/Continued-fraction/AutoHotkey/continued-fraction-3.ahk @@ -0,0 +1,3 @@ +sqrt 2 = 1.4142135623730951 +e = 2.7182818284590455 +pi = 3.1415926533405418 diff --git a/Task/Conways-Game-of-Life/00DESCRIPTION b/Task/Conways-Game-of-Life/00DESCRIPTION index ac65efa898..d1e79ede50 100644 --- a/Task/Conways-Game-of-Life/00DESCRIPTION +++ b/Task/Conways-Game-of-Life/00DESCRIPTION @@ -1,4 +1,5 @@ -The '''Game of Life''' is a [[wp:cellular automaton|cellular automaton]] devised by the British mathematician [[wp:John Horton Conway|John Horton Conway]] in 1970. It is the best-known example of a cellular automaton. +The '''Game of Life''' is a [[wp:cellular automaton|cellular automaton]] devised by the British mathematician [[wp:John Horton Conway|John Horton Conway]] in 1970. +It is the best-known example of a cellular automaton. Conway's game of life is described [[wp:Conway%27s_Game_of_Life|here]]: @@ -19,3 +20,6 @@ Although you should test your implementation on more complex examples such as th ;References: * Its creator John Conway, explains [http://www.youtube.com/watch?v=E8kUJL04ELA the game of life]. Video from numberphile on youtube. * John Conway [http://www.youtube.com/watch?v=R9Plq-D1gEk Inventing Game of Life]- Numberphile video. + +;See also: +* [[Langton's ant]] - another well known cellular automaton. diff --git a/Task/Conways-Game-of-Life/AWK/conways-game-of-life.awk b/Task/Conways-Game-of-Life/AWK/conways-game-of-life.awk index c1ba9e9f08..c16b314bcb 100644 --- a/Task/Conways-Game-of-Life/AWK/conways-game-of-life.awk +++ b/Task/Conways-Game-of-Life/AWK/conways-game-of-life.awk @@ -1,6 +1,9 @@ -BEGIN { c=220; d=619; i=10000; printf("\033[2J"); +BEGIN { + c=220; d=619; i=10000; + printf("\033[2J"); # Clear screen while(i--) m[i]=0; while(d--) m[int(rand()*1000)]=1; + while(c--){ for(i=52; i<=949; i++){ d=m[i-1]+m[i+1]+m[i-51]+m[i-50]+m[i-49]+m[i+49]+m[i+50]+m[i+51]; @@ -9,13 +12,14 @@ BEGIN { c=220; d=619; i=10000; printf("\033[2J"); else if(m[i]==1 && d<2) n[i]=0; else if(m[i]==1 && d>3) n[i]=0; } - printf("\033[1;1H"); - for(i=1;i<=1000;i++) + printf("\033[1;1H"); # Home cursor + for(i=1;i<=1000;i++) # gridsize 50x20 { if(n[i]) printf("O"); else printf("."); m[i]=n[i]; if(!(i%50)) printf("\n"); } - printf("%3d\n",c); x=30000; while(x--) ; + printf("%3d\n",c); # Countdown + x=30000; while(x--) ; # Delay } } diff --git a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 new file mode 100644 index 0000000000..f28433510b --- /dev/null +++ b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-1.basic256 @@ -0,0 +1,8 @@ +# Conway's_Game_of_Life + +X = 59 : Y = 35 : H = 4 + +fastgraphics +graphsize X*H,Y*H + +dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y) diff --git a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life.basic256 b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 similarity index 87% rename from Task/Conways-Game-of-Life/BASIC256/conways-game-of-life.basic256 rename to Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 index fb58ef6e31..408b2663f8 100644 --- a/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life.basic256 +++ b/Task/Conways-Game-of-Life/BASIC256/conways-game-of-life-2.basic256 @@ -1,10 +1,5 @@ -X = 59 : Y = 35 : H = 4 - -fastgraphics -graphsize X*H,Y*H - -dim c(X,Y) : dim cn(X,Y) : dim cl(X,Y) -c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1 # Thunderbird methuselah +# Thunderbird methuselah +c[X/2-1,Y/3+1] = 1 : c[X/2,Y/3+1] = 1 : c[X/2+1,Y/3+1] = 1 c[X/2,Y/3+3] = 1 : c[X/2,Y/3+4] = 1 : c[X/2,Y/3+5] = 1 s = 0 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 5e87e1c51c..0f6a84ba48 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 @@ -1,23 +1,22 @@ -import std.stdio, std.string, std.algorithm, std.typetuple, - std.array, std.conv; +import std.stdio, std.string, std.algorithm, std.array, std.conv; struct GameOfLife { enum Cell : char { dead = ' ', alive = '#' } Cell[][] grid, newGrid; - this(in int x, in int y) pure nothrow { + this(in int x, in int y) pure nothrow @safe { grid = new typeof(grid)(y + 2, x + 2); newGrid = new typeof(grid)(y + 2, x + 2); } void opIndexAssign(in string[] v, in size_t y, in size_t x) - pure /*nothrow*/ { + pure /*nothrow*/ @safe /*@nogc*/ { foreach (immutable nr, row; v) foreach (immutable nc, state; row) grid[y + nr][x + nc] = state.to!Cell; } - void iteration() pure nothrow { + void iteration() pure nothrow @safe @nogc { newGrid[0][] = Cell.dead; newGrid[$ - 1][] = Cell.dead; foreach (row; newGrid) @@ -35,18 +34,18 @@ struct GameOfLife { newGrid[r][c] = a ? Cell.alive : Cell.dead; } - swap(grid, newGrid); + grid.swap(newGrid); } - string toString() const pure nothrow { + string toString() const pure /*nothrow @safe*/ { auto ret = "-".replicate(grid[0].length - 1) ~ "\n"; foreach (const row; grid[1 .. $ - 1]) - ret ~= "|" ~ cast(char[])row[1 .. $ - 1] ~ "|\n"; + ret ~= "|%(%c%)|\n".format(row[1 .. $ - 1]); return ret ~ "-".replicate(grid[0].length - 1); } } -void main() { +void main() /*@safe*/ { immutable glider1 = [" #", "# #", " ##"]; immutable glider2 = ["# ", "# #", "## "]; @@ -56,10 +55,10 @@ void main() { uni[3, 19] = glider1; uni[3, 32] = glider2; uni[5, 50] = [" # #", "# ", "# #", "#### "]; - writeln(uni); + uni.writeln; foreach (immutable _; 0 .. 20) { - uni.iteration(); - writeln(uni); + uni.iteration; + uni.writeln; } } 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 dc7d09b940..a7b053e30c 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 @@ -1,32 +1,25 @@ import std.stdio, std.string, std.algorithm, std.typetuple, std.array, std.conv; -template Iota(int start, int stop) { - static if (stop <= start) - alias TypeTuple!() Iota; - else - alias TypeTuple!(Iota!(start, stop - 1), stop - 1) Iota; -} - struct GameOfLife { enum Cell : char { dead = ' ', alive = '#' } Cell[] grid, newGrid; immutable size_t nCols; - this(in int nx, in int ny) pure nothrow { + this(in int nx, in int ny) pure nothrow @safe { nCols = nx + 2; grid = new typeof(grid)(nCols * (ny + 2)); newGrid = new typeof(grid)(grid.length); } void opIndexAssign(in string[] v, in size_t y, in size_t x) - pure /*nothrow*/ { + pure /*nothrow*/ @safe /*@nogc*/ { foreach (immutable nr, const row; v) foreach (immutable nc, immutable state; row) grid[(y + nr) * nCols + x + nc] = state.to!Cell; } - void iteration() { + void iteration() pure nothrow @safe @nogc { newGrid[0 .. nCols] = Cell.dead; newGrid[$ - nCols .. $] = Cell.dead; foreach (immutable nr; 1 .. (newGrid.length / nCols) - 1) { @@ -38,13 +31,12 @@ struct GameOfLife { size_t nr_nCols = nr * nCols; foreach (immutable nc; 1 .. nCols - 1) { uint count = 0; - /*static*/ foreach (immutable i; Iota!(-1, 2)) - /*static*/ foreach (immutable j; Iota!(-1, 2)) + /*static*/ foreach (immutable i; TypeTuple!(-1, 0, 1)) + /*static*/ foreach (immutable j; TypeTuple!(-1, 0, 1)) static if (i != 0 || j != 0) - count += - (grid[nr_nCols + i * nCols + nc + j] == Cell.alive); - const a = count == 3 || - (count == 2 && grid[nr_nCols + nc] == Cell.alive); + count += (grid[nr_nCols + i * nCols + nc + j] == Cell.alive); + immutable a = count == 3 || + (count == 2 && grid[nr_nCols + nc] == Cell.alive); newGrid[nr_nCols + nc] = a ? Cell.alive : Cell.dead; } } @@ -52,12 +44,10 @@ struct GameOfLife { swap(grid, newGrid); } - string toString() const pure nothrow { + string toString() const pure /*nothrow @safe*/ { string ret = "-".replicate(nCols - 1) ~ "\n"; foreach (immutable nr; 1 .. (grid.length / nCols) - 1) - ret ~= "|" ~ - cast(char[])grid[nr * nCols + 1 .. nr * nCols + nCols - 1] - ~ "|\n"; + ret ~= "|%(%c%)|\n".format(grid[nr * nCols + 1 .. nr * nCols + nCols - 1]); return ret ~ "-".replicate(nCols - 1); } } @@ -72,10 +62,10 @@ void main() { uni[3, 19] = glider1; uni[3, 32] = glider2; uni[5, 50] = [" # #", "# ", "# #", "#### "]; - writeln(uni); + uni.writeln; foreach (immutable _; 0 .. 20) { - uni.iteration(); - writeln(uni); + uni.iteration; + uni.writeln; } } diff --git a/Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia b/Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia new file mode 100644 index 0000000000..b223e056b7 --- /dev/null +++ b/Task/Conways-Game-of-Life/Julia/conways-game-of-life.julia @@ -0,0 +1,11 @@ +julia> Pkg.add("CellularAutomata") +INFO: Installing CellularAutomata v0.1.2 +INFO: Package database updated + +julia> using CellularAutomata + +julia> gameOfLife{T<:Int}(n::T, m::T, gen::T) = CA2d([3], [2,3], int(randbool(n, m)), gen) +gameOfLife (generic function with 1 method) + +julia> gameOfLife(15, 30, 5) +30x15x5 Cellular Automaton diff --git a/Task/Conways-Game-of-Life/Pascal/conways-game-of-life.pascal b/Task/Conways-Game-of-Life/Pascal/conways-game-of-life.pascal new file mode 100644 index 0000000000..f1404599eb --- /dev/null +++ b/Task/Conways-Game-of-Life/Pascal/conways-game-of-life.pascal @@ -0,0 +1,179 @@ +program Gol; +// Game of life +{$IFDEF FPC} + //save as gol.pp/gol.pas + {$Mode delphi} +{$ELSE} + //for Delphi save as gol.dpr + {$Apptype Console} +{$ENDIF} +uses + crt; + +const + colMax = 76; + rowMax = 22; + dr = colMax+2; // element count of one row + + cDelay = 20; // delay in ms + +(* +expand field by one row/column before and after +for easier access no special treatment of torus +*) + +type + tFldElem = byte;//0..1 + tpFldElem = ^tFldElem; + tRow = array[0..colMax+1] of tFldElem; + tpRow = ^tRow; + tBoard = array[0..rowMax+1] of tRow; + tpBoard = ^tBoard; + tpBoards = array[0..1] of tpBoard; + +type + tIntArr = array[0..2*dr+2] of tFldElem; + tpIntArr = ^tIntArr; + +var + aBoard,bBoard : tBoard; + pBoards :tpBoards; + gblActBoard : byte; + gblUseTorus :boolean; + gblGenCnt : integer; + +procedure PrintGen; +const + cChar: array[0..1] of char = (' ','#'); +var + p0 : tpIntArr; + col,row: integer; + s : string[colMax]; +begin + setlength(s,colmax); + gotoxy(1,1); + writeln(gblGenCnt:10); + For row := 1 to rowMax do + begin + p0 := @pBoards[gblActBoard]^[row,0];; + For col := 1 to colMax do + s[col] := cChar[p0[col]]; + writeln(s); + end; + delay(cDelay); +end; + +procedure Init0(useTorus:boolean); +begin + gblUseTorus := useTorus; + gblGenCnt := 0; + fillchar(aBoard,SizeOf(aBoard),#0); + pBoards[0] := @aBoard; + pBoards[1] := @bBoard; + gblActBoard := 0; + + clrscr; +end; + +procedure InitRandom(useTorus:boolean); +var + col,row : integer; +begin + Init0(useTorus); + For row := 1 to rowMax do + For col := 1 to colMax do + aBoard[row,col]:= tFldElem(random>0.9); +end; + +procedure InitBlinker(useTorus:boolean); +var + col,row : integer; +begin + Init0(useTorus); + For col := 1 to colMax do + begin + IF (col+2) mod 4 = 0 then + begin + For row := 1 to rowmax do + IF row mod 4 <> 0 then + aBoard[row,col]:= 1; + end; + end; +end; + +procedure Torus; +var + p0 : tpIntArr; + row: integer; +begin + //copy column 1-> colMax+1 and colMax-> 0 + p0 := @pBoards[gblActBoard]^[1,0]; + For row := 1 to rowMax do + begin + p0^[0] := p0^[colMax]; + p0^[colmax+1] := p0^[1]; + //next row + p0 := Pointer(PtrUint(p0)+SizeOf(tRow)); + end; + //copy row 1-> rowMax+1 + move(pBoards[gblActBoard]^[1,0],pBoards[gblActBoard]^[rowMax+1,0],sizeof(trow)); + //copy row rowMax-> 0 + move(pBoards[gblActBoard]^[rowMax,0],pBoards[gblActBoard]^[0,0],sizeof(trow)); +end; + +function Survive(p: tpIntArr):tFldElem; +//p points to actual_board [row-1,col-1] +//calculates the sum of alive around [row,col] aka p^[dr+1] +//really fast using fpc 2.6.4 no element on stack +const + cSurvives : array[boolean,0..8] of byte = + //0,1,2,3,4,5,6,7,8 sum of alive neighbours + ((0,0,0,1,0,0,0,0,0), {alive =false 1->born} + (0,0,1,1,0,0,0,0,0)); {alive =true 0->die } +var + sum : integer; +begin + // row above + // sum := byte(aBoard[row-1,col-1])+byte(aBoard[row-1,col])+byte(aBoard[row-1,col+1]); + sum := integer(p^[ 0])+integer(p^[ 1])+integer(p^[ 2]); + sum := sum+integer(p^[ dr+0]) +integer(p^[ dr+2]); + sum := sum+integer(p^[2*dr+0])+integer(p^[2*dr+1])+integer(p^[2*dr+2]); + survive := cSurvives[boolean(p^[dr+1]),sum]; +end; + +procedure NextGen; +var + p0,p1 : tpFldElem; + row: NativeInt; + col :NativeInt; +begin + if gblUseTorus then + Torus; + p1 := @pBoards[1-gblActBoard]^[1,1]; + //One row above and one column before because of survive + p0 := @pBoards[ gblActBoard]^[0,0]; + For row := rowMax-1 downto 0 do + begin + For col := colMax-1 downto 0 do + begin + p1^ := survive(tpIntArr(p0)); + inc(p0); + inc(p1); + end; + // jump over the borders + inc(p1,2); + inc(p0,2); + end; + //aBoard := bBoard; + gblActBoard :=1-gblActBoard; + inc(gblGenCnt); +end; + +begin + InitBlinker(false); + repeat + PrintGen; + NextGen; + until keypressed; + PrintGen; +end. diff --git a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 index 1f3b5602fe..68039f5305 100644 --- a/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 +++ b/Task/Conways-Game-of-Life/Perl-6/conways-game-of-life.pl6 @@ -1,7 +1,6 @@ class Automaton { subset World of Str where { - .lines.pick.chars == all(.lines>>.chars) - and m/^^<[.#\n]>+$$/ + .lines>>.chars.uniq == 1 and m/^^<[.#\n]>+$$/ } has Int ($.width, $.height); has @.a; diff --git a/Task/Conways-Game-of-Life/Python/conways-game-of-life-2.py b/Task/Conways-Game-of-Life/Python/conways-game-of-life-2.py index 7ca1d95961..54bc27d36e 100644 --- a/Task/Conways-Game-of-Life/Python/conways-game-of-life-2.py +++ b/Task/Conways-Game-of-Life/Python/conways-game-of-life-2.py @@ -5,19 +5,17 @@ def life(world, N): for g in range(N+1): display(world, g) counts = Counter(n for c in world for n in offset(neighboring_cells, c)) - world = set(c for c in counts if counts[c] == 3 - or counts[c] == 2 and c in world) - return world - + world = {c for c in counts + if counts[c] == 3 or (counts[c] == 2 and c in world)} neighboring_cells = [(-1, -1), (-1, 0), (-1, 1), ( 0, -1), ( 0, 1), ( 1, -1), ( 1, 0), ( 1, 1)] -def offset(world, delta): - "Slide/offset all the cells in world by delta, a (dx, dy) vector." +def offset(cells, delta): + "Slide/offset all the cells by delta, a (dx, dy) vector." (dx, dy) = delta - return set((x+dx, y+dy) for (x, y) in world) + return {(x+dx, y+dy) for (x, y) in cells} def display(world, g): "Display the world as a grid of characters." diff --git a/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx new file mode 100644 index 0000000000..664cc119d2 --- /dev/null +++ b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-1.rexx @@ -0,0 +1,53 @@ +/*REXX program displays Conway's game of life, it stops after N repeats.*/ +signal on halt /*handle cell growth interruptus.*/ +parse arg peeps '(' generations rows cols bare! life! clearScreen repeats + blank = 'BLANK' /*the "name" for blank*/ +generations = p(generations 100) /*#generations allowed*/ + rows = p(rows 3) /*number of cell rows.*/ + cols = p(cols 3) /* " " " cols.*/ + bare! = pickChar(bare! blank) /*an empty cell thingy*/ +clearScreen = p(clearScreen 0) /*1 = clear the screen*/ + life! = pickChar(life! '☼') /*looks like an ameba.*/ + repeats = p(repeats 2) /*stop if 2 repeats.*/ +fents=max(linesize()-1,cols) /*fence width shown after display*/ +#repeats=0; $.=bare! /*the universe is new, and barren*/ +gens=abs(generations) /*use this for convenience. */ +x=space(peeps) /*remove superfluous spaces. */ +if x=='' then x='2,1 2,2 2,3' /* [↓] process the cells given.*/ + do while x\==''; parse var x _ x; parse var _ r ',' c . + $.r.c=life!; rows=max(rows,r); cols=max(cols,c) + end /*while*/ +life=0; !.=0; call showCells /*show initial state of the cells*/ +/*─────────────────────────────────────watch cell colony grow/live/die. */ + do life=1 for gens; @.=bare! + do r=1 for rows + do c=1 for cols; ??=$.r.c; n=neighbors() + if ??==bare! then do; if n==3 then ??=life!; end + else if n<2 | n>3 then ??=bare! + @.r.c=?? + end /*c*/ + end /*r*/ + call assign$ /*assign alternate cells ──► real*/ + if generations>0 | life==gens then call showCells + end /*life*/ +/*─────────────────────────────────────stop watching the universe (life)*/ +halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────SHOWCELLS subroutine───────────────────*/ +showCells: if clearScreen then 'CLS' /* ◄─── change this for your OS.*/ +call showRows /*show the rows in proper order. */ +say right(copies('═',fents)life,fents) /*show&tell for a bunch of cells.*/ +if _=='' then exit /*if no life, then stop the run. */ +if !._ then #repeats=#repeats+1 /*we detected a repeated pattern.*/ +!._=1 /*existence state & compare later*/ +if repeats\==0 & #repeats<=repeats then return /*so far, so good.*/ +say '"Life" repeated itself' repeats "times, program is stopping." +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────1─liner subroutines───────────────────────────────────────────────────────────────────────*/ +$: parse arg _row,_col; return $._row._col==life! +assign$: do r=1 for rows; do c=1 for cols; $.r.c=@.r.c; end; end; return +err: say;say;say center(' error! ',max(40,linesize()%2),"*");say;do j=1 for arg();say arg(j);say;end;say;exit 13 +neighbors: return $(r-1,c-1)+$(r-1,c)+$(r-1,c+1)+$(r,c-1)+$(r,c+1)+$(r+1,c-1)+$(r+1,c)+$(r+1,c+1) +p: return word(arg(1),1) +pickChar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_)==3 then _=d2c(_);if length(_)==2 then _=x2c(_);return _ +showRows: _=; do r=rows by -1 for rows; z=; do c=1 for cols; z=z||$.r.c; end; z=strip(z,'T'); say z; _=_||z; end; return diff --git a/Task/Conways-Game-of-Life/REXX/conways-game-of-life-2.rexx b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-2.rexx new file mode 100644 index 0000000000..ed4ba91fa2 --- /dev/null +++ b/Task/Conways-Game-of-Life/REXX/conways-game-of-life-2.rexx @@ -0,0 +1,185 @@ +/* REXX --------------------------------------------------------------- +* 02.08.2014 Walter Pachl +* Input is a file containing the initial pattern +* The compute area is extended when needed +* (cells are born outside the current compute area) +* The program stops when the picture shown is the same as the first +* or equal to the previous one +*--------------------------------------------------------------------*/ +Parse Arg f +If f='' Then f='bipole' +fid=f'.in' +oid=f'.txt'; 'erase' oid +debug=0 +If debug Then Do + dbg=f'.xxx'; 'erase' dbg + End +ml=0 +l.='' +Do ri=3 By 1 While lines(fid)>0 + l.ri=' 'linein(fid) + ml=max(ml,length(strip(l.ri,'T'))) + End +ml=ml+2 +ri=ri+1 +yy=ri +If debug Then + say 'ml='ml 'yy='yy +yb=1 +a.=' ' +b.=' ' +m.='' +x.='' +Parse Value 1 ml 1 yy With xmi xma ymi yma +Parse Value '999 0' With xmin xmax +Parse Value '999 0' With ymin ymax + +Do y=1 To yy + z=yy-y-1 + l=l.z + Do x=1 By 1 While l<>'' + Parse Var l c +1 l + If c='*' Then Do + a.x.z='*' + End + End + End +Call show +Do step=1 To 60 + Call store + If step>1 & is_equal(step,1) Then Leave + If step>1 & is_equal(step,step-1) Then Leave + Call show_neighbors + Do y=yma To ymi By -1 + ol=format(x,2)' ' + Do x=xmi To xma + neighbors=neighbors(x,y) + If a.x.y=' ' Then Do /* dead cell */ + If neighbors=3 Then Do + b.x.y='*' /* gets life */ + mmo=xmi xma ymi yma + xmi=min(xmi,x-1) + xma=max(xma,x+1) + ymi=min(ymi,y-1) + yma=max(yma,y+1) + mm=xmi xma ymi yma + If mm<>mmo Then + Call debug mmo '->' mm + End + Else /* life cell */ + b.x.y=' ' /* remains dead */ + + End + Else Do /* life cell */ + If neighbors=2 |, + neighbors=3 Then b.x.y='*' /* remains life */ + Else b.x.y=' ' /* dies */ + End + End + End + /* b. is the new state and is now copied to a. */ + Do y=yma To ymi By -1 + Do x=xmi To xma + a.x.y=b.x.y + End + End + End +/* Output name and all states */ +Call lineout oid,' 'f +st=' +' /* top and bottom border */ +sb=' +' /* top and bottom border */ +Do s=1 To step + st=st||'-'right(s,2,'-')||copies('-',xmax-xmin)'+' + sb=sb||copies('-',xmax-xmin+3)'+' + End +Call lineout oid,st /* top border */ +Do y=ymin To ymax + ol='' + Do s=1 To step + ol=ol '|' substr(m.s.y,xmin,xmax-xmin+1) + End + Call lineout oid,ol '|' + End +Call lineout oid,sb /* bottom border */ +Call lineout oid +'type' oid +If debug Then Do + Say 'original area' 1 ml '/' 1 yy + Say 'compute area ' xmi xma '/' ymi yma + End +Exit + +set: Parse Arg x,y + a.x.y='*' + Return + +neighbors: Procedure Expose a. debug + Parse Arg x,y + neighbors=0 + do xa=x-1 to x+1 + do ya=y-1 to y+1 + If xa<>x | ya<>y then + If a.xa.ya='*' Then + neighbors=neighbors+1 + End + End + Return neighbors + +store: +/* store current state (a.) in lines m.step.* */ +Do y=yy To 1 By -1 + ol='' + Do x=1 To ml + z=a.x.y + ol=ol||z + End + x.step.y=ol + If ol<>'' then Do + ymin=min(ymin,y) + ymax=max(ymax,y) + p=pos('*',ol) + q=length(strip(ol,'T')) + If p>0 Then + xmin=min(xmin,p) + xmax=max(xmax,q) + End + m.step.y=ol + Call debug '====>' right(step,2) y ol xmin xmax + End +Return + +is_equal: +/* test ist state a.b is equal to state a.a */ + Parse Arg a,b + Do y=yy To 1 By -1 + If x.b.y<>x.a.y Then + Return 0 + End + Return 1 + +show: Procedure Expose dbg a. yy ml debug +Do y=1 To yy + ol='>' + Do x=1 To ml + ol=ol||a.x.y + End + Call debug ol + End +Return + +show_neighbors: Procedure Expose a. xmi xma ymi yma dbg debug + Do y=yma To ymi By -1 + ol=format(y,2)' ' + + Do x=xmi To xma + ol=ol||neighbors(x,y) + End + Call debug ol + End + Return + +debug: + If debug Then + Return lineout(dbg,arg(1)) + Else + Return diff --git a/Task/Conways-Game-of-Life/REXX/conways-game-of-life.rexx b/Task/Conways-Game-of-Life/REXX/conways-game-of-life.rexx deleted file mode 100644 index 92930e832a..0000000000 --- a/Task/Conways-Game-of-Life/REXX/conways-game-of-life.rexx +++ /dev/null @@ -1,70 +0,0 @@ -/*REXX program displays Conway's game of life. - ┌───────────────────────────elided version─────────────────────────┐ - ├─── full version has many more options and enhanced displays. ────┤ - └──────────────────────────────────────────────────────────────────┘ */ -signal on syntax; signal on novalue /*handle REXX program errors. */ -signal on halt /*handle cell growth interruptus.*/ -parse arg peeps '(' generations rows cols bare! life! clearscreen every repeats -@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU - blank = 'BLANK' -generations = p(generations 100) - rows = p(rows 3) - cols = p(cols 3) - bare! = pickchar(bare! blank) -clearscreen = p(clearscreen 0) - every = p(every 999999999) - life! = pickchar(life! '☼') - repeats = p(repeats 2) -fents=max(79,cols) /*fence width shown after display*/ -#repeats=0; $.=bare! /*the universe is new, and barren*/ -gens=abs(generations) /*use this for convenience. */ -x=space(peeps) /*remove superfluous spaces. */ -if x=='' then x='2,1 2,2 2,3' - - do while x \=='' - parse var x p x; parse var p r ',' c .; $.r=overlay(life!,$.r,c+1) - end -life=0; !.=0; call showCells /*show initial state of the cells*/ -/*─────────────────────────────────────watch cell colony grow/live/die. */ - do life=1 for gens - do r=1 for rows; rank=bare! - do c=2 for cols; ?=substr($.r,c,1); ??=?; n=neighbors() - select /*select da quickest choice first*/ - when ?==bare! then if n==3 then ??=life! - otherwise if n<2 | n>3 then ??=bare! - end /*select*/ - rank=rank || ?? - end /*c*/ - @.r=rank - end /*c*/ - - do r=1 for rows; $.r=@.r; end /*assign alternate cells ──► real*/ - if life//every==0 | generations>0 | life==gens then call showCells - end /*life*/ -/*─────────────────────────────────────stop watching the universe (life)*/ -halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────SHOWCELLS subroutine─-─────────────────*/ -showCells: if clearscreen then 'CLS' /* ◄─── change this for your OS.*/ -_=; do r=rows by -1 for rows /*show the forest in proper order*/ - z=strip(substr($.r,2),'T') /*pick off the meat of the row. */ - say z; _=_ || z /*be neat about trailing blanks. */ - end /*r*/ -say right(copies('═',fents)life,fents) /*show&tell for a stand of trees.*/ -if _=='' then exit /*if no life, then stop the run. */ -if !._ then #repeats=#repeats+1 /*we detected a repeated pattern.*/ -!._=1 /*assign a state & compare later.*/ -if repeats\==0 & #repeats<=repeats then return /*so far, so good. */ -say '"Life" repeated itself' repeats "times, program is stopping." -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────NEIGHBORS subroutine───────────────────*/ -neighbors: rp=r+1; cp=c+1; rm=r-1; cm=c-1 /*count 8 neighbors of a cell*/ -return (substr($.rm,cm,1)==life!) + (substr($.rm,c ,1)==life!) + , - (substr($.rm,cp,1)==life!) + (substr($.r ,cm,1)==life!) + , - (substr($.r ,cp,1)==life!) + (substr($.rp,cm,1)==life!) + , - (substr($.rp,c ,1)==life!) + (substr($.rp,cp,1)==life!) -/*───────────────────────────────1-liner subroutines────────────────────*/ -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) -pickchar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_) ==3 then _=d2c(_);if length(_) ==2 then _=x2c(_);return _ -p: return word(arg(1),1) diff --git a/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-1.rb b/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-1.rb index 091d33881b..ad80f977e3 100644 --- a/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-1.rb +++ b/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-1.rb @@ -1,18 +1,19 @@ def game_of_life(name, size, generations, initial_life=nil) board = new_board size seed board, size, initial_life - print_board board, 0, name + print_board board, name, 0 reason = generations.times do |gen| new = evolve board, size - print_board new, gen+1, name + print_board new, name, gen+1 break :all_dead if barren? new, size break :static if board == new board = new end if reason == :all_dead then puts "no more life." elsif reason == :static then puts "no movement" - else puts "specified lifetime ended" + else puts "specified lifetime ended" end + puts end def new_board(n) @@ -22,7 +23,6 @@ end def seed(board, n, points=nil) if points.nil? # randomly seed board - srand indices = [] n.times {|x| n.times {|y| indices << [x,y] }} indices.shuffle[0,10].each {|x,y| board[y][x] = 1} @@ -54,13 +54,11 @@ def barren?(board, n) true end -def print_board(m, generation, name) +def print_board(m, name, generation) puts "#{name}: generation #{generation}" m.each {|row| row.each {|val| print "#{val == 1 ? '#' : '.'} "}; puts} - puts end - game_of_life "blinker", 3, 2, [[1,0],[1,1],[1,2]] -#game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]] -#game_of_life "random", 5, 10 +game_of_life "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]] +game_of_life "random", 5, 10 diff --git a/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-2.rb b/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-2.rb index 74ed9fabcf..d028931e44 100644 --- a/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-2.rb +++ b/Task/Conways-Game-of-Life/Ruby/conways-game-of-life-2.rb @@ -1,148 +1,105 @@ class Game - def initialize(name, size, generations, initial_life=nil) - @board = GameBoard.new size, initial_life - @board.display 0, name + def initialize(name, size, generations, initial_life=nil) + @size = size + @board = GameBoard.new size, initial_life + @board.display name, 0 - reason = generations.times do |gen| - new_board = evolve - new_board.display gen+1, name - break :all_dead if new_board.barren? - break :static if @board == new_board - @board = new_board - end - - if reason == :all_dead then puts "No more life." - elsif reason == :static then puts "No movement." - else puts "Specified lifetime ended." - end + reason = generations.times do |gen| + new_board = evolve + new_board.display name, gen+1 + break :all_dead if new_board.barren? + break :static if @board == new_board + @board = new_board end - def evolve - new_board = GameBoard.new @board.size, @board.life - @board.size.times do |i| - @board.size.times do |j| - if cell_fate i, j - new_board[i,j].live - else - new_board[i,j].die - end - end - end - new_board + case reason + when :all_dead then puts "No more life." + when :static then puts "No movement." + else puts "Specified lifetime ended." end + puts + end - def cell_fate(i, j) - left = [0, i-1].max; right = [i+1, @board.size-1].min - top = [0, j-1].max; bottom = [j+1, @board.size-1].min - sum = 0 - for x in (left..right) - for y in (top..bottom) - sum += @board[x,y].value if (x != i or y != j) - end - end - (sum == 3 or (sum == 2 and @board[i,j].alive?)) + def evolve + life = @board.each_index.select {|i,j| cell_fate(i,j)} + GameBoard.new @size, life + end + + def cell_fate(i, j) + left_right = [0, i-1].max .. [i+1, @size-1].min + top_bottom = [0, j-1].max .. [j+1, @size-1].min + sum = 0 + for x in left_right + for y in top_bottom + sum += @board[x,y].value if x != i or y != j + end end + sum == 3 or (sum == 2 and @board[i,j].alive?) + end end class GameBoard - attr_reader :size + include Enumerable - def initialize(size, initial_life=nil) - @size = size - @board = Array.new(size) {Array.new(size) {Cell.new false}} - self.seed_board initial_life - end + def initialize(size, initial_life=nil) + @size = size + @board = Array.new(size) {Array.new(size) {Cell.new false}} + seed_board initial_life + end - def seed_board(life) - if life.nil? - # randomly seed board - srand # seed the random number generator - indices = [] - @size.times {|x| @size.times {|y| indices << [x,y] }} - indices.shuffle[0,10].each {|x,y| @board[y][x].live} - else - life.each {|x, y| @board[y][x].live} - end + def seed_board(life) + if life.nil? + # randomly seed board + each_index.to_a.sample(10).each {|x,y| @board[y][x].live} + else + life.each {|x,y| @board[y][x].live} end + end - def [](x, y) - @board[y][x] - end + def each + @size.times {|x| @size.times {|y| yield @board[y][x] }} + end - def ==(board) - self.life == board.life - end + def each_index + return to_enum(__method__) unless block_given? + @size.times {|x| @size.times {|y| yield x,y }} + end - def barren? - @size.times do |i| - @size.times do |j| - return false if @board[i][j].alive? - end - end - true - end + def [](x, y) + @board[y][x] + end - def life - indices = [] - @size.times do |x| - @size.times do |y| - if @board[y][x].alive? - indices << [x,y] - end - end - end - indices - end + def ==(board) + self.life == board.life + end - def display(generation, name) - puts "#{name}: generation #{generation}" - @board.each do |row| - row.each do |cell| - print "#{cell.alive? ? '#' : '.'} " - end - puts - end - puts - end + def barren? + none? {|cell| cell.alive?} + end - def apocalypse - # utility function to entirely clear the game board - @board.each do |row| - row.each do |cell| - if cell.alive? - cell.die - end - end - end - end + def life + each_index.select {|x,y| @board[y][x].alive?} + end + + def display(name, generation) + puts "#{name}: generation #{generation}" + puts @board.map {|row| row.map {|cell| cell.alive? ? '#' : '.'}.join(' ')} + end + + def apocalypse + # utility function to entirely clear the game board + each {|cell| cell.die} + end end class Cell - def initialize is_alive - @is_alive = is_alive - end - - def alive? - @is_alive - end - - def value - if self.alive? - return 1 - else - return 0 - end - end - - def live - @is_alive = true - end - - def die - @is_alive = false - end + def initialize(alive) @alive = alive end + def alive?; @alive end + def value; @alive ? 1 : 0 end + def live; @alive = true end + def die; @alive = false end end -game_of_life = Game.new "blinker", 3, 2, [[1,0],[1,1],[1,2]] -game_of_life = Game.new "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]] -game_of_life = Game.new "random", 5, 10 +Game.new "blinker", 3, 2, [[1,0],[1,1],[1,2]] +Game.new "glider", 4, 4, [[1,0],[2,1],[0,2],[1,2],[2,2]] +Game.new "random", 5, 10 diff --git a/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit new file mode 100644 index 0000000000..c1f5784b3a --- /dev/null +++ b/Task/Conways-Game-of-Life/Vedit-macro-language/conways-game-of-life.vedit @@ -0,0 +1,58 @@ +IT("Generation 0 ") IN +IT(".O.") IN +IT(".O.") IN +IT(".O.") + +#9 = 2 // number of generations to calculate +#10 = Cur_Line +#11 = Cur_Col-1 +for (#2 = 1; #2 <= #9; #2++) { + Update() + Get_Key("Next gen...", STATLINE) + Call("calculate") + itoa(#2, 20, LEFT) + GL(1) GC(12) Reg_Ins(20, OVERWRITE) +} +EOF +Return + +// Calculate one generation +:calculate: +Goto_Line(2) +While (At_EOF == 0) { + Search("|A",ERRBREAK) // find next living cell + #3 = Cur_Line + #4 = #7 = #8 = Cur_Col + if (#4 > 1) { // increment cell at left + #7 = #4-1 + Goto_Col(#7) + Ins_Char(Cur_Char+1,OVERWRITE) + } + if (#4 < #11) { // increment cell at right + #8 = #4+1 + Goto_Col(#8) + Ins_Char(Cur_Char+1,OVERWRITE) + } + if (#3 > 2) { // increment 3 cells above + Goto_Line(#3-1) + Call("inc_3") + } + if (#3 < #10) { // increment 3 cells below + Goto_Line(#3+1) + Call("inc_3") + } + Goto_Line(#3) + Goto_Col(#4+1) +} + +Replace("[1QR]", "O", REGEXP+BEGIN+ALL) // these cells alive +Replace("[/-7P-X]", ".", REGEXP+BEGIN+ALL) // these cells dead +Return + +// increment values of 3 characters in a row +:inc_3: +for (#1 = #7; #1 <= #8; #1++) { + Goto_Col(#1) + Ins_Char(Cur_Char+1,OVERWRITE) +} +Return diff --git a/Task/Copy-a-string/00DESCRIPTION b/Task/Copy-a-string/00DESCRIPTION index 8e5efbca12..094ec6d895 100644 --- a/Task/Copy-a-string/00DESCRIPTION +++ b/Task/Copy-a-string/00DESCRIPTION @@ -1 +1,4 @@ -This task is about copying a string. Where it is relevant, distinguish between copying the contents of a string versus making an additional reference to an existing string. +{{omit from|bc}} +This task is about copying a string. +Where it is relevant, distinguish between copying the contents of a string +versus making an additional reference to an existing string. diff --git a/Task/Copy-a-string/00META.yaml b/Task/Copy-a-string/00META.yaml index 3bdc51ea57..9ec0e0a94f 100644 --- a/Task/Copy-a-string/00META.yaml +++ b/Task/Copy-a-string/00META.yaml @@ -1,4 +1,5 @@ --- category: - String manipulation +- Simple note: Basic language learning diff --git a/Task/Copy-a-string/Babel/copy-a-string.pb b/Task/Copy-a-string/Babel/copy-a-string.pb new file mode 100644 index 0000000000..852e410cac --- /dev/null +++ b/Task/Copy-a-string/Babel/copy-a-string.pb @@ -0,0 +1,4 @@ +"Hello, world\n" dup cp +str2ar dup 'Y' str2ar 0 paste ar2str +<< +<< diff --git a/Task/Copy-a-string/REXX/copy-a-string.rexx b/Task/Copy-a-string/REXX/copy-a-string.rexx index cb58d9bd01..6d7223de5c 100644 --- a/Task/Copy-a-string/REXX/copy-a-string.rexx +++ b/Task/Copy-a-string/REXX/copy-a-string.rexx @@ -1,3 +1,2 @@ src = "this is a string" -

Note that all REXX values (variables) are stored as character strings. dst = src diff --git a/Task/Copy-a-string/Ruby/copy-a-string-1.rb b/Task/Copy-a-string/Ruby/copy-a-string-1.rb new file mode 100644 index 0000000000..fae1da61bb --- /dev/null +++ b/Task/Copy-a-string/Ruby/copy-a-string-1.rb @@ -0,0 +1,9 @@ +original = "hello" +reference = original # copies reference +copy1 = original.dup # instance of original.class +copy2 = String.new(original) # instance of String + +original << " world!" # append +p reference #=> "hello world!" +p copy1 #=> "hello" +p copy2 #=> "hello" diff --git a/Task/Copy-a-string/Ruby/copy-a-string-2.rb b/Task/Copy-a-string/Ruby/copy-a-string-2.rb new file mode 100644 index 0000000000..5f65e0bdfc --- /dev/null +++ b/Task/Copy-a-string/Ruby/copy-a-string-2.rb @@ -0,0 +1,7 @@ +original = "hello".freeze # prevents further modifications +copy1 = original.dup # copies contents (without status) +copy2 = original.clone # copies contents (with status) +p copy1.frozen? #=> false +p copy1 << " world!" #=> "hello world!" +p copy2.frozen? #=> true +p copy2 << " world!" #=> can't modify frozen String (RuntimeError) diff --git a/Task/Copy-a-string/Ruby/copy-a-string.rb b/Task/Copy-a-string/Ruby/copy-a-string.rb deleted file mode 100644 index 12dff3df12..0000000000 --- a/Task/Copy-a-string/Ruby/copy-a-string.rb +++ /dev/null @@ -1,4 +0,0 @@ -original = "hello" -reference = original -copy1 = original.dup # instance of original.class -copy2 = String.new(original) # instance of String diff --git a/Task/Copy-a-string/Vim-Script/copy-a-string.vim b/Task/Copy-a-string/Vim-Script/copy-a-string.vim new file mode 100644 index 0000000000..adff2b1518 --- /dev/null +++ b/Task/Copy-a-string/Vim-Script/copy-a-string.vim @@ -0,0 +1,6 @@ +let str1 = "original string" +let str2 = str1 +let str1 = "new string" + +echo "String 1:" str1 +echo "String 2:" str2 diff --git a/Task/Count-in-factors/Ada/count-in-factors.ada b/Task/Count-in-factors/Ada/count-in-factors.ada index 560a84c10e..d8647d3ba1 100644 --- a/Task/Count-in-factors/Ada/count-in-factors.ada +++ b/Task/Count-in-factors/Ada/count-in-factors.ada @@ -1,39 +1,8 @@ -with Ada.Command_Line; -with Ada.Text_IO; +with Ada.Command_Line, Ada.Text_IO, Prime_Numbers; procedure Count is - type Number_List is array (Positive range <>) of Positive; - - function Decompose (N : Natural) return Number_List is - Size : Natural := 0; - M : Natural := N; - K : Natural := 2; - begin - if N = 1 then - return (1 => 1); - end if; - -- Estimation of the result length from above - while M >= 2 loop - M := (M + 1) / 2; - Size := Size + 1; - end loop; - M := N; - -- Filling the result with prime numbers - declare - Result : Number_List (1 .. Size); - Index : Positive := 1; - begin - while N >= K loop -- Divisors loop - while 0 = (M mod K) loop -- While divides - Result (Index) := K; - Index := Index + 1; - M := M / K; - end loop; - K := K + 1; - end loop; - return Result (1 .. Index - 1); - end; - end Decompose; + package Prime_Nums is new Prime_Numbers + (Number => Natural, Zero => 0, One => 1, Two => 2); use Prime_Nums; procedure Put (List : Number_List) is begin @@ -46,11 +15,11 @@ procedure Count is end Put; N : Natural := 1; - Max_N : Natural := 15; + Max_N : Natural := 15; -- the default for Max_N begin - if Ada.Command_Line.Argument_Count = 1 then + if Ada.Command_Line.Argument_Count = 1 then -- read Max_N from command line Max_N := Integer'Value (Ada.Command_Line.Argument (1)); - end if; + end if; -- else use the default loop Ada.Text_IO.Put (Integer'Image (N) & ": "); Put (Decompose (N)); diff --git a/Task/Count-in-factors/C++/count-in-factors.cpp b/Task/Count-in-factors/C++/count-in-factors.cpp new file mode 100644 index 0000000000..9b630902a6 --- /dev/null +++ b/Task/Count-in-factors/C++/count-in-factors.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +using namespace std; + +void getPrimeFactors( int li ) +{ + int f = 2; string res; + if( li == 1 ) res = "1"; + else + { + while( true ) + { + if( !( li % f ) ) + { + stringstream ss; ss << f; + res += ss.str(); + li /= f; if( li == 1 ) break; + res += " x "; + } + else f++; + } + } + cout << res << "\n"; +} + +int main( int argc, char* argv[] ) +{ + for( int x = 1; x < 101; x++ ) + { + cout << right << setw( 4 ) << x << ": "; + getPrimeFactors( x ); + } + cout << 2144 << ": "; getPrimeFactors( 2144 ); + cout << "\n\n"; + return system( "pause" ); +} diff --git a/Task/Count-in-factors/Eiffel/count-in-factors.e b/Task/Count-in-factors/Eiffel/count-in-factors.e new file mode 100644 index 0000000000..be90caa806 --- /dev/null +++ b/Task/Count-in-factors/Eiffel/count-in-factors.e @@ -0,0 +1,33 @@ +class + COUNT_IN_FACTORS + +feature + display_factor(p: INTEGER) + --- uses the feature factor (Task: prime decomposition) + require + p_positive: p>0 + local + i,j:INTEGER + factors: ARRAY[INTEGER] + do + create factors.make_empty + from + i:= 1 + until + i>p + loop + io.put_string ("%N" + i.out + " ") + factors:= factor(i) + io.put_string (factors[1].out) + from + j:= 2 + until + j> factors.count + loop + io.put_string (" x " + factors[j].out) + j:= j +1 + end + i:= i+1 + end + end +end diff --git a/Task/Count-in-factors/Perl/count-in-factors-1.pl b/Task/Count-in-factors/Perl/count-in-factors-1.pl new file mode 100644 index 0000000000..24c6a047f1 --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-1.pl @@ -0,0 +1,2 @@ +use ntheory qw/factor/; +print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010; diff --git a/Task/Count-in-factors/Perl/count-in-factors-2.pl b/Task/Count-in-factors/Perl/count-in-factors-2.pl new file mode 100644 index 0000000000..5ba0ef1e13 --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-2.pl @@ -0,0 +1,6 @@ +use Math::Pari qw/factorint/; +sub factor { + my ($pn,$pc) = @{Math::Pari::factorint(shift)}; + return map { ($pn->[$_]) x $pc->[$_] } 0 .. $#$pn; +} +print "$_ = ", join(" x ", factor($_)), "\n" for 1000000000000000000 .. 1000000000000000010; diff --git a/Task/Count-in-factors/Perl/count-in-factors-3.pl b/Task/Count-in-factors/Perl/count-in-factors-3.pl new file mode 100644 index 0000000000..09ebfd944e --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-3.pl @@ -0,0 +1,2 @@ +use Math::Factor::XS qw/prime_factors/; +print "$_ = ", join(" x ", prime_factors($_)), "\n" for 1000000000000000000 .. 1000000000000000010; diff --git a/Task/Count-in-factors/Perl/count-in-factors-4.pl b/Task/Count-in-factors/Perl/count-in-factors-4.pl new file mode 100644 index 0000000000..e5acfb4eee --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-4.pl @@ -0,0 +1,16 @@ +sub factors { + my($n, $p, @out) = (shift, 3); + return if $n < 1; + while (!($n&1)) { $n >>= 1; push @out, 2; } + while ($n > 1 && $p*$p <= $n) { + while ( ($n % $p) == 0) { + $n /= $p; + push @out, $p; + } + $p += 2; + } + push @out, $n if $n > 1; + @out; +} + +print "$_ = ", join(" x ", factors($_)), "\n" for 100000000000 .. 100000000100; diff --git a/Task/Count-in-factors/Perl/count-in-factors-5.pl b/Task/Count-in-factors/Perl/count-in-factors-5.pl new file mode 100644 index 0000000000..bd3fce9d46 --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-5.pl @@ -0,0 +1,16 @@ +tie my @primes, 'Tie::SieveOfEratosthenes'; + +sub factors { + my($n, $i, $p, @out) = (shift, 0, 2); + while ($n >= $p * $p) { + while ($n % $p == 0) { + push @out, $p; + $n /= $p; + } + $p = $primes[++$i]; + } + push @out, $n if $n > 1 || !@out; + @out; +} + +print "$_ = ", join(" x ", factors($_)), "\n" for 100000000000 .. 100000000010; diff --git a/Task/Count-in-factors/Perl/count-in-factors-6.pl b/Task/Count-in-factors/Perl/count-in-factors-6.pl new file mode 100644 index 0000000000..b9665cc505 --- /dev/null +++ b/Task/Count-in-factors/Perl/count-in-factors-6.pl @@ -0,0 +1,32 @@ +#!perl -C +use utf8; +use strict; +use warnings; + +my $limit = 1000; + +print "$_ = $_\n" for 1..3; + +my @p_and_sq = ( [2, 4], [3, 9] ); + +N: for my $n ( 4 .. 1000 ) { + print $n, " = "; + for( my $i = 0; $i <= $#p_and_sq; ++$i ) { + my ($p, $sq) = @{ $p_and_sq[$i] }; + if( $sq > $n ) { + print $n, "\n"; + push @p_and_sq, [ $n, $n*$n ]; + next N; + } + while( 0 == ($n % $p) ) { + print $p; + $n /= $p; + if( $n == 1 ) { + print "\n"; + next N; + } + print " × "; + } + } + die "Ran out of primes?!"; +} diff --git a/Task/Count-in-factors/Perl/count-in-factors.pl b/Task/Count-in-factors/Perl/count-in-factors.pl deleted file mode 100644 index 4a16f3863b..0000000000 --- a/Task/Count-in-factors/Perl/count-in-factors.pl +++ /dev/null @@ -1,26 +0,0 @@ -use utf8; -sub factors { - my $n = shift; - my $p = 2; - my @out; - - while ($n >= $p * $p) { - while ($n % $p == 0) { - push @out, $p; - $n /= $p; - } - $p = next_prime($p); - } - push @out, $n if $n > 1 || !@out; - @out; -} - -sub next_prime { - my $p = shift; - do { $p = $p == 2 ? 3 : $p + 2 } until is_prime($p); - $p; -} - -sub is_prime { factors(shift) == 1 } - -print "$_ = ", join(" × ", factors($_)), "\n" for (1 .. 1000); diff --git a/Task/Count-in-factors/REXX/count-in-factors.rexx b/Task/Count-in-factors/REXX/count-in-factors.rexx index ddca145f2a..5d38b2330d 100644 --- a/Task/Count-in-factors/REXX/count-in-factors.rexx +++ b/Task/Count-in-factors/REXX/count-in-factors.rexx @@ -10,8 +10,8 @@ primes=0 /*number of primes detected. */ do n=low to high /*process single number | a range*/ y=factr(n); /*squish (or not) the blanks. */ #=words(translate(y,,'x')) - (n==1) /*# of prime factors. */ - if #==1 then primes=primes+1 /*bump primes counter (exlude 1).*/ - if high\==oHigh then iterate /*only show facters of HIGH is >0*/ + if #==1 then primes=primes+1 /*bump primes counter (exclude 1)*/ + if high\==oHigh then iterate /*only show factors if HIGH is >0*/ say right(n,w) '=' @.# space(y,blanks) /*prime flag, factors.*/ end /*n*/ /*if BLANKS=0, no spaces around X*/ say @@ -23,7 +23,7 @@ if x<2 then return x /*handle a couple special cases. */ 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).*/ + j=5 /*start where 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? */ diff --git a/Task/Count-in-octal/00META.yaml b/Task/Count-in-octal/00META.yaml new file mode 100644 index 0000000000..ae2451129f --- /dev/null +++ b/Task/Count-in-octal/00META.yaml @@ -0,0 +1,5 @@ +--- +category: +- Radices +- Iteration +note: Basic language learning diff --git a/Task/Count-in-octal/D/count-in-octal.d b/Task/Count-in-octal/D/count-in-octal.d index 64d8328190..84f09ae43c 100644 --- a/Task/Count-in-octal/D/count-in-octal.d +++ b/Task/Count-in-octal/D/count-in-octal.d @@ -1,6 +1,6 @@ -import std.stdio; - void main() { + import std.stdio; + ubyte i; do writefln("%o", i++); while(i); diff --git a/Task/Count-in-octal/REXX/count-in-octal.rexx b/Task/Count-in-octal/REXX/count-in-octal.rexx index 41db76f767..6be820e8a3 100644 --- a/Task/Count-in-octal/REXX/count-in-octal.rexx +++ b/Task/Count-in-octal/REXX/count-in-octal.rexx @@ -1,19 +1,17 @@ /*REXX program counts in octal until the number exceeds #pgm statements.*/ - /*┌────────────────────────────────────────────────────────────────────┐ │ Count all the protons (and electrons!) in the universe. │ │ │ - │ According to Sir Author Eddington in 1938 at his Tamer Lecture at │ - │ Trinity Collecge (Cambridge), he postulated that there are exactly │ + │ According to Sir Arthur Eddington in 1938 at his Tamer Lecture at │ + │ Trinity College (Cambridge), he postulated that there are exactly │ │ │ - │ 136 ∙ 2^245 │ + │ 136 ∙ 2^256 │ │ │ │ protons in the universe, and the same number of electrons, which │ │ is equal to around 1.57477e+79. │ │ │ │ [Although, a modern estimate is around 10^80.] │ └────────────────────────────────────────────────────────────────────┘*/ - numeric digits 100000 /*handle almost all big numbers. */ numIn=right('number in', 20) /*used for indentation of output.*/ w=length(sourceline()) /*used for formatting width of #s*/ @@ -26,8 +24,7 @@ w=length(sourceline()) /*used for formatting width of #s*/ o=o'0'substr(_,k,3) end /*k*/ - say numIn 'base ten = ' right(#,w) numIn "octal = " right(b2x(o)+0,w+w) - - if #>sourceline() then leave /*stop if #protons > program statements.*/ + say numIn 'base ten = ' right(#,w) numIn "octal = " right(b2x(o)+0,w+w) + if #>sourceline() then leave /*stop if #protons>pgm statements*/ end /*#*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Count-in-octal/Ruby/count-in-octal.rb b/Task/Count-in-octal/Ruby/count-in-octal.rb index 8418bf9b82..8701c9aaae 100644 --- a/Task/Count-in-octal/Ruby/count-in-octal.rb +++ b/Task/Count-in-octal/Ruby/count-in-octal.rb @@ -13,3 +13,8 @@ end 0.upto(1/0.0) do |n| printf "%o\n", n end + +# version 2.1 later +0.step do |n| + puts format("%o", n) +end diff --git a/Task/Count-in-octal/Seed7/count-in-octal.seed7 b/Task/Count-in-octal/Seed7/count-in-octal.seed7 index aa680a484f..95549e63b6 100644 --- a/Task/Count-in-octal/Seed7/count-in-octal.seed7 +++ b/Task/Count-in-octal/Seed7/count-in-octal.seed7 @@ -5,7 +5,7 @@ const proc: main is func var integer: i is 0; begin repeat - writeln(str(i, 8)); + writeln(i radix 8); incr(i); until FALSE; end func; diff --git a/Task/Count-in-octal/Vim-Script/count-in-octal.vim b/Task/Count-in-octal/Vim-Script/count-in-octal.vim new file mode 100644 index 0000000000..fd22ca8578 --- /dev/null +++ b/Task/Count-in-octal/Vim-Script/count-in-octal.vim @@ -0,0 +1,5 @@ +let counter = 0 +while counter >= 0 + echon printf("%o\n", counter) + let counter += 1 +endwhile diff --git a/Task/Count-occurrences-of-a-substring/00DESCRIPTION b/Task/Count-occurrences-of-a-substring/00DESCRIPTION index 5110419319..13396aedbb 100644 --- a/Task/Count-occurrences-of-a-substring/00DESCRIPTION +++ b/Task/Count-occurrences-of-a-substring/00DESCRIPTION @@ -1,4 +1,6 @@ -The task is to either create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string. The function should take two arguments: the first argument being the string to search and the second a substring to be searched for. It should return an integer count. +The task is to either create a function, or show a built-in function, to count the number of non-overlapping occurrences of a substring inside a string.
+The function should take two arguments: the first argument being the string to search and the second a substring to be searched for.
+It should return an integer count. print countSubstring("the three truths","th") 3 @@ -7,4 +9,5 @@ The task is to either create a function, or show a built-in function, to count t print countSubstring("ababababab","abab") 2 -The matching should yield the highest number of non-overlapping matches. In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page). +The matching should yield the highest number of non-overlapping matches. +In general, this essentially means matching from left-to-right or right-to-left (see proof on talk page). diff --git a/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring.basic b/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-1.basic similarity index 100% rename from Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring.basic rename to Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-1.basic diff --git a/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-2.basic b/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-2.basic new file mode 100644 index 0000000000..ecc8f6ebb6 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/BASIC/count-occurrences-of-a-substring-2.basic @@ -0,0 +1,20 @@ +10 F$ = "TH" +20 S$ = "THE THREE TRUTHS" +30 GOSUB 100"COUNT SUBSTRING +40 PRINT R +50 F$ = "ABAB" +60 S$ = "ABABABABAB" +70 GOSUB 100"COUNT SUBSTRING +80 PRINT R +90 END + +100 R = 0 +110 F = LEN(F$) +120 S = LEN(S$) +130 IF F > S THEN RETURN +140 IF F = 0 THEN RETURN +150 IF F = S AND F$ = S$ THEN R = 1 : RETURN +160 FOR I = 1 TO S - F +170 IF F$ = MID$(S$, I, F) THEN R = R + 1 : I = I + F - 1 +180 NEXT I +190 RETURN diff --git a/Task/Count-occurrences-of-a-substring/PARI-GP/count-occurrences-of-a-substring.pari b/Task/Count-occurrences-of-a-substring/PARI-GP/count-occurrences-of-a-substring.pari new file mode 100644 index 0000000000..a8c7d2234d --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/PARI-GP/count-occurrences-of-a-substring.pari @@ -0,0 +1,14 @@ +subvec(v,u)={ + my(i=1,s); + while(i+#u<=#v, + for(j=1,#u, + if(v[i+j-1]!=u[j], i++; next(2)) + ); + s++; + i+=#u + ); + s +}; +substr(s1,s2)=subvec(Vec(s1),Vec(s2)); +substr("the three truths","th") +substr("ababababab","abab") diff --git a/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-1.pro b/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-1.pro new file mode 100644 index 0000000000..1efa0c1a4e --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-1.pro @@ -0,0 +1,16 @@ +count_substring(String, Sub, Total) :- + count_substring(String, Sub, 0, Total). + +count_substring(String, Sub, Count, Total) :- + ( substring_rest(String, Sub, Rest) + -> + succ(Count, NextCount), + count_substring(Rest, Sub, NextCount, Total) + ; + Total = Count + ). + +substring_rest(String, Sub, Rest) :- + sub_string(String, Before, Length, Remain, Sub), + DropN is Before + Length, + sub_string(String, DropN, Remain, 0, Rest). diff --git a/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-2.pro b/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-2.pro new file mode 100644 index 0000000000..3e1c3cd891 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Prolog/count-occurrences-of-a-substring-2.pro @@ -0,0 +1,5 @@ +?- count_substring("the three truths","th",X). +X = 3. + +?- count_substring("ababababab","abab",X). +X = 2. diff --git a/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx b/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx index d7eb4f4eea..39ee54a226 100644 --- a/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx +++ b/Task/Count-occurrences-of-a-substring/REXX/count-occurrences-of-a-substring.rexx @@ -1,15 +1,16 @@ -/*REXX program: use a subroutine that counts occurrences of a substring.*/ +/*REXX program counts occurrences of a substring (with no overlap). */ bag = "the three truths" x = "th" - say left(bag,30) left(x,15) 'found' countstr(bag,x) + say left(bag,30) left(x,15) 'found' countstr(bag,x) bag = "ababababab" x = "abab" - say left(bag,30) left(x,15) 'found' countstr(bag,x) + say left(bag,30) left(x,15) 'found' countstr(bag,x) exit /*stick a fork in it, we're done.*/ /*─────────────────────────────────────COUNTSTR subroutine──────────────*/ -countstr: procedure; parse arg haystack, needle, startAt -if startAt=='' then startAt=1; width=length(needle) - do k=0 until _==0; _=pos(needle,haystack,startAt) - startAt = _ + width - end /*k*/ +countstr: procedure; parse arg haystack, needle, startAt +if startAt=='' then startAt=1; width=length(needle) + + do k=0 until _==0; _=pos(needle,haystack,startAt) + startAt = _ + width + end /*k*/ return k diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-1.scala similarity index 71% rename from Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring.scala rename to Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-1.scala index 9830defcf0..45abf635be 100644 --- a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring.scala +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-1.scala @@ -6,6 +6,3 @@ def countSubstring(str1:String, str2:String):Int={ } count(0,0) } - -println(countSubstring("ababababab", "abab")) -println(countSubstring("the three truths", "th")) diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala new file mode 100644 index 0000000000..8738e236f0 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-2.scala @@ -0,0 +1 @@ +def countSubstring( str:String, substr:String ) = substr.r.findAllMatchIn(str).length diff --git a/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala new file mode 100644 index 0000000000..6930881857 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Scala/count-occurrences-of-a-substring-3.scala @@ -0,0 +1,2 @@ +println(countSubstring("ababababab", "abab")) +println(countSubstring("the three truths", "th")) diff --git a/Task/Count-occurrences-of-a-substring/Scheme/count-occurrences-of-a-substring.ss b/Task/Count-occurrences-of-a-substring/Scheme/count-occurrences-of-a-substring.ss new file mode 100644 index 0000000000..f96dd3fdc9 --- /dev/null +++ b/Task/Count-occurrences-of-a-substring/Scheme/count-occurrences-of-a-substring.ss @@ -0,0 +1,6 @@ +gosh> (use gauche.lazy) +# +gosh> (length (lrxmatch "th" "the three truths")) +3 +gosh> (length (lrxmatch "abab" "ababababab")) +2 diff --git a/Task/Count-the-coins/ALGOL-68/count-the-coins.alg b/Task/Count-the-coins/ALGOL-68/count-the-coins.alg new file mode 100644 index 0000000000..d7d5139d47 --- /dev/null +++ b/Task/Count-the-coins/ALGOL-68/count-the-coins.alg @@ -0,0 +1,31 @@ +# + Rosetta Code "Count the coins" + This is a direct translation of a Haskell version, using an array rather than + a list. LWB, UPB, and array slicing makes the mapping very simple: + + LWB > UPB <=> [] + LWB = UPB <=> [x] + a[LWB a] <=> head xs + a[LWB a + 1:] <=> tail xs +# + +BEGIN + PROC ways to make change = ([] INT denoms, INT amount) INT : + BEGIN + IF amount = 0 THEN + 1 + ELIF LWB denoms > UPB denoms THEN + 0 + ELIF LWB denoms = UPB denoms THEN + (amount MOD denoms[LWB denoms] = 0 | 1 | 0) + ELSE + INT sum := 0; + FOR i FROM 0 BY denoms[LWB denoms] TO amount DO + sum +:= ways to make change(denoms[LWB denoms + 1:], amount - i) + OD; + sum + FI + END; + [] INT denoms = (25, 10, 5, 1); + print((ways to make change(denoms, 100), newline)) +END diff --git a/Task/Count-the-coins/Clojure/count-the-coins.clj b/Task/Count-the-coins/Clojure/count-the-coins.clj new file mode 100644 index 0000000000..5877a7b0f2 --- /dev/null +++ b/Task/Count-the-coins/Clojure/count-the-coins.clj @@ -0,0 +1,14 @@ +(def denomination-kind [1 5 10 25]) + +(defn- cc [amount denominations] + (cond (= amount 0) 1 + (or (< amount 0) (empty? denominations)) 0 + :else (+ (cc amount (rest denominations)) + (cc (- amount (first denominations)) denominations)))) + +(defn count-change + "Calculates the number of times you can give change with the given denominations." + [amount denominations] + (cc amount denominations)) + +(count-change 15 denomination-kind) ; = 6 diff --git a/Task/Count-the-coins/Common-Lisp/count-the-coins-1.lisp b/Task/Count-the-coins/Common-Lisp/count-the-coins-1.lisp new file mode 100644 index 0000000000..b2750608a1 --- /dev/null +++ b/Task/Count-the-coins/Common-Lisp/count-the-coins-1.lisp @@ -0,0 +1,18 @@ +(defun count-change (amount coins + &optional + (length (1- (length coins))) + (cache (make-array (list (1+ amount) (length coins)) + :initial-element nil))) + (cond ((< length 0) 0) + ((< amount 0) 0) + ((= amount 0) 1) + (t (or (aref cache amount length) + (setf (aref cache amount length) + (+ (count-change (- amount (first coins)) coins length cache) + (count-change amount (rest coins) (1- length) cache))))))) + +; (compile 'count-change) ; for CLISP + +(print (count-change 100 '(25 10 5 1))) ; = 242 +(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501 +(terpri) diff --git a/Task/Count-the-coins/Common-Lisp/count-the-coins-2.lisp b/Task/Count-the-coins/Common-Lisp/count-the-coins-2.lisp new file mode 100644 index 0000000000..b5c19abec4 --- /dev/null +++ b/Task/Count-the-coins/Common-Lisp/count-the-coins-2.lisp @@ -0,0 +1,6 @@ +(defun count-change (amount coins &aux (ways (make-array (1+ amount) :initial-element 0))) + (setf (aref ways 0) 1) + (loop for coin in coins do + (loop for j from coin upto amount + do (incf (aref ways j) (aref ways (- j coin))))) + (aref ways amount)) diff --git a/Task/Count-the-coins/Common-Lisp/count-the-coins.lisp b/Task/Count-the-coins/Common-Lisp/count-the-coins.lisp deleted file mode 100644 index 7ce5f072e2..0000000000 --- a/Task/Count-the-coins/Common-Lisp/count-the-coins.lisp +++ /dev/null @@ -1,23 +0,0 @@ -(defun count-change (amount coins) - (let ((cache (make-array (list (1+ amount) (length coins)) - :initial-element nil))) - (macrolet ((h () `(aref cache n l))) - (labels - ((recur (n coins &optional (l (1- (length coins)))) - (cond ((< l 0) 0) - ((< n 0) 0) - ((= n 0) 1) - (t (if (h) (h) ; cached - (setf (h) ; or not - (+ (recur (- n (car coins)) coins l) - (recur n (cdr coins) (1- l))))))))) - - ;; enable next line if recursions too deep - ;(loop for i from 0 below amount do (recur i coins)) - (recur amount coins))))) - -; (compile 'count-change) ; for CLISP - -(print (count-change 100 '(25 10 5 1))) ; = 242 -(print (count-change 100000 '(100 50 25 10 5 1))) ; = 13398445413854501 -(terpri) diff --git a/Task/Count-the-coins/D/count-the-coins-1.d b/Task/Count-the-coins/D/count-the-coins-1.d index b6fcffa8f3..2207ac0496 100644 --- a/Task/Count-the-coins/D/count-the-coins-1.d +++ b/Task/Count-the-coins/D/count-the-coins-1.d @@ -4,12 +4,12 @@ auto changes(int amount, int[] coins) { auto ways = new BigInt[amount + 1]; ways[0] = 1; foreach (coin; coins) - foreach (j; coin .. amount+1) + foreach (j; coin .. amount + 1) ways[j] += ways[j - coin]; - return ways[amount]; + return ways[$ - 1]; } void main() { - writeln(changes( 1_00, [25, 10, 5, 1])); - writeln(changes(1000_00, [100, 50, 25, 10, 5, 1])); + changes( 1_00, [25, 10, 5, 1]).writeln; + changes(1000_00, [100, 50, 25, 10, 5, 1]).writeln; } 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 79ceae3c35..92763c38bc 100644 --- a/Task/Count-the-coins/D/count-the-coins-2.d +++ b/Task/Count-the-coins/D/count-the-coins-2.d @@ -1,42 +1,21 @@ -import std.stdio, std.bigint; +import std.stdio, core.checkedint; -BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ { - immutable n = coins.length; - int cycle; - foreach (immutable c; coins) - if (c <= amount && c >= cycle) - cycle = c + 1; - cycle *= n; - auto table = new BigInt[cycle]; - table[0 .. n] = 1.BigInt; - - int pos = n; - foreach (immutable s; 1 .. amount + 1) { - foreach (immutable i; 0 .. n) { - if (i == 0 && pos >= cycle) - pos = 0; - if (coins[i] <= s) { - immutable int q = pos - (coins[i] * n); - table[pos] = (q >= 0) ? table[q] : table[q + cycle]; - } - if (i) - table[pos] += table[pos - 1]; - pos++; - } - } - - return table[pos - 1]; +auto changes(int amount, int[] coins, ref bool overflow) { + auto ways = new ulong[amount + 1]; + ways[0] = 1; + foreach (coin; coins) + foreach (j; coin .. amount + 1) + ways[j] = ways[j].addu(ways[j - coin], overflow); + return ways[amount]; } void main() { - immutable usCoins = [100, 50, 25, 10, 5, 1]; - immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1]; - - 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; - } + bool overflow = false; + changes( 1_00, [25, 10, 5, 1], overflow).writeln; + if (overflow) + "Overflow".puts; + overflow = false; + changes( 1000_00, [100, 50, 25, 10, 5, 1], overflow).writeln; + if (overflow) + "Overflow".puts; } 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 77ce234d9c..79ceae3c35 100644 --- a/Task/Count-the-coins/D/count-the-coins-3.d +++ b/Task/Count-the-coins/D/count-the-coins-3.d @@ -1,49 +1,31 @@ -import std.stdio, std.bigint, std.algorithm, std.conv, std.functional; +import std.stdio, std.bigint; -struct Ucent { /// Simplified 128-bit integer (like ucent). - ulong hi, lo; - static immutable one = Ucent(0, 1); - - void opOpAssign(string op="+")(in ref Ucent y) pure nothrow { - this.hi += y.hi; - if (this.lo >= ~y.lo) - this.hi++; - this.lo += y.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 { +BigInt countChanges(in int amount, in int[] coins) pure /*nothrow*/ { immutable n = coins.length; + int cycle; + foreach (immutable c; coins) + if (c <= amount && c >= cycle) + cycle = c + 1; + cycle *= n; + auto table = new BigInt[cycle]; + table[0 .. n] = 1.BigInt; - // 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 (immutable i; 0 .. n) { - if (i) - p[i] = coins[i - 1] + p[i - 1]; - *p[i] = Ucent.one; - q[i] = p[i]; + int pos = n; + foreach (immutable s; 1 .. amount + 1) { + foreach (immutable i; 0 .. n) { + if (i == 0 && pos >= cycle) + pos = 0; + if (coins[i] <= s) { + immutable int q = pos - (coins[i] * n); + table[pos] = (q >= 0) ? table[q] : table[q + cycle]; + } + if (i) + table[pos] += table[pos - 1]; + pos++; + } } - Ucent prev; - 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; - if (i) - *q[i] += prev; - prev = *q[i]; - } - - return prev; + return table[pos - 1]; } void main() { diff --git a/Task/Count-the-coins/D/count-the-coins-4.d b/Task/Count-the-coins/D/count-the-coins-4.d index 73cb6a7fdd..97219632f6 100644 --- a/Task/Count-the-coins/D/count-the-coins-4.d +++ b/Task/Count-the-coins/D/count-the-coins-4.d @@ -1,32 +1,60 @@ -import std.stdio, std.conv, std.string, std.algorithm, std.range; +import std.stdio, std.bigint, std.algorithm, std.conv, std.functional; -void printChange(in uint tot, in uint[] coins) -in { - assert(coins.isSorted); -} body { - auto freqs = new uint[coins.length]; +struct Ucent { /// Simplified 128-bit integer (like ucent). + ulong hi, lo; + static immutable one = Ucent(0, 1); - void inner(in uint curTot, in size_t start) { - if (curTot == tot) - return writefln("%-(%s %)", - zip(coins, freqs) - .filter!(cf => cf[1] != 0) - .map!(cf => format("%u:%u", cf[]))); - - foreach (immutable i; start .. coins.length) { - immutable ci = coins[i]; - for (auto v = (freqs[i] + 1) * ci; v <= tot; v += ci) - if (curTot + v <= tot) { - freqs[i] += v / ci; - inner(curTot + v, i + 1); - freqs[i] -= v / ci; - } - } + void opOpAssign(string op="+")(in ref Ucent y) pure nothrow @nogc @safe { + this.hi += y.hi; + if (this.lo >= ~y.lo) + this.hi++; + this.lo += y.lo; } - inner(0, 0); + string toString() const /*pure nothrow @safe*/ { + return text((this.hi.BigInt << 64) + this.lo); + } +} + +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]; + auto q = new Ucent*[n]; // iterates it. + auto buf = new Ucent[coins.sum]; + + p[0] = buf.ptr; + foreach (immutable i; 0 .. n) { + if (i) + p[i] = coins[i - 1] + p[i - 1]; + *p[i] = Ucent.one; + q[i] = p[i]; + } + + Ucent prev; + 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; + if (i) + *q[i] += prev; + prev = *q[i]; + } + + return prev; } void main() { - printChange(1_00, [1, 5, 10, 25]); + immutable usCoins = [100, 50, 25, 10, 5, 1]; + immutable euCoins = [200, 100, 50, 20, 10, 5, 2, 1]; + + 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-5.d b/Task/Count-the-coins/D/count-the-coins-5.d new file mode 100644 index 0000000000..73cb6a7fdd --- /dev/null +++ b/Task/Count-the-coins/D/count-the-coins-5.d @@ -0,0 +1,32 @@ +import std.stdio, std.conv, std.string, std.algorithm, std.range; + +void printChange(in uint tot, in uint[] coins) +in { + assert(coins.isSorted); +} body { + auto freqs = new uint[coins.length]; + + void inner(in uint curTot, in size_t start) { + if (curTot == tot) + return writefln("%-(%s %)", + zip(coins, freqs) + .filter!(cf => cf[1] != 0) + .map!(cf => format("%u:%u", cf[]))); + + foreach (immutable i; start .. coins.length) { + immutable ci = coins[i]; + for (auto v = (freqs[i] + 1) * ci; v <= tot; v += ci) + if (curTot + v <= tot) { + freqs[i] += v / ci; + inner(curTot + v, i + 1); + freqs[i] -= v / ci; + } + } + } + + inner(0, 0); +} + +void main() { + printChange(1_00, [1, 5, 10, 25]); +} diff --git a/Task/Count-the-coins/REXX/count-the-coins-1.rexx b/Task/Count-the-coins/REXX/count-the-coins-1.rexx new file mode 100644 index 0000000000..2d33e55871 --- /dev/null +++ b/Task/Count-the-coins/REXX/count-the-coins-1.rexx @@ -0,0 +1,21 @@ +/*REXX program makes change from some amount with various specie (coins)*/ +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.*/ + $.j=word($,j) /*define a stemmed array element.*/ + end /*j*/ + +say 'with an amount of ' N " cents, there are " kaChing(N, coins) +say 'ways to make change with coins of the following denominations: ' $ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────KACHING subroutine──────────────────*/ +kaChing: procedure expose $.; parse arg a,k /*sub is recursive. */ +if a==0 then return 1 /*unroll special case*/ +if k==1 then return 1 /* " " " */ +if k==2 then f=1 /*handle special case*/ + else f=kaChing(a, k-1) /*recurse the amount.*/ +if a==$.k then return f + 1 /*handle special case*/ +if a <$.k then return f /* " " " */ + return f + kaChing(a-$.k, k) /*use diminished $. */ diff --git a/Task/Count-the-coins/REXX/count-the-coins-2.rexx b/Task/Count-the-coins/REXX/count-the-coins-2.rexx new file mode 100644 index 0000000000..1fc2d16141 --- /dev/null +++ b/Task/Count-the-coins/REXX/count-the-coins-2.rexx @@ -0,0 +1,24 @@ +/*REXX program makes change from some amount with various specie (coins)*/ +numeric digits 20 /*be able to handle large amounts*/ +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*/ +!.=. /*used for memoization for A & K.*/ + 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 " cents, there are " kaChing(N, coins) +say 'ways to make change with coins of the following denominations: ' $ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────KACHING subroutine──────────────────*/ +kaChing: procedure expose $. !.; parse arg a,k /*sub is recursive. */ +if a==0 then return 1 /*unroll special case*/ +if k==1 then return 1 /* " " " */ +if k==2 then f=1 /*handle special case*/ + else f=kaChing(a,k-1) /*recurse the amount.*/ +if !.a.k\==. then return !.a.k /*found A & K before?*/ +if a==$.k then do; !.a.k=f+1; return f+1; end /*handle special case*/ +if a <$.k then do; !.a.k=f; return f; end /* " " " */ +!.a.k=f + kaChing(a-$.k, k); return !.a.k /*compute,set,return.*/ diff --git a/Task/Count-the-coins/REXX/count-the-coins.rexx b/Task/Count-the-coins/REXX/count-the-coins.rexx deleted file mode 100644 index 8587da2cfe..0000000000 --- a/Task/Count-the-coins/REXX/count-the-coins.rexx +++ /dev/null @@ -1,23 +0,0 @@ -/*REXX program makes change from some amount with various specie (coins)*/ -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.*/ - $.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: ' $ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────kaChing subroutine──────────────────*/ -kaChing: procedure expose $.; parse arg a,k /*this sub is recused.*/ - -if a==0 then f=1 /*unroll some special cases. */ - else if k==1 then f=0 /*unroll some more special cases.*/ - else f=kaChing(a, k-1) /*recurse the amount.*/ - -if a==$.k then return f+1 /*handle another special case. */ -if a <$.k then return f /*if amount is >SOURCE FORMAT IS FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. MAKE-TAPE-FILE. + +ENVIRONMENT DIVISION. +INPUT-OUTPUT SECTION. +FILE-CONTROL. + SELECT TAPE-FILE + ASSIGN "./TAPE.FILE" + ORGANIZATION IS LINE SEQUENTIAL. + +DATA DIVISION. +FILE SECTION. +FD TAPE-FILE. +01 TAPE-FILE-RECORD PIC X(51). + +PROCEDURE DIVISION. + OPEN OUTPUT SHARING WITH ALL OTHER TAPE-FILE + WRITE TAPE-FILE-RECORD + FROM "COBOL treats tape files and text files identically." + END-WRITE + STOP RUN. diff --git a/Task/Create-a-file-on-magnetic-tape/Clojure/create-a-file-on-magnetic-tape.clj b/Task/Create-a-file-on-magnetic-tape/Clojure/create-a-file-on-magnetic-tape.clj new file mode 100644 index 0000000000..82ebb57b78 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Clojure/create-a-file-on-magnetic-tape.clj @@ -0,0 +1 @@ +(spit "/dev/tape" "Hello, World!") diff --git a/Task/Create-a-file-on-magnetic-tape/Go/create-a-file-on-magnetic-tape.go b/Task/Create-a-file-on-magnetic-tape/Go/create-a-file-on-magnetic-tape.go new file mode 100644 index 0000000000..d11a896feb --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Go/create-a-file-on-magnetic-tape.go @@ -0,0 +1,53 @@ +package main + +import ( + "archive/tar" + "compress/gzip" + "flag" + "io" + "log" + "os" + "time" +) + +func main() { + filename := flag.String("file", "TAPE.FILE", "filename within TAR") + data := flag.String("data", "", "data for file") + outfile := flag.String("out", "", "output file or device (e.g. /dev/tape)") + gzipFlag := flag.Bool("gzip", false, "use gzip compression") + flag.Parse() + + var w io.Writer = os.Stdout + if *outfile != "" { + f, err := os.Create(*outfile) + if err != nil { + log.Fatalf("opening/creating %q: %v", *outfile, err) + } + defer f.Close() + w = f + } + + if *gzipFlag { + zw := gzip.NewWriter(w) + defer zw.Close() + w = zw + } + + tw := tar.NewWriter(w) + defer tw.Close() + w = tw + tw.WriteHeader(&tar.Header{ + Name: *filename, + Mode: 0660, + Size: int64(len(*data)), + ModTime: time.Now(), + Typeflag: tar.TypeReg, + Uname: "guest", + Gname: "guest", + }) + + _, err := w.Write([]byte(*data)) + if err != nil { + log.Fatal("writing data:", err) + } +} diff --git a/Task/Create-a-file-on-magnetic-tape/Icon/create-a-file-on-magnetic-tape.icon b/Task/Create-a-file-on-magnetic-tape/Icon/create-a-file-on-magnetic-tape.icon new file mode 100644 index 0000000000..eda544f6f3 --- /dev/null +++ b/Task/Create-a-file-on-magnetic-tape/Icon/create-a-file-on-magnetic-tape.icon @@ -0,0 +1,3 @@ +procedure main() + write(open("/dev/tape","w"),"Hi") +end diff --git a/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx b/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx index 1cadad83d5..7351d7b32a 100644 --- a/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx +++ b/Task/Create-a-file-on-magnetic-tape/REXX/create-a-file-on-magnetic-tape.rexx @@ -1,13 +1,4 @@ /*REXX pgm demonstrates writing records to an attached magnetic tape.*/ -/* The actual mounting & attaching would be performed by the appropriate*/ -/* operating system (and/or user) commands. DSNAME (below) would be */ -/* the REXX variable that is associated with a dataset that is assigned */ -/* to a magnetic tape device. The association would be different, */ -/* depending on upon the operating system being used. VM/CMS would use */ -/* a CP ATTACH command, coupled with a CMS FILEDEF command which*/ -/* associates a DSNAME (dataset name) that will be written to on the */ -/* attached (and mounted) magnetic tape device. */ - dsName = 'TAPE.FILE' /*dsName of "file" being written.*/ do j=1 for 100 /*write 100 records to mag tape. */ diff --git a/Task/Create-a-file/00META.yaml b/Task/Create-a-file/00META.yaml index 40458d9f21..308143aadb 100644 --- a/Task/Create-a-file/00META.yaml +++ b/Task/Create-a-file/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: File System Operations diff --git a/Task/Create-a-file/Fortran/create-a-file.f b/Task/Create-a-file/Fortran/create-a-file.f index 1a99e9bc02..3876cf3498 100644 --- a/Task/Create-a-file/Fortran/create-a-file.f +++ b/Task/Create-a-file/Fortran/create-a-file.f @@ -1,4 +1,12 @@ +PROGRAM CREATION OPEN (UNIT=5, FILE="output.txt", STATUS="NEW") ! Current directory CLOSE (UNIT=5) OPEN (UNIT=5, FILE="/output.txt", STATUS="NEW") ! Root directory CLOSE (UNIT=5) + +!Directories (Use System from GNU Fortran Compiler) +! -- Added by Anant Dixit, November 2014 +call system("mkdir docs/") +call system("mkdir ~/docs/") + +END PROGRAM diff --git a/Task/Create-a-file/Maple/create-a-file.maple b/Task/Create-a-file/Maple/create-a-file.maple new file mode 100644 index 0000000000..4741ca7a27 --- /dev/null +++ b/Task/Create-a-file/Maple/create-a-file.maple @@ -0,0 +1,4 @@ +FileTools:-Text:-WriteFile("output.txt", ""); # make empty file in current dir +FileTools:-MakeDirectory("docs"); # make empty dir in current dir +FileTools:-Text:-WriteFile("/output.txt", ""); # make empty file in root dir +FileTools:-MakeDirectory("/docs"); # make empty dir in root dir diff --git a/Task/Create-a-file/Scala/create-a-file.scala b/Task/Create-a-file/Scala/create-a-file.scala new file mode 100644 index 0000000000..8eb38ec97b --- /dev/null +++ b/Task/Create-a-file/Scala/create-a-file.scala @@ -0,0 +1,12 @@ +import java.io.File + +object CreateFile extends App { + try { new File("output.txt").createNewFile() } + catch { case e: Exception => println(s"Exception caught: $e with creating output.txt") } + try { new File(s"${File.separator}output.txt").createNewFile() } + catch { case e: Exception => println(s"Exception caught: $e with creating ${File.separator}output.txt") } + try { new File("docs").mkdir() } + catch { case e: Exception => println(s"Exception caught: $e with creating directory docs") } + try { new File(s"${File.separator}docs").mkdir() } + catch { case e: Exception => println(s"Exception caught: $e with creating directory ${File.separator}docs") } +} diff --git a/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-2.c b/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-2.c index 583ce5cfe3..771d86ccbe 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-2.c +++ b/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-2.c @@ -1,20 +1,116 @@ -#include -#include -int main(int argc, char **argv) -{ - int user1 = 0, user2 = 0; - int *a1, **array, row; +/* + assume this file is c.c , + compile and run on linux: cc -Wall -g -DCOMPILE_EXAMPLE c.c -lm -o c && ./c +*/ - printf("Enter two integers. Space delimited, please: "); - scanf("%d %d",&user1, &user2); +#include +#include - a1 = malloc(user1*user2*sizeof(int)); - array = malloc(user2*sizeof(int*)); - for (row=0; row +#include + +#define Z 5 +#define Y 10 +#define X 39 + +#define BIND(A,L,H) ((L)<(A)?(A)<(H)?(A):(H):(L)) + +void p_char(void*pv) { + char s[3]; + int i = 0; + s[i++] = ' ', s[i++] = *(char*)pv, s[i++] = 0; + fputs(s, stdout); +} + +void display(void*a,size_t rank,size_t*shape,void(*f)(void*)) { + int i; + if (0 == rank) + (*f)(a); + else if (1 == rank) { + for (i = 0; i < *shape; ++i) + (*f)(a+i); + putchar('\n'); + } else { + for (i = 0; i < *shape; ++i) + display(((void**)a)[i], rank-1, shape+1, f); + putchar('\n'); + } +} + +int main() { /* character cell 3D graphics. Whoot */ + char***array; + float x,y,z; + size_t rank, shape[3], i, j, k; + rank = 0; + shape[rank++] = Z, shape[rank++] = Y, shape[rank++] = X; + array = allocarray(rank, shape, sizeof(char)); + memset(**array, ' ', X*Y*Z*(sizeof(***array))); /* load the array with spaces */ + for (i = 0; i < X; ++i) { + x = i/(float)X; + for (j = 0; j < Y; ++j) { + y = j/(float)X; + z = x*y*(4*M_PI); + z = 5.2*(0.5+(0.276765 - sin(z)*cos(z)*exp(1-z))/0.844087); /* a somewhat carefully designed silly function */ + /* printf("%g %g %g\n", x, y, z); */ + k = (int)z; + array[BIND(k, 0, Z-1)][j][i] = '@'; /* BIND ensures a valid index */ + } + } + display(array, rank, shape, p_char); + puts("\nIt is what it is."); + free(array); + return EXIT_SUCCESS; +} +#endif diff --git a/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-3.c b/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-3.c index 3af061047b..ca377590aa 100644 --- a/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-3.c +++ b/Task/Create-a-two-dimensional-array-at-runtime/C/create-a-two-dimensional-array-at-runtime-3.c @@ -2,26 +2,18 @@ #include int main(int argc, char **argv) { - int user1 = 0; - int space_needed; - int *a1, **array; - int row, col; + int user1 = 0, user2 = 0; + int *a1, **array, row; - printf("Enter size of array: "); - scanf("%d",&user1); + printf("Enter two integers. Space delimited, please: "); + scanf("%d %d",&user1, &user2); - space_needed = (user1+1)*user1/2; - a1 = malloc(space_needed); + a1 = malloc(user1*user2*sizeof(int)); array = malloc(user1*sizeof(int*)); - for (row=0,offset=0; row -#include +#include int main(int argc, char **argv) { - int user1 = 0, user2 = 0; - int *a1, **array, row; + int user1 = 0; + int space_needed; + int *a1, **array; + int row, col, offset; - printf("Enter two integers. Space delimited, please: "); - scanf("%d %d",&user1, &user2); + printf("Enter size of array: "); + scanf("%d",&user1); - a1 = alloca(user1*user2*sizeof(int)); - array = alloca(user1*sizeof(int*)); - for (row=0; row +#include +int main(int argc, char **argv) +{ + int user1 = 0, user2 = 0; + int *a1, **array, row; + + printf("Enter two integers. Space delimited, please: "); + scanf("%d %d",&user1, &user2); + + a1 = alloca(user1*user2*sizeof(int)); + array = alloca(user1*sizeof(int*)); + for (row=0; row - new XElement - ( + var cols = headers.Select(name => + new XElement( "th", name, new XAttribute("text-align", "center") ) ); - var rows = Enumerable.Range(0, 4) - .Select - ( - rowIndex => - new XElement - ( - "tr", - new XElement("td", rowIndex), - Enumerable.Range(0, 4) - .Select - ( - colIndex => - new XElement - ( - "td", - colIndex, - new XAttribute("text-align", "center") - ) - ) + var rows = Enumerable.Range(0, 4).Select(ri => + new XElement( + "tr", + new XElement("td", ri), + Enumerable.Range(0, 4).Select(ci => + new XElement( + "td", + ci, + new XAttribute("text-align", "center") + ) ) - ); + ) + ); - var xml = new XElement - ( + var xml = new XElement( "table", - new XElement - ( + new XElement( "thead", - new XElement("tr", headerColumns), + new XElement("tr", cols), new XElement("tbody", rows) ) ); diff --git a/Task/Create-an-HTML-table/Clojure/create-an-html-table.clj b/Task/Create-an-HTML-table/Clojure/create-an-html-table.clj new file mode 100644 index 0000000000..51fd1c40d4 --- /dev/null +++ b/Task/Create-an-HTML-table/Clojure/create-an-html-table.clj @@ -0,0 +1,11 @@ +(ns rosettacode.html-table + (:use 'hiccup.core)) + +(defn [el sq] + [:tr (map vector (cycle [el]) sq)]) + +(html + [:table + ( :th ["" \X \Y \Z]) + (for [n (range 1 4)] + (->> #(rand-int 10000) (repeatedly 3) (cons n) ( :td)))]) diff --git a/Task/Create-an-HTML-table/D/create-an-html-table.d b/Task/Create-an-HTML-table/D/create-an-html-table.d index d6333a60b1..dd7b240c26 100644 --- a/Task/Create-an-HTML-table/D/create-an-html-table.d +++ b/Task/Create-an-HTML-table/D/create-an-html-table.d @@ -1,9 +1,9 @@ -import std.stdio, std.random; - void main() { + import std.stdio, std.random; + writeln(``); writeln(""); - foreach (i; 0 .. 4) + foreach (immutable i; 0 .. 4) writefln("", i, uniform(0,1000), uniform(0,1000), uniform(0,1000)); writeln("
XYZ
%d%d%d%d
"); diff --git a/Task/Create-an-HTML-table/Go/create-an-html-table-1.go b/Task/Create-an-HTML-table/Go/create-an-html-table-1.go index c45c450481..2f76572fa5 100644 --- a/Task/Create-an-HTML-table/Go/create-an-html-table-1.go +++ b/Task/Create-an-HTML-table/Go/create-an-html-table-1.go @@ -12,10 +12,10 @@ type row struct { var tmpl = ` -{{range $ix, $row := .}} ` + - `` + - `` + - ` +{{range $ix, $row := .}} + + + {{end}}
XYZ
{{$ix}}{{$row.X}}{{$row.Y}}{{$row.Z}}
{{$ix}}{{$row.X}}{{$row.Y}}{{$row.Z}}
` diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh new file mode 100644 index 0000000000..038d7dc99d --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-1.psh @@ -0,0 +1,7 @@ +# Converts Microsoft .NET Framework objects into HTML that can be displayed in a Web browser. +ConvertTo-Html -inputobject (Get-Date) + +# Create a PowerShell object using a HashTable +$object = New-Object -TypeName PSObject -Property (@{'A'=(Get-Random -Minimum 0 -Maximum 10);'B'=(Get-Random -Minimum 0 -Maximum 10);'C'=(Get-Random -Minimum 0 -Maximum 10)}) + +$object | ConvertTo-Html diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh new file mode 100644 index 0000000000..ae0821366c --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-2.psh @@ -0,0 +1,25 @@ + + + +HTML TABLE + + + + + +
DisplayHintDateTimeDateDayDayOfWeekDayOfYearHourKindMilliseco +ndMinuteMonthSecondTicksTimeOfDayYear
DateTimeSunday, October 26, 2014 2:32:31 PM10/26/2014 12:00:00 AM26Sunday29914< +/td>Local56332103163549930751563463814:32:31.56346382014
+ + + + + +HTML TABLE + + + + + +
CBA
873
+ diff --git a/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh new file mode 100644 index 0000000000..5f5cf4f5a1 --- /dev/null +++ b/Task/Create-an-HTML-table/PowerShell/create-an-html-table-3.psh @@ -0,0 +1 @@ +$object | ConvertTo-Html | Out-File -FilePath $env:temp\test.html ; invoke-item $env:temp\test.html diff --git a/Task/Create-an-HTML-table/PureBasic/create-an-html-table-1.purebasic b/Task/Create-an-HTML-table/PureBasic/create-an-html-table-1.purebasic new file mode 100644 index 0000000000..efb830eb56 --- /dev/null +++ b/Task/Create-an-HTML-table/PureBasic/create-an-html-table-1.purebasic @@ -0,0 +1,40 @@ +Title.s="Create an HTML table" + +head.s="" +head.s+""+Title.s+""+chr(13)+chr(10) + +tablehead.s +tablehead.s+""+chr(13)+chr(10) +tablehead.s+""+chr(13)+chr(10) + +index=0 + +tablebody.s="" +for row=1 to 4 +index+1 +tablebody.s+"" +for col=1 to 3 +tablebody.s+"" +next +tablebody.s+""+chr(13)+chr(10) +next + +tablefoot.s="" +tablefoot.s+"
XYZ
"+str(index)+""+str(Random(9999,1))+"
"+chr(13)+chr(10) + +foot.s="" +foot.s+""+chr(13)+chr(10) + +FileName.s="Create_an_HTML_table.html" +If CreateFile(0,FileName.s) + WriteString(0,head.s) + WriteString(0,tablehead.s) + WriteString(0,tablebody.s) + WriteString(0,tablefoot.s) + WriteString(0,foot.s) + CloseFile(0) + Else + Debug "Not WriteString :"+FileName.s +EndIf + +; RunProgram(FileName.s) diff --git a/Task/Create-an-HTML-table/PureBasic/create-an-html-table-2.purebasic b/Task/Create-an-HTML-table/PureBasic/create-an-html-table-2.purebasic new file mode 100644 index 0000000000..5b83a9535a --- /dev/null +++ b/Task/Create-an-HTML-table/PureBasic/create-an-html-table-2.purebasic @@ -0,0 +1,9 @@ +Create an HTML table + + + + + + +
XYZ
1663858385360
2299538563093
3377644812
4442811003721
+ diff --git a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx index cf270b1745..dea32ed52d 100644 --- a/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx +++ b/Task/Create-an-HTML-table/REXX/create-an-html-table.rexx @@ -1,32 +1,32 @@ -/*REXX program to create an HTML table of five rows and three columns. */ +/*REXX program to create an HTML table of five rows and three columns.*/ +arg rows .; if rows=='' then rows=5 /*no ROWS specified? Use default*/ + cols = 3 /*specify three columns for table*/ + maxRand = 9999 /*4-digit numbers, allow negative*/ +headerInfo = 'X Y Z' /*column header information. */ + oFID = 'a_table.html' /*name of the output file. */ + w = 0 /*number of writes to output file*/ -arg rows .; if rows=='' then rows=5 /*no ROWS specified? Use default*/ - cols=3 - maxRand=9999 /*4-digit numbers, allow negative*/ -headerInfo='X Y Z' /*column header information. */ - oFID='a_table.html' +call wrt "" +call wrt "" +call wrt "" +call wrt "" -call lineout oFid,"" -call lineout oFid,"" -call lineout oFid,"" -call lineout oFid,"
" + do r=0 to rows /* [↓] handle row zero special. */ + if r==0 then call wrt "" + else call wrt "" - do r=0 to rows - if r==0 then call lineout oFid,"" - else call lineout oFid,"" - - do c=1 for cols - if r==0 then call lineout oFid,"" - else call lineout oFid,"" + do c=1 for cols /* [↓] for row zero, add hdrInfo*/ + if r==0 then call wrt "" + else call wrt "" end /*c*/ + end /*r*/ - end /*r*/ - -call lineout oFid,"
" r "
" r "" word(headerInfo,c) "" rnd() "" word(headerInfo,c) "" rnd() "
" -call lineout oFid,"" -call lineout oFid,"" -exit - -/*─────────────────────────────────────RND subroutine───────────────────*/ - /*subroutine was subroutinized for better viewfulabilityness.*/ +call wrt "" +call wrt "" +call wrt "" +say; say w ' records were written to the output file: ' oFID +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one-liner subroutines───────────────*/ rnd: return right(random(0,maxRand*2)-maxRand,5) /*REXX doesn't gen negs*/ +wrt: call lineout oFID,arg(1); say '══►' arg(1); w=w+1; return /*write.*/ + /* [↑] functions were subroutinized for better viewabilityness.*/ diff --git a/Task/Create-an-HTML-table/Scala/create-an-html-table.scala b/Task/Create-an-HTML-table/Scala/create-an-html-table.scala new file mode 100644 index 0000000000..ae78c9586e --- /dev/null +++ b/Task/Create-an-HTML-table/Scala/create-an-html-table.scala @@ -0,0 +1,17 @@ +object TableGenerator extends App { + val data = List(List("X", "Y", "Z"), List(11, 12, 13), List(12, 22, 23), List(13, 32, 33)) + + def generateTable(data: List[List[Any]]) = { + + {data.zipWithIndex.map { case (row, rownum) => (if (rownum == 0) Nil else rownum) +: row}. + map(row => + {row.map(cell => + )} + )} +
+ {cell} +
+ } + + println(generateTable(data)) +} diff --git a/Task/Create-an-HTML-table/UNIX-Shell/create-an-html-table.sh b/Task/Create-an-HTML-table/UNIX-Shell/create-an-html-table.sh new file mode 100644 index 0000000000..492a1b26b3 --- /dev/null +++ b/Task/Create-an-HTML-table/UNIX-Shell/create-an-html-table.sh @@ -0,0 +1,38 @@ +function emit_table { + nameref d=$1 + typeset -i idx=0 + echo "" + emit_row th "" "${d[idx++][@]}" + for (( ; idx<${#d[@]}; idx++ )); do + emit_row td $idx "${d[idx][@]}" + done + echo "
" +} + +function emit_row { + typeset tag=$1; shift + typeset row="" + for elem; do + row+=$(printf "<%s>%s" "$tag" "$elem" "${tag## *}") + done + row+="" + echo "$row" +} + +function addrow { + nameref d=$1 + typeset n=${#d[@]} + typeset -i i + for ((i=0; i<$2; i++)); do + d[n][i]=$(( $RANDOM % 10000 )) + done +} + +n=3 +typeset -a data +data[0]=("X" "Y" "Z") +for i in {1..4}; do + addrow data $n +done + +emit_table data diff --git a/Task/Create-an-HTML-table/XSLT/create-an-html-table-1.xslt b/Task/Create-an-HTML-table/XSLT/create-an-html-table-1.xslt new file mode 100644 index 0000000000..90d995f6e0 --- /dev/null +++ b/Task/Create-an-HTML-table/XSLT/create-an-html-table-1.xslt @@ -0,0 +1,58 @@ + + + + + + + + + + + Rosetta Code: Create an HTML table (XSLT) + + + + + + + + + + + + + + + + + + + +
+ XYZ
+
+ + + + + + + + + + + + + + +
diff --git a/Task/Create-an-HTML-table/XSLT/create-an-html-table-2.xslt b/Task/Create-an-HTML-table/XSLT/create-an-html-table-2.xslt new file mode 100644 index 0000000000..cd5307c9fc --- /dev/null +++ b/Task/Create-an-HTML-table/XSLT/create-an-html-table-2.xslt @@ -0,0 +1,18 @@ + + + 1578 + 4828 + 1154 + 4950 + 6497 + 2355 + 9341 + 1927 + 8720 + 4490 + 1218 + 6675 + 8181 + 1403 + 4637 + diff --git a/Task/Create-an-HTML-table/XSLT/create-an-html-table-3.xslt b/Task/Create-an-HTML-table/XSLT/create-an-html-table-3.xslt new file mode 100644 index 0000000000..aa6afb22ac --- /dev/null +++ b/Task/Create-an-HTML-table/XSLT/create-an-html-table-3.xslt @@ -0,0 +1,45 @@ + + + + +Rosetta Code: Create an HTML table (XSLT) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
XYZ
1157848281154
2495064972355
3934119278720
4449012186675
5818114034637
+ diff --git a/Task/Cut-a-rectangle/D/cut-a-rectangle.d b/Task/Cut-a-rectangle/D/cut-a-rectangle.d index 3b783cf178..cf64c71d70 100644 --- a/Task/Cut-a-rectangle/D/cut-a-rectangle.d +++ b/Task/Cut-a-rectangle/D/cut-a-rectangle.d @@ -1,12 +1,4 @@ -import core.stdc.stdio, core.stdc.stdlib, - core.stdc.string, std.typetuple; - -template Range(uint stop) { // For loop unwinding. - static if (stop <= 0) - alias TypeTuple!() Range; - else - alias TypeTuple!(Range!(stop - 1), stop - 1) Range; -} +import core.stdc.stdio, core.stdc.stdlib, core.stdc.string, std.typecons; enum int[2][4] dir = [[0, -1], [-1, 0], [0, 1], [1, 0]]; @@ -15,7 +7,7 @@ __gshared uint w, h, len; __gshared ulong cnt; __gshared uint[4] next; -void walk(in uint y, in uint x) nothrow { +void walk(in uint y, in uint x) nothrow @nogc { if (!y || y == h || !x || x == w) { cnt += 2; return; @@ -25,7 +17,7 @@ void walk(in uint y, in uint x) nothrow { grid[t]++; grid[len - t]++; - foreach (i; Range!4) // Manual loop unwinding. + foreach (immutable i; staticIota!(0, 4)) if (!grid[t + next[i]]) walk(y + dir[i][0], x + dir[i][1]); @@ -33,7 +25,7 @@ void walk(in uint y, in uint x) nothrow { grid[len - t]--; } -ulong solve(in uint hh, in uint ww, in bool recur) nothrow { +ulong solve(in uint hh, in uint ww, in bool recur) nothrow @nogc { h = (hh & 1) ? ww : hh; w = (hh & 1) ? hh : ww; diff --git a/Task/Cut-a-rectangle/Go/cut-a-rectangle.go b/Task/Cut-a-rectangle/Go/cut-a-rectangle.go new file mode 100644 index 0000000000..8b121d4acb --- /dev/null +++ b/Task/Cut-a-rectangle/Go/cut-a-rectangle.go @@ -0,0 +1,82 @@ +package main + +import "fmt" + +var grid []byte +var w, h, last int +var cnt int +var next [4]int +var dir = [4][2]int{{0, -1}, {-1, 0}, {0, 1}, {1, 0}} + +func walk(y, x int) { + if y == 0 || y == h || x == 0 || x == w { + cnt += 2 + return + } + t := y*(w+1) + x + grid[t]++ + grid[last-t]++ + for i, d := range dir { + if grid[t+next[i]] == 0 { + walk(y+d[0], x+d[1]) + } + } + grid[t]-- + grid[last-t]-- +} + +func solve(hh, ww, recur int) int { + h = hh + w = ww + + if h&1 != 0 { + h, w = w, h + } + switch { + case h&1 == 1: + return 0 + case w == 1: + return 1 + case w == 2: + return h + case h == 2: + return w + } + cy := h / 2 + cx := w / 2 + + grid = make([]byte, (h+1)*(w+1)) + last = len(grid) - 1 + next[0] = -1 + next[1] = -w - 1 + next[2] = 1 + next[3] = w + 1 + + if recur != 0 { + cnt = 0 + } + for x := cx + 1; x < w; x++ { + t := cy*(w+1) + x + grid[t] = 1 + grid[last-t] = 1 + walk(cy-1, x) + } + cnt++ + + if h == w { + cnt *= 2 + } else if w&1 == 0 && recur != 0 { + solve(w, h, 0) + } + return cnt +} + +func main() { + for y := 1; y <= 10; y++ { + for x := 1; x <= y; x++ { + if x&1 == 0 || y&1 == 0 { + fmt.Printf("%d x %d: %d\n", y, x, solve(y, x, 1)) + } + } + } +} diff --git a/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 b/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 new file mode 100644 index 0000000000..a36bf2e977 --- /dev/null +++ b/Task/Cut-a-rectangle/Perl-6/cut-a-rectangle.pl6 @@ -0,0 +1,75 @@ +subset Byte of Int where ^256; +my @grid of Byte = 0; + +my Int ($w, $h, $len); +my Int $cnt = 0; + +my @next; +my @dir = [0, -1], [-1, 0], [0, 1], [1, 0]; +sub walk(Int $y, Int $x) { + my ($i, $t); + if !$y || $y == $h || !$x || $x == $w { + $cnt += 2; + return; + } + $t = $y * ($w + 1) + $x; + @grid[$t]++, @grid[$len - $t]++; + + loop ($i = 0; $i < 4; $i++) { + if !@grid[$t + @next[$i]] { + walk($y + @dir[$i][0], $x + @dir[$i][1]); + } + } + + @grid[$t]--, @grid[$len - $t]--; +} + +sub solve(Int $hh, Int $ww, Int $recur) returns Int { + my ($t, $cx, $cy, $x); + $h = $hh, $w = $ww; + + if $h +& 1 { $t = $w, $w = $h, $h = $t; } + if $h +& 1 { return 0; } + if $w == 1 { return 1; } + if $w == 2 { return $h; } + if $h == 2 { return $w; } + + $cy = $h div 2, $cx = $w div 2; + + $len = ($h + 1) * ($w + 1); + @grid = (); + @grid[$len--] = 0; + + @next[0] = -1; + @next[1] = -$w - 1; + @next[2] = 1; + @next[3] = $w + 1; + + if $recur { $cnt = 0; } + loop ($x = $cx + 1; $x < $w; $x++) { + $t = $cy * ($w + 1) + $x; + @grid[$t] = 1; + @grid[$len - $t] = 1; + walk($cy - 1, $x); + } + $cnt++; + + if $h == $w { + $cnt *= 2; + } elsif !($w +& 1) && $recur { + solve($w, $h, 0); + } + + return $cnt; +} + +sub MAIN { + my ($y, $x); + loop ($y = 1; $y <= 10; $y++) { + loop ($x = 1; $x <= $y; $x++) { + if (!($x +& 1) || !($y +& 1)) { + printf("%d x %d: %d\n", $y, $x, solve($y, $x, 1)); + } + } + } +} diff --git a/Task/Cut-a-rectangle/Perl/cut-a-rectangle.pl b/Task/Cut-a-rectangle/Perl/cut-a-rectangle.pl new file mode 100644 index 0000000000..64d95264ed --- /dev/null +++ b/Task/Cut-a-rectangle/Perl/cut-a-rectangle.pl @@ -0,0 +1,82 @@ +use strict; +use warnings; +my @grid = 0; + +my ($w, $h, $len); +my $cnt = 0; + +my @next; +my @dir = ([0, -1], [-1, 0], [0, 1], [1, 0]); + +sub walk { + my ($y, $x) = @_; + + if (!$y || $y == $h || !$x || $x == $w) { + $cnt += 2; + return; + } + + my $t = $y * ($w + 1) + $x; + $grid[$_]++ for $t, $len - $t; + + for my $i (0 .. 3) { + if (!$grid[$t + $next[$i]]) { + walk($y + $dir[$i]->[0], $x + $dir[$i]->[1]); + } + } + + $grid[$_]-- for $t, $len - $t; +} + +sub solve { + my ($hh, $ww, $recur) = @_; + my ($t, $cx, $cy, $x); + ($h, $w) = ($hh, $ww); + + if ($h & 1) { ($t, $w, $h) = ($w, $h, $w); } + if ($h & 1) { return 0; } + if ($w == 1) { return 1; } + if ($w == 2) { return $h; } + if ($h == 2) { return $w; } + + { + use integer; + ($cy, $cx) = ($h / 2, $w / 2); + } + + $len = ($h + 1) * ($w + 1); + @grid = (); + $grid[$len--] = 0; + + @next = (-1, -$w - 1, 1, $w + 1); + + if ($recur) { $cnt = 0; } + for ($x = $cx + 1; $x < $w; $x++) { + $t = $cy * ($w + 1) + $x; + @grid[$t, $len - $t] = (1, 1); + walk($cy - 1, $x); + } + $cnt++; + + if ($h == $w) { + $cnt *= 2; + } elsif (!($w & 1) && $recur) { + solve($w, $h); + } + + return $cnt; +} + +sub MAIN { + print "ok\n"; + my ($y, $x); + for my $y (1 .. 10) { + for my $x (1 .. $y) { + if (!($x & 1) || !($y & 1)) { + printf("%d x %d: %d\n", $y, $x, solve($y, $x, 1)); + } + } + } +} + +MAIN(); diff --git a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx b/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx index 39e059b743..fbc0af8bff 100644 --- a/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx +++ b/Task/Cut-a-rectangle/REXX/cut-a-rectangle.rexx @@ -1,7 +1,7 @@ /*REXX program cuts rectangles into two symmetric pieces, the rectangles*/ /*──────────────────── are cut along unit dimensions and may be rotated.*/ numeric digits 20 /*be able to handle big integers.*/ -parse arg N .; if N=='' then N=10 /*Not specified? Use the default?*/ +parse arg N .; if N=='' then N=10 /*N not specified? Use default.*/ dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*directions.*/ do y=2 to N; say /*calculate rectangles up to NxN.*/ @@ -11,31 +11,22 @@ dir.=0; dir.0.1=-1; dir.1.0=-1; dir.2.1=1; dir.3.0=1 /*directions.*/ end /*x*/ end /*y*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────WALK subroutine─────────────────────*/ -walk: procedure expose # dir. @. h len next. w; parse arg y,x -if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit.*/ -if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */ -if x==w then do; #=#+2; return; end /* ◄──┤ " " " */ -if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */ -t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely►─┐*/ -@._=@._+1 /* └─────────────────────────┘*/ - do j=0 for 4; _ = t+next.j /*try four directions*/ - if @._==0 then call walk y+dir.j.0, x+dir.j.1 - end /*j*/ - -@.t=@.t-1; _=len-t; @._=@._-1 -return /*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) +s: if arg(1)=1 then return arg(3); return word(arg(2) 's',1) /*plurals*/ /*──────────────────────────────────SOLVE subroutine────────────────────*/ solve: procedure expose # dir. @. h len next. w -parse arg hh 1 h,ww 1 w,recur; @. = 0 /*zero the rectangle coördinates.*/ -if h//2 then do; t=w; w=h; h=t; if h//2 then return 0; end -if w==1 then return 1; if w==2 then return h; if h==2 then return w -cy = h%2; cx=w%2 /*cut the [XY] rectangle in ½. */ -len = (h+1) * (w+1) - 1 /*extended area of the rectangle.*/ -next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*compute direction dist*/ -if recur then #=0 +parse arg hh 1 h,ww 1 w,recur; @.=0 /*zero the rectangle coördinates.*/ + +if h//2 then do; t=w; w=h; h=t + if h//2 then return 0 + end +if w==1 then return 1 +if w==2 then return h +if h==2 then return w +cy = h%2; cx=w%2 /*cut the [XY] rectangle in half.*/ +len = (h+1) * (w+1) - 1 /*extended area of the rectangle.*/ +next.0=-1; next.1=-w-1; next.2=1; next.3=w+1 /*direction distance.*/ +if recur then #=0 do x=cx+1 to w-1; t=x+cy*(w+1) @.t=1; _=len-t; @._=1; call walk cy-1,x end /*x*/ @@ -43,3 +34,17 @@ if recur then #=0 if h==w then #=#+# /*double count of rectangle cuts.*/ else if w//2==0 & recur then call solve w,h,0 return # +/*──────────────────────────────────WALK subroutine─────────────────────*/ +walk: procedure expose # dir. @. h len next. w; parse arg y,x +if y==h then do; #=#+2; return; end /* ◄──┐ REXX short circuit.*/ +if x==0 then do; #=#+2; return; end /* ◄──┤ " " " */ +if x==w then do; #=#+2; return; end /* ◄──┤ " " " */ +if y==0 then do; #=#+2; return; end /* ◄──┤ " " " */ +t=x + y*(w+1); @.t=@.t+1; _=len-t /* │ ordered by most likely►─┐*/ +@._=@._+1 /* └─────────────────────────┘*/ + do j=0 for 4; _ = t+next.j /*try 4 directions*/ + if @._==0 then call walk y+dir.j.0, x+dir.j.1 + end /*j*/ +@.t=@.t-1 +_=len-t; @._=@._-1 +return diff --git a/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-1.rb b/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-1.rb new file mode 100644 index 0000000000..0ad6011be7 --- /dev/null +++ b/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-1.rb @@ -0,0 +1,40 @@ +def cut_it(h, w) + if h.odd? + return 0 if w.odd? + h, w = w, h + end + return 1 if w == 1 + + nxt = [[w+1, 1, 0], [-w-1, -1, 0], [-1, 0, -1], [1, 0, 1]] # [next,dy,dx] + blen = (h + 1) * (w + 1) - 1 + grid = [false] * (blen + 1) + + walk = lambda do |y, x, count=0| + return count+1 if y==0 or y==h or x==0 or x==w + t = y * (w + 1) + x + grid[t] = grid[blen - t] = true + nxt.each do |nt, dy, dx| + count += walk[y + dy, x + dx] unless grid[t + nt] + end + grid[t] = grid[blen - t] = false + count + end + + t = h / 2 * (w + 1) + w / 2 + if w.odd? + grid[t] = grid[t + 1] = true + count = walk[h / 2, w / 2 - 1] + count + walk[h / 2 - 1, w / 2] * 2 + else + grid[t] = true + count = walk[h / 2, w / 2 - 1] + return count * 2 if h == w + count + walk[h / 2 - 1, w / 2] + end +end + +for w in 1..9 + for h in 1..w + puts "%d x %d: %d" % [w, h, cut_it(w, h)] if (w * h).even? + end +end diff --git a/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-2.rb b/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-2.rb new file mode 100644 index 0000000000..ef5677cc2f --- /dev/null +++ b/Task/Cut-a-rectangle/Ruby/cut-a-rectangle-2.rb @@ -0,0 +1,74 @@ +class Rectangle + DIRS = [[1, 0], [-1, 0], [0, -1], [0, 1]] + def initialize(h, w) + raise ArgumentError if (h.odd? and w.odd?) or h<=0 or w<=0 + @h, @w = h, w + @limit = h * w / 2 + end + + def cut(disp=true) + @cut = {} + @select = [] + @result = [] + @grid = make_grid + walk(0,0) + display if disp + @result + end + + def make_grid + Array.new(@h+1) {|i| Array.new(@w+1) {|j| true if i<@h and j<@w }} + end + + def walk(y, x) + @grid[y][x] = @grid[@h-y-1][@w-x-1] = false + @select.push([y,x]) + select = @select.sort + unless @cut[select] + @cut[select] = true + if @select.size == @limit + @result << select + else + search_next.each {|yy,xx| walk(yy,xx)} + end + end + @select.pop + @grid[y][x] = @grid[@h-y-1][@w-x-1] = true + end + + def search_next + nxt = {} + @select.each do |y,x| + DIRS.each do |dy, dx| + nxt[[y+dy, x+dx]] = true if @grid[y+dy][x+dx] + end + end + nxt.keys + end + + def display + @result.each do |select| + @grid = make_grid + select.each {|y,x| @grid[y][x] = false} + puts to_s + end + end + + def to_s + text = Array.new(@h*2+1) {" " * (@w*4+1)} + for i in 0..@h + for j in 0..@w + text[i*2][j*4+1,3] = "---" if @grid[i][j] != @grid[i-1][j] + text[i*2+1][j*4] = "|" if @grid[i][j] != @grid[i][j-1] + text[i*2][j*4] = "+" + end + end + text.join("\n") + end +end + +rec = Rectangle.new(2,2) +puts rec.cut.size + +rec = Rectangle.new(3,4) +puts rec.cut.size diff --git a/Task/DNS-query/R/dns-query-1.r b/Task/DNS-query/R/dns-query-1.r new file mode 100644 index 0000000000..2a590d4040 --- /dev/null +++ b/Task/DNS-query/R/dns-query-1.r @@ -0,0 +1,47 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace Rcpp ; + +// [[Rcpp::export]] +CharacterVector getNameInfo(std::string fqdn) { + + struct addrinfo hints, *res, *res0; + int error; + char host[NI_MAXHOST]; + + memset(&hints, 0, sizeof hints); + hints.ai_family = PF_UNSPEC; + hints.ai_socktype = SOCK_DGRAM; + + error = getaddrinfo(fqdn.c_str(), NULL, &hints, &res0); + if (error) { return(NA_STRING); } + + int i = 0 ; + for (res = res0; res; res = res->ai_next) { + error = getnameinfo(res->ai_addr, res->ai_addrlen, + host, sizeof host, NULL, 0, NI_NUMERICHOST); + if (!error) { i++ ; } + } + + CharacterVector results(i) ; + + i = 0; + + for (res = res0; res; res = res->ai_next) { + error = getnameinfo(res->ai_addr, res->ai_addrlen, + host, sizeof host, NULL, 0, NI_NUMERICHOST); + if (!error) { results[i++] = host ; } + } + + freeaddrinfo(res0); + + return(results) ; + +} diff --git a/Task/DNS-query/R/dns-query-2.r b/Task/DNS-query/R/dns-query-2.r new file mode 100644 index 0000000000..cbd624e0cc --- /dev/null +++ b/Task/DNS-query/R/dns-query-2.r @@ -0,0 +1,5 @@ +library(Rcpp) +sourceCpp("dns.cpp") +getNameInfo("www.kame.net") +## [1] "203.178.141.194" +## [2] "2001:200:dff:fff1:216:3eff:feb1:44d7" diff --git a/Task/DNS-query/REXX/dns-query.rexx b/Task/DNS-query/REXX/dns-query.rexx index 94ee61cc35..a656d748dc 100644 --- a/Task/DNS-query/REXX/dns-query.rexx +++ b/Task/DNS-query/REXX/dns-query.rexx @@ -1,16 +1,16 @@ -/*REXX pgm displays IPv4 and IPv6 addresses for a supplied domain name. */ +/*REXX pgm displays IPv4 and IPv6 addresses for a supplied domain name.*/ trace off /*don't show the PING return code*/ parse arg dn . /*get the optional domain name. */ -if dn=='' then dn='www.kame.net' /*Not specified? Then use default*/ -tmp='\TEMP\TEMP.PING' /*define temp file to store IPv4.*/ +if dn=='' then dn = 'www.kame.net' /*Not specified? Then use default*/ +tmp = '\TEMP\TEMP.PING' /*define temp file to store IPv4.*/ do j=4 to 6 by 2 /*handle IPv4 and IPv6 addresses.*/ 'PING' (-j) '-l 0 -n 1' dn ">" tmp /*restrict PING's output to min. */ q=charin(tmp,1,999) /*read output file from PING cmd.*/ parse var q '[' IPA ']' /*parse IP a ddress from output.*/ say 'IPv'j 'for domain name ' dn " is " IPA /*IPv4 | IPv6 addr.*/ - call lineout tmp /*needed by most REXXes to force */ - end /*j*/ /* [↑] file integrity. */ + call lineout tmp /*needed by most REXXes to ··· */ + end /*j*/ /* [↑] ··· force file integrity.*/ 'ERASE' tmp /*clean up the temporary file. */ /*stick a fork in it, we're done.*/ diff --git a/Task/DNS-query/Scala/dns-query.scala b/Task/DNS-query/Scala/dns-query.scala new file mode 100644 index 0000000000..60c035648b --- /dev/null +++ b/Task/DNS-query/Scala/dns-query.scala @@ -0,0 +1,9 @@ +import java.net.{InetAddress,Inet4Address,Inet6Address} + +object DnsQuery extends App { + val ipAddresses = InetAddress.getAllByName("www.kame.net"); + ipAddresses.foreach { ipAddr => + if (ipAddr.isInstanceOf[Inet4Address]) println("IPv4 : " + ipAddr.getHostAddress()) + else if (ipAddr.isInstanceOf[Inet6Address]) println("IPv6 : " + ipAddr.getHostAddress()) + } +} diff --git a/Task/Date-format/JavaScript/date-format.js b/Task/Date-format/JavaScript/date-format.js index cc7c9e5e0d..be54a1aa40 100644 --- a/Task/Date-format/JavaScript/date-format.js +++ b/Task/Date-format/JavaScript/date-format.js @@ -1,8 +1,7 @@ -var - now = new Date(), - fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(), - weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], - months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], - fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear(); -print(fmt1); -print(fmt2); +var now = new Date(), + weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], + months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], + fmt1 = now.getFullYear() + '-' + (1 + now.getMonth()) + '-' + now.getDate(), + fmt2 = weekdays[now.getDay()] + ', ' + months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear(); +console.log(fmt1); +console.log(fmt2); diff --git a/Task/Date-format/Prolog/date-format.pro b/Task/Date-format/Prolog/date-format.pro new file mode 100644 index 0000000000..b190821be2 --- /dev/null +++ b/Task/Date-format/Prolog/date-format.pro @@ -0,0 +1,5 @@ +display_date :- + get_time(Time), + format_time(atom(Short), '%Y-%M-%d', Time), + format_time(atom(Long), '%A, %B %d, %Y', Time), + format('~w~n~w~n', [Short, Long]). diff --git a/Task/Date-format/REXX/date-format-1.rexx b/Task/Date-format/REXX/date-format-1.rexx new file mode 100644 index 0000000000..1b3b060665 --- /dev/null +++ b/Task/Date-format/REXX/date-format-1.rexx @@ -0,0 +1,12 @@ +/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/ + x = date('S') /*get current date as yyyymmdd */ +yyyy = left(x,4) /*pick off year (4 digs).*/ + dd = right(x,2) /*pick off day-of-month (2 digs).*/ + mm = substr(x,5,2) /*pick off month number (2 digs).*/ +say yyyy'-'mm"-"dd /*yyyy-mm-dd with leading zeroes.*/ + +weekday = date('W') /*dayofweek (Monday or somesuch).*/ +month = date('M') /*Month (August or somesuch).*/ +zdd = dd+0 /*remove leading zero from DD */ +say weekday',' month zdd"," yyyy /*format date as: Month dd, yyyy*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Date-format/REXX/date-format-2.rexx b/Task/Date-format/REXX/date-format-2.rexx new file mode 100644 index 0000000000..2a0b525abd --- /dev/null +++ b/Task/Date-format/REXX/date-format-2.rexx @@ -0,0 +1,28 @@ +/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/ +/* ╔══════════════════════════════════════════════════════════════════╗ + ║ function returns a specific example ║ + ║ ─────────── ─────────────────────────── ──────────────────── ║ + ║ date() dd mon yyyy 3 Jun 2009 ║ + ║ date('N') (same as above) ║ + ║ date('B') days since Jan 1, year 1 735382 ║ + ║ date('C') days since Jan 1 this century 5264 ║ + ║ date('D') days since Jan 1, this yr 154 ║ + ║ date('E') dd/mm/yy 03/06/09 ║ + ║ date('I') yyyy-mm-dd 2009-03-06 ║ + ║ date('J') yyddd 2009154 ║ + ║ date('M') month name June ║ + ║ date('O') yy/mm/dd 09/03/06 ║ + ║ date('S') yyyyddmm 20090603 ║ + ║ date('T') seconds since Jan 1st, 1970 1401483686 ║ + ║ date('U') mm/dd/yy 03/06/09 ║ + ║ date('W') day─of─the─week Wednesday ║ + ║ ─────────── ─────────────────────────── ──────────────────── ║ + ║ ║ + ║ Note: not all of the above are supported by all REXX versions. ║ + ╚══════════════════════════════════════════════════════════════════╝ */ +parse value date('S') with yyyy 5 mm 7 dd /*get various pieces of date*/ +say yyyy'-'mm"-"dd /*yyyy-mm-dd with leading zeroes.*/ + +say date('W')"," date('M') word(date(), 1)"," yyyy + /* [↑] dayofweek Month dd, yyyy*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Date-format/REXX/date-format-3.rexx b/Task/Date-format/REXX/date-format-3.rexx new file mode 100644 index 0000000000..4a35cce81e --- /dev/null +++ b/Task/Date-format/REXX/date-format-3.rexx @@ -0,0 +1,6 @@ +/*REXX pgm shows current date: yyyy-mm-dd & Dayofweek, Month dd, yyyy*/ +say date('I') /*yyyy-mm-dd with leading zeroes.*/ + +say date('W')"," date('M') word(date(), 1)"," left(date('S'),4) + /* [↑] dayofweek Month dd, yyyy*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Date-format/REXX/date-format.rexx b/Task/Date-format/REXX/date-format.rexx deleted file mode 100644 index 37ac8b675a..0000000000 --- a/Task/Date-format/REXX/date-format.rexx +++ /dev/null @@ -1,11 +0,0 @@ -/*show current date in yyyy-mm-dd and also Dayofweek, Month dd, yyyy*/ -x=date('s') /* yyyymmdd */ -yyyy=left(x,4) /* pick off the year. */ -dd=right(x,2) /* pick off the day of month */ -say yyyy'-'substr(x,5,2)"-"dd /*yyyy-mm-dd with leading 0s */ - -weekday =date('w') /* Dayofweek (Saturday) */ -month =date('m') /* Month (December) */ -zdd =dd+0 /* remove leading zero of DD */ -say weekday',' month zdd"," yyyy /*Month dd, yyyy */ - /*stick a fork in it, we're done.*/ diff --git a/Task/Date-format/Ruby/date-format.rb b/Task/Date-format/Ruby/date-format.rb index 292fc1524a..f97dc18e23 100644 --- a/Task/Date-format/Ruby/date-format.rb +++ b/Task/Date-format/Ruby/date-format.rb @@ -1,3 +1,4 @@ puts Time.now puts Time.now.strftime('%Y-%m-%d') +puts Time.now.strftime('%F') # same as %Y-%m-%d (ISO 8601 date formats) puts Time.now.strftime('%A, %B %d, %Y') diff --git a/Task/Date-format/Smalltalk/date-format.st b/Task/Date-format/Smalltalk/date-format.st new file mode 100644 index 0000000000..551f078740 --- /dev/null +++ b/Task/Date-format/Smalltalk/date-format.st @@ -0,0 +1,4 @@ +| d | +d := Date today. +d printFormat: #(3 2 1 $- 1 1 2). +(d weekday asString), ', ', (d monthName), ' ', (d dayOfMonth asString), ', ', (d year asString) diff --git a/Task/Date-manipulation/00DESCRIPTION b/Task/Date-manipulation/00DESCRIPTION index cb23a7e51e..29c00aa465 100644 --- a/Task/Date-manipulation/00DESCRIPTION +++ b/Task/Date-manipulation/00DESCRIPTION @@ -1,3 +1,7 @@ -Given the date string "March 7 2009 7:30pm EST", output the time 12 hours later in any human-readable format. +{{omit from|ML/I}} +{{omit from|PARI/GP|No real capacity for string manipulation}} + +Given the date string "March 7 2009 7:30pm EST",
+output the time 12 hours later in any human-readable format. As extra credit, display the resulting time in a time zone different from your own. diff --git a/Task/Date-manipulation/00META.yaml b/Task/Date-manipulation/00META.yaml index 88eb5468ca..69501dea68 100644 --- a/Task/Date-manipulation/00META.yaml +++ b/Task/Date-manipulation/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Date and time note: Text processing diff --git a/Task/Date-manipulation/J/date-manipulation-1.j b/Task/Date-manipulation/J/date-manipulation-1.j new file mode 100644 index 0000000000..a151c6e63f --- /dev/null +++ b/Task/Date-manipulation/J/date-manipulation-1.j @@ -0,0 +1,27 @@ +require'dates' +months=: <;._2 tolower 0 :0 +January +February +March +April +May +June +July +August +September +October +November +December +) + +numbers=: _".' '"_`(1 I.@:-e.&(":i.10)@])`]}~ +words=: [:;:@tolower' '"_`(I.@(tolower = toupper)@])`]}~ +getyear=: >./@numbers +getmonth=: 1 + months <./@i. words +getday=: {.@(numbers -. getyear) +gethour=: (2 { numbers) + 12 * (<'pm') e. words +getminsec=: 2 {. 3}. numbers + +getts=: getyear, getmonth, getday, gethour, getminsec +timeadd=: 1&tsrep@+&tsrep +deltaT=: (1 tsrep 0)&([ + -@#@[ {. ]) diff --git a/Task/Date-manipulation/J/date-manipulation-2.j b/Task/Date-manipulation/J/date-manipulation-2.j new file mode 100644 index 0000000000..9176c01c28 --- /dev/null +++ b/Task/Date-manipulation/J/date-manipulation-2.j @@ -0,0 +1,6 @@ + (deltaT 12 0 0) timeadd getts 'March 7 2009 7:30pm EST' +2009 3 8 7 30 0 + timestamp (deltaT 12 0 0) timeadd getts 'March 7 2009 7:30pm EST' +08 Mar 2009 07:30:00 + isotimestamp (deltaT 12 0 0) timeadd getts 'March 7 2009 7:30pm EST' +2009-03-08 07:30:00.000 diff --git a/Task/Date-manipulation/JavaScript/date-manipulation.js b/Task/Date-manipulation/JavaScript/date-manipulation.js index c8b63269c5..3a83f88f3f 100644 --- a/Task/Date-manipulation/JavaScript/date-manipulation.js +++ b/Task/Date-manipulation/JavaScript/date-manipulation.js @@ -1,51 +1,41 @@ function add12hours(dateString) { // Get the parts of the date string - var parts = dateString.split(/\s+/); - var date = parts[1]; - var month = parts[0]; - var year = parts[2]; - var time = parts[3]; - var ampm = time && time.match(/[a-z]+$/i)[0]; - var hr = Number(time.split(':')[0]); - var min = Number(time.split(':')[1].replace(/\D/g,'')); - var zone = parts[4].toUpperCase(); + var parts = dateString.split(/\s+/), + date = parts[1], + month = parts[0], + year = parts[2], + time = parts[3]; + + var hr = Number(time.split(':')[0]), + min = Number(time.split(':')[1].replace(/\D/g,'')), + ampm = time && time.match(/[a-z]+$/i)[0], + zone = parts[4].toUpperCase(); + var months = ['January','February','March','April','May','June', - 'July','August','September','October','November','December']; - var zones = {'EST': 300, 'AEST': -600}; // Minutes to add to zone time to get UTC + 'July','August','September','October','November','December']; + var zones = {'EST': 300, 'AEST': -600}; // Minutes to add to zone time to get UTC - // Convert month name to number, zero indexed - // Could use indexOf but not supported widely - for (var i=0, iLen=months.length; i2121 + & ( wday$(!y,12,25):0 + & put$(str$(!y "-12-25\n")) + | + ) + & 1+!y:?y + ) +& done; diff --git a/Task/Day-of-the-week/REXX/day-of-the-week-3.rexx b/Task/Day-of-the-week/REXX/day-of-the-week-3.rexx index 40839c6afe..2fa6450c15 100644 --- a/Task/Day-of-the-week/REXX/day-of-the-week-3.rexx +++ b/Task/Day-of-the-week/REXX/day-of-the-week-3.rexx @@ -1,14 +1,14 @@ -/*REXX program displays which years December 25th falls on a Sunday. */ +/*REXX program displays which years December 25th falls on a Sunday.*/ parse arg start finish . /*get the start and finish years.*/ -if start=='' then start=2008 /*None specified? Assume default*/ -if finish=='' then finish=2121 /*None specified? Assume default*/ +if start=='' then start=2008 /*None specified? Assume default*/ +if finish=='' then finish=2121 /*None specified? Assume default*/ - do y=start to finish /*process the years specified. */ + do y=start to finish /*process the years specified. */ - if date('Weekday',y"-12-25",'ISO')\=='Sunday' then iterate - /* if date('w' ,y"-12-25",'i' )\== ... (same as above). */ + if date('Weekday',y"-12-25",'ISO')\=='Sunday' then iterate + /* if date('w' ,y"-12-25",'i' ) ··· (same as above). */ /* option yyyy-mm-dd fmt */ - say 'December 25th,' y "falls on a Sunday." + say 'December 25th,' y "falls on a Sunday." end /*y*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx b/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx index b328c0df33..f34bfadffa 100644 --- a/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx +++ b/Task/Day-of-the-week/REXX/day-of-the-week-4.rexx @@ -1,14 +1,13 @@ -/*REXX program (old school) displays which years 12/25 falls on a Sunday*// - +/*REXX program (old school) displays which years 12/25 falls on a Sunday*/ parse arg start finish . /*get the start and finish years.*/ -if start=='' then start=2008 /*None specified? Assume default*/ -if finish=='' then finish=2121 /*None specified? Assume default*/ +if start=='' then start=2008 /*None specified? Assume default*/ +if finish=='' then finish=2121 /*None specified? Assume default*/ - do y=start to finish /*process the years specified. */ - if dow(12,25,y)==1 then say 'December 25th,' y "falls on a Sunday." + do y=start to finish /*process the years specified. * + if dow(12,25,y)==1 then say 'December 25th,' y "falls on a Sunday." end /*y*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DOW (day of week) subroutine────────*/ -dow: procedure; arg m,d,y; if m<3 then do; m=m+12; y=y-1; end +dow: procedure; parse 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 /*Sunday=1, Monday=2, ... Saturday=7*/ +if w==0 then w=7; return w /*Sunday=1, Monday=2, ··· Saturday=7*/ diff --git a/Task/Day-of-the-week/Ruby/day-of-the-week-2.rb b/Task/Day-of-the-week/Ruby/day-of-the-week-2.rb index 3b79c5a947..ede6430f38 100644 --- a/Task/Day-of-the-week/Ruby/day-of-the-week-2.rb +++ b/Task/Day-of-the-week/Ruby/day-of-the-week-2.rb @@ -1,11 +1 @@ -SUNDAY = 0 - -(2008..2121).each do |year| - begin - day = Time.local(year, 12, 25) - puts "25 Dec #{year}" if day.wday == SUNDAY # Ruby 1.9: if day.sunday? - rescue ArgumentError - puts '%d is the last year we can specify' % (year-1) - break - end -end +(2008..2121).each {|year| puts "25 Dec #{year}" if Time.local(year, 12, 25).sunday?} 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 index 79c5e57b4f..48a50d889a 100644 --- 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 @@ -3,12 +3,16 @@ 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 + + val yuletide = + years.filter(year => (new GregorianCalendar(year, DECEMBER, 25)).get(DAY_OF_WEEK) == SUNDAY) + + // If you want a test: (optional) + assert(yuletide == + Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, + 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118)) println(yuletide.mkString( - s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + s"${yuletide.length} 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 index 30b1b7eb07..d8f822140d 100644 --- 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 @@ -1,11 +1,16 @@ import java.time.{ DayOfWeek, LocalDate } -object DayOfTheWeek2 extends App { +object DayOfTheWeek1 extends App { val years = 2008 to 2121 val yuletide = - years.filter(yr => LocalDate.of(yr, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) + years.filter(year => (LocalDate.of(year, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY)) + + // If you want a test: (optional) + assert(yuletide == + Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, + 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118)) println(yuletide.mkString( - s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + s"${yuletide.length} 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 index d8617d84e8..79d0fa17d8 100644 --- 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 @@ -8,13 +8,18 @@ object DayOfTheWeek3 extends App { 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)) + (if (LocalDate.of(anni.head, 12, 25).getDayOfWeek() == DayOfWeek.SUNDAY) List(anni.head) + else Nil)) } inner(years.toList, Nil) } + // If you want a test: (optional) + assert(yuletide == + Seq(2011, 2016, 2022, 2033, 2039, 2044, 2050, 2061, + 2067, 2072, 2078, 2089, 2095, 2101, 2107, 2112, 2118)) + println(yuletide.mkString( - s"${yuletide.count(p => true)} Years between ${years.head} and ${years.last}" + + s"${yuletide.length} Years between ${years.head} and ${years.last}" + " including where Christmas is observed on Sunday:\n", ", ", ".")) } diff --git a/Task/Day-of-the-week/XPL0/day-of-the-week.xpl0 b/Task/Day-of-the-week/XPL0/day-of-the-week.xpl0 index 125ccaad68..6da6add3ce 100644 --- a/Task/Day-of-the-week/XPL0/day-of-the-week.xpl0 +++ b/Task/Day-of-the-week/XPL0/day-of-the-week.xpl0 @@ -1,6 +1,6 @@ include c:\cxpl\codes; \intrinsic 'code' declarations -proc WeekDay(Year, Month, Day); \Return day of week (0=Sat 1=Sun..6=Fri) +func WeekDay(Year, Month, Day); \Return day of week (0=Sat 1=Sun..6=Fri) int Year, Month, Day; [if Month<=2 then [Month:= Month+12; Year:= Year-1]; return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7); diff --git a/Task/Deal-cards-for-FreeCell/00DESCRIPTION b/Task/Deal-cards-for-FreeCell/00DESCRIPTION index ab482c99bc..ced986f8be 100644 --- a/Task/Deal-cards-for-FreeCell/00DESCRIPTION +++ b/Task/Deal-cards-for-FreeCell/00DESCRIPTION @@ -1,6 +1,9 @@ -''Free Cell'' is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to ''FreeCell'' and reimplemented the game for [[DOS]], then [[Windows]]. This version introduced 32000 numbered deals. (The [http://www.solitairelaboratory.com/fcfaq.html FreeCell FAQ] tells this history.) +''Free Cell'' is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to ''FreeCell'' and reimplemented the game for [[DOS]], then [[Windows]].
+This version introduced 32000 numbered deals. (The [http://www.solitairelaboratory.com/fcfaq.html FreeCell FAQ] tells this history.) -As the game became popular, Jim Horne disclosed [http://www.solitairelaboratory.com/mshuffle.txt the algorithm], and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range. +As the game became popular, Jim Horne disclosed [http://www.solitairelaboratory.com/mshuffle.txt the algorithm], and other implementations of FreeCell began to reproduce the Microsoft deals.
+These deals are numbered from 1 to 32000. +Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range. The algorithm uses this [[linear congruential generator]] from Microsoft C: @@ -48,6 +51,8 @@ KD 5H 9S 3C 8S 7H 4D JS JD KS KC 4H |} -Deals can also be checked against [http://freecellgamesolutions.com/ FreeCell solutions to 1000000 games]. (Summon a video solution, and it displays the initial deal.) +Deals can also be checked against [http://freecellgamesolutions.com/ FreeCell solutions to 1000000 games]. +(Summon a video solution, and it displays the initial deal.) -Write a program to take a deal number and deal cards in the same order as this algorithm. The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way. +Write a program to take a deal number and deal cards in the same order as this algorithm. +The program may display the cards with ASCII, with Unicode, by drawing graphics, or any other way. diff --git a/Task/Deal-cards-for-FreeCell/00META.yaml b/Task/Deal-cards-for-FreeCell/00META.yaml index a2413d963b..940aa7be0b 100644 --- a/Task/Deal-cards-for-FreeCell/00META.yaml +++ b/Task/Deal-cards-for-FreeCell/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Cards note: Games 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 9b455b9d7d..0fc06f422b 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 @@ -3,7 +3,7 @@ import std.stdio, std.conv, std.algorithm, std.range; struct RandomGenerator { uint seed = 1; - @property uint next() pure nothrow { + @property uint next() pure nothrow @safe @nogc { seed = (seed * 214_013 + 2_531_011) & int.max; return seed >> 16; } @@ -12,25 +12,25 @@ struct RandomGenerator { struct Deck { int[52] cards; - void deal(in uint seed) pure /*nothrow*/ { + void deal(in uint seed) pure nothrow @safe @nogc { enum int nc = cards.length; // Must be signed for iota. - iota(nc - 1, -1, -1).copy(cards[]); // iota isn't nothrow. + nc.iota.retro.copy(cards[]); auto rnd = RandomGenerator(seed); foreach (immutable i, ref c; cards) c.swap(cards[(nc - 1) - rnd.next % (nc - i)]); } - void show() const { + void show() const @safe { writefln("%(%-( %s%)\n%)", cards[] .chunks(8) - .map!(row => row.map!(c => ["A23456789TJQK"[c / 4]] ~ - "CDHS"[c % 4]))); + .map!(row => row.map!(c => only("A23456789TJQK"[c / 4], + "CDHS"[c % 4])))); } } -void main(in string[] args) { +void main(in string[] args) @safe { immutable seed = (args.length == 2) ? args[1].to!uint : 11_982; writeln("Hand ", seed); Deck cards; diff --git a/Task/Deal-cards-for-FreeCell/Fortran/deal-cards-for-freecell.f b/Task/Deal-cards-for-FreeCell/Fortran/deal-cards-for-freecell.f new file mode 100644 index 0000000000..02d581d352 --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Fortran/deal-cards-for-freecell.f @@ -0,0 +1,55 @@ +module Freecell + use lcgs + implicit none + + character(4) :: suit = "CDHS" + character(13) :: rank = "A23456789TJQK" + character(2) :: deck(0:51) + +contains + +subroutine Createdeck() + integer :: i, j, n + + n = 0 + do i = 1, 13 + do j = 1, 4 + deck(n) = rank(i:i) // suit(j:j) + n = n + 1 + end do + end do + +end subroutine + +subroutine Freecelldeal(game) + integer, intent(in) :: game + integer(i64) :: rnum + integer :: i, n + character(2) :: tmp + + call Createdeck() + rnum = msrand(game) + + do i = 51, 1, -1 + n = mod(rnum, i+1) + tmp = deck(n) + deck(n) = deck(i) + deck(i) = tmp + rnum = msrand() + end do + + write(*, "(a, i0)") "Game #", game + write(*, "(8(a, tr1))") deck(51:0:-1) + write(*,*) + +end subroutine +end module Freecell + +program Freecell_test + use Freecell + implicit none + + call Freecelldeal(1) + call Freecelldeal(617) + +end program diff --git a/Task/Deal-cards-for-FreeCell/Seed7/deal-cards-for-freecell.seed7 b/Task/Deal-cards-for-FreeCell/Seed7/deal-cards-for-freecell.seed7 new file mode 100644 index 0000000000..21aa5a94ce --- /dev/null +++ b/Task/Deal-cards-for-FreeCell/Seed7/deal-cards-for-freecell.seed7 @@ -0,0 +1,65 @@ +$ include "seed7_05.s7i"; + include "console.s7i"; + +const string: suits is "♣♦♥♠"; +const string: nums is "A23456789TJQK"; + +var integer: randomSeed is 1; + +const func integer: random is func + result + var integer: rand is 1; + begin + randomSeed := (randomSeed * 214013 + 2531011) mod 2 ** 31; + rand := randomSeed >> 16; + end func; + +const proc: show (in array integer: cards) is func + local + var integer: index is 0; + begin + for index range 1 to 52 do + write(" " <& suits[succ(cards[index] rem 4)] <& nums[succ(cards[index] div 4)]); + if index rem 8 = 0 or index = 52 then + writeln; + end if; + end for; + end func; + +const func array integer: deal (in integer: gameNum) is func + result + var array integer: cards is 52 times 0; + local + var integer: i is 0; + var integer: j is 0; + var integer: s is 0; + begin + randomSeed := gameNum; + for i range 1 to 52 do + cards[i] := 52 - i; + end for; + for i range 1 to 51 do + j := 52 - random mod (53 - i); + s := cards[i]; + cards[i] := cards[j]; + cards[j] := s; + end for; + end func; + +const proc: main is func + local + var integer: gameNum is 11982; + var array integer: cards is 0 times 0; + begin + OUT := STD_CONSOLE; + if length(argv(PROGRAM)) >= 1 then + block + gameNum := integer parse (argv(PROGRAM)[1]); + exception + catch RANGE_ERROR: noop; + end block; + end if; + cards := deal(gameNum); + writeln("Hand " <& gameNum); + show(cards); + end func; diff --git a/Task/Death-Star/D/death-star.d b/Task/Death-Star/D/death-star.d index 2f6115f016..1cf4d1f64d 100644 --- a/Task/Death-Star/D/death-star.d +++ b/Task/Death-Star/D/death-star.d @@ -3,12 +3,12 @@ import std.stdio, std.math, std.numeric, std.algorithm; struct V3 { double[3] v; - @property V3 normalize() pure nothrow const { + @property V3 normalize() pure nothrow const @nogc { immutable double len = dotProduct(v, v).sqrt; return [v[0] / len, v[1] / len, v[2] / len].V3; } - double dot(in ref V3 y) pure nothrow const { + double dot(in ref V3 y) pure nothrow const @nogc { immutable double d = dotProduct(v, y.v); return d < 0 ? -d : 0; } @@ -23,7 +23,7 @@ void drawSphere(in double k, in double ambient, in V3 light) nothrow { static bool hitSphere(in ref Sphere sph, in double x0, in double y0, out double z1, - out double z2) pure nothrow { + out double z2) pure nothrow @nogc { immutable double x = x0 - sph.cx; immutable double y = y0 - sph.cy; immutable double zsq = sph.r ^^ 2 - (x ^^ 2 + y ^^ 2); diff --git a/Task/Death-Star/JavaScript/death-star.js b/Task/Death-Star/JavaScript/death-star.js new file mode 100644 index 0000000000..f7dc982d87 --- /dev/null +++ b/Task/Death-Star/JavaScript/death-star.js @@ -0,0 +1,41 @@ + + + + + Your browser does not support the HTML5 canvas tag. + + + + diff --git a/Task/Death-Star/REXX/death-star.rexx b/Task/Death-Star/REXX/death-star.rexx index 7d9e0fe031..8e01935930 100644 --- a/Task/Death-Star/REXX/death-star.rexx +++ b/Task/Death-Star/REXX/death-star.rexx @@ -1,10 +1,10 @@ /*REXX program to draw a "deathstar", a sphere with another subtracted. */ -signal on syntax; signal on novalue /*handle REXX program errors. */ +signal on syntax; signal on noValue /*handle REXX program errors. */ numeric digits 20 /*use a fair amount of precision.*/ lightSource = norm('-50 30 50') call drawSphereM 2, .5, lightSource exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────drawSphereM subroutine──────────────*/ +/*──────────────────────────────────DRAWSPHEREM subroutine──────────────*/ drawSphereM: procedure; parse arg k,ambient,lightSource z1=0; z2=0 parse var lightSource s1 s2 s3 /*break-apart the light source. */ @@ -21,7 +21,7 @@ ship= 20 20 0 20 ; parse var ship ship.cx ship.cy ship.cz ship.radius hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius do i=floor(ship.cy-ship.radius) to ceil(ship.cy+ship.radius)+1; y=i+.5; aLine= - do j=trunc(floor(ship.cx - 2*ship.radius) ) to, + do j=trunc(floor(ship.cx - 2*ship.radius) ) to , trunc( ceil(ship.cx + 2*ship.radius) +1) x=.5*(j-ship.cx) + .5 + ship.cx; !bg=0; !pos=0; !neg=0; z1=0; z2=0 ?=hitSphere(ship, x, y); zb1=z1; zb2=z2 @@ -52,7 +52,7 @@ hole=' 1 1 -6 20'; parse var hole hole.cx hole.cy hole.cz hole.radius end /*i*/ return -/*──────────────────────────────────hitSphere subroutine────────────────*/ +/*──────────────────────────────────HITSPHERE subroutine────────────────*/ hitSphere: procedure expose z1 z2; parse arg $.cx $.cy $.cz $.radius, x0, y0 x=x0-$.cx y=y0-$.cy @@ -61,15 +61,15 @@ hitSphere: procedure expose z1 z2; parse arg $.cx $.cy $.cz $.radius, x0, y0 z1=$.cz-_ z2=$.cz+_ return 1 -/*──────────────────────────────────"1-liner" subroutines───────────────*/ -V3: procedure; parse arg v; return norm(v) +/*──────────────────────────────────one─liner subroutines────────────────────────────────────────────────────────────────────────────────────────────────────────*/ dot.: procedure; parse arg x,y; d=dot(x,y); if d<0 then return -d; return 0 dot: procedure; parse arg x,y; s=0; do j=1 for words(x); s=s+word(x,j)*word(y,j); end; return s 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) ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) * (x\=_) floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_) norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_ +noValue: syntax: call err 'REXX program' condition('C') "error", condition('D'),'REXX source statement (line' sigl"):",sourceline(sigl) sqrt: procedure; parse arg x; if x=0 then return 0; return .sqrt(x)/1 .sqrt: 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 by -1 to 0;if m.k>11 then numeric digits m.k;g=.5*(g+x/g);end;return g .sqrtG: numeric form; m.=11; p=d+d%4+2; v=format(x,2,1,,0) 'E0'; parse var v g 'E' _ .; return g*.5'E'_%2 +V3: procedure; parse arg v; return norm(v) diff --git a/Task/Deconvolution-1D/00DESCRIPTION b/Task/Deconvolution-1D/00DESCRIPTION index 630e811fc5..9d2d8d706f 100644 --- a/Task/Deconvolution-1D/00DESCRIPTION +++ b/Task/Deconvolution-1D/00DESCRIPTION @@ -4,7 +4,8 @@ satisfying : G(n) = \sum_{m=-\infty}^{\infty} F(m) H(n-m) -for all integers \mathit{n}. Assume F(n) can be non-zero only for 0\mathit{n}|\mathit{F}|, where |\mathit{F}| is the "length" of \mathit{F}, and similarly for \mathit{G} and \mathit{H}, so that the functions can be modeled as finite sequences by identifying f_0, f_1, f_2, \dots with F(0), F(1), F(2), \dots, etc. Then for example, values of |\mathit{F}| = 6 and |\mathit{H}| = 5 would determine the following value of \mathit{g} by definition. +for all integers \mathit{n}. Assume F(n) can be non-zero only for 0\mathit{n}|\mathit{F}|, where |\mathit{F}| is the "length" of \mathit{F}, and similarly for \mathit{G} and \mathit{H}, so that the functions can be modeled as finite sequences by identifying f_0, f_1, f_2, \dots with F(0), F(1), F(2), \dots, etc. +Then for example, values of |\mathit{F}| = 6 and |\mathit{H}| = 5 would determine the following value of \mathit{g} by definition. : \begin{array}{lllllllllll} diff --git a/Task/Deconvolution-1D/C/deconvolution-1d.c b/Task/Deconvolution-1D/C/deconvolution-1d.c new file mode 100644 index 0000000000..0d1cec01f9 --- /dev/null +++ b/Task/Deconvolution-1D/C/deconvolution-1d.c @@ -0,0 +1,92 @@ +#include +#include +#include +#include + +double PI; +typedef double complex cplx; + +void _fft(cplx buf[], cplx out[], int n, int step) +{ + if (step < n) { + _fft(out, buf, n, step * 2); + _fft(out + step, buf + step, n, step * 2); + + for (int i = 0; i < n; i += 2 * step) { + cplx t = cexp(-I * PI * i / n) * out[i + step]; + buf[i / 2] = out[i] + t; + buf[(i + n)/2] = out[i] - t; + } + } +} + +void fft(cplx buf[], int n) +{ + cplx out[n]; + for (int i = 0; i < n; i++) out[i] = buf[i]; + _fft(buf, out, n, 1); +} + +/* pad array length to power of two */ +cplx *pad_two(double g[], int len, int *ns) +{ + int n = 1; + if (*ns) n = *ns; + else while (n < len) n *= 2; + + cplx *buf = calloc(sizeof(cplx), n); + for (int i = 0; i < len; i++) buf[i] = g[i]; + *ns = n; + return buf; +} + +void deconv(double g[], int lg, double f[], int lf, double out[]) { + int ns = 0; + cplx *g2 = pad_two(g, lg, &ns); + cplx *f2 = pad_two(f, lf, &ns); + + fft(g2, ns); + fft(f2, ns); + + cplx h[ns]; + for (int i = 0; i < ns; i++) h[i] = g2[i] / f2[i]; + fft(h, ns); + + for (int i = 0; i >= lf - lg; i--) + out[-i] = h[(i + ns) % ns]/32; + free(g2); + free(f2); +} + +int main() +{ + PI = atan2(1,1) * 4; + double g[] = {24,75,71,-34,3,22,-45,23,245,25,52,25,-67,-96,96,31,55,36,29,-43,-7}; + double f[] = { -3,-6,-1,8,-6,3,-1,-9,-9,3,-2,5,2,-2,-7,-1 }; + double h[] = { -8,-9,-3,-1,-6,7 }; + + int lg = sizeof(g)/sizeof(double); + int lf = sizeof(f)/sizeof(double); + int lh = sizeof(h)/sizeof(double); + + double h2[lh]; + double f2[lf]; + + printf("f[] data is : "); + for (int i = 0; i < lf; i++) printf(" %g", f[i]); + printf("\n"); + + printf("deconv(g, h): "); + deconv(g, lg, h, lh, f2); + for (int i = 0; i < lf; i++) printf(" %g", f2[i]); + printf("\n"); + + printf("h[] data is : "); + for (int i = 0; i < lh; i++) printf(" %g", h[i]); + printf("\n"); + + printf("deconv(g, f): "); + deconv(g, lg, f, lf, h2); + for (int i = 0; i < lh; i++) printf(" %g", h2[i]); + printf("\n"); +} diff --git a/Task/Deconvolution-1D/Java/deconvolution-1d.java b/Task/Deconvolution-1D/Java/deconvolution-1d.java index daf4bd250a..61cd5cbbcb 100644 --- a/Task/Deconvolution-1D/Java/deconvolution-1d.java +++ b/Task/Deconvolution-1D/Java/deconvolution-1d.java @@ -1,26 +1,29 @@ import java.util.Arrays; public class Deconvolution1D { - public static double[] deconv(double[] f, double[] g) { - double[] h = new double[g.length - f.length + 1]; + public static int[] deconv(int[] g, int[] f) { + int[] h = new int[g.length - f.length + 1]; for (int n = 0; n < h.length; n++) { h[n] = g[n]; int lower = Math.max(n - f.length + 1, 0); for (int i = lower; i < n; i++) - h[n] -= h[i] * f[n-i]; + h[n] -= h[i] * f[n - i]; h[n] /= f[0]; } return h; } public static void main(String[] args) { - double[] h = {-8, -9, -3, -1, -6, 7}; - double[] f = {-3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1}; - double[] g = {24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, - 96, 31, 55, 36, 29, -43, -7}; - System.out.println(Arrays.toString(h)); - System.out.println(Arrays.toString(deconv(g, f))); - System.out.println(Arrays.toString(f)); - System.out.println(Arrays.toString(deconv(g, h))); + int[] h = { -8, -9, -3, -1, -6, 7 }; + int[] f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 }; + int[] g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, 25, -67, -96, + 96, 31, 55, 36, 29, -43, -7 }; + + StringBuilder sb = new StringBuilder(); + sb.append("h = " + Arrays.toString(h) + "\n"); + sb.append("deconv(g, f) = " + Arrays.toString(deconv(g, f)) + "\n"); + sb.append("f = " + Arrays.toString(f) + "\n"); + sb.append("deconv(g, h) = " + Arrays.toString(deconv(g, h)) + "\n"); + System.out.println(sb.toString()); } } diff --git a/Task/Deconvolution-2D+/D/deconvolution-2d+.d b/Task/Deconvolution-2D+/D/deconvolution-2d+.d index 4e58b189f3..8a826fb0c8 100644 --- a/Task/Deconvolution-2D+/D/deconvolution-2d+.d +++ b/Task/Deconvolution-2D+/D/deconvolution-2d+.d @@ -1,87 +1,90 @@ -import std.stdio, std.conv, std.array, std.algorithm, std.numeric, - std.range; +import std.stdio, std.conv, std.algorithm, std.numeric, std.range; class M(T) { private size_t[] dim; private size_t[] subsize; private T[] d; - this(size_t[] dimension ...) { + this(size_t[] dimension...) pure nothrow { setDimension(dimension); d[] = 0; // init each entry to zero; } M!T dup() { - M!T m = new M!T(dim); + auto m = new M!T(dim); return m.set1DArray(d); } - M!T setDimension(size_t[] dimension ...) { - foreach (e; dimension) + M!T setDimension(size_t[] dimension ...) pure nothrow { + foreach (const e; dimension) assert(e > 0, "no zero dimension"); dim = dimension.dup; subsize = dim.dup; - foreach (i; 0 .. dim.length) - subsize[i] = reduce!"a*b"(1, dim[i + 1 .. $]); - auto dlength = dim[0] * subsize[0]; + foreach (immutable i; 0 .. dim.length) + subsize[i] = reduce!q{a * b}(1, dim[i + 1 .. $]); + immutable dlength = dim[0] * subsize[0]; if (d.length != dlength) d = new T[dlength]; return this; } - M!T set1DArray(T[] t ...) { + M!T set1DArray(in T[] t ...) pure nothrow @nogc { auto minLen = min(t.length, d.length); d[] = 0; d[0 .. minLen] = t[0 .. minLen]; return this; } - size_t[] seq2idx(size_t seq) { + size_t[] seq2idx(in size_t seq) const pure nothrow { size_t acc = seq, tmp; size_t[] idx; - foreach (e; subsize) { + foreach (immutable e; subsize) { idx ~= tmp = acc / e; - acc = acc - tmp * e; // same as % (mod) e; + acc = acc - tmp * e; // same as % (mod) e. } return idx; } - size_t size() const @property { return d.length; } + size_t size() const pure nothrow @nogc @property { + return d.length; + } - size_t rank() const @property { return dim.length; } + size_t rank() const pure nothrow @nogc @property { + return dim.length; + } - size_t[] shape() const @property { return dim.dup; } + size_t[] shape() const pure nothrow @property { return dim.dup; } - T[] raw() const @property { return d.dup; } + T[] raw() const pure nothrow @property { return d.dup; } - bool checkBound(size_t[] idx ...) const { + bool checkBound(size_t[] idx ...) const pure nothrow @nogc { if (idx.length > dim.length) return false; - foreach (i, dm; idx) + foreach (immutable i, immutable dm; idx) if (dm >= dim[i]) return false; return true; } - T opIndex(size_t[] idx ...) { + T opIndex(size_t[] idx ...) const pure nothrow @nogc { assert(checkBound(idx), "OOPS"); return d[dotProduct(idx, subsize)]; } - T opIndexAssign(T v, size_t[] idx ...) { + T opIndexAssign(T v, size_t[] idx ...) pure nothrow @nogc { assert(checkBound(idx), "OOPS"); d[dotProduct(idx, subsize)] = v; return v; } - override bool opEquals(Object o) { - auto rhs = to!(M!T)(o); + override bool opEquals(Object o) const pure { + const rhs = to!(M!T)(o); return dim == rhs.dim && d == rhs.d; } - int opApply(int delegate(ref size_t[]) dg) { + int opApply(int delegate(ref size_t[]) dg) const { size_t[] yieldIdx; - foreach (i; 0 .. d.length) { + foreach (immutable i; 0 .. d.length) { yieldIdx = seq2idx(i); if (dg(yieldIdx)) break; @@ -91,83 +94,86 @@ class M(T) { int opApply(int delegate(ref size_t[], ref T) dg) { size_t idx1d = 0; - foreach (size_t[] idx; this) { + foreach (idx; this) { if (dg(idx, d[idx1d++])) break; } return 0; } - M!T convolute(M!T rhs) { // _this_ is h, rhs is f, output g + // _this_ is h, rhs is f, output g. + M!T convolute(M!T rhs) const pure nothrow { auto dm = dim.dup; dm[] += rhs.dim[] - 1; - M!T m = new M!T(dm); // dm will be reused as m's idx + M!T m = new M!T(dm); // dm will be reused as m's idx. auto bound = m.size; - foreach (i; 0 .. d.length) { + foreach (immutable i; 0 .. d.length) { auto thisIdx = seq2idx(i); - foreach (j; 0 .. rhs.d.length) { + foreach (immutable j; 0 .. rhs.d.length) { dm[] = thisIdx[] + rhs.seq2idx(j)[]; - auto midx1d = dotProduct(dm, m.subsize); - if ( midx1d < bound) + immutable midx1d = dotProduct(dm, m.subsize); + if (midx1d < bound) m.d[midx1d] += d[i] * rhs.d[j]; else - break; // bound reach, ok to break + break; // Bound reach, OK to break. } } return m; } - M!T deconvolute(M!T rhs) { // _this_ is g, rhs is f, output is h + // _this_ is g, rhs is f, output is h. + M!T deconvolute(M!T rhs) const pure nothrow { auto dm = dim.dup; foreach (i, e; dm) assert(e + 1 > rhs.dim[i], "deconv : dimensions is zero or negative"); dm[] -= (rhs.dim[] - 1); - M!T m = new M!T(dm); // dm will be reused as rhs' idx + auto m = new M!T(dm); // dm will be reused as rhs' idx. - foreach (i; 0 .. m.size) { + foreach (immutable i; 0 .. m.size) { auto idx = m.seq2idx(i); m.d[i] = this[idx]; - foreach (j; 0 .. i) { - auto jdx = m.seq2idx(j); + foreach (immutable j; 0 .. i) { + immutable jdx = m.seq2idx(j); dm[] = idx[] - jdx[]; if (rhs.checkBound(dm)) m.d[i] -= m.d[j] * rhs[dm]; } - m.d[i] /= rhs.d[0]; + m.d[i] /= rhs.d[0]; } return m; } - override string toString() { return to!string(d); } + override string toString() const pure { return d.text; } } -auto fold(T)(T[] arr, ref size_t[] d) { +auto fold(T)(T[] arr, ref size_t[] d) pure { if (d.length == 0) d ~= arr.length; - static if (is(T U : U[])) { // is arr an array of arrays? + + static if (is(T U : U[])) { // Is arr an array of arrays? assert(arr.length > 0, "no empty dimension"); d ~= arr[0].length; foreach (e; arr) - assert(e.length == arr[0].length, "not rectangular"); - return fold(reduce!q{a ~ b}(arr), d); + assert(e.length == arr[0].length, "Not rectangular"); + return fold(arr.reduce!q{a ~ b}, d); } else { - assert(arr.length == reduce!q{a * b}(d), "not same size"); + assert(arr.length == d.reduce!q{a * b}, "Not same size"); return arr; } } -auto arr2M(T)(T a) { +auto arr2M(T)(T a) pure { size_t[] dm; auto d = fold(a, dm); - alias ElementType!(typeof(d)) E; + alias E = ElementType!(typeof(d)); auto m = new M!E(dm); m.set1DArray(d); return m; } void main() { - alias M!int Mi; + alias Mi = M!int; auto hh = [[[-6, -8, -5, 9], [-7, 9, -6, -8], [2, -7, 9, 8]], [[7, 4, 4, -6], [9, 9, 4, -4], [-3, 7, -2, -3]]]; auto ff = [[[-9, 5, -8], [3, 5, 1]],[[-1, -7, 2], [-5, -6, 6]], @@ -175,7 +181,7 @@ void main() { auto h = arr2M(hh); auto f = arr2M(ff); - auto g = h.convolute(f); + const g = h.convolute(f); writeln("g == f convolute h ? ", g == f.convolute(h)); writeln("h == g deconv f ? ", h == g.deconvolute(f)); diff --git a/Task/Deepcopy/Babel/deepcopy.pb b/Task/Deepcopy/Babel/deepcopy.pb new file mode 100644 index 0000000000..50380930d5 --- /dev/null +++ b/Task/Deepcopy/Babel/deepcopy.pb @@ -0,0 +1,4 @@ +((main {foo cp bs2gv <<}) +(foo (foo bar baz)) +(bar (foo bar baz)) +(baz (foo bar baz))) diff --git a/Task/Define-a-primitive-data-type/00DESCRIPTION b/Task/Define-a-primitive-data-type/00DESCRIPTION index 8ae8a5e4ed..e6a1a5da69 100644 --- a/Task/Define-a-primitive-data-type/00DESCRIPTION +++ b/Task/Define-a-primitive-data-type/00DESCRIPTION @@ -1,3 +1 @@ -{{omit from|BBC BASIC}} -[[Category:Type System]] Demonstrate how to define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10. Include all bounds checking you need to write, or explain how the compiler or interpreter creates those bounds checks for you. diff --git a/Task/Define-a-primitive-data-type/00META.yaml b/Task/Define-a-primitive-data-type/00META.yaml index 659c8686af..77d4ea9670 100644 --- a/Task/Define-a-primitive-data-type/00META.yaml +++ b/Task/Define-a-primitive-data-type/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Type System note: Basic language learning diff --git a/Task/Define-a-primitive-data-type/Clojure/define-a-primitive-data-type.clj b/Task/Define-a-primitive-data-type/Clojure/define-a-primitive-data-type.clj new file mode 100644 index 0000000000..bc686f2fc0 --- /dev/null +++ b/Task/Define-a-primitive-data-type/Clojure/define-a-primitive-data-type.clj @@ -0,0 +1,6 @@ +(defn tinyint [^long value] + (if (<= 1 value 10) + (proxy [Number] [] + (doubleValue [] value) + (longValue [] value)) + (throw (ArithmeticException. "integer overflow")))) diff --git a/Task/Define-a-primitive-data-type/Scala/define-a-primitive-data-type.scala b/Task/Define-a-primitive-data-type/Scala/define-a-primitive-data-type.scala new file mode 100644 index 0000000000..72e56f74fe --- /dev/null +++ b/Task/Define-a-primitive-data-type/Scala/define-a-primitive-data-type.scala @@ -0,0 +1,14 @@ + class TinyInt(val int: Byte) { + import TinyInt._ + require(int >= lower && int <= upper, "TinyInt out of bounds.") + + override def toString = int.toString + } + + object TinyInt { + val (lower, upper) = (1, 10) + + def apply(i: Byte) = new TinyInt(i) + } + + val test = (TinyInt.lower to TinyInt.upper).map(n => TinyInt(n.toByte)) diff --git a/Task/Define-a-primitive-data-type/UNIX-Shell/define-a-primitive-data-type.sh b/Task/Define-a-primitive-data-type/UNIX-Shell/define-a-primitive-data-type.sh new file mode 100644 index 0000000000..0aa35ed7e1 --- /dev/null +++ b/Task/Define-a-primitive-data-type/UNIX-Shell/define-a-primitive-data-type.sh @@ -0,0 +1,16 @@ +typeset -i boundedint +function boundedint.set { + nameref var=${.sh.name} + if (( 1 <= .sh.value && .sh.value <= 10 )); then + # stash the valid value as a backup, in case we need to restore it + typeset -i var.previous_value=${.sh.value} + else + print -u2 "value out of bounds" + # restore previous value + .sh.value=${var.previous_value} + fi +} + +boundedint=-5; echo $boundedint +boundedint=5; echo $boundedint +boundedint=15; echo $boundedint diff --git a/Task/Delegates/Aime/delegates.aime b/Task/Delegates/Aime/delegates.aime index 5a9b4ac521..4e401da4b9 100644 --- a/Task/Delegates/Aime/delegates.aime +++ b/Task/Delegates/Aime/delegates.aime @@ -10,8 +10,8 @@ operation(record delegator) text s; if (r_key(delegator, "delegate")) { - if (r_key(r_query(delegator, "delegate"), "thing")) { - s = __text(call(r_query(r_query(delegator, "delegate"), "thing"))); + if (r_key(delegator["delegate"], "thing")) { + s = call(r_query(delegator["delegate"], "thing")); } else { s = "default implementation"; } diff --git a/Task/Delegates/Java/delegates.java b/Task/Delegates/Java/delegates-1.java similarity index 100% rename from Task/Delegates/Java/delegates.java rename to Task/Delegates/Java/delegates-1.java diff --git a/Task/Delegates/Java/delegates-2.java b/Task/Delegates/Java/delegates-2.java new file mode 100644 index 0000000000..7d09428bdc --- /dev/null +++ b/Task/Delegates/Java/delegates-2.java @@ -0,0 +1,6 @@ +package delegate; + +@FunctionalInterface +public interface Thingable { + public String thing(); +} diff --git a/Task/Delegates/Java/delegates-3.java b/Task/Delegates/Java/delegates-3.java new file mode 100644 index 0000000000..41cc1e6fa8 --- /dev/null +++ b/Task/Delegates/Java/delegates-3.java @@ -0,0 +1,19 @@ +package delegate; + +import java.util.Optional; + +public interface Delegator { + public Thingable delegate(); + public Delegator delegate(Thingable thingable); + + public static Delegator new_() { + return $Delegator.new_(); + } + + public default String operation() { + return Optional.ofNullable(delegate()) + .map(Thingable::thing) + .orElse("default implementation") + ; + } +} diff --git a/Task/Delegates/Java/delegates-4.java b/Task/Delegates/Java/delegates-4.java new file mode 100644 index 0000000000..8cb6181e7d --- /dev/null +++ b/Task/Delegates/Java/delegates-4.java @@ -0,0 +1,17 @@ +package delegate; + +@FunctionalInterface +/* package */ interface $Delegator extends Delegator { + @Override + public default Delegator delegate(Thingable thingable) { + return new_(thingable); + } + + public static $Delegator new_() { + return new_(() -> null); + } + + public static $Delegator new_(Thingable thingable) { + return () -> thingable; + } +} diff --git a/Task/Delegates/Java/delegates-5.java b/Task/Delegates/Java/delegates-5.java new file mode 100644 index 0000000000..f8b37299a6 --- /dev/null +++ b/Task/Delegates/Java/delegates-5.java @@ -0,0 +1,8 @@ +package delegate; + +public final class Delegate implements Thingable { + @Override + public String thing() { + return "delegate implementation"; + } +} diff --git a/Task/Delegates/Java/delegates-6.java b/Task/Delegates/Java/delegates-6.java new file mode 100644 index 0000000000..f0b6c23f79 --- /dev/null +++ b/Task/Delegates/Java/delegates-6.java @@ -0,0 +1,36 @@ +package delegate; + +// Example usage +// Memory management ignored for simplification +public interface DelegateTest { + public static String thingable() { + return "method reference implementation"; + } + + public static void main(String... arguments) { + // Without a delegate: + Delegator d1 = Delegator.new_(); + assert d1.operation().equals("default implementation"); + + // With a delegate: + Delegator d2 = d1.delegate(new Delegate()); + assert d2.operation().equals("delegate implementation"); + + // Same as the above, but with an anonymous class: + Delegator d3 = d2.delegate(new Thingable() { + @Override + public String thing() { + return "anonymous delegate implementation"; + } + }); + assert d3.operation().equals("anonymous delegate implementation"); + + // Same as the above, but with a method reference: + Delegator d4 = d3.delegate(DelegateTest::thingable); + assert d4.operation().equals("method reference implementation"); + + // Same as the above, but with a lambda expression: + Delegator d5 = d4.delegate(() -> "lambda expression implementation"); + assert d5.operation().equals("lambda expression implementation"); + } +} diff --git a/Task/Delegates/Racket/delegates.rkt b/Task/Delegates/Racket/delegates.rkt new file mode 100644 index 0000000000..e5aa55559d --- /dev/null +++ b/Task/Delegates/Racket/delegates.rkt @@ -0,0 +1,34 @@ +#lang racket +;; Delegates. Tim Brown 2014-10-16 + +(define delegator% + (class object% + (init-field [delegate #f]) + (define/public (operation) + (cond [(and (object? delegate) (object-method-arity-includes? delegate 'thing 0)) + (send delegate thing)] + [else "default implementation"])) + (super-new))) + +(define non-thinging-delegate% (class object% (super-new))) + +(define thinging-delegate% + (class object% + (define/public (thing) "delegate implementation") + (super-new))) + +(module+ test + (require tests/eli-tester) + (define delegator-1 (new delegator%)) + (define delegator-2 (new delegator%)) + (define non-thinging-delegate (new non-thinging-delegate%)) + (define thinging-delegate (new thinging-delegate%)) + + (test + (send delegator-1 operation) => "default implementation" + (send delegator-2 operation) => "default implementation" + (set-field! delegate delegator-1 non-thinging-delegate) => (void) + (set-field! delegate delegator-2 thinging-delegate) => (void) + (send delegator-1 operation) => "default implementation" + (send delegator-2 operation) => "delegate implementation" + (send (new delegator% [delegate thinging-delegate]) operation) => "delegate implementation")) diff --git a/Task/Delete-a-file/Groovy/delete-a-file.groovy b/Task/Delete-a-file/Groovy/delete-a-file.groovy new file mode 100644 index 0000000000..ebfb681f1b --- /dev/null +++ b/Task/Delete-a-file/Groovy/delete-a-file.groovy @@ -0,0 +1,18 @@ +// Gets the first filesystem root. On most systems this will be / or c:\ +def fsRoot = File.listRoots().first() + +// Create our list of files (including directories) +def files = [ + new File("input.txt"), + new File(fsRoot, "input.txt"), + new File("docs"), + new File(fsRoot, "docs") +] + +/* +We use it.directory to determine whether each file is a regular file or directory. If it is a directory, we delete +it with deleteDir(), otherwise we just use delete(). + */ +files.each{ + it.directory ? it.deleteDir() : it.delete() +} diff --git a/Task/Delete-a-file/Maple/delete-a-file.maple b/Task/Delete-a-file/Maple/delete-a-file.maple new file mode 100644 index 0000000000..95484554c9 --- /dev/null +++ b/Task/Delete-a-file/Maple/delete-a-file.maple @@ -0,0 +1,4 @@ +FileTools:-Remove("input.txt"); +FileTools:-RemoveDirectory("docs"); +FileTools:-Remove("/input.txt"); +FileTools:-RemoveDirectory("/docs"); diff --git a/Task/Delete-a-file/NewLISP/delete-a-file.newlisp b/Task/Delete-a-file/NewLISP/delete-a-file.newlisp new file mode 100644 index 0000000000..9b3c669de7 --- /dev/null +++ b/Task/Delete-a-file/NewLISP/delete-a-file.newlisp @@ -0,0 +1,4 @@ +(delete-file "input.txt") +(delete-file "/input.txt") +(remove-dir "docs") +(remove-dir "/docs") diff --git a/Task/Delete-a-file/Scala/delete-a-file.scala b/Task/Delete-a-file/Scala/delete-a-file.scala index 365dbd3b45..c30a79cd1a 100644 --- a/Task/Delete-a-file/Scala/delete-a-file.scala +++ b/Task/Delete-a-file/Scala/delete-a-file.scala @@ -2,17 +2,14 @@ import java.util._ import java.io.File object FileDeleteTest extends App { - - def deleteFile(filename: String) = { - new File(filename).delete(); - } + def deleteFile(filename: String) = { new File(filename).delete() } def test(typ: String, filename: String) = { System.out.println("The following " + typ + " called " + filename + (if (deleteFile(filename)) " was deleted." else " could not be deleted.")) } - test("file", "input.txt"); - test("file", File.separatorChar + "input.txt"); - test("directory", "docs"); - test("directory", File.separatorChar + "docs" + File.separatorChar); + test("file", "input.txt") + test("file", File.separatorChar + "input.txt") + test("directory", "docs") + test("directory", File.separatorChar + "docs" + File.separatorChar) } diff --git a/Task/Delete-a-file/Seed7/delete-a-file.seed7 b/Task/Delete-a-file/Seed7/delete-a-file.seed7 new file mode 100644 index 0000000000..8592e2b8d1 --- /dev/null +++ b/Task/Delete-a-file/Seed7/delete-a-file.seed7 @@ -0,0 +1,10 @@ +$ include "seed7_05.s7i"; + include "osfiles.s7i"; + +const proc: main is func + begin + removeFile("input.txt"); + removeFile("/input.txt"); + removeTree("docs"); + removeTree("/docs"); + end func; diff --git a/Task/Detect-division-by-zero/00DESCRIPTION b/Task/Detect-division-by-zero/00DESCRIPTION index ee7afd59e8..14e2f1f798 100644 --- a/Task/Detect-division-by-zero/00DESCRIPTION +++ b/Task/Detect-division-by-zero/00DESCRIPTION @@ -1 +1,2 @@ -Write a function to detect a divide by zero error without checking if the denominator is zero. +Write a function to detect a divide by zero error +without checking if the denominator is zero. diff --git a/Task/Detect-division-by-zero/00META.yaml b/Task/Detect-division-by-zero/00META.yaml new file mode 100644 index 0000000000..df58a6932c --- /dev/null +++ b/Task/Detect-division-by-zero/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Simple diff --git a/Task/Detect-division-by-zero/Emacs-Lisp/detect-division-by-zero.l b/Task/Detect-division-by-zero/Emacs-Lisp/detect-division-by-zero.l new file mode 100644 index 0000000000..1ec711611a --- /dev/null +++ b/Task/Detect-division-by-zero/Emacs-Lisp/detect-division-by-zero.l @@ -0,0 +1,4 @@ +(condition-case nil + (/ 1 0) + (arith-error + (message "Divide by zero (either integer or float)"))) diff --git a/Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-1.pari b/Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-1.pari new file mode 100644 index 0000000000..4867022cc8 --- /dev/null +++ b/Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-1.pari @@ -0,0 +1,4 @@ +iferr(1/0, + err, + print("division by 0"); print("or other non-invertible divisor"), + errname(err) == "e_INV"); diff --git a/Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero.pari b/Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-2.pari similarity index 100% rename from Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero.pari rename to Task/Detect-division-by-zero/PARI-GP/detect-division-by-zero-2.pari diff --git a/Task/Detect-division-by-zero/PL-I/detect-division-by-zero.pli b/Task/Detect-division-by-zero/PL-I/detect-division-by-zero.pli index 65bf7aaa4f..8e860e709b 100644 --- a/Task/Detect-division-by-zero/PL-I/detect-division-by-zero.pli +++ b/Task/Detect-division-by-zero/PL-I/detect-division-by-zero.pli @@ -1,5 +1,10 @@ -/* A function is not required to detect division by zero. */ -/* The following statement is executed anywhere prior to */ -/* executing the statement containing the division by zero. */ +Proc DivideDZ(a,b) Returns(Float Bin(33)); + Dcl (a,b,c) Float Bin(33); + On ZeroDivide GoTo MyError; + c=a/b; + Return(c); +MyError: + Put Skip List('Divide by Zero Detected!'); +End DivideDZ; -on zerodivide snap go to trap_zerodivide; +xx=DivideDZ(1,0); diff --git a/Task/Determine-if-a-string-is-numeric/AWK/determine-if-a-string-is-numeric.awk b/Task/Determine-if-a-string-is-numeric/AWK/determine-if-a-string-is-numeric.awk index e275298c53..a15fcdba28 100644 --- a/Task/Determine-if-a-string-is-numeric/AWK/determine-if-a-string-is-numeric.awk +++ b/Task/Determine-if-a-string-is-numeric/AWK/determine-if-a-string-is-numeric.awk @@ -1,2 +1 @@ -$ awk 'function isnum(x){return(x==x+0)}BEGIN{print isnum("hello"),isnum("-42")}' -0 1 +$ awk 'function isnum(x){return(x==x+0)} BEGIN{print isnum("hello"),isnum("-42")}' diff --git a/Task/Determine-if-a-string-is-numeric/Aime/determine-if-a-string-is-numeric.aime b/Task/Determine-if-a-string-is-numeric/Aime/determine-if-a-string-is-numeric.aime index 0089b17489..fa8b3a39ce 100644 --- a/Task/Determine-if-a-string-is-numeric/Aime/determine-if-a-string-is-numeric.aime +++ b/Task/Determine-if-a-string-is-numeric/Aime/determine-if-a-string-is-numeric.aime @@ -1,13 +1,7 @@ -integer -numeric(text s) -{ - return alpha(s, 0); -} - integer is_numeric(text s) { - return !trap(numeric, s); + return !trap_q(alpha, s, 0); } integer diff --git a/Task/Determine-if-a-string-is-numeric/Batch-File/determine-if-a-string-is-numeric.bat b/Task/Determine-if-a-string-is-numeric/Batch-File/determine-if-a-string-is-numeric.bat new file mode 100644 index 0000000000..a5fcb429a2 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Batch-File/determine-if-a-string-is-numeric.bat @@ -0,0 +1,10 @@ +set /a a=%arg%+0 >nul +if %a% == 0 ( + if not "%arg%"=="0" ( + echo Non Numeric. + ) else ( + echo Numeric. + ) +) else ( + echo Numeric. +) diff --git a/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-1.d b/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-1.d index 83c1e79a64..bd34a5c787 100644 --- a/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-1.d +++ b/Task/Determine-if-a-string-is-numeric/D/determine-if-a-string-is-numeric-1.d @@ -1,7 +1,7 @@ import std.stdio, std.string, std.array; void main() { - foreach (const s; ["12", " 12\t", "hello12", "-12", "02" + foreach (const s; ["12", " 12\t", "hello12", "-12", "02", "0-12", "+12", "1.5", "1,000", "1_000", "0x10", "0b10101111_11110000_11110000_00110011", "-0b10101", "0x10.5"]) 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 a3476e4e53..b39e964c0d 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 @@ -19,7 +19,7 @@ bool isNumeric(in string s) pure { } void main() { - foreach (immutable 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"]) diff --git a/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-1.pro b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-1.pro new file mode 100644 index 0000000000..21628a45ff --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-1.pro @@ -0,0 +1,3 @@ +numeric_string(String) :- + atom_string(Atom, String), + atom_number(Atom, _). diff --git a/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-2.pro b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-2.pro new file mode 100644 index 0000000000..b4019673e5 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-2.pro @@ -0,0 +1,8 @@ +test_strings(Strings) :- + forall( member(String, Strings), + ( ( numeric_string(String) + -> Result = a + ; Result = 'not a' ), + format('~w is ~w number.~n', [String, Result]) + ) + ). diff --git a/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-3.pro b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-3.pro new file mode 100644 index 0000000000..3be22c5af5 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Prolog/determine-if-a-string-is-numeric-3.pro @@ -0,0 +1,7 @@ +?- test_strings(["123", "0.123", "-123.1", "NotNum", "1."]). +123 is a number. +0.123 is a number. +-123.1 is a number. +NotNum is not a number. +1. is not a number. +true. diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py index 66c76bcf88..c21b0db3a8 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-1.py @@ -1,5 +1,5 @@ s = '123' try: i = float(s) -except ValueError, TypeError: +except (ValueError, TypeError): print 'not numeric' diff --git a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py index b7d100d015..44802a8f1a 100644 --- a/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py +++ b/Task/Determine-if-a-string-is-numeric/Python/determine-if-a-string-is-numeric-2.py @@ -1,3 +1,3 @@ s = '123' if s.isdigit(): - # numeric + print int(s) diff --git a/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx b/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx index 6f3100103e..3a9c11892a 100644 --- a/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx +++ b/Task/Determine-if-a-string-is-numeric/REXX/determine-if-a-string-is-numeric.rexx @@ -36,7 +36,7 @@ if \datatype(yyy,'n') then say 'oops, not numeric:' yyy if \datatype(yyy,'N') then say 'oops, not numeric:' yyy if ¬datatype(yyy,'N') then say 'oops, not numeric:' yyy if ¬datatype(yyy,'numeric') then say 'oops, not numeric:' yyy -if ¬datatype(yyy,'nimrod.') then say 'oops, not numeric:' yyy +if ¬datatype(yyy,'nim.') then say 'oops, not numeric:' yyy if datatype(yyy)\=='NUM' then say 'oops, not numeric:' yyy if datatype(yyy)/=='NUM' then say 'oops, not numeric:' yyy if datatype(yyy)¬=='NUM' then say 'oops, not numeric:' yyy diff --git a/Task/Determine-if-a-string-is-numeric/RapidQ/determine-if-a-string-is-numeric.rapidq b/Task/Determine-if-a-string-is-numeric/RapidQ/determine-if-a-string-is-numeric.rapidq index 7c8da42498..f4b17ea25a 100644 --- a/Task/Determine-if-a-string-is-numeric/RapidQ/determine-if-a-string-is-numeric.rapidq +++ b/Task/Determine-if-a-string-is-numeric/RapidQ/determine-if-a-string-is-numeric.rapidq @@ -1 +1,49 @@ isnumeric +$Typecheck on + +Defint FALSE, TRUE + +FALSE = 0 +TRUE = NOT FALSE + +Function isNumeric(s as string, optchar as string) as integer + If len(s) = 0 then + Result = FALSE + Exit Function + End If + if instr(s,"+") > 1 then + Result = FALSE + exit function + end if + if instr(s,"-") > 1 then + Result = FALSE + exit function + end if + Defint i, ndex = 0 + For i = 1 to len(s) + select case asc(mid$(s,i,1)) + case 43 '+ + case 45 '- + case 46 '. + if ndex = 1 then + Result = FALSE + Exit function + end if + ndex = 1 + case 48 to 57 '0 to 9 + case else + if instr(optchar,(mid$(s,i,1))) = 0 then + Result = FALSE + exit function + end if + end select + next + Result = TRUE +End Function + +'============================================================ +'Begin +'============================================================ + +showmessage (str$(isNumeric("-152.34",""))) +end diff --git a/Task/Determine-if-a-string-is-numeric/Run-BASIC/determine-if-a-string-is-numeric.run b/Task/Determine-if-a-string-is-numeric/Run-BASIC/determine-if-a-string-is-numeric.run index eb5d742a66..69e947a103 100644 --- a/Task/Determine-if-a-string-is-numeric/Run-BASIC/determine-if-a-string-is-numeric.run +++ b/Task/Determine-if-a-string-is-numeric/Run-BASIC/determine-if-a-string-is-numeric.run @@ -11,14 +11,14 @@ isNumeric = 1 f$ = trim$(f$) if left$(f$,1) = "-" or left$(f$,1) = "+" then f$ = mid$(f$,2) for i = 1 to len(f$) - if mid$(f$,i,1) = "." then - if dot$ = "." then isNumeric = 0 + d$ = mid$(f$,i,1) + if d$ = "," then goto [nxtDigit] + if d$ = "." then + if dot$ = "." then isNumeric = 0 dot$ = "." goto [nxtDigit] end if - if mid$(f$,i,1) = "," then goto [nxtDigit] - if mid$(f$,i,1) < "0" then isNumeric = 0 - if mid$(f$,i,1) > "9" then isNumeric = 0 + if (d$ < "0") or (d$ > "9") then isNumeric = 0 [nxtDigit] next i END FUNCTION diff --git a/Task/Determine-if-a-string-is-numeric/Seed7/determine-if-a-string-is-numeric.seed7 b/Task/Determine-if-a-string-is-numeric/Seed7/determine-if-a-string-is-numeric.seed7 new file mode 100644 index 0000000000..9bb5a61410 --- /dev/null +++ b/Task/Determine-if-a-string-is-numeric/Seed7/determine-if-a-string-is-numeric.seed7 @@ -0,0 +1,12 @@ +$ include "seed7_05.s7i"; + include "scanstri.s7i"; + +const func boolean: isNumeric (in var string: stri) is func + result + var boolean: isNumeric is FALSE; + local + var string: numberStri is ""; + begin + numberStri := getNumber(stri); + isNumeric := stri = ""; + end func; diff --git a/Task/Digital-root/00DESCRIPTION b/Task/Digital-root/00DESCRIPTION index 02d372d43c..384c1bdea9 100644 --- a/Task/Digital-root/00DESCRIPTION +++ b/Task/Digital-root/00DESCRIPTION @@ -1,20 +1,21 @@ -Related task [[Sum digits of an integer]] - -The digital root (X) of a number (N) is calculated: -: find X as the sum of the digits of N -: find a new X by summing the digits of X repeating until X has only one digit. +The digital root, X, of a number, n, is calculated: +: find X as the sum of the digits of n +: find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. -The task is to calculate the additive persistence and the digital root of a number. e.g. -:627615 has additive persistence 2 and digital root of 9; -:39390 has additive persistence 2 and digital root of 6; -:588225 has additive persistence 2 and digital root of 3; -:393900588225 has additive persistence 2 and digital root of 9; +The task is to calculate the additive persistence and the digital root of a number, e.g.: +:627615 has additive persistence 2 and digital root of 9; +:39390 has additive persistence 2 and digital root of 6; +:588225 has additive persistence 2 and digital root of 3; +:393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. See: *[[Casting out nines]] for this wiki's use of this procedure. +*[[Digital root/Multiplicative digital root]] +*[[Sum digits of an integer]] *[[oeis:A010888|Digital root sequence on OEIS]] *[[oeis:A031286|Additive persistence sequence on OEIS]] +*[[Iterated digits squaring]] diff --git a/Task/Digital-root/Ada/digital-root-1.ada b/Task/Digital-root/Ada/digital-root-1.ada new file mode 100644 index 0000000000..22c263a2a6 --- /dev/null +++ b/Task/Digital-root/Ada/digital-root-1.ada @@ -0,0 +1,15 @@ +package Generic_Root is + type Number is range 0 .. 2**63-1; + type Number_Array is array(Positive range <>) of Number; + type Base_Type is range 2 .. 16; -- any reasonable base to write down numb + + generic + with function "&"(X, Y: Number) return Number; + -- instantiate with "+" for additive digital roots + -- instantiate with "*" for multiplicative digital roots + procedure Compute_Root(N: Number; + Root, Persistence: out Number; + Base: Base_Type := 10); + -- computes Root and Persistence of N; + +end Generic_Root; diff --git a/Task/Digital-root/Ada/digital-root-2.ada b/Task/Digital-root/Ada/digital-root-2.ada new file mode 100644 index 0000000000..9efe179168 --- /dev/null +++ b/Task/Digital-root/Ada/digital-root-2.ada @@ -0,0 +1,26 @@ +package body Generic_Root is + + procedure Compute_Root(N: Number; + Root, Persistence: out Number; + Base: Base_Type := 10) is + + function Digit_Sum(N: Number) return Number is + begin + if N < Number(Base) then + return N; + else + return (N mod Number(Base)) & Digit_Sum(N / Number(Base)); + end if; + end Digit_Sum; + + begin + if N < Number(Base) then + Root := N; + Persistence := 0; + else + Compute_Root(Digit_Sum(N), Root, Persistence, Base); + Persistence := Persistence + 1; + end if; + end Compute_Root; + +end Generic_Root; diff --git a/Task/Digital-root/Ada/digital-root-3.ada b/Task/Digital-root/Ada/digital-root-3.ada new file mode 100644 index 0000000000..561431596b --- /dev/null +++ b/Task/Digital-root/Ada/digital-root-3.ada @@ -0,0 +1,26 @@ +with Generic_Root, Ada.Text_IO; use Generic_Root; + +procedure Digital_Root is + + procedure Compute is new Compute_Root("+"); + -- "+" for additive digital roots + + package TIO renames Ada.Text_IO; + + procedure Print_Roots(Inputs: Number_Array; Base: Base_Type) is + package NIO is new TIO.Integer_IO(Number); + Root, Pers: Number; + begin + for I in Inputs'Range loop + Compute(Inputs(I), Root, Pers, Base); + NIO.Put(Inputs(I), Base => Integer(Base), Width => 12); + NIO.Put(Root, Base => Integer(Base), Width => 9); + NIO.Put(Pers, Base => Integer(Base), Width => 12); + TIO.Put_Line(" " & Base_Type'Image(Base)); + end loop; + end Print_Roots; +begin + TIO.Put_Line(" Number Root Persistence Base"); + Print_Roots((961038, 923594037444, 670033, 448944221089), Base => 10); + Print_Roots((16#7e0#, 16#14e344#, 16#12343210#), Base => 16); +end Digital_Root; diff --git a/Task/Digital-root/Ada/digital-root.ada b/Task/Digital-root/Ada/digital-root.ada deleted file mode 100644 index ed39a307aa..0000000000 --- a/Task/Digital-root/Ada/digital-root.ada +++ /dev/null @@ -1,48 +0,0 @@ -with Ada.Text_IO; - -procedure Digital_Root is - - type Number is range 0 .. 2**63-1; - type Number_Array is array(Positive range <>) of Number; - type Base_Type is range 2 .. 16; -- any reasonable base to write down numbers - - procedure Compute(N: Number; Digital_Root, Persistence: out Number; - Base: Base_Type := 10) is - - function Digit_Sum(N: Number) return Number is - begin - if N < Number(Base) then - return N; - else - return (N mod Number(Base)) + Digit_Sum(N / Number(Base)); - end if; - end Digit_Sum; - - begin - if N < Number(Base) then - Digital_Root := N; - Persistence := 0; - else - Compute(Digit_Sum(N), Digital_Root, Persistence, Base); - Persistence := Persistence + 1; - end if; - end Compute; - - procedure Compute_And_Write(Values: Number_Array; Base: Base_Type := 10) is - Root, Pers: Number; - package NIO is new Ada.Text_IO.Integer_IO(Number); - begin - for I in Values'Range loop - Compute(Values(I), Root, Pers, Base); - NIO.Put(Values(I), Base => Integer(Base), Width => 12); - Ada.Text_IO.Put(" has digital root "); - NIO.Put(Root, Base => Integer(Base), Width => 0); - Ada.Text_IO.Put(" and additive persistence" & Number'Image(Pers)); - Ada.Text_IO.Put_Line(" (base" & Base_Type'Image(Base) & ")."); - end loop; - end Compute_And_Write; - -begin - Compute_And_Write((961038, 923594037444, 670033, 448944221089)); - Compute_And_Write((16#7e0#, 16#14e344#, 16#12343210#), 16); -end Digital_Root; diff --git a/Task/Digital-root/D/digital-root.d b/Task/Digital-root/D/digital-root.d index ab1ed1c7cd..40e4610b7f 100644 --- a/Task/Digital-root/D/digital-root.d +++ b/Task/Digital-root/D/digital-root.d @@ -2,7 +2,7 @@ import std.stdio, std.typecons, std.conv, std.bigint, std.math, std.traits; Tuple!(uint, Unqual!T) digitalRoot(T)(in T inRoot, in uint base) -pure /*nothrow*/ +pure nothrow in { assert(base > 1); } body { diff --git a/Task/Digital-root/Eiffel/digital-root.e b/Task/Digital-root/Eiffel/digital-root.e new file mode 100644 index 0000000000..70022954de --- /dev/null +++ b/Task/Digital-root/Eiffel/digital-root.e @@ -0,0 +1,69 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + digital_root_test_values: ARRAY [INTEGER_64] + -- Test values. + once + Result := <<670033, 39390, 588225, 393900588225>> -- base 10 + end + + digital_root_expected_result: ARRAY [INTEGER_64] + -- Expected result values. + once + Result := <<1, 6, 3, 9>> -- base 10 + end + + make + local + results: ARRAY [INTEGER_64] + i: INTEGER + do + from + i := 1 + until + i > digital_root_test_values.count + loop + results := compute_digital_root (digital_root_test_values [i], 10) + if results [2] ~ digital_root_expected_result [i] then + print ("%N" + digital_root_test_values [i].out + " has additive persistence " + results [1].out + " and digital root " + results [2].out) + else + print ("Error in the calculation of the digital root of " + digital_root_test_values [i].out + ". Expected value: " + digital_root_expected_result [i].out + ", produced value: " + results [2].out) + end + i := i + 1 + end + end + +compute_digital_root (a_number: INTEGER_64; a_base: INTEGER): ARRAY [INTEGER_64] + -- Returns additive persistence and digital root of `a_number' using `a_base'. + require + valid_number: a_number >= 0 + valid_base: a_base > 1 + local + temp_num: INTEGER_64 + do + create Result.make_filled (0, 1, 2) + from + Result [2] := a_number + until + Result [2] < a_base + loop + from + temp_num := Result [2] + Result [2] := 0 + until + temp_num = 0 + loop + Result [2] := Result [2] + (temp_num \\ a_base) + temp_num := temp_num // a_base + end + Result [1] := Result [1] + 1 + end + end diff --git a/Task/Digital-root/Erlang/digital-root.erl b/Task/Digital-root/Erlang/digital-root.erl index 2aaf33390e..4eab4fc8db 100644 --- a/Task/Digital-root/Erlang/digital-root.erl +++ b/Task/Digital-root/Erlang/digital-root.erl @@ -8,7 +8,6 @@ task() -> [io:fwrite("~p has additive persistence ~p and digital root of ~p~n", [X, Y, Z]) || {X, {Y, Z}} <- lists:zip(Ns, Persistances)]. - persistance_root( X ) -> persistance_root( sum_digits:sum_digits(X), 1 ). persistance_root( X, N ) when X < 10 -> {N, X}; diff --git a/Task/Digital-root/Fortran/digital-root.f b/Task/Digital-root/Fortran/digital-root.f new file mode 100644 index 0000000000..e712ea69bf --- /dev/null +++ b/Task/Digital-root/Fortran/digital-root.f @@ -0,0 +1,31 @@ +program prec +implicit none +integer(kind=16) :: i +i = 627615 +call root_pers(i) +i = 39390 +call root_pers(i) +i = 588225 +call root_pers(i) +i = 393900588225 +call root_pers(i) +end program + +subroutine root_pers(i) +implicit none +integer(kind=16) :: N, s, a, i +write(*,*) 'Number: ', i +n = i +a = 0 +do while(n.ge.10) + a = a + 1 + s = 0 + do while(n.gt.0) + s = s + n-int(real(n,kind=8)/10.0D0,kind=8) * 10_8 + n = int(real(n,kind=16)/real(10,kind=8),kind=8) + end do + n = s +end do +write(*,*) 'digital root = ', s +write(*,*) 'additive persistance = ', a +end subroutine diff --git a/Task/Digital-root/Go/digital-root.go b/Task/Digital-root/Go/digital-root.go index 036d677e99..a50b81f2cb 100644 --- a/Task/Digital-root/Go/digital-root.go +++ b/Task/Digital-root/Go/digital-root.go @@ -1,56 +1,68 @@ package main import ( - "fmt" - "log" - "strconv" - - "digit" + "fmt" + "log" + "strconv" ) -type testCase struct { - n string - base int - persistence int - root int +func Sum(i uint64, base int) (sum int) { + b64 := uint64(base) + for ; i > 0; i /= b64 { + sum += int(i % b64) + } + return } -var testCases = []testCase{ - {"627615", 10, 2, 9}, - {"39390", 10, 2, 6}, - {"588225", 10, 2, 3}, - {"393900588225", 10, 2, 9}, +func DigitalRoot(n uint64, base int) (persistence, root int) { + root = int(n) + for x := n; x >= uint64(base); x = uint64(root) { + root = Sum(x, base) + persistence++ + } + return } -func root(n string, base int) (persistence, root int, err error) { - i, err := digit.Sum(n, base) - if err != nil { - return 0, 0, err - } - if len(n) == 1 { - return 0, int(i), nil - } - for { - persistence++ - n := strconv.FormatInt(i, base) - if len(n) == 1 { - root = int(i) - break - } - i, _ = digit.Sum(n, base) - } - return +// Normally the below would be moved to a *_test.go file and +// use the testing package to be runnable as a regular test. + +var testCases = []struct { + n string + base int + persistence int + root int +}{ + {"627615", 10, 2, 9}, + {"39390", 10, 2, 6}, + {"588225", 10, 2, 3}, + {"393900588225", 10, 2, 9}, + {"1", 10, 0, 1}, + {"11", 10, 1, 2}, + {"e", 16, 0, 0xe}, + {"87", 16, 1, 0xf}, + // From Applesoft BASIC example: + {"DigitalRoot", 30, 2, 26}, // 26 is Q base 30 + // From C++ example: + {"448944221089", 10, 3, 1}, + {"7e0", 16, 2, 0x6}, + {"14e344", 16, 2, 0xf}, + {"d60141", 16, 2, 0xa}, + {"12343210", 16, 2, 0x1}, + // From the D example: + {"1101122201121110011000000", 3, 3, 1}, } func main() { - for _, tc := range testCases { - p, r, err := root(tc.n, tc.base) - if err != nil { - log.Fatal(err) - } - if p != tc.persistence || r != tc.root { - log.Fatal("test case", tc) - } - } - fmt.Println("all tests passed") + for _, tc := range testCases { + n, err := strconv.ParseUint(tc.n, tc.base, 64) + if err != nil { + log.Fatal(err) + } + p, r := DigitalRoot(n, tc.base) + fmt.Printf("%12v (base %2d) has additive persistence %d and digital root %s\n", + tc.n, tc.base, p, strconv.FormatInt(int64(r), tc.base)) + if p != tc.persistence || r != tc.root { + log.Fatalln("bad result:", tc, p, r) + } + } } diff --git a/Task/Digital-root/Haskell/digital-root-1.hs b/Task/Digital-root/Haskell/digital-root-1.hs index 547a2e3323..dff616585c 100644 --- a/Task/Digital-root/Haskell/digital-root-1.hs +++ b/Task/Digital-root/Haskell/digital-root-1.hs @@ -1,10 +1,10 @@ -digSum base = f 0 where - f a n = let (q,r) = n`divMod`base in - if q == 0 then a+r else f (a+r) q +import Data.List (unfoldr) -digRoot base = f 0 where - f p n | n < base = (p,n) - | otherwise = f (p+1) (digSum base n) +digSum base = sum . unfoldr f where + f 0 = Nothing + f n = Just (r,q) where (q,r) = n `divMod` base + +digRoot base = head . dropWhile ((>= base).snd) . zip [0..] . iterate (digSum base) main = do putStrLn "in base 10:" diff --git a/Task/Digital-root/Haskell/digital-root-2.hs b/Task/Digital-root/Haskell/digital-root-2.hs index 3df61a7be5..319ebab156 100644 --- a/Task/Digital-root/Haskell/digital-root-2.hs +++ b/Task/Digital-root/Haskell/digital-root-2.hs @@ -1,4 +1,4 @@ -import Data.List (elemIndex) +import Data.List (elemIndex, unfoldr) import Data.Maybe (fromJust) import Numeric (readInt, showIntAtBase) @@ -22,17 +22,16 @@ printDigRoot b s = do -- Convert a base b number to a list of digits, from least to most significant. toDigits :: Integral a => a -> a -> [a] -toDigits b n = toDigits' n 0 - where toDigits' 0 0 = [0] - toDigits' 0 _ = [] - toDigits' m _ = let (q, r) = m `quotRem` b in r : toDigits' q r +toDigits b = unfoldr f + where f 0 = Nothing + f n = Just (r,q) where (q,r) = n `quotRem` b -- A list of digits, for bases up to 36. digits :: String digits = ['0'..'9'] ++ ['A'..'Z'] -- Return a number's base b string representation. -intToStr :: Integral a => a -> a -> String +intToStr :: (Integral a, Show a) => a -> a -> String intToStr b n | b < 2 || b > 36 = error "intToStr: base must be in [2..36]" | otherwise = showIntAtBase b (digits !!) n "" diff --git a/Task/Digital-root/JavaScript/digital-root.js b/Task/Digital-root/JavaScript/digital-root.js new file mode 100644 index 0000000000..fee716ab28 --- /dev/null +++ b/Task/Digital-root/JavaScript/digital-root.js @@ -0,0 +1,16 @@ +/// Digital root of 'x' in base 'b'. +/// @return {addpers, digrt} +function digitalRootBase(x,b) { + if (x < b) + return {addpers:0, digrt:x}; + + var fauxroot = 0; + while (b <= x) { + x = (x / b) | 0; + fauxroot += x % b; + } + + var rootobj = digitalRootBase(fauxroot,b); + rootobj.addpers += 1; + return rootobj; +} diff --git a/Task/Digital-root/Lua/digital-root.lua b/Task/Digital-root/Lua/digital-root.lua new file mode 100644 index 0000000000..4a29a0e84d --- /dev/null +++ b/Task/Digital-root/Lua/digital-root.lua @@ -0,0 +1,13 @@ +function digital_root(n, base) + p = 0 + while n > 9.5 do + n = sum_digits(n, base) + p = p + 1 + end + return n, p +end + +print(digital_root(627615, 10)) +print(digital_root(39390, 10)) +print(digital_root(588225, 10)) +print(digital_root(393900588225, 10)) diff --git a/Task/Digital-root/PL-I/digital-root.pli b/Task/Digital-root/PL-I/digital-root-1.pli similarity index 100% rename from Task/Digital-root/PL-I/digital-root.pli rename to Task/Digital-root/PL-I/digital-root-1.pli diff --git a/Task/Digital-root/PL-I/digital-root-2.pli b/Task/Digital-root/PL-I/digital-root-2.pli new file mode 100644 index 0000000000..90c71bdac4 --- /dev/null +++ b/Task/Digital-root/PL-I/digital-root-2.pli @@ -0,0 +1,15 @@ +digital: procedure options (main); /* 29 April 2014 */ + declare 1 pict union, + 2 x picture '9999999999999', + 2 d(13) picture '9'; + declare ap fixed, n fixed (15); + + do n = 5, 627615, 39390, 588225, 393900588225, 99999999999; + x = n; + do ap = 1 by 1 until (x < 10); + x = sum(d); + end; + put skip data (n, x, ap); + end; + +end digital; diff --git a/Task/Digital-root/REXX/digital-root-2.rexx b/Task/Digital-root/REXX/digital-root-2.rexx index ca0869427c..4f1c4c1281 100644 --- a/Task/Digital-root/REXX/digital-root-2.rexx +++ b/Task/Digital-root/REXX/digital-root-2.rexx @@ -1,8 +1,8 @@ -/*REXX program calculates the digital root and additive persistence. */ +/*REXX program calculates the digital root and additive persisteance. */ numeric digits 1000 /*lets handle biguns.*/ say 'digital' /*part of the header.*/ -say ' root persistence' center('number',79) /* " " " " */ -say '═══════ ═══════════' center('' ,79,'═') /* " " " " */ +say ' root persistence' center('number',81) /* " " " " */ +say '═══════ ═══════════' center('' ,81,'═') /* " " " " */ call digRoot 627615 call digRoot 39390 call digRoot 588225 @@ -11,11 +11,11 @@ call digRoot 8999999999999999999999999999999999999999999999999999999999999999999 exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DIGROOT subroutine──────────────────*/ digRoot: procedure; parse arg x 1 ox /*get the num, save as original. */ - do pers=0 while length(x)\==1; r=0 /*keep summing until digRoot=1dig*/ - do j=1 for length(x) /*add each digit in the number. */ + do pers=0 while length(x)\==1; r=0 /*keep summing until digRoot=1dig*/ + do j=1 for length(x) /*add each digit in the number. */ r=r+substr(x,j,1) /*add a digit to the digital root*/ end /*j*/ x=r /*'new' num, it may be multi-dig.*/ end /*pers*/ -say center(x,7) center(pers,11) ox /*show a nicely formatted line. */ +say center(x,7) center(pers,11) ox /*show a nicely formatted line. */ return diff --git a/Task/Digital-root/REXX/digital-root-3.rexx b/Task/Digital-root/REXX/digital-root-3.rexx index fd0c7c7d3f..c60533449c 100644 --- a/Task/Digital-root/REXX/digital-root-3.rexx +++ b/Task/Digital-root/REXX/digital-root-3.rexx @@ -1,11 +1,14 @@ + ∙ + ∙ + ∙ /*──────────────────────────────────DIGROOT subroutine──────────────────*/ digRoot: procedure; parse arg x 1 ox /*get the num, save as original. */ - do pers=0 while length(x)\==1; r=0 /*keep summing until digRoot=1dig*/ - do j=1 for length(x) /*add each digit in the number. */ + do pers=0 while length(x)\==1; r=0 /*keep summing until digRoot=1dig*/ + do j=1 for length(x) /*add each digit in the number. */ ?=substr(x,j,1) /*pick off a char, maybe a dig ? */ - if datatype(?,'W') then r=r+? /*add a digit to the digital root*/ + if datatype(?,'W') then r=r+? /*add a digit to the digital root*/ end /*j*/ x=r /*'new' num, it may be multi-dig.*/ end /*pers*/ -say center(x,7) center(pers,11) ox /*show a nicely formatted line. */ +say center(x,7) center(pers,11) ox /*show a nicely formatted line. */ return diff --git a/Task/Digital-root/Ruby/digital-root.rb b/Task/Digital-root/Ruby/digital-root.rb index c6e3ae1044..439077c9c6 100644 --- a/Task/Digital-root/Ruby/digital-root.rb +++ b/Task/Digital-root/Ruby/digital-root.rb @@ -1,19 +1,24 @@ class String - def digroot_persistence(base) + def digroot_persistence(base=10) num = self.to_i(base) persistence = 0 until num < base do - num = num.to_s(base).each_char.reduce(0){|m, c| m += c.to_i(base) } + num = num.to_s(base).each_char.reduce(0){|m, c| m + c.to_i(base) } persistence += 1 end [num.to_s(base), persistence] end end -#Handles bases upto 36; Demo: +puts "--- Examples in 10-Base ---" +%w(627615 39390 588225 393900588225).each do |str| + puts "%12s has a digital root of %s and a persistence of %s." % [str, *str.digroot_persistence] +end +puts "\n--- Examples in other Base ---" +format = "%s base %s has a digital root of %s and a persistence of %s." [["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 persistence of %s." % str.digroot_persistence(base) } + ["5", 8], + ["50YE8N29", 36]].each do |(str, base)| + puts format % [str, base, *str.digroot_persistence(base)] +end diff --git a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION index 34159920f2..5248139f09 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION +++ b/Task/Dinesmans-multiple-dwelling-problem/00DESCRIPTION @@ -1,8 +1,18 @@ -The task is to '''solve Dinesman's multiple dwelling [http://www-mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''. Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. +{{omit from|GUISS}} +The task is to '''solve Dinesman's multiple dwelling [http://www-mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3.2 problem] but in a way that most naturally follows the problem statement given below'''. + +Solutions are allowed (but not required) to parse and interpret the problem text, but should remain flexible and should state what changes to the problem text are allowed. Flexibility and ease of expression are valued. Examples may be be split into "setup", "problem statement", and "output" sections where the ease and naturalness of stating the problem and getting an answer, as well as the ease and flexibility of modifying the problem are the primary concerns. Example output should be shown here, as well as any comments on the examples flexibility. ;The problem: -:''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?'' +: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?'' diff --git a/Task/Dinesmans-multiple-dwelling-problem/00META.yaml b/Task/Dinesmans-multiple-dwelling-problem/00META.yaml new file mode 100644 index 0000000000..ef1a722e3e --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Dinesman's multiple-dwelling problem diff --git a/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem.c b/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem.c new file mode 100644 index 0000000000..66917bcff2 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/C/dinesmans-multiple-dwelling-problem.c @@ -0,0 +1,81 @@ +#include +#include + +int verbose = 0; +#define COND(a, b) int a(int *s) { return (b); } +typedef int(*condition)(int *); + +/* BEGIN problem specific setup */ +#define N_FLOORS 5 +#define TOP (N_FLOORS - 1) +int solution[N_FLOORS] = { 0 }; +int occupied[N_FLOORS] = { 0 }; + +enum tenants { + baker = 0, + cooper, + fletcher, + miller, + smith, + phantom_of_the_opera, +}; + +const char *names[] = { + "baker", + "cooper", + "fletcher", + "miller", + "smith", +}; + +COND(c0, s[baker] != TOP); +COND(c1, s[cooper] != 0); +COND(c2, s[fletcher] != 0 && s[fletcher] != TOP); +COND(c3, s[miller] > s[cooper]); +COND(c4, abs(s[smith] - s[fletcher]) != 1); +COND(c5, abs(s[cooper] - s[fletcher]) != 1); +#define N_CONDITIONS 6 + +condition cond[] = { c0, c1, c2, c3, c4, c5 }; + +/* END of problem specific setup */ + + +int solve(int person) +{ + int i, j; + if (person == phantom_of_the_opera) { + /* check condition */ + for (i = 0; i < N_CONDITIONS; i++) { + if (cond[i](solution)) continue; + + if (verbose) { + for (j = 0; j < N_FLOORS; j++) + printf("%d %s\n", solution[j], names[j]); + printf("cond %d bad\n\n", i); + } + return 0; + } + + printf("Found arrangement:\n"); + for (i = 0; i < N_FLOORS; i++) + printf("%d %s\n", solution[i], names[i]); + return 1; + } + + for (i = 0; i < N_FLOORS; i++) { + if (occupied[i]) continue; + solution[person] = i; + occupied[i] = 1; + if (solve(person + 1)) return 1; + occupied[i] = 0; + } + return 0; +} + +int main() +{ + verbose = 0; + if (!solve(0)) printf("Nobody lives anywhere\n"); + return 0; +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/D/dinesmans-multiple-dwelling-problem-2.d b/Task/Dinesmans-multiple-dwelling-problem/D/dinesmans-multiple-dwelling-problem-2.d index 98f5ee21f3..db520c56e0 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/D/dinesmans-multiple-dwelling-problem-2.d +++ b/Task/Dinesmans-multiple-dwelling-problem/D/dinesmans-multiple-dwelling-problem-2.d @@ -1,6 +1,6 @@ -import std.stdio, std.math, std.algorithm, permutations2; - void main() { + import std.stdio, std.math, std.algorithm, permutations2; + ["Baker", "Cooper", "Fletcher", "Miller", "Smith"] .permutations .filter!(s => diff --git a/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-1.pl6 b/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-1.pl6 new file mode 100644 index 0000000000..09ac46be23 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-1.pl6 @@ -0,0 +1,39 @@ +sub parse_and_solve ($text) { + my %ids; + my $expr = (grammar { + rule TOP { + { make join ' && ', $>>.made } } + + rule fact { (not)? + { make sprintf $.made.fmt($0 ?? "!(%s)" !! "%s"), + $.made } + } + rule position { + || on bottom { make "\@f[%s] == 1" } + || on top { make "\@f[%s] == +\@f" } + || lower than { make "\@f[%s] < \@f[{$.made}]" } + || higher than { make "\@f[%s] > \@f[{$.made}]" } + || directly below { make "\@f[%s] == \@f[{$.made}] - 1" } + || directly above { make "\@f[%s] == \@f[{$.made}] + 1" } + || adjacent to { make "\@f[%s] == \@f[{$.made}] + (-1|1)" } + || on { make "\@f[%s] == {$.made}" } + || { note "Failed to parse line " ~ +$/.prematch.comb(/^^/); exit 1; } + } + + token name { :i <[a..z]>+ { make %ids{~$/} //= (state $)++ } } + token ordinal { [1st | 2nd | 3rd | \d+th] { make +$/.match(/(\d+)/)[0] } } + }).parse($text).made; + + EVAL 'for [1..%ids.elems].permutations -> @f { + say %ids.kv.map({ "$^a=@f[$^b]" }) if (' ~ $expr ~ '); + }' +} + +parse_and_solve Q:to/END/; + Baker not on top + Cooper not on bottom + Fletcher not on top + Fletcher not on bottom + Miller higher than Cooper + Smith not adjacent to Fletcher + Fletcher not adjacent to Cooper + END diff --git a/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem.pl6 b/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-2.pl6 similarity index 58% rename from Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem.pl6 rename to Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-2.pl6 index 12f8f50dfc..b7f2d9c972 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem.pl6 +++ b/Task/Dinesmans-multiple-dwelling-problem/Perl-6/dinesmans-multiple-dwelling-problem-2.pl6 @@ -1,20 +1,5 @@ -sub next_perm ( @a is copy ) { - my $j = @a.end - 1; - return Nil if --$j < 0 while [>] @a[ $j, $j+1 ]; - - my $aj = @a[$j]; - my $k = @a.end; - $k-- while [>] $aj, @a[$k]; - @a[ $j, $k ] .= reverse; - - my $r = @a.end; - my $s = $j + 1; - @a[ $r--, $s++ ] .= reverse while $r > $s; - return @a; -} - # Contains only five floors. 5! = 120 permutations. -for [1..5], &next_perm ...^ !* -> [ $b, $c, $f, $m, $s ] { +for [1..5].permutations -> $b, $c, $f, $m, $s { say "Baker=$b Cooper=$c Fletcher=$f Miller=$m Smith=$s" if $b != 5 # Baker !live on top floor. and $c != 1 # Cooper !live on bottom floor. diff --git a/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-1.pl b/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-1.pl new file mode 100644 index 0000000000..d7df37608f --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-1.pl @@ -0,0 +1,55 @@ +use strict; +use warnings; +use feature qw(state say); +use List::Util 1.33 qw(pairmap); +use Algorithm::Permute qw(permute); + +our %predicates = ( +# | object | sprintf format for Perl expression | +# --------------------+-----------+------------------------------------+ + 'on bottom' => [ '' , '$f[%s] == 1' ], + 'on top' => [ '' , '$f[%s] == @f' ], + 'lower than' => [ 'person' , '$f[%s] < $f[%s]' ], + 'higher than' => [ 'person' , '$f[%s] > $f[%s]' ], + 'directly below' => [ 'person' , '$f[%s] == $f[%s] - 1' ], + 'directly above' => [ 'person' , '$f[%s] == $f[%s] + 1' ], + 'adjacent to' => [ 'person' , 'abs($f[%s] - $f[%s]) == 1' ], + 'on' => [ 'ordinal' , '$f[%s] == \'%s\'' ], +); + +our %nouns = ( + 'person' => qr/[a-z]+/i, + 'ordinal' => qr/1st | 2nd | 3rd | \d+th/x, +); + +sub parse_and_solve { + my @facts = @_; + + state $parser = qr/^(?$nouns{person}) (?not )?(?|@{[ + join '|', pairmap { + "(?$a)" . + ($b->[0] ? " (?$nouns{$b->[0]})" : '') + } %predicates + ]})$/; + + my (@expressions, %ids, $i); + my $id = sub { defined $_[0] ? $ids{$_[0]} //= $i++ : () }; + + foreach (@facts) { + /$parser/ or die "Cannot parse '$_'\n"; + + my $pred = $predicates{$+{pred}}; + my $expr = '(' . sprintf($pred->[1], $id->($+{subj}), + $pred->[0] eq 'person' ? $id->($+{obj}) : $+{obj}). ')'; + $expr = '!' . $expr if $+{not}; + + push @expressions, $expr; + } + + my @f = 1..$i; + eval 'no warnings "numeric"; + permute { + say join(", ", pairmap { "$f[$b] $a" } %ids) + if ('.join(' && ', @expressions).'); + } @f;'; +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-2.pl b/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-2.pl new file mode 100644 index 0000000000..5d8a2573c2 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Perl/dinesmans-multiple-dwelling-problem-2.pl @@ -0,0 +1,10 @@ +parse_and_solve(); + +__DATA__ +Baker not on top +Cooper not on bottom +Fletcher not on top +Fletcher not on bottom +Miller higher than Cooper +Smith not adjacent to Fletcher +Fletcher not adjacent to Cooper diff --git a/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-1.scala b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-1.scala index 14ff415481..04d51bc5d7 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-1.scala +++ b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-1.scala @@ -1,31 +1,27 @@ -object Dinesman extends App { +import scala.math.abs - val tenants = List("Baker", "Cooper", "Fletcher", "Miller", "Smith") - val floors = (1 to tenants.size).toList +object Dinesman3 extends App { + val tenants = List("Baker", "Cooper2", "Fletcher4", "Miller", "Smith") + val (groundFloor, topFloor) = (1, tenants.size) - // define the predicates - import scala.math.abs - val predicates = - List((perm: Map[String, Int]) => !(perm("Baker")==floors.size) - ,(perm: Map[String, Int]) => !(perm("Cooper")==1) - ,(perm: Map[String, Int]) => !(perm("Fletcher")==1 || perm("Fletcher")==floors.size) - ,(perm: Map[String, Int]) => !(perm("Miller")<=perm("Cooper")) - ,(perm: Map[String, Int]) => !(abs(perm("Smith")-perm("Fletcher"))==1) - ,(perm: Map[String, Int]) => !(abs(perm("Fletcher")-perm("Cooper"))==1) - ) - - val p: Seq[(String, Int)] => Boolean = perm => !predicates.map(_(perm.toMap)).contains(false) - - tenants.permutations.map(_ zip floors).toList - .map(perm=>Pair(perm,p(perm))).filter(_._2==true).map(p=>p._1.toList) - match { - case Nil => println("no solution") - case xss => { println("solutions: "+xss.size) - xss.foreach{l=> - println("possible solution:") - l.foreach(p=>println(" "+p._1+ " lives on floor number "+p._2)) - } - } - } + /** Rules with related tenants and restrictions*/ + val exclusions = + List((suggestedFloor0: Map[String, Int]) => suggestedFloor0("Baker") != topFloor, + (suggestedFloor1: Map[String, Int]) => suggestedFloor1("Cooper2") != groundFloor, + (suggestedFloor2: Map[String, Int]) => !List(groundFloor, topFloor).contains(suggestedFloor2("Fletcher4")), + (suggestedFloor3: Map[String, Int]) => suggestedFloor3("Miller") > suggestedFloor3("Cooper2"), + (suggestedFloor4: Map[String, Int]) => abs(suggestedFloor4("Smith") - suggestedFloor4("Fletcher4")) != 1, + (suggestedFloor5: Map[String, Int]) => abs(suggestedFloor5("Fletcher4") - suggestedFloor5("Cooper2")) != 1) + tenants.permutations.map(_ zip (groundFloor to topFloor)). + filter(p => exclusions.forall(_(p.toMap))).toList match { + case Nil => println("No solution") + case xss => { + println(s"Solutions: ${xss.size}") + xss.foreach { l => + println("possible solution:") + l.foreach(p => println(f"${p._1}%11s lives on floor number ${p._2}")) + } + } + } } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-2.scala b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-2.scala index 72040e4237..333373cd23 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-2.scala +++ b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-2.scala @@ -1,11 +1,31 @@ -... - val tenants = List("Baker", "Cooper", "Fletcher", "Miller", "Smith", "Rollo") -... - val predicates = - List((perm: Map[String, Int]) => !(perm("Baker")==floors.size) -... - ,(perm: Map[String, Int]) => !(perm("Rollo")==floors.size || perm("Rollo")==3 || perm("Rollo")==4) - ,(perm: Map[String, Int]) => !(perm("Rollo")>perm("Smith")) - ,(perm: Map[String, Int]) => !(perm("Rollo") suggestedFloor0("Baker") != topFloor, + (suggestedFloor1: Map[String, Int]) => suggestedFloor1("Cooper2") != groundFloor, + (suggestedFloor2: Map[String, Int]) => !List(groundFloor, topFloor).contains(suggestedFloor2("Fletcher4")), + (suggestedFloor3: Map[String, Int]) => suggestedFloor3("Miller") > suggestedFloor3("Cooper2"), + (suggestedFloor4: Map[String, Int]) => abs(suggestedFloor4("Smith") - suggestedFloor4("Fletcher4")) != 1, + (suggestedFloor5: Map[String, Int]) => abs(suggestedFloor5("Fletcher4") - suggestedFloor5("Cooper2")) != 1, + + (suggestedFloor6: Map[String, Int]) => !List(3, 4, topFloor).contains(suggestedFloor6("Rollo5")), + (suggestedFloor7: Map[String, Int]) => suggestedFloor7("Rollo5") < suggestedFloor7("Smith"), + (suggestedFloor8: Map[String, Int]) => suggestedFloor8("Rollo5") > suggestedFloor8("Fletcher4")) + + tenants.permutations.map(_ zip (groundFloor to topFloor)). + filter(p => exclusions.forall(_(p.toMap))).toList match { + case Nil => println("No solution") + case xss => { + println(s"Solutions: ${xss.size}") + xss.foreach { l => + println("possible solution:") + l.foreach(p => println(f"${p._1}%11s lives on floor number ${p._2}")) + } + } + } +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-3.scala b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-3.scala new file mode 100644 index 0000000000..25413af779 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Scala/dinesmans-multiple-dwelling-problem-3.scala @@ -0,0 +1,47 @@ +import scala.math.abs + +object Dinesman2 extends App { + val groundFloor = 1 + + abstract class Rule(val person: String) { val exclusion: Map[String, Int] => Boolean } + + /** Rules with related tenants and restrictions*/ + def rulesDef(topFloor: Int) = List( + new Rule("Baker") { val exclusion = (_: Map[String, Int])(person) != topFloor }, + new Rule("Cooper2") { val exclusion = (_: Map[String, Int])(person) != groundFloor }, + new Rule("Fletcher4") { + val exclusion = (suggestedFloor2: Map[String, Int]) => !List(groundFloor, topFloor).contains(suggestedFloor2(person)) + }, new Rule("Miller") { + val exclusion = (suggestedFloor3: Map[String, Int]) => suggestedFloor3(person) > suggestedFloor3("Cooper2") + }, new Rule("Smith") { + val exclusion = (suggestedFloor4: Map[String, Int]) => abs(suggestedFloor4(person) - suggestedFloor4("Fletcher4")) != 1 + }, new Rule("Fletcher4") { + val exclusion = (suggestedFloor5: Map[String, Int]) => abs(suggestedFloor5(person) - suggestedFloor5("Cooper2")) != 1 + }) + + def extensionDef(topFloor: Int) = List(new Rule("Rollo5") { + val exclusion = (suggestedFloor6: Map[String, Int]) => !List(3, 4, topFloor).contains((suggestedFloor6: Map[String, Int])(person)) + }, new Rule("Rollo5") { + val exclusion = (suggestedFloor7: Map[String, Int]) => suggestedFloor7(person) < suggestedFloor7("Smith") + }, new Rule("Rollo5") { + val exclusion = (suggestedFloor8: Map[String, Int]) => suggestedFloor8(person) > suggestedFloor8("Fletcher4") + }) + + def allRulesDef(topFloor: Int) = rulesDef(topFloor) ++ extensionDef(topFloor) + + val tenants = allRulesDef(0).map(_.person).distinct // Pilot balloon to get # of tenants + val topFloor = tenants.size + val exclusions = allRulesDef(topFloor).map(_.exclusion) + + tenants.permutations.map(_ zip (groundFloor to topFloor)). + filter(p => exclusions.forall(_(p.toMap))).toList match { + case Nil => println("No solution") + case xss => { + println(s"Solutions: ${xss.size}") + xss.foreach { l => + println("possible solution:") + l.foreach(p => println(f"${p._1}%11s lives on floor number ${p._2}")) + } + } + } +} diff --git a/Task/Discordian-date/00DESCRIPTION b/Task/Discordian-date/00DESCRIPTION index 2a77e38ad6..a88b322033 100644 --- a/Task/Discordian-date/00DESCRIPTION +++ b/Task/Discordian-date/00DESCRIPTION @@ -1,4 +1 @@ -Convert a given date from the Gregorian calendar to the Discordian calendar. - -'''See Also''' -* [[wp:Discordian calendar|Discordian calendar (wiki)]] +Convert a given date from the [[wp:Gregorian calendar|Gregorian calendar]] to the [[wp:Discordian calendar|Discordian calendar]]. diff --git a/Task/Discordian-date/00META.yaml b/Task/Discordian-date/00META.yaml new file mode 100644 index 0000000000..776d3a14cc --- /dev/null +++ b/Task/Discordian-date/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Date and time +note: Discordian date diff --git a/Task/Discordian-date/Clojure/discordian-date.clj b/Task/Discordian-date/Clojure/discordian-date.clj new file mode 100644 index 0000000000..3fe3b54ac6 --- /dev/null +++ b/Task/Discordian-date/Clojure/discordian-date.clj @@ -0,0 +1,23 @@ +(require '[clj-time.core :as tc]) + +(def seasons ["Chaos" "Discord" "Confusion" "Bureaucracy" "The Aftermath"]) +(def weekdays ["Sweetmorn" "Boomtime" "Pungenday" "Prickle-Prickle" "Setting Orange"]) +(def year-offset 1166) + +(defn leap-year? [year] + (= 29 (tc/number-of-days-in-the-month year 2))) + +(defn discordian-day [day leap] + (let [offset (if (and leap (>= day 59)) 1 0) + day-off (- day offset) + day-num (inc (rem day-off 73)) + season (seasons (quot day-off 73)) + weekday (weekdays (mod day-off 5))] + (if (and (= day 59) (= offset 1)) + "St. Tib's Day" + (str weekday ", " season " " day-num)))) + +(defn discordian-date [year month day] + (let [day-of-year (dec (.getDayOfYear (tc/date-time year month day))) + dday (discordian-day day-of-year (leap-year? year))] + (format "%s, YOLD %s" dday (+ year year-offset)))) diff --git a/Task/Discordian-date/Java/discordian-date.java b/Task/Discordian-date/Java/discordian-date.java new file mode 100644 index 0000000000..18be9a8483 --- /dev/null +++ b/Task/Discordian-date/Java/discordian-date.java @@ -0,0 +1,57 @@ +import java.util.Calendar; +import java.util.GregorianCalendar; + +public class DiscordianDate { + + final static String[] seasons = {"Chaos", "Discord", "Confusion", + "Bureaucracy", "The Aftermath"}; + + final static String[] weekday = {"Sweetmorn", "Boomtime", "Pungenday", + "Prickle-Prickle", "Setting Orange"}; + + final static String[] apostle = {"Mungday", "Mojoday", "Syaday", + "Zaraday", "Maladay"}; + + final static String[] holiday = {"Chaoflux", "Discoflux", "Confuflux", + "Bureflux", "Afflux"}; + + public static String discordianDate(final GregorianCalendar date) { + int y = date.get(Calendar.YEAR) + 1166; + int m = date.get(Calendar.MONTH); + int d = date.get(Calendar.DATE); + + if (date.isLeapYear(y) && m == 2 && d == 29) + return "St. Tib's Day, in the YOLD " + y; + + int dayOfYear = date.get(Calendar.DAY_OF_YEAR); + if (date.isLeapYear(y) && dayOfYear >= 60) + dayOfYear--; + + int seasonDay = dayOfYear % 73; + if (seasonDay == 5) + return apostle[dayOfYear / 73] + ", in the YOLD " + y; + if (seasonDay == 50) + return holiday[dayOfYear / 73] + ", in the YOLD " + y; + + String season = seasons[dayOfYear / 73]; + String dayOfWeek = weekday[(dayOfYear - 1) % 5]; + + return String.format("%s, day %s of %s in the YOLD %s", + dayOfWeek, seasonDay, season, y); + } + + public static void main(String[] args) { + System.out.println(discordianDate(new GregorianCalendar())); + + test(2010, 7, 22, "Pungenday, day 57 of Confusion in the YOLD 3176"); + test(2012, 2, 28, "Prickle-Prickle, day 59 of Chaos in the YOLD 3178"); + test(2012, 2, 29, "St. Tib's Day, in the YOLD 3178"); + test(2012, 3, 1, "Setting Orange, day 60 of Chaos in the YOLD 3178"); + test(2010, 1, 5, "Mungday, in the YOLD 3176"); + test(2011, 5, 3, "Discoflux, in the YOLD 3177"); + } + + private static void test(int y, int m, int d, final String result) { + assert (discordianDate(new GregorianCalendar(y, m, d)).equals(result)); + } +} diff --git a/Task/Discordian-date/Perl/discordian-date.pl b/Task/Discordian-date/Perl/discordian-date.pl new file mode 100644 index 0000000000..dcab23fadc --- /dev/null +++ b/Task/Discordian-date/Perl/discordian-date.pl @@ -0,0 +1,33 @@ +use 5.010; +use strict; +use warnings; +use Time::Piece (); + +my @seasons = (qw< Chaos Discord Confusion Bureaucracy >, 'The Aftermath'); +my @week_days = (qw< Sweetmorn Boomtime Pungenday Prickle-Prickle >, 'Setting Orange'); + +sub ordinal { + my ($n) = @_; + return $n . "th" if int($n/10) == 1; + return $n . ((qw< th st nd rd th th th th th th>)[$n % 10]); +} + +sub ddate { + my $d = Time::Piece->strptime( $_[0], '%Y-%m-%d' ); + my $yold = 'in the YOLD ' . ($d->year + 1166); + + my $day_of_year0 = $d->day_of_year; + + if( $d->is_leap_year ) { + return "St. Tib's Day, $yold" if $d->mon == 2 and $d->mday == 29; + $day_of_year0-- if $day_of_year0 >= 60; # Compensate for St. Tib's Day + } + + my $weekday = $week_days[ $day_of_year0 % @week_days ]; + my $season = $seasons[ $day_of_year0 / 73 ]; + my $season_day = ordinal( $day_of_year0 % 73 + 1 ); + + return "$weekday, the $season_day day of $season $yold"; +} + +say "$_ is " . ddate($_) for qw< 2010-07-22 2012-02-28 2012-02-29 2012-03-01 >; diff --git a/Task/Documentation/Emacs-Lisp/documentation-1.l b/Task/Documentation/Emacs-Lisp/documentation-1.l new file mode 100644 index 0000000000..3a408eb82b --- /dev/null +++ b/Task/Documentation/Emacs-Lisp/documentation-1.l @@ -0,0 +1,3 @@ +(defun hello (n) + "Say hello to the user." + (message "hello %d" n)) diff --git a/Task/Documentation/Emacs-Lisp/documentation-2.l b/Task/Documentation/Emacs-Lisp/documentation-2.l new file mode 100644 index 0000000000..4d4502b030 --- /dev/null +++ b/Task/Documentation/Emacs-Lisp/documentation-2.l @@ -0,0 +1,2 @@ +(defvar one-hundred 100 + "The number one hundred.") diff --git a/Task/Dot-product/Clojure/dot-product.clj b/Task/Dot-product/Clojure/dot-product.clj index 888b409395..432c7bd44f 100644 --- a/Task/Dot-product/Clojure/dot-product.clj +++ b/Task/Dot-product/Clojure/dot-product.clj @@ -2,5 +2,13 @@ {:pre [(apply == (map count matrix))]} (apply + (apply map * matrix))) +(defn dot-product2 [x y] + (->> (interleave x y) + (partition 2 2) + (map #(apply * %)) + (reduce +))) + + ;Example Usage (println (dot-product [1 3 -5] [4 -2 -1])) +(println (dot-product2 [1 3 -5] [4 -2 -1])) diff --git a/Task/Dot-product/Eiffel/dot-product.e b/Task/Dot-product/Eiffel/dot-product.e new file mode 100644 index 0000000000..e9b0ce0362 --- /dev/null +++ b/Task/Dot-product/Eiffel/dot-product.e @@ -0,0 +1,34 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + do + print(dot_product(<<1, 3, -5>>, <<4, -2, -1>>).out) + end + +feature -- Access + + dot_product (a, b: ARRAY[INTEGER]): INTEGER + -- Dot product of vectors `a' and `b'. + require + a.lower = b.lower + a.upper = b.upper + local + i: INTEGER + do + from + i := a.lower + until + i > a.upper + loop + Result := Result + a[i] * b[i] + i := i + 1 + end + end +end diff --git a/Task/Dot-product/Groovy/dot-product-1.groovy b/Task/Dot-product/Groovy/dot-product-1.groovy index 37716e8e76..98eed5b488 100644 --- a/Task/Dot-product/Groovy/dot-product-1.groovy +++ b/Task/Dot-product/Groovy/dot-product-1.groovy @@ -1,4 +1,4 @@ def dotProduct = { x, y -> assert x && y && x.size() == y.size() - [x, y].transpose().collect{ it[0] * it[1] }.sum() + [x, y].transpose().collect{ xx, yy -> xx * yy }.sum() } diff --git a/Task/Dot-product/JavaScript/dot-product.js b/Task/Dot-product/JavaScript/dot-product-1.js similarity index 100% rename from Task/Dot-product/JavaScript/dot-product.js rename to Task/Dot-product/JavaScript/dot-product-1.js diff --git a/Task/Dot-product/JavaScript/dot-product-2.js b/Task/Dot-product/JavaScript/dot-product-2.js new file mode 100644 index 0000000000..20a4a575cf --- /dev/null +++ b/Task/Dot-product/JavaScript/dot-product-2.js @@ -0,0 +1,10 @@ +function dotp(x,y) { + function dotp_sum(a,b) { return a + b; } + function dotp_times(a,i) { return x[i] * y[i]; } + if (x.length != y.length) + throw "can't find dot product: arrays have different lengths"; + return x.map(dotp_times).reduce(dotp_sum,0); +} + +dotp([1,3,-5],[4,-2,-1]); // ==> 3 +dotp([1,3,-5],[4,-2,-1,0]); // ==> exception diff --git a/Task/Dot-product/REBOL/dot-product.rebol b/Task/Dot-product/REBOL/dot-product.rebol new file mode 100644 index 0000000000..a2d960f24d --- /dev/null +++ b/Task/Dot-product/REBOL/dot-product.rebol @@ -0,0 +1,16 @@ +REBOL [] + +a: [1 3 -5] +b: [4 -2 -1] + +dot-product: function [v1 v2] [sum] [ + if (length? v1) != (length? v2) [ + make error! "error: vector sizes must match" + ] + sum: 0 + repeat i length? v1 [ + sum: sum + ((pick v1 i) * (pick v2 i)) + ] +] + +dot-product a b diff --git a/Task/Dot-product/Rust/dot-product.rust b/Task/Dot-product/Rust/dot-product.rust new file mode 100644 index 0000000000..e6763b16b9 --- /dev/null +++ b/Task/Dot-product/Rust/dot-product.rust @@ -0,0 +1,14 @@ +fn dot_product(a: Vec, b: Vec) -> int { + let mut s = 0; + for i in range(0, a.len()) { + s += a[i] * b[i]; + } + return s; +} + +fn main() { + let v1 = vec!(1, 3, -5); + let v2 = vec!(4, -2, -1); + + println!("{}", dot_product(v1, v2)); +} diff --git a/Task/Dot-product/Scala/dot-product.scala b/Task/Dot-product/Scala/dot-product.scala index 7b0ea63e33..4a8ca5d1a5 100644 --- a/Task/Dot-product/Scala/dot-product.scala +++ b/Task/Dot-product/Scala/dot-product.scala @@ -1,11 +1,8 @@ -import scala.language.postfixOps -import scala.language.implicitConversions - class Dot[T](v1: Seq[T])(implicit n: Numeric[T]) { import n._ // import * operator def dot(v2: Seq[T]) = { require(v1.size == v2.size) - v1 zip v2 map Function.tupled(_ * _) sum + (v1 zip v2).map{ Function.tupled(_ * _)}.sum } } diff --git a/Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition.go b/Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-1.go similarity index 100% rename from Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition.go rename to Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-1.go diff --git a/Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-2.go b/Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-2.go new file mode 100644 index 0000000000..278c2a8e8f --- /dev/null +++ b/Task/Doubly-linked-list-Definition/Go/doubly-linked-list-definition-2.go @@ -0,0 +1,18 @@ +package main + +import "fmt" +import "container/list" + +func main() { + // Create a new list and put some values in it. + l := list.New() + e4 := l.PushBack(4) + e1 := l.PushFront(1) + l.InsertBefore(3, e4) + l.InsertAfter("two", e1) + + // Iterate through list and print its contents. + for e := l.Front(); e != nil; e = e.Next() { + fmt.Println(e.Value) + } +} diff --git a/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go b/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-1.go similarity index 100% rename from Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition.go rename to Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-1.go diff --git a/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-2.go b/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-2.go new file mode 100644 index 0000000000..fdfa172a10 --- /dev/null +++ b/Task/Doubly-linked-list-Element-definition/Go/doubly-linked-list-element-definition-2.go @@ -0,0 +1,4 @@ +import "container/list" + +var node list.Element +// and using: node.Next(), node.Prev(), node.Value diff --git a/Task/Dragon-curve/00DESCRIPTION b/Task/Dragon-curve/00DESCRIPTION index ade2ed67b8..b785d7aa99 100644 --- a/Task/Dragon-curve/00DESCRIPTION +++ b/Task/Dragon-curve/00DESCRIPTION @@ -78,7 +78,7 @@ BitAboveLowestOne = n BITAND AboveMask * 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. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex by whether the segment either East or West is on the curve.) +: 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 it works is slightly subtle but the calculation is not difficult. (Check segment by applying an offset to move X,Y to an "even" position before dividing i+1. Check vertex 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/PARI-GP/dragon-curve-1.pari b/Task/Dragon-curve/PARI-GP/dragon-curve-1.pari new file mode 100644 index 0000000000..e1fad854b5 --- /dev/null +++ b/Task/Dragon-curve/PARI-GP/dragon-curve-1.pari @@ -0,0 +1,17 @@ +level = 13 +p = [0, 1]; \\ complex number points, initially 0 to 1 + +\\ "unfold" at the current endpoint p[#p]. +\\ p[^-1] so as not to duplicate that endpoint. +\\ +\\ * end +\\ --> | +\\ / | +\\ v +\\ *------->* +\\ 0,0 p[#p] +\\ +for(i=1,level, my(end = (1+I)*p[#p]); \ + p = concat(p, apply(z->(end - I*z), Vecrev(p[^-1])))) + +plothraw(apply(real,p),apply(imag,p), 1); \\ flag=1 join points diff --git a/Task/Dragon-curve/PARI-GP/dragon-curve-2.pari b/Task/Dragon-curve/PARI-GP/dragon-curve-2.pari new file mode 100644 index 0000000000..215b4773aa --- /dev/null +++ b/Task/Dragon-curve/PARI-GP/dragon-curve-2.pari @@ -0,0 +1,17 @@ +len=256; + +bit_above_low_1(n) = bittest(n, valuation(n,2)+1); + +plotinit(0); +plotscale(0, -32,32, 32,-32); \\ Y increasing up the screen +plotmove(0, 0,0); +plotstring(0, "start", 8+32); \\ flags 8=top + 32=gap + +dx=1; +dy=0; +turn_right()= [dx,dy]=[-dy,dx]; +turn_left() = [dx,dy]=[dy,-dx]; + +for(i=1,len, plotrline(0,dx,dy); \ + if(bit_above_low_1(i), turn_right(), turn_left())); +plotdraw([0,100,100]); diff --git a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 index 4eec9c2d0f..a4a3fd3b8c 100644 --- a/Task/Dragon-curve/Perl-6/dragon-curve.pl6 +++ b/Task/Dragon-curve/Perl-6/dragon-curve.pl6 @@ -1,25 +1,32 @@ +role Lindenmayer { + has %.rules; + method succ { + self.comb.map( + { %!rules{$^c} // $c } + ).join but Lindenmayer(%!rules) + } +} + +my $dragon = "FX" but Lindenmayer( + { X => 'X+YF+', Y => '-FX-Y' } +); + +$dragon++ for ^10; + say " "; -my $order = 10; # akin to number of recursion steps -my $d_size = 1000; # size in pixels -my $turn_angle = pi/2; # turn angle of each segment, 90 degrees for the canonical dragon +for $dragon.comb { + state ($x, $y) = 100, 100; + state $d = 2 + 0i; -my $angle = pi - ($order * (pi/4)); # starting angle -my $len = ($d_size/1.5) / sqrt(2)**$order; # size of each segment -my ($x, $y) = ($d_size*5/6, $d_size*1/3); # starting point - -for 0..2**$order-1 -> $i -{ - # find which side to turn based on the iteration - $angle += ((($i +& -$i) +< 1) +& $i) ?? -$turn_angle !! $turn_angle; - - my ($dx, $dy) = ($x + $len * $angle.sin, $y - $len * $angle.cos); - say ""; - ($x, $y) = ($dx, $dy); + if /F/ { + say ""; + } + elsif /< + - >/ { $d *= "{$_}1i" } } say ""; diff --git a/Task/Dragon-curve/Perl/dragon-curve.pl b/Task/Dragon-curve/Perl/dragon-curve.pl new file mode 100644 index 0000000000..325cad9c3f --- /dev/null +++ b/Task/Dragon-curve/Perl/dragon-curve.pl @@ -0,0 +1,36 @@ +use strict; +use warnings; + +use constant halfpi => atan2(1, 0); + +# Computing the dragon with a L-System +my $dragon = 'FX'; +for (1 .. 10) { + $dragon =~ s/X/x+yF+/g; + $dragon =~ s/Y/-Fx-y/g; + $dragon =~ tr/xy/XY/; +} + +# Drawing the dragon in SVG +my ($x, $y) = (100, 100); +my $theta = 0; +my $r = 2; + +print " + +\n"; + +for (split //, $dragon) { + if (/F/) { + printf "\n"; + } + elsif (/\+/) { $theta += halfpi; } + elsif (/\-/) { $theta -= halfpi; } +} + +print ""; diff --git a/Task/Dragon-curve/R/dragon-curve.r b/Task/Dragon-curve/R/dragon-curve.r new file mode 100644 index 0000000000..dac01e9e74 --- /dev/null +++ b/Task/Dragon-curve/R/dragon-curve.r @@ -0,0 +1,32 @@ +Dragon<-function(Iters){ + Rotation<-matrix(c(0,-1,1,0),ncol=2,byrow=T) ########Rotation multiplication matrix + Iteration<-list() ###################################Set up list for segment matrices for 1st + Iteration[[1]] <- matrix(rep(0,16), ncol = 4) + Iteration[[1]][1,]<-c(0,0,1,0) + Iteration[[1]][2,]<-c(1,0,1,-1) + Moveposition<-rep(0,Iters) ##########################Which point should be shifted to origin + Moveposition[1]<-4 + if(Iters > 1){#########################################where to move to get to origin + for(l in 2:Iters){#####################################only if >1, because 1 set before for loop + Moveposition[l]<-(Moveposition[l-1]*2)-2#############sets vector of all positions in matrix where last point is + }} + Move<-list() ########################################vector to add to all points to shift start at origin +for (i in 1:Iters){ +half<-dim(Iteration[[i]])[1]/2 +half<-1:half +for(j in half){########################################Rotate all points 90 degrees clockwise + Iteration[[i]][j+length(half),]<-c(Iteration[[i]][j,1:2]%*%Rotation,Iteration[[i]][j,3:4]%*%Rotation) +} +Move[[i]]<-matrix(rep(0,4),ncol=4) +Move[[i]][1,1:2]<-Move[[i]][1,3:4]<-(Iteration[[i]][Moveposition[i],c(3,4)]*-1) +Iteration[[i+1]]<-matrix(rep(0,2*dim(Iteration[[i]])[1]*4),ncol=4)##########move the dragon, set next Iteration's matrix +for(k in 1:dim(Iteration[[i]])[1]){#########################################move dragon by shifting all previous iterations point + Iteration[[i+1]][k,]<-Iteration[[i]][k,]+Move[[i]]###so the start is at the origin +} +xlimits<-c(min(Iteration[[i]][,3])-2,max(Iteration[[i]][,3]+2))#Plot +ylimits<-c(min(Iteration[[i]][,4])-2,max(Iteration[[i]][,4]+2)) +plot(0,0,type='n',axes=FALSE,xlab="",ylab="",xlim=xlimits,ylim=ylimits) +s<-dim(Iteration[[i]])[1] +s<-1:s +segments(Iteration[[i]][s,1], Iteration[[i]][s,2], Iteration[[i]][s,3], Iteration[[i]][s,4], col= 'red') +}}######################################################################### diff --git a/Task/Dragon-curve/REXX/dragon-curve.rexx b/Task/Dragon-curve/REXX/dragon-curve.rexx index 123817063b..debe23e79c 100644 --- a/Task/Dragon-curve/REXX/dragon-curve.rexx +++ b/Task/Dragon-curve/REXX/dragon-curve.rexx @@ -1,7 +1,7 @@ /*REXX program to draw an ASCII Dragon Curve (or Harter-Heighway dragon)*/ d.=1; d.L=-1; @.=' '; x=0; x2=x; y=0; y2=y; @.x.y='∙'; z=1 plot_pts='123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZΘ' -minx=0; maxx=0; miny=0; maxy=0 /*assign various constants & vars*/ +minX=0; maxX=0; minY=0; maxY=0 /*assign various constants & vars*/ parse arg # p c . /*# is # iterations, P=init dir.*/ if #=='' | #==',' then #=11 /*Not specified? Use the default*/ if p=='' | p==',' then p=0 /*Not specified? Use the default*/ @@ -10,27 +10,27 @@ if length(c)==2 then c=x2c(c) /*hexadecimal code was specified?*/ if length(c)==3 then c=d2c(c) /* decimal " " " ?*/ $= /*nullify the dragon curve string*/ do # /*create the dragon curve string.*/ - $=$'R'reverse(translate($,'RL','LR')) /*append,flip,reverse.*/ + $=$'R'reverse(translate($, 'RL', 'LR')) /*append,flip,reverse.*/ end /*#*/ /*create dragon curve.*/ - do j=1 for length($); _=substr($,j,1) /*get next direction.*/ - p=(p+d._)//4; if p<0 then p=p+4 /*move in a direction.*/ - if p==0 then do; y=y+1; y2=y+1; end /*going east map-wise.*/ - if p==1 then do; x=x+1; x2=x+1; end /* " south " */ - if p==2 then do; y=y-1; y2=y-1; end /* " west " */ - if p==3 then do; x=x-1; x2=x-1; end /* " north " */ + do j=1 for length($); _=substr($, j, 1) /*get next direction.*/ + p=(p+d._)//4; if p<0 then p=p+4 /*move in a direction.*/ + if p==0 then do; y=y+1; y2=y+1; end /*going east map-wise.*/ + if p==1 then do; x=x+1; x2=x+1; end /* " south " */ + if p==2 then do; y=y-1; y2=y-1; end /* " west " */ + if p==3 then do; x=x-1; x2=x-1; end /* " north " */ if j>2**z then z=z+1 /*the curve being done*/ !=substr(c,z,1); if !==' ' then !=right(c,1) /*choose plot pt char.*/ - @.x.y=!; @.x2.y2=! /*draw part of dragon.*/ - minx=min(minx,x,x2); maxx=max(maxx,x,x2); x=x2 /*define graph limits.*/ - miny=min(miny,y,y2); maxy=max(maxy,y,y2); y=y2 /* " " " */ + @.x.y=!; @.x2.y2=! /*draw part of dragon.*/ + minX=min(minX,x,x2); maxX=max(maxX,x,x2); x=x2 /*define graph limits.*/ + minY=min(minY,y,y2); maxY=max(maxY,y,y2); y=y2 /* " " " */ end /*j*/ - /*display dragon curve on screen.*/ - do r=minx to maxx; a= /*nullify the line to be drawn. */ - do c=miny to maxy /*create a line (row) of points. */ - a=a || @.r.c /*build one column at a time. */ - end /*c*/ - a=strip(a,'T') /*be nice & strip trailing blanks*/ - if a\=='' then say a /*display a line (row) of points.*/ - end /*r*/ + /* [↓] display the dragon curve.*/ + do r=minX to maxX; a= /*nullify the line to be drawn. */ + do c=minY to maxY /*create a line (row) of points. */ + a=a || @.r.c /*build one column at a time. */ + end /*c*/ + a=strip(a, 'T') /*be nice & strip trailing blanks*/ + if a\=='' then say a /*display a line (row) of points.*/ + end /*r*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Dragon-curve/Visual-Basic-.NET/dragon-curve.visual b/Task/Dragon-curve/Visual-Basic-.NET/dragon-curve.visual new file mode 100644 index 0000000000..4f61de149c --- /dev/null +++ b/Task/Dragon-curve/Visual-Basic-.NET/dragon-curve.visual @@ -0,0 +1,54 @@ +Option Explicit On +Imports System.Math + +Public Class DragonCurve + Dim nDepth As Integer = 12 + Dim angle As Double + Dim MouseX, MouseY As Integer + Dim CurrentX, CurrentY As Integer + Dim nColor As Color = Color.Black + + Private Sub DragonCurve_Click(sender As Object, e As EventArgs) Handles Me.Click + SubDragonCurve() + End Sub + + Sub DrawClear() + Me.CreateGraphics.Clear(Color.White) + End Sub + + Sub DrawMove(ByVal X As Double, ByVal Y As Double) + CurrentX = X + CurrentY = Y + End Sub + + Sub DrawLine(ByVal X As Double, ByVal Y As Double) + Dim MyGraph As Graphics = Me.CreateGraphics + Dim PenColor As Pen = New Pen(nColor) + Dim NextX, NextY As Long + NextX = CurrentX + X + NextY = CurrentY + Y + MyGraph.DrawLine(PenColor, CurrentX, CurrentY, NextX, NextY) + CurrentX = NextX + CurrentY = NextY + End Sub + + Sub DragonProc(size As Double, ByVal split As Integer, d As Integer) + If split = 0 Then + DrawLine(-Cos(angle) * size, Sin(angle) * size) + Else + angle = angle + d * PI / 4 + DragonProc(size / Sqrt(2), split - 1, 1) + angle = angle - d * PI / 2 + DragonProc(size / Sqrt(2), split - 1, -1) + angle = angle + d * PI / 4 + End If + End Sub + + Sub SubDragonCurve() + Const xcoefi = 0.74, xcoefl = 0.59 + DrawClear() + DrawMove(Me.Width * xcoefi, Me.Height / 3) + DragonProc(Me.Width * xcoefl, nDepth, 1) + End Sub + +End Class diff --git a/Task/Dragon-curve/Visual-Basic/dragon-curve.vb b/Task/Dragon-curve/Visual-Basic/dragon-curve.vb new file mode 100644 index 0000000000..6f3dd4318a --- /dev/null +++ b/Task/Dragon-curve/Visual-Basic/dragon-curve.vb @@ -0,0 +1,30 @@ +Option Explicit +Const Pi As Double = 3.14159265358979 +Dim angle As Double +Dim nDepth As Integer +Dim nColor As Long + +Private Sub Form_Load() + nColor = vbBlack + nDepth = 12 + DragonCurve +End Sub + +Sub DragonProc(size As Double, ByVal split As Integer, d As Integer) + If split = 0 Then + xForm.Line -Step(-Cos(angle) * size, Sin(angle) * size), nColor + Else + angle = angle + d * Pi / 4 + Call DragonProc(size / Sqr(2), split - 1, 1) + angle = angle - d * Pi / 2 + Call DragonProc(size / Sqr(2), split - 1, -1) + angle = angle + d * Pi / 4 + End If +End Sub + +Sub DragonCurve() + Const xcoefi = 0.74 + Const xcoefl = 0.59 + xForm.PSet (xForm.Width * xcoefi, xForm.Height / 3), nColor + Call DragonProc(xForm.Width * xcoefl, nDepth, 1) +End Sub diff --git a/Task/Draw-a-cuboid/00DESCRIPTION b/Task/Draw-a-cuboid/00DESCRIPTION index d9c45e5366..5adc1a0d72 100644 --- a/Task/Draw-a-cuboid/00DESCRIPTION +++ b/Task/Draw-a-cuboid/00DESCRIPTION @@ -1 +1,8 @@ -The task is to draw a cuboid with relative dimensions of 2x3x4. The cuboid can be represented graphically, or in ascii art, depending on the language capabilities. To fulfil the criteria of being a cuboid, three faces must be visible. Either static or rotational projection is acceptable for this task. +The task is to draw a [http://en.wikipedia.org/wiki/Cuboid cuboid] +with relative dimensions of 2x3x4. + +The cuboid can be represented graphically, or in ascii art, +depending on the language capabilities. + +To fulfil the criteria of being a cuboid, three faces must be visible.
+Either static or rotational projection is acceptable for this task. diff --git a/Task/Draw-a-cuboid/00META.yaml b/Task/Draw-a-cuboid/00META.yaml index 15987484ad..591401085b 100644 --- a/Task/Draw-a-cuboid/00META.yaml +++ b/Task/Draw-a-cuboid/00META.yaml @@ -1,4 +1,6 @@ --- +category: +- 3D note: Geometric Primitives requires: - Graphics diff --git a/Task/Draw-a-cuboid/C/draw-a-cuboid.c b/Task/Draw-a-cuboid/C/draw-a-cuboid.c new file mode 100644 index 0000000000..dee16bab57 --- /dev/null +++ b/Task/Draw-a-cuboid/C/draw-a-cuboid.c @@ -0,0 +1,136 @@ +#include +#include +#include + +const char *shades = ".:!*oe&#%@"; + +void vsub(double *v1, double *v2, double *s) { + s[0] = v1[0] - v2[0]; + s[1] = v1[1] - v2[1]; + s[2] = v1[2] - v2[2]; +} + +double normalize(double * v) { + double len = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); + v[0] /= len; v[1] /= len; v[2] /= len; + return len; +} + +double dot(double *x, double *y) { + return x[0]*y[0] + x[1]*y[1] + x[2]*y[2]; +} + +double * cross(double x[3], double y[3], double s[3]) { + s[0] = x[1] * y[2] - x[2] * y[1]; + s[1] = x[2] * y[0] - x[0] * y[2]; + s[2] = x[0] * y[1] - x[1] * y[0]; + return s; +} + +double* madd(double *x, double *y, double d, double *r) { + r[0] = x[0] + y[0] * d; + r[1] = x[1] + y[1] * d; + r[2] = x[2] + y[2] * d; + return r; +} + +double v000[] = { -4, -3, -2 }; +double v100[] = { 4, -3, -2 }; +double v010[] = { -4, 3, -2 }; +double v110[] = { 4, 3, -2 }; +double v001[] = { -4, -3, 2 }; +double v101[] = { 4, -3, 2 }; +double v011[] = { -4, 3, 2 }; +double v111[] = { 4, 3, 2 }; + +typedef struct { + double * v[4]; + double norm[3]; +} face_t; + +face_t f[] = { + { { v000, v010, v110, v100 }, { 0, 0, -1 } }, + { { v001, v011, v111, v101 }, { 0, 0, 1 } }, + { { v000, v010, v011, v001 }, { -1, 0, 0 } }, + { { v100, v110, v111, v101 }, { 1, 0, 0 } }, + { { v000, v100, v101, v001 }, { 0, -1, 0 } }, + { { v010, v110, v111, v011 }, { 0, 1, 0 } }, +}; + +int in_range(double x, double x0, double x1) { + return (x - x0) * (x - x1) <= 0; +} + +int face_hit(face_t *face, double src[3], double dir[3], double hit[3], double *d) +{ + int i; + double dist; + for (i = 0; i < 3; i++) + if (face->norm[i]) + dist = (face->v[0][i] - src[i]) / dir[i]; + + madd(src, dir, dist, hit); + *d = fabs(dot(dir, face->norm) * dist); + + if (face->norm[0]) { + return in_range(hit[1], face->v[0][1], face->v[2][1]) && + in_range(hit[2], face->v[0][2], face->v[2][2]); + } + else if (face->norm[1]) { + return in_range(hit[0], face->v[0][0], face->v[2][0]) && + in_range(hit[2], face->v[0][2], face->v[2][2]); + } + else if (face->norm[2]) { + return in_range(hit[0], face->v[0][0], face->v[2][0]) && + in_range(hit[1], face->v[0][1], face->v[2][1]); + } + return 0; +} + +int main() +{ + int i, j, k; + double eye[3] = { 7, 7, 6 }; + double dir[3] = { -1, -1, -1 }, orig[3] = {0, 0, 0}; + double hit[3], dx[3], dy[3] = {0, 0, 1}, proj[3]; + double d, *norm, dbest, b; + double light[3] = { 6, 8, 6 }, ldist[3], decay, strength = 10; + + normalize(cross(eye, dy, dx)); + normalize(cross(eye, dx, dy)); + + for (i = -10; i <= 17; i++) { + for (j = -35; j < 35; j++) { + vsub(orig, orig, proj); + madd(madd(proj, dx, j / 6., proj), dy, i/3., proj); + vsub(proj, eye, dir); + dbest = 1e100; + norm = 0; + for (k = 0; k < 6; k++) { + if (!face_hit(f + k, eye, dir, hit, &d)) continue; + if (dbest > d) { + dbest = d; + norm = f[k].norm; + } + } + + if (!norm) { + putchar(' '); + continue; + } + + vsub(light, hit, ldist); + decay = normalize(ldist); + b = dot(norm, ldist) / decay * strength; + if (b < 0) b = 0; + else if (b > 1) b = 1; + b += .2; + if (b > 1) b = 0; + else b = 1 - b; + putchar(shades[(int)(b * (sizeof(shades) - 2))]); + } + putchar('\n'); + } + + return 0; +} diff --git a/Task/Draw-a-cuboid/Clojure/draw-a-cuboid.clj b/Task/Draw-a-cuboid/Clojure/draw-a-cuboid.clj new file mode 100644 index 0000000000..dc4845d558 --- /dev/null +++ b/Task/Draw-a-cuboid/Clojure/draw-a-cuboid.clj @@ -0,0 +1,22 @@ +(use 'quil.core) + +(def w 500) +(def h 400) + +(defn setup [] + (background 0)) + +(defn draw [] + (push-matrix) + (translate (/ w 2) (/ h 2) 0) + (rotate-x 0.7) + (rotate-z 0.5) + (box 100 150 200) ; 2x3x4 relative dimensions + (pop-matrix)) + +(defsketch main + :title "cuboid" + :setup setup + :size [w h] + :draw draw + :renderer :opengl) diff --git a/Task/Draw-a-cuboid/Java/draw-a-cuboid.java b/Task/Draw-a-cuboid/Java/draw-a-cuboid.java new file mode 100644 index 0000000000..250c0c39f8 --- /dev/null +++ b/Task/Draw-a-cuboid/Java/draw-a-cuboid.java @@ -0,0 +1,46 @@ +import java.awt.*; +import javax.swing.*; + +public class Cuboid extends JFrame { + + public static void main(String[] args) { + JFrame f = new Cuboid(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setVisible(true); + } + + public Cuboid() { + Container content = getContentPane(); + content.setLayout(new BorderLayout()); + content.add(new CuboidPanel(), BorderLayout.CENTER); + setTitle("Cuboid"); + setResizable(false); + pack(); + setLocationRelativeTo(null); + } +} + +class CuboidPanel extends JPanel { + + public CuboidPanel() { + setPreferredSize(new Dimension(600, 500)); + setBackground(Color.white); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + g.translate(165, -80); + + g.drawRect(50, 275, 100, 100); + g.drawLine(50, 275, 130, 240); + g.drawLine(150, 275, 210, 240); + g.drawLine(130, 240, 210, 240); + g.drawLine(210, 240, 210, 340); + g.drawLine(150, 375, 210, 340); + } +} diff --git a/Task/Draw-a-cuboid/Python/draw-a-cuboid.py b/Task/Draw-a-cuboid/Python/draw-a-cuboid-1.py similarity index 100% rename from Task/Draw-a-cuboid/Python/draw-a-cuboid.py rename to Task/Draw-a-cuboid/Python/draw-a-cuboid-1.py diff --git a/Task/Draw-a-cuboid/Python/draw-a-cuboid-2.py b/Task/Draw-a-cuboid/Python/draw-a-cuboid-2.py new file mode 100644 index 0000000000..c56ce7ba22 --- /dev/null +++ b/Task/Draw-a-cuboid/Python/draw-a-cuboid-2.py @@ -0,0 +1,3 @@ +from visual import * +mybox = box(pos=(0,0,0), length=4, height=2, width=3, axis=(-0.1,-0.1,0.1) ) +scene.title = "VPython: cuboid" diff --git a/Task/Draw-a-cuboid/Python/draw-a-cuboid-3.py b/Task/Draw-a-cuboid/Python/draw-a-cuboid-3.py new file mode 100644 index 0000000000..ac0cc9aed1 --- /dev/null +++ b/Task/Draw-a-cuboid/Python/draw-a-cuboid-3.py @@ -0,0 +1,261 @@ +from __future__ import print_function, division +from visual import * +import itertools + +title = "VPython: Draw a cuboid" +scene.title = title +print( "%s\n" % title ) + +msg = """ +Drag with right mousebutton to rotate view. +Drag up+down with middle mousebutton to zoom. +Left mouseclick to show info. + +Press x,X, y,Y, z,Z to rotate the box in single steps. +Press b, c,o,m to change background, color, opacity, material. +Press r,R to rotate, d,a for demo, automatic, space to stop. +Press h to show this help, ESC or q to quit. +""" + +#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+... + +## Rotate one step per keypress: + +def rotX(obj, a) : + obj.rotate( angle=a, axis=(1,0,0) ) +def rotY(obj, a) : + obj.rotate( angle=a, axis=(0,1,0) ) +def rotZ(obj, a) : + obj.rotate( angle=a, axis=(0,0,1) ) + +## Selection of background-colors: + +bg_list = [color.gray(0.2), color.gray(0.4), color.gray(0.7), color.gray(0.9)] +bg = itertools.cycle(bg_list) +def backgr() : + b = next(bg) + print("BackgroundColor=",b) + scene.background = b + +## Selection of colors: + +col_list = [color.white, color.red, color.orange, color.yellow, + color.green, color.blue, color.cyan, color.magenta, + color.black] +col = itertools.cycle(col_list) +#c = col.next() +#c = next(col) +def paint(obj) : + c = next(col) + print("Color=",c) + obj.color = c + +## Selection of opacity / transparancy : + +opa_list = [1.0, 0.7, 0.5, 0.2] +opa = itertools.cycle(opa_list) +def solid(obj) : + o = next(opa) + print("opacity =",o) + obj.opacity = o + +## Selection of materials: + +mName_list = ["None", + "wood", + "rough", + "bricks", + "glass", + "earth", + "plastic", + "ice", + "diffuse", + "marble" ] +mat_list = [ None, + materials.wood, + materials.rough, + materials.bricks, + materials.glass, + materials.earth, + materials.plastic, + materials.ice, + materials.diffuse, + materials.marble ] +mName = itertools.cycle(mName_list) +mat = itertools.cycle(mat_list) +def surface(obj) : + mM = next(mat) + mN = next(mName) + print("Material:", mN) + obj.material = mM + obj.mat = mN + +## Selection for rotation-angle & axis : + +rotAng_list = [ 0.0, 0.005, 0.0, -0.005 ] +rotDir_list = [ (1,0,0), (0,1,0), (0,0,1) ] + +rotAng = itertools.cycle(rotAng_list) +rotDir = itertools.cycle(rotDir_list) + +rotAn = next(rotAng) # rotAn = 0.005 +rotAx = next(rotDir) # rotAx = (1,0,0) + +def rotAngle() : + global rotAn + rotAn = next(rotAng) + print("RotateAngle=",rotAn) + +def rotAxis() : + global rotAx + rotAx = next(rotDir) + print("RotateAxis=",rotAx) + +## List of keypresses for demo: + +#demoC_list = [ "h", "c", "a", "o", "m", "b" ] +demoCmd_list = "rcbr"+"robr"+"rmR_r?" +demoCmd = itertools.cycle(demoCmd_list) +def demoStep() : + k = next(demoCmd) + print("Demo:",k) + cmd(k) + +#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+... + +def objCount(): + n=0 + for obj in scene.objects: + n=n+1 + return n + +def objInfo(obj) : + print( "\nObject:", obj ) + print( "Pos:", obj.pos, "Size:", obj.size ) + print( "Axis:", obj.axis, "Up:", obj.up ) + print( "Color", obj.color, obj.opacity ) + print( "Mat:", obj.mat, obj.material ) + +def sceneInfo(sc) : + print( "\nScene:", sc ) + print( ".width x height:", sc.width, "x", sc.height ) + print( ".range:", sc.range, ".scale:", sc.scale ) + print( ".center:", sc.center ) # Camera + print( ".forward:", sc.forward, ".fov:", sc.fov ) + print( "Mouse:", sc.mouse.camera, "ray:", sc.mouse.ray ) + print( ".ambient:", sc.ambient ) + print( "Lights:", sc.lights ) # distant_light + print( "objects:", objCount(), scene.objects ) + +#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+... + +scene.width = 600 +scene.height = 400 +scene.range = 4 +#scene.autocenter = True +#scene.background = color.gray(0.2) +scene.background = next(bg) + +autoDemo = -1 + +print( msg ) + + +## Create cuboid (aka "box") : + +# c = box() # using default-values --> cube +# c = box(pos=(0,0,0), length=4, height=2, width=3, axis=(-0.1,-0.1,0.1) ) +##c = box(pos =( 0.0, 0.0, 0.0 ), +## size=( 4, 2, 3 ), # L,H,W +## axis=( 1.0, 0.0, 0.0 ), +## up =( 0.0, 1.0, 0.0 ), +## color = color.orange, +## opacity = 1.0, +## material= materials.marble +## ) +c = box(pos =( 0.0, 0.0, 0.0 ), + size=( 4, 2, 3 ), # L,H,W + axis=( 1.0, 0.0, 0.0 ), + up =( 0.0, 1.0, 0.0 ) + ) +print("Box:", c) +paint(c) # c.color = color.red +solid(c) # c.opacity = 1.0 +surface(c) # c.material = materials.marble + +rotX(c,0.4) # rotate box, to bring three faces into view +rotY(c,0.6) + +#sceneInfo(scene) +#objInfo(c) +print("\nPress 'a' to start auto-running demo.") + +#...+....1....+....2....+....3....+....4....+....5....+....6....+....7....+... + + +## Processing of input: + +cCount = 0 +def click(): + global cCount + cCount=cCount+1 + sceneInfo(scene) + objInfo(c) +scene.bind( 'click', click ) + +def keyInput(): + key = scene.kb.getkey() + print( 'Key: "%s"' % key ) + + if ( (key == 'esc') or (key == 'q') ) : + print( "Bye!" ) + exit(0) + else : + cmd(key) +scene.bind('keydown', keyInput) + +def cmd(key): + global autoDemo + if (key == 'h') : print( msg ) + if (key == '?') : print( msg ) + if (key == 's') : sceneInfo(scene) + if (key == 'i') : objInfo(c) + + if (key == 'x') : rotX(c, 0.1) + if (key == 'X') : rotX(c,-0.1) + if (key == 'y') : rotY(c, 0.1) + if (key == 'Y') : rotY(c,-0.1) + if (key == 'z') : rotZ(c, 0.1) + if (key == 'Z') : rotZ(c,-0.1) + + if (key == 'c') : paint(c) + if (key == 'o') : solid(c) + if (key == 'm') : surface(c) + + if (key == 'b') : backgr() + if (key == 'r') : rotAngle() + if (key == 'R') : rotAxis() + if (key == 'd') : demoStep() + if (key == 'a') : autoDemo = -autoDemo + if (key == 'A') : autoDemo = -autoDemo + if (key == ' ') : stop() + +def stop() : + global autoDemo, rotAn + autoDemo = -1 + while rotAn <> 0 : + rotAngle() + print("**Stop**") + +r=100 +t=0 +while True: # Animation-loop + rate(50) + t = t+1 + if rotAn != 0 : + c.rotate( angle=rotAn, axis=rotAx ) + + if t>=r : + t=0 + if autoDemo>0 : + demoStep() diff --git a/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx b/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx index 750bc117a6..3700d42d06 100644 --- a/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx +++ b/Task/Draw-a-cuboid/REXX/draw-a-cuboid.rexx @@ -11,9 +11,9 @@ x=p(x 1); y=p(y x); z=p(z y); indent=p(indent 0) call sayer , , "+-" exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────P subroutjne────────────────────────*/ +/*──────────────────────────────────P subroutine────────────────────────*/ p: return word(arg(1),1) /*pick the first word in the list*/ -/*──────────────────────────────────SAYER subroutjne────────────────────*/ +/*──────────────────────────────────SAYER subroutine────────────────────*/ sayer: parse arg times,a,_ /*get the arguments specified. */ say left('',indent)right(left(_,1),pick1(times 1)) || , copies(substr(_,2,1),4*x)left(_,1)right(substr(_,3,1),pick1(a 0)+1) diff --git a/Task/Draw-a-cuboid/Retro/draw-a-cuboid.retro b/Task/Draw-a-cuboid/Retro/draw-a-cuboid.retro new file mode 100644 index 0000000000..489ef86752 --- /dev/null +++ b/Task/Draw-a-cuboid/Retro/draw-a-cuboid.retro @@ -0,0 +1,19 @@ +3 elements d h w + +: spaces ( n- ) &space times ; +: --- ( - ) '+ putc @w 2 * [ '- putc ] times '+ putc ; +: ? ( n- ) @h <> [ '| ] [ '+ ] if ; +: slice ( n- ) '/ putc @w 2 * spaces '/ putc @d swap - dup spaces ? putc cr ; +: |...|/ ( - ) @h [ '| putc @w 2 * spaces '| putc 1- spaces '/ putc cr ] iterd ; +: face ( - ) + --- @w 1+ spaces '/ putc cr + |...|/ + --- cr ; + +: cuboid ( whd- ) + !d !h !w cr + @d 1+ spaces --- cr + @d [ dup spaces slice ] iterd + face ; + +2 3 4 cuboid diff --git a/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb b/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb new file mode 100644 index 0000000000..ed5ff0d1e0 --- /dev/null +++ b/Task/Draw-a-cuboid/Ruby/draw-a-cuboid.rb @@ -0,0 +1,26 @@ +DIR = {"-" => [1,0], "|" => [0,1], "/" => [1,1]} + +def cuboid(nx, ny, nz) + puts "cuboid %d %d %d:" % [nx, ny, nz] + x, y, z = 8*nx, 2*ny, 4*nz + area = Array.new(y+z+1){" " * (x+y+1)} + line = lambda do |n, sx, sy, c| + dx, dy = DIR[c] + (n+1).times do |i| + xi, yi = sx+i*dx, sy+i*dy + area[yi][xi] = (area[yi][xi]==" " ? c : "+") + end + end + nz .times {|i| line[x, 0, 4*i, "-"]} + (ny+1).times {|i| line[x, 2*i, z+2*i, "-"]} + nx .times {|i| line[z, 8*i, 0, "|"]} + (ny+1).times {|i| line[z, x+2*i, 2*i, "|"]} + nz .times {|i| line[y, x, 4*i, "/"]} + (nx+1).times {|i| line[y, 8*i, z, "/"]} + puts area.reverse +end + +cuboid(2, 3, 4) +cuboid(1, 1, 1) +cuboid(6, 2, 1) +cuboid(2, 4, 1) diff --git a/Task/Draw-a-sphere/00DESCRIPTION b/Task/Draw-a-sphere/00DESCRIPTION index bf434c8e38..d685926366 100644 --- a/Task/Draw-a-sphere/00DESCRIPTION +++ b/Task/Draw-a-sphere/00DESCRIPTION @@ -1 +1,6 @@ -The task is to draw a sphere. The sphere can be represented graphically, or in ascii art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. +The task is to draw a sphere. + +The sphere can be represented graphically, or in ascii art, +depending on the language capabilities. + +Either static or rotational projection is acceptable for this task. diff --git a/Task/Draw-a-sphere/00META.yaml b/Task/Draw-a-sphere/00META.yaml index ca818300c2..e866bda979 100644 --- a/Task/Draw-a-sphere/00META.yaml +++ b/Task/Draw-a-sphere/00META.yaml @@ -1,3 +1,5 @@ --- +category: +- 3D requires: - Graphics diff --git a/Task/Draw-a-sphere/C/draw-a-sphere-2.c b/Task/Draw-a-sphere/C/draw-a-sphere-2.c index 0f0664360a..dc31435dd2 100644 --- a/Task/Draw-a-sphere/C/draw-a-sphere-2.c +++ b/Task/Draw-a-sphere/C/draw-a-sphere-2.c @@ -1,61 +1,162 @@ - #############%%%% - ##&&eeeeeeeeee&&&&&&&####%%%%%%%% - &&eeooooooooooooooeeeee&&&&######%%%%%%%% - eeoo**************oooooooeeee&&&&####%%%%%%%% - &&oo**!!!!!!::!!!!!!!!****oooooee&&&&######%%%%%%%%%% - eeoo!!!!::::::::::::::!!!!*****ooeeee&&&&####%%%%%%%%%%%% - ee**!!::::............::::!!!!***ooooeeee&&######%%%%%%%%%%%% - &&oo!!::..................::!!!!*****ooeeee&&&&####%%%%%%%%%%%%%% - oo!!::....................::::!!*****ooeeee&&&&####%%%%%%%%%%%%%% - ee**!!::....................::::!!*****ooeeee&&&&####%%%%%%%%%%%%%%%% - &&oo!!::......................::::!!*****ooeeee&&&&######%%%%%%%%%%%%%%%% - ee**!!::......................::::!!*****ooeeee&&&&######%%%%%%%%%%%%%%%% - ##oo**!!::......................::!!!!*****ooeeee&&&&####%%%%%%%%%%%%%%%%%%%% - &&oo**::::....................::::!!!!***ooooeeee&&&&####%%%%%%%%%%%%%%%%%%%% - eeoo**!!::..................::::!!!!*****ooooee&&&&######%%%%%%%%%%%%%%%%%%%% - eeoo**!!::................::::!!!!****oooooeeee&&&&######%%%%%%%%%%%%%%%%%%%% -#eeoo**!!::::............::::!!!!!!****oooeeee&&&&&&######%%%%%%%%%%%%%%%%%%%%%% -#eeoo**!!!!::::::::::::::::!!!!!!****oooooeeee&&&&######%%%%%%%%%%%%%%%%%%%%%%%% -#eeoooo**!!!!!!::::::::!!!!!!******ooooeeeee&&&&&&######%%%%%%%%%%%%%%%%%%%%%%%% -#&&eeoo****!!!!!!!!!!!!!!!!******ooooeeeee&&&&&&######%%%%%%%%%%%%%%%%%%%%%%%%%% -#&&eeoooo********************ooooooeeee&&&&&&&######%%%%%%%%%%%%%%%%%%%%%%%%%%%% -#&&&&eeoooooo************ooooooeeeeee&&&&&&&########%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%##&&eeeeeeooooooooooooooooooeeeeee&&&&&&&########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -%####&&&&eeeeeeeeeeeeeeeeeeeeee&&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%##&&&&&&eeeeeeeeeeeeeeee&&&&&&&&&&#########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%######&&&&&&&&&&&&&&&&&&&&&&&&###########%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%########&&&&&&&&&&&&&&############%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%##############################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%######################%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%####%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% - %%%%%%%%%%%%%%%%% +#include +#include +#include - ::..:::::!!** - .............::!!**oo - ...................::!!**ooee - .......................::!!ooeeee - .......................::!!**ooee - .........................::!!**ooeeee - .........................::!!**ooeeee -:.........................::!!**ooeeeeee -........................::!!**ooooeeeeee -:.......................::!!**ooeeeeeeee -:.....................::!!****ooeeeeeeee -!::................:::!!****ooeeeeeeeeee -*!!::..........::::!!!****ooooeeeeeeeeee - **!!::::::::::!!!!*****ooooeeeeeeeeee - oo**!!!!!!!!!!*******ooooeeeeeeeeeeee - oooo********oooooooeeeeeeeeeeeeee - eeeeooooooooooeeeeeeeeeeeeeeeeeee - eeeeeeeeeeeeeeeeeeeeeeeeeeeee - eeeeeeeeeeeeeeeeeeeee - eeeeeeeeeeeee +#define MAXD 8 +int g[] = { -1, 1, -1, 1 }; +/* Perlin-like noise */ +inline void +hashed(int *data, int *out, int len) { +# define ror(a, d) ((a << (d)) | (a >> (32 - d))) + register unsigned int h = 0x12345678, tmp; + unsigned int *d = (void*)data; + int i = len; + + while (i--) { + tmp = *d++; + h += ror(h, 15) ^ ror(tmp, 5); + } + + h ^= ror(h, 7); + h += ror(h, 23); + h ^= ror(h, 19); + h += ror(h, 11); + h ^= ror(h, 13); + h += ror(h, 17); +# undef ror + for (i = len; i--; ) { + out[i] = g[h & 3]; + h >>= 2; + } +} + +double scale[MAXD], scale_u[MAXD]; +void noise_init() +{ + int i; + for (i = 1; i < MAXD; i++) { + scale[i] = 1 / (1 + sqrt(i + 1)); + scale_u[i] = scale[i] / sqrt(i + 1); + } +} + +double noise(double *x, int d) +{ +# define sum(s, x) for (s = 0, j = 0; j < d; j++) s += x + register int i, j; + int n[MAXD], o[MAXD], g[MAXD], tmp; + double s, r, t, w, ret, u[MAXD]; + + sum(s, x[j]); + s *= scale[d]; + + for (i = 0; i < d; i++) { + o[i] = i; + t = x[i] + s; + u[i] = t - (n[i] = floor(t)); + } + o[d] = 0; + + for (i = 0; i < d - 1; i++) + for (j = i; j < d; j++) + if (u[o[i]] < u[o[j]]) + tmp = o[i], o[i] = o[j], o[j] = tmp; + + ret = w = 0, r = 1; + for (s = 0, j = 0; j < d; j++) s += n[j]; + s *= scale_u[d]; + + for (i = 0; i <= d; i++) { + for (j = 0; j < d; j++) + u[j] = x[j] + s - n[j]; + + for (t = (d + 1.) / (2 * d), j = 0; j < d; j++) { + t -= u[j] * u[j]; + if (t <= 0) break; + } + + if (t >= 0) { + r = 0; + hashed(n, g, d); + for (j = 0; j < d; j++) + if (g[j]) r += (g[j] == 1 ? u[j] : -u[j]); + t *= t; + ret += r * t * t; + } + + if (i < d) { + n[o[i]]++; + s += scale_u[d]; + } + } + return ret * (d * d); +} + +double get_noise2(double x, double y) +{ + int i, ws; + double r = 0, v[2]; + + for (i = 1, ws = 0; i <= 128; i <<= 1) { + v[0] = x * i, v[1] = y * i; + r += noise(v, 2); + ws ++; + } + r /= ws; + return r; +} + +double get_noise3(double x, double y, double z) +{ + int i, ws; + double r = 0, v[3], w; + + for (i = 1, ws = 0; i <= 32; i <<= 1) { + v[0] = x * i, v[1] = y * i, v[2] = z * i; + w = 1./sqrt(i); + r += noise(v, 3) * w; + ws += w; + } + return r / ws; +} + + +int main(int c, char** v) +{ + unsigned char pix[256 * 256], *p; + int i, j; + double x, y, z, w; + FILE *fp; + + noise_init(); + + for (p = pix, i = 0; i < 256 * 256; i++) *p++ = 0; + + for (p = pix, i = 0; i < 256; i++) { + y = (i - 128) / 125.; + for (j = 0; j < 256; j++, p++) { + x = (j - 128) / 125.; + *p = (get_noise2(i/256., j/256.) + 1) / 6 * i; + + z = 1- x*x - y*y; + if (z < 0) continue; + + z = sqrt(z); + + w = get_noise3(x, y, z); + + w = (w + 1) / 2; + w *= (1 + x - y + z) / 3.5; + if (w < 0) w = 0; + + *p = w * 255; + } + } + + fp = fopen("out.pgm", "w+"); + fprintf(fp, "P5\n256 256\n255\n"); + fwrite(pix, 1, 256 * 256, fp); + fclose(fp); + + return 0; +} diff --git a/Task/Draw-a-sphere/Clojure/draw-a-sphere.clj b/Task/Draw-a-sphere/Clojure/draw-a-sphere.clj new file mode 100644 index 0000000000..ab479d9004 --- /dev/null +++ b/Task/Draw-a-sphere/Clojure/draw-a-sphere.clj @@ -0,0 +1,20 @@ +(use 'quil.core) + +(def w 500) +(def h 400) + +(defn setup [] + (background 0)) + +(defn draw [] + (push-matrix) + (translate 250 200 0) + (sphere 100) + (pop-matrix)) + +(defsketch main + :title "sphere" + :setup setup + :size [w h] + :draw draw + :renderer :opengl) diff --git a/Task/Draw-a-sphere/D/draw-a-sphere.d b/Task/Draw-a-sphere/D/draw-a-sphere.d index 828ae554e7..4ae46177ea 100644 --- a/Task/Draw-a-sphere/D/draw-a-sphere.d +++ b/Task/Draw-a-sphere/D/draw-a-sphere.d @@ -1,39 +1,40 @@ import std.stdio, std.math, std.algorithm, std.numeric; -alias double[3] V3; -V3 light = [30, 30, -50]; +alias V3 = double[3]; +immutable light = normalize([30.0, 30.0, -50.0]); -void normalize(ref V3 v) pure { +V3 normalize(V3 v) pure @nogc { v[] /= dotProduct(v, v) ^^ 0.5; + return v; } -double dot(in ref V3 x, in ref V3 y) pure nothrow { +double dot(in ref V3 x, in ref V3 y) pure nothrow @nogc { immutable double d = dotProduct(x, y); return d < 0 ? -d : 0; } -void drawSphere(in double R, in double k, in double ambient) { +void drawSphere(in double R, in double k, in double ambient) @nogc { enum shades = ".:!*oe&#%@"; - foreach (int i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) { + foreach (immutable i; cast(int)floor(-R) .. cast(int)ceil(R) + 1) { immutable double x = i + 0.5; - foreach (int j; cast(int)floor(-2*R)..cast(int)ceil(2*R)+1){ + foreach (immutable j; cast(int)floor(-2 * R) .. + cast(int)ceil(2 * R) + 1) { immutable double y = j / 2. + 0.5; if (x ^^ 2 + y ^^ 2 <= R ^^ 2) { - V3 vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5]; - vec.normalize(); + immutable vec = [x, y, (R^^2 - x^^2 - y^^2) ^^ 0.5] + .normalize; immutable double b = dot(light, vec) ^^ k + ambient; - int intensity = cast(int)((1-b) * (shades.length-1)); - intensity = min(shades.length-1, max(intensity, 0)); - putchar(shades[intensity]); + int intensity = cast(int)((1 - b) * (shades.length-1)); + intensity = min(shades.length - 1, max(intensity, 0)); + shades[intensity].putchar; } else - putchar(' '); + ' '.putchar; } - putchar('\n'); + '\n'.putchar; } } void main() { - light.normalize(); drawSphere(20, 4, 0.1); drawSphere(10, 2, 0.4); } diff --git a/Task/Draw-a-sphere/JavaScript/draw-a-sphere.js b/Task/Draw-a-sphere/JavaScript/draw-a-sphere.js new file mode 100644 index 0000000000..f8e1a7c791 --- /dev/null +++ b/Task/Draw-a-sphere/JavaScript/draw-a-sphere.js @@ -0,0 +1,62 @@ + + + + +Draw a sphere + + + +R= +
+k= +
+ambient= +
+Unsupportive browser...
+ + diff --git a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 index 66900dcd8f..4f41110b8f 100644 --- a/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 +++ b/Task/Draw-a-sphere/Perl-6/draw-a-sphere.pl6 @@ -8,7 +8,7 @@ my $depth = 255; sub MAIN ($outfile = 'sphere-perl6.pgm') { my $out = open( $outfile, :w, :bin ) or die "$!\n"; $out.say("P5\n$x $y\n$depth"); # .pgm header - $out.print( draw_sphere( ($x-1)/2, .9, .2)».chrs ); + $out.write( Blob.new(draw_sphere( ($x-1)/2, .9, .2) ) ); $out.close; } diff --git a/Task/Draw-a-sphere/Python/draw-a-sphere-2.py b/Task/Draw-a-sphere/Python/draw-a-sphere-2.py index aac759dfff..dccf067d9d 100644 --- a/Task/Draw-a-sphere/Python/draw-a-sphere-2.py +++ b/Task/Draw-a-sphere/Python/draw-a-sphere-2.py @@ -4,774 +4,3 @@ import time import sys import random import math -class Tricubic: - def __init__(self,pts): - self.coefficients = [] - for plane in pts: - planecoeffs = [] - for line in plane: - p = (line[3]-line[2])-(line[0]-line[1]) - q = (line[0]-line[1])-p - r = line[2]-line[0] - s = line[1] - planecoeffs.append([p,q,r,s]) - self.coefficients.append(planecoeff) - def Eval(at): - return Misc.Cubic([CoeffBicubic(coeffs[0],d),CoeffBicubic(coeffs[1],d),CoeffBicubic(coeffs[2],d),CoeffBicubic(coeffs[3],d)],d.z) - def CoeffCubic(coeffs,d): - return (coeffs[0]*(d.x**3))+(coeffs[1]*(d.x**2))+(coeffs[2]*d.x)+coeffs[3] - def CoeffBicubic(coeffs,d): - return Misc.Cubic([CoeffCubic(coeffs[0],d),CoeffCubic(coeffs[1],d),CoeffCubic(coeffs[2],d),CoeffCubic(coeffs[3],d)],d.y) -class Misc: - def LinePara(line,t): - return Vector3.Add(line[0],Vector3.Scale(Vector3.Subtract(line[1],line[0]),t)) - def LUR(at,above): - look = at.Unit() - right = Vector3.Cross(look,above).Unit() - up = Vector3.Scale(Vector3.Cross(look,right),-1) - return [look,up,right] - def LinePlane(line,triangle,cp=True): - try: - u = Vector3.Subtract(triangle.points[1].point,triangle.points[0]) - v = Vector3.Subtract(triangle.points[2],triangle.points[0]) - n = Vector3.Cross(u,v) - r = (Vector3.Dot(n,Vector3.Subtract(triangle.points[0],line.start))/Vector3.Dot(n,line.direction)) - if stp: - point = Vector3.Add(Vector3.Scale(line.direction,r),line.start) - w = Vector3.Subtract(point,triangle.points[0]) - udv = Vector3.Dot(u,v) - wdv = Vector3.Dot(w,v) - vdv = Vector3.Dot(v,v) - wdu = Vector3.Dot(w,u) - udu = Vector3.Dot(u,u) - denominator = (udv**2)-(udu*vdv) - s = ((udv*wdv)-(vdv*wdu))/denominator - t = ((udv*wdu)-(udu*wdv))/denominator - return [r,Vector2(s,t),point] - print('hooray') - else: - return [r] - except: - return None - def Cubic(pts,d): - p = (pts[3]-pts[2])-(pts[0]-pts[1]) - q = (pts[0]-pts[1])-p - r = pts[2]-pts[0] - s = pts[1] - return (p*(d**3))+(q*(d**2))+(r*d)+s - def Bicubic(pts,d): - return Misc.Cubic([Misc.Cubic(pts[0],d.x),Misc.Cubic(pts[1],d.x),Misc.Cubic(pts[2],d.x),Misc.Cubic(pts[3],d.x)],d.y) - def Tricubic(pts,d): - return Misc.Cubic([Misc.Bicubic(pts[0],d),Misc.Bicubic(pts[1],d),Misc.Bicubic(pts[2],d),Misc.Bicubic(pts[3],d)],d.z) - def Quadcubic(pts,d): - return Misc.Cubic([Misc.Tricubic(pts[0],d),Misc.Tricubic(pts[1],d),Misc.Tricubic(pts[2],d),Misc.Tricubic(pts[3],d)],d.w) - def Linear(pts,d): - return (pts[2]*d)+(pts[1]*(1-d)) - def Bilinear(pts,d): - return Misc.Linear([0,Misc.Linear(pts[1],d.x),Misc.Linear(pts[2],d.x)],d.y) - def Trilinear(pts,d): - return Misc.Linear([0,Misc.Bilinear(pts[1],d),Misc.Bilinear(pts[2],d)],d.z) - def LP2(line,triangle,cp=True): - try: - bla = triangle.points[1] - bla = triangle.points[0] - u = Vector3.Subtract(triangle.points[1].point,triangle.points[0].point) - v = Vector3.Subtract(triangle.points[2].point,triangle.points[0].point) - n = Vector3.Cross(u,v) - d = Vector3.Subtract(line[1],line[0]) - r = (Vector3.Dot(n,Vector3.Subtract(triangle.points[0].point,line[0]))/Vector3.Dot(n,d)) - if cp: - point = Vector3.Add(Vector3.Scale(d,r),line[0]) - w = Vector3.Subtract(point,triangle.points[0].point) - udv = Vector3.Dot(u,v) - wdv = Vector3.Dot(w,v) - vdv = Vector3.Dot(v,v) - wdu = Vector3.Dot(w,u) - udu = Vector3.Dot(u,u) - denominator = (udv**2)-(udu*vdv) - s = ((udv*wdv)-(vdv*wdu))/denominator - t = ((udv*wdu)-(udu*wdv))/denominator - return (r,Vector2(s,t),point) - else: - return (r) - except: - return None - def Phong(normal,viewer,light,material,term): - # light (vector_to,diffuse,specular) - # material (ambient,diffuse,specular,shininess) - n = normal.Unit() - v = viewer.Unit() - l = light[0].Unit() - ldn = Vector3.Dot(l,n) - #print(ldn) - val = 0 - if ldn > 0: - val += material[1][term]*ldn*light[1][term] - rdv = Vector3.Dot(Vector3.Subtract(Vector3.Scale(n,2*ldn),l),v) - if rdv > 0: - val += (material[2][term]*(rdv**material[3])*light[2][term]) - #print(val) - return val - def Lighting(ambient,normal,viewer,lights,material,term): - # lights [(vector_to,diffuse,specular)] - # material (ambient,diffuse,specular,shininess) - val = material[0][term]*ambient[term] - for light in lights: - val += Misc.Phong(normal,viewer,light,material,term) - return val - def Lighting2(start,direction,ambient,intersect,triangle,lights): - coord = intersect[1] - val = Color.Add(Color.Multiply(ambient,Color.Multiply(triangle.material.color['ambient'],triangle.Map('ambient',coord))), - Color.Multiply(triangle.material.color['glow'],triangle.Map('glow',coord))) - for light in lights: - for n in range(3): - val[n] += Misc.Phong(triangle.InterpolatedNormal(coord), - Vector3.Scale(direction,-1), - (light.To(intersect[2]),light.Diffuse(intersect[2]),light.Specular(intersect[2])), - (Color(), - Color.Multiply(triangle.material.color['diffuse'],triangle.Map('diffuse',coord)), - Color.Multiply(triangle.material.color['specular'],triangle.Map('specular',coord)), - triangle.material.shiny),n) - return val - def Ray(start,direction,scene,color=True,sector=None): - intersect = None - intersected = None - col = None - for triangle in scene.triangles: - possible = True - if sector != None: - possible = False - for point in triangle.points: - if not(point.sector.x < sector.x): - possible = True - if possible: - possible = False - for point in triangle.points: - if not(point.sector.x > sector.x): - possible = True - if possible: - possible = False - for point in triangle.points: - if not(point.sector.y < sector.y): - possible = True - if possible: - possible = False - for point in triangle.points: - if not(point.sector.y > sector.y): - possible = True - possible = True - if possible: - tmp = Misc.LP2([start,Vector3.Add(start,direction)],triangle,color) - write = False - if type(tmp) == type(5.1): - tmp = None - if (tmp != None): - if (intersect == None): - if (tmp[0] > 0) and (tmp[1].x >= 0) and (tmp[1].y >= 0) and (tmp[1].x+tmp[1].y <= 1): - write = True - elif (tmp[0] > 0) and (tmp[0] < intersect[0]) and (tmp[1].x >= 0) and (tmp[1].y >= 0) and (tmp[1].x+tmp[1].y <= 1): - write = True - if write: - intersect = tmp - intersected = triangle - if color and (intersect != None): - applicable = [] - for light in scene.lights: - block = Misc.Ray(intersect[2],light.To(intersect[2]),scene,False) - if block == None: - applicable.append(light) - elif light.location != None: - if Vector3.Subtract(light.location,intersect[2]).Magnitude() < block[0]: - applicable.append(light) - col = Misc.Lighting2(start,direction,scene.ambient,intersect,intersected,applicable) - return (intersect,col) - else: - return intersect -class DirLight: - def __init__(self,direction,diffuse,specular): - self.location = None - self.direction = direction.Unit() - self.diffuse = diffuse - self.specular = specular - def To(self,frm): - return Vector3.Scale(self.direction,-1) - def Diffuse(self,to): - return self.diffuse - def Specular(self,to): - return self.specular -class Material: - def __init__(self): - self.color = {'ambient':Color(1,1,1), - 'diffuse':Color(1,1,1), - 'specular':Color(1,1,1), - 'glow':Color(1,1,1)} - self.maps = {'ambient':Map(), - 'diffuse':Map(), - 'specular':Map(), - 'glow':Map(), - 'bump':Map()} - self.shiny = 10 -class Map: - def __init__(self,surface=None): - self.surface = surface - if self.surface != None: - self.width = self.surface.get_width() - self.height = self.surface.get_height() - def __getitem__(self,index): - if self.surface == None: - return Color(1,1,1) - else: - try: - return Color.From255(self.surface.get_at((int(index.x*(self.width-1)),int(index.y*(self.height-1))))) - except: - return Color(0,0,1) -class Color: - def __init__(self,r=0,g=0,b=0): - self.r = r - self.g = g - self.b = b - def __getitem__(self,index): - if index == 0: - return self.r - elif index == 1: - return self.g - elif index == 2: - return self.b - def __setitem__(self,index,value): - if index == 0: - self.r = value - elif index == 1: - self.g = value - elif index == 2: - self.b = value - def Multiply(A,B): - return Color(A.r*B.r,A.g*B.g,A.b*B.b) - def Add(A,B): - return Color(A.r+B.r,A.g+B.g,A.b+B.b) - def From255(A): - return Color(A.r/255,A.g/255,A.b/255) -class Vertex: - def __init__(self,point,normal,maps): - self.bpoint = point - self.bnormal = normal - self.maps = maps - for name in ['ambient','diffuse','specular','glow','bump']: - try: - bla = self.maps[name] - except: - self.maps[name] = Vector2() - self.sector = None - def Transform(self,points,norms): - self.point = Matrix2.Multiply(self.bpoint.Horizontal(),points).Vectorize() - self.normal = Matrix2.Multiply(self.bnormal.Horizontal(),norms).Vectorize() -class Triangle: - def __init__(self,vertices,material=Material()): - self.points = vertices - self.material = material - def Map(self,name,coord): - pts = [] - for n in range(3): - pts.append(self.points[n].maps[name]) - loc = Vector2.Add(pts[0], - Vector2.Add(Vector2.Scale(Vector2.Subtract(pts[1],pts[0]),coord.x), - Vector2.Scale(Vector2.Subtract(pts[2],pts[0]),coord.y))) - #print(loc.x,loc.y) - return self.material.maps[name][loc] - def InterpolatedNormal(self,coord): - return Vector3.Add(Vector3.Scale(self.points[0].normal,1-coord.x-coord.y), - Vector3.Add(Vector3.Scale(self.points[1].normal,coord.x),Vector3.Scale(self.points[2].normal,coord.y))).Unit() -class Line: - def __init__(self,A,B=None,direction=None): - self.start = A - if B != None: - self.direction = Vector3.Subtract(B,A).Unit() - elif direction != None: - self.direction = direction - else: - raise RuntimeError('Neither B nor direction are specified') -class Scene: - def __init__(self): - self.triangles = [] - self.vertices = [] - self.lights = [] - self.exterior = [] - self.ambient = 0 -class Matrix2: - def __init__(self,data=[[]]): - self.FromData(data) - def __getitem__(self,index): - return self.data[index[1]][index[0]] - def __setitem__(self,index,value): - self.data[index[1]][index[0]]=value - def Dimension(self): - self.rows = len(self.data) - self.cols = len(self.data[0]) - def FromData(self,data): - self.data = data - length=len(data[0]) - for row in data: - if len(row)!=length: - self.data=None - raise RuntimeError('Data rows are not of uniform length.') - self.Dimension() - def Multiply(A,B): - if A.cols!=B.rows: - raise RuntimeError('Column count of Matrix2 \"A\" does not match row count of Matrix2 \"B\".') - matrix = Matrix2.Empty(B.cols,A.rows) - x=0 - while x 1: - light = 1 - elif light < 0: - light = 0 - coloring.append(round(255*light)) - screen.set_at((x,height-y),pygame.Color(coloring[0],coloring[1],coloring[2])) - pygame.display.update() -pygame.image.save(screen,"PythonSphere.png") -while True: - for event in pygame.event.get(): - if event.type == QUIT: - pygame.quit() - sys.exit() - if event.type == KEYDOWN: - pass diff --git a/Task/Draw-a-sphere/Python/draw-a-sphere-3.py b/Task/Draw-a-sphere/Python/draw-a-sphere-3.py new file mode 100644 index 0000000000..7918dcaa33 --- /dev/null +++ b/Task/Draw-a-sphere/Python/draw-a-sphere-3.py @@ -0,0 +1,771 @@ +class Tricubic: + def __init__(self,pts): + self.coefficients = [] + for plane in pts: + planecoeffs = [] + for line in plane: + p = (line[3]-line[2])-(line[0]-line[1]) + q = (line[0]-line[1])-p + r = line[2]-line[0] + s = line[1] + planecoeffs.append([p,q,r,s]) + self.coefficients.append(planecoeff) + def Eval(at): + return Misc.Cubic([CoeffBicubic(coeffs[0],d),CoeffBicubic(coeffs[1],d),CoeffBicubic(coeffs[2],d),CoeffBicubic(coeffs[3],d)],d.z) + def CoeffCubic(coeffs,d): + return (coeffs[0]*(d.x**3))+(coeffs[1]*(d.x**2))+(coeffs[2]*d.x)+coeffs[3] + def CoeffBicubic(coeffs,d): + return Misc.Cubic([CoeffCubic(coeffs[0],d),CoeffCubic(coeffs[1],d),CoeffCubic(coeffs[2],d),CoeffCubic(coeffs[3],d)],d.y) +class Misc: + def LinePara(line,t): + return Vector3.Add(line[0],Vector3.Scale(Vector3.Subtract(line[1],line[0]),t)) + def LUR(at,above): + look = at.Unit() + right = Vector3.Cross(look,above).Unit() + up = Vector3.Scale(Vector3.Cross(look,right),-1) + return [look,up,right] + def LinePlane(line,triangle,cp=True): + try: + u = Vector3.Subtract(triangle.points[1].point,triangle.points[0]) + v = Vector3.Subtract(triangle.points[2],triangle.points[0]) + n = Vector3.Cross(u,v) + r = (Vector3.Dot(n,Vector3.Subtract(triangle.points[0],line.start))/Vector3.Dot(n,line.direction)) + if stp: + point = Vector3.Add(Vector3.Scale(line.direction,r),line.start) + w = Vector3.Subtract(point,triangle.points[0]) + udv = Vector3.Dot(u,v) + wdv = Vector3.Dot(w,v) + vdv = Vector3.Dot(v,v) + wdu = Vector3.Dot(w,u) + udu = Vector3.Dot(u,u) + denominator = (udv**2)-(udu*vdv) + s = ((udv*wdv)-(vdv*wdu))/denominator + t = ((udv*wdu)-(udu*wdv))/denominator + return [r,Vector2(s,t),point] + print('hooray') + else: + return [r] + except: + return None + def Cubic(pts,d): + p = (pts[3]-pts[2])-(pts[0]-pts[1]) + q = (pts[0]-pts[1])-p + r = pts[2]-pts[0] + s = pts[1] + return (p*(d**3))+(q*(d**2))+(r*d)+s + def Bicubic(pts,d): + return Misc.Cubic([Misc.Cubic(pts[0],d.x),Misc.Cubic(pts[1],d.x),Misc.Cubic(pts[2],d.x),Misc.Cubic(pts[3],d.x)],d.y) + def Tricubic(pts,d): + return Misc.Cubic([Misc.Bicubic(pts[0],d),Misc.Bicubic(pts[1],d),Misc.Bicubic(pts[2],d),Misc.Bicubic(pts[3],d)],d.z) + def Quadcubic(pts,d): + return Misc.Cubic([Misc.Tricubic(pts[0],d),Misc.Tricubic(pts[1],d),Misc.Tricubic(pts[2],d),Misc.Tricubic(pts[3],d)],d.w) + def Linear(pts,d): + return (pts[2]*d)+(pts[1]*(1-d)) + def Bilinear(pts,d): + return Misc.Linear([0,Misc.Linear(pts[1],d.x),Misc.Linear(pts[2],d.x)],d.y) + def Trilinear(pts,d): + return Misc.Linear([0,Misc.Bilinear(pts[1],d),Misc.Bilinear(pts[2],d)],d.z) + def LP2(line,triangle,cp=True): + try: + bla = triangle.points[1] + bla = triangle.points[0] + u = Vector3.Subtract(triangle.points[1].point,triangle.points[0].point) + v = Vector3.Subtract(triangle.points[2].point,triangle.points[0].point) + n = Vector3.Cross(u,v) + d = Vector3.Subtract(line[1],line[0]) + r = (Vector3.Dot(n,Vector3.Subtract(triangle.points[0].point,line[0]))/Vector3.Dot(n,d)) + if cp: + point = Vector3.Add(Vector3.Scale(d,r),line[0]) + w = Vector3.Subtract(point,triangle.points[0].point) + udv = Vector3.Dot(u,v) + wdv = Vector3.Dot(w,v) + vdv = Vector3.Dot(v,v) + wdu = Vector3.Dot(w,u) + udu = Vector3.Dot(u,u) + denominator = (udv**2)-(udu*vdv) + s = ((udv*wdv)-(vdv*wdu))/denominator + t = ((udv*wdu)-(udu*wdv))/denominator + return (r,Vector2(s,t),point) + else: + return (r) + except: + return None + def Phong(normal,viewer,light,material,term): + # light (vector_to,diffuse,specular) + # material (ambient,diffuse,specular,shininess) + n = normal.Unit() + v = viewer.Unit() + l = light[0].Unit() + ldn = Vector3.Dot(l,n) + #print(ldn) + val = 0 + if ldn > 0: + val += material[1][term]*ldn*light[1][term] + rdv = Vector3.Dot(Vector3.Subtract(Vector3.Scale(n,2*ldn),l),v) + if rdv > 0: + val += (material[2][term]*(rdv**material[3])*light[2][term]) + #print(val) + return val + def Lighting(ambient,normal,viewer,lights,material,term): + # lights [(vector_to,diffuse,specular)] + # material (ambient,diffuse,specular,shininess) + val = material[0][term]*ambient[term] + for light in lights: + val += Misc.Phong(normal,viewer,light,material,term) + return val + def Lighting2(start,direction,ambient,intersect,triangle,lights): + coord = intersect[1] + val = Color.Add(Color.Multiply(ambient,Color.Multiply(triangle.material.color['ambient'],triangle.Map('ambient',coord))), + Color.Multiply(triangle.material.color['glow'],triangle.Map('glow',coord))) + for light in lights: + for n in range(3): + val[n] += Misc.Phong(triangle.InterpolatedNormal(coord), + Vector3.Scale(direction,-1), + (light.To(intersect[2]),light.Diffuse(intersect[2]),light.Specular(intersect[2])), + (Color(), + Color.Multiply(triangle.material.color['diffuse'],triangle.Map('diffuse',coord)), + Color.Multiply(triangle.material.color['specular'],triangle.Map('specular',coord)), + triangle.material.shiny),n) + return val + def Ray(start,direction,scene,color=True,sector=None): + intersect = None + intersected = None + col = None + for triangle in scene.triangles: + possible = True + if sector != None: + possible = False + for point in triangle.points: + if not(point.sector.x < sector.x): + possible = True + if possible: + possible = False + for point in triangle.points: + if not(point.sector.x > sector.x): + possible = True + if possible: + possible = False + for point in triangle.points: + if not(point.sector.y < sector.y): + possible = True + if possible: + possible = False + for point in triangle.points: + if not(point.sector.y > sector.y): + possible = True + possible = True + if possible: + tmp = Misc.LP2([start,Vector3.Add(start,direction)],triangle,color) + write = False + if type(tmp) == type(5.1): + tmp = None + if (tmp != None): + if (intersect == None): + if (tmp[0] > 0) and (tmp[1].x >= 0) and (tmp[1].y >= 0) and (tmp[1].x+tmp[1].y <= 1): + write = True + elif (tmp[0] > 0) and (tmp[0] < intersect[0]) and (tmp[1].x >= 0) and (tmp[1].y >= 0) and (tmp[1].x+tmp[1].y <= 1): + write = True + if write: + intersect = tmp + intersected = triangle + if color and (intersect != None): + applicable = [] + for light in scene.lights: + block = Misc.Ray(intersect[2],light.To(intersect[2]),scene,False) + if block == None: + applicable.append(light) + elif light.location != None: + if Vector3.Subtract(light.location,intersect[2]).Magnitude() < block[0]: + applicable.append(light) + col = Misc.Lighting2(start,direction,scene.ambient,intersect,intersected,applicable) + return (intersect,col) + else: + return intersect +class DirLight: + def __init__(self,direction,diffuse,specular): + self.location = None + self.direction = direction.Unit() + self.diffuse = diffuse + self.specular = specular + def To(self,frm): + return Vector3.Scale(self.direction,-1) + def Diffuse(self,to): + return self.diffuse + def Specular(self,to): + return self.specular +class Material: + def __init__(self): + self.color = {'ambient':Color(1,1,1), + 'diffuse':Color(1,1,1), + 'specular':Color(1,1,1), + 'glow':Color(1,1,1)} + self.maps = {'ambient':Map(), + 'diffuse':Map(), + 'specular':Map(), + 'glow':Map(), + 'bump':Map()} + self.shiny = 10 +class Map: + def __init__(self,surface=None): + self.surface = surface + if self.surface != None: + self.width = self.surface.get_width() + self.height = self.surface.get_height() + def __getitem__(self,index): + if self.surface == None: + return Color(1,1,1) + else: + try: + return Color.From255(self.surface.get_at((int(index.x*(self.width-1)),int(index.y*(self.height-1))))) + except: + return Color(0,0,1) +class Color: + def __init__(self,r=0,g=0,b=0): + self.r = r + self.g = g + self.b = b + def __getitem__(self,index): + if index == 0: + return self.r + elif index == 1: + return self.g + elif index == 2: + return self.b + def __setitem__(self,index,value): + if index == 0: + self.r = value + elif index == 1: + self.g = value + elif index == 2: + self.b = value + def Multiply(A,B): + return Color(A.r*B.r,A.g*B.g,A.b*B.b) + def Add(A,B): + return Color(A.r+B.r,A.g+B.g,A.b+B.b) + def From255(A): + return Color(A.r/255,A.g/255,A.b/255) +class Vertex: + def __init__(self,point,normal,maps): + self.bpoint = point + self.bnormal = normal + self.maps = maps + for name in ['ambient','diffuse','specular','glow','bump']: + try: + bla = self.maps[name] + except: + self.maps[name] = Vector2() + self.sector = None + def Transform(self,points,norms): + self.point = Matrix2.Multiply(self.bpoint.Horizontal(),points).Vectorize() + self.normal = Matrix2.Multiply(self.bnormal.Horizontal(),norms).Vectorize() +class Triangle: + def __init__(self,vertices,material=Material()): + self.points = vertices + self.material = material + def Map(self,name,coord): + pts = [] + for n in range(3): + pts.append(self.points[n].maps[name]) + loc = Vector2.Add(pts[0], + Vector2.Add(Vector2.Scale(Vector2.Subtract(pts[1],pts[0]),coord.x), + Vector2.Scale(Vector2.Subtract(pts[2],pts[0]),coord.y))) + #print(loc.x,loc.y) + return self.material.maps[name][loc] + def InterpolatedNormal(self,coord): + return Vector3.Add(Vector3.Scale(self.points[0].normal,1-coord.x-coord.y), + Vector3.Add(Vector3.Scale(self.points[1].normal,coord.x),Vector3.Scale(self.points[2].normal,coord.y))).Unit() +class Line: + def __init__(self,A,B=None,direction=None): + self.start = A + if B != None: + self.direction = Vector3.Subtract(B,A).Unit() + elif direction != None: + self.direction = direction + else: + raise RuntimeError('Neither B nor direction are specified') +class Scene: + def __init__(self): + self.triangles = [] + self.vertices = [] + self.lights = [] + self.exterior = [] + self.ambient = 0 +class Matrix2: + def __init__(self,data=[[]]): + self.FromData(data) + def __getitem__(self,index): + return self.data[index[1]][index[0]] + def __setitem__(self,index,value): + self.data[index[1]][index[0]]=value + def Dimension(self): + self.rows = len(self.data) + self.cols = len(self.data[0]) + def FromData(self,data): + self.data = data + length=len(data[0]) + for row in data: + if len(row)!=length: + self.data=None + raise RuntimeError('Data rows are not of uniform length.') + self.Dimension() + def Multiply(A,B): + if A.cols!=B.rows: + raise RuntimeError('Column count of Matrix2 \"A\" does not match row count of Matrix2 \"B\".') + matrix = Matrix2.Empty(B.cols,A.rows) + x=0 + while x 1: + light = 1 + elif light < 0: + light = 0 + coloring.append(round(255*light)) + screen.set_at((x,height-y),pygame.Color(coloring[0],coloring[1],coloring[2])) + pygame.display.update() +pygame.image.save(screen,"PythonSphere.png") +while True: + for event in pygame.event.get(): + if event.type == QUIT: + pygame.quit() + sys.exit() + if event.type == KEYDOWN: + pass diff --git a/Task/Draw-a-sphere/Python/draw-a-sphere-4.py b/Task/Draw-a-sphere/Python/draw-a-sphere-4.py new file mode 100644 index 0000000000..902d7ff998 --- /dev/null +++ b/Task/Draw-a-sphere/Python/draw-a-sphere-4.py @@ -0,0 +1,3 @@ +from visual import * +scene.title = "VPython: Draw a sphere" +sphere() # using defaults, see http://www.vpython.org/contents/docs/defaults.html defaults] diff --git a/Task/Draw-a-sphere/Python/draw-a-sphere-5.py b/Task/Draw-a-sphere/Python/draw-a-sphere-5.py new file mode 100644 index 0000000000..c494b85a0e --- /dev/null +++ b/Task/Draw-a-sphere/Python/draw-a-sphere-5.py @@ -0,0 +1,22 @@ +from __future__ import print_function, division +from visual import * + +title = "VPython: Draw a sphere" +scene.title = title +print( "%s\n" % title ) + +print( 'Drag with right mousebutton to rotate view' ) +print( 'Drag up+down with middle mousebutton to zoom') + +scene.autocenter = True + +# uncomment any (or all) of those variants: +S1 = sphere(pos=(0.0, 0.0, 0.0), radius=1.0, color=color.blue) +#S2 = sphere(pos=(2.0, 0.0, 0.0), radius=1.0, material=materials.earth) +#S3 = sphere(pos=(0.0, 2.0, 0.0), radius=1.0, material=materials.BlueMarble) +#S4 = sphere(pos=(0.0, 0.0, 2.0), radius=1.0, +# color=color.orange, material=materials.marble) + +while True: # Animation-loop + rate(100) + pass # no animation in this demo diff --git a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx index 512006fc08..52be4305b8 100644 --- a/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx +++ b/Task/Draw-a-sphere/REXX/draw-a-sphere.rexx @@ -1,39 +1,38 @@ -/*REXX program to express a lighted sphere with simple chars for shading*/ -call drawSphere 19, 4, 2/10 -call drawSphere 10, 2, 4/10 +/*REXX program expresses a lighted sphere with simple chars for shading.*/ +call drawSphere 19, 4, 2/10 /*draw a sphere with radius 19. */ +call drawSphere 10, 2, 4/10 /*draw a sphere with radius ten. */ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────drawSphere subroutine───────────────*/ -drawSphere: procedure; parse arg r, k, ambient -if 1=='f1'x then shading='.:!*oe&#%@' /*for EBCDIC machs.*/ - else shading='·:!ºoe@░▒▓' /*for ASCI machines*/ - lightSource = '30 30 -50' /*the light source.*/ +/*──────────────────────────────────DRAWSPHERE subroutine───────────────*/ +drawSphere: procedure; parse arg r, k, ambient /*get the arguments*/ +if 1=='f1'x then shading='.:!*oe&#%@' /*EBCDIC dithering.*/ + else shading='·:!°oe@░▒▓' /*ASCII " */ +lightSource = '30 30 -50' /*the light source.*/ parse value norm(lightSource) with s1 s2 s3 /*normalize light S*/ -sLen=length(shading); sLen1=sLen-1; rr=r*r +sLen=length(shading); sLen1=sLen-1; rr=r*r /*handy-dandy vars.*/ - do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; aLine= + do i=floor(-r) to ceil(r) ; x= i+.5; xx=x**2; aLine= do j=floor(-2*r) to ceil(2*r); y=j/2+.5; yy=y**2 - if xx+yy<=rr then do + if xx+yy<=rr then do /*within the phere?*/ parse value norm(x y sqrt(rr-xx-yy)) with v1 v2 v3 - dot=s1*v1 + s2*v2 + s3*v3 - if dot>0 then dot=0 - b=abs(dot)**k + ambient + dot=s1*v1 + s2*v2 + s3*v3 /*dot product of Vs*/ + if dot>0 then dot=0 /*if pos, make it 0*/ + b=abs(dot)**k + ambient /*calc. brightness.*/ if b<=0 then brite=sLenm1 else brite=trunc( max( (1-b) * sLen1, 0) ) - aLine=aLine || substr(shading,brite+1,1) + aLine=aLine || substr(shading,brite+1,1) /*build.*/ end - else aLine=aLine' ' + else aLine=aLine' ' /*append a blank. */ end /*j*/ - say strip(aLine,'trailing') - end /*i*/ + say strip(aLine,'trailing') /*show a line of it*/ + end /*i*/ /* [↑] show sphere*/ return -/*─────────────────────────────────────"1-liner" subroutines────────────*/ +/*─────────────────────────────────────subroutines────────────────────────────*/ ceil: procedure; parse arg x; _=trunc(x); return _ + (x>0) * (x\=_) floor: procedure; parse arg x; _=trunc(x); return _ - (x<0) * (x\=_) -norm: parse arg _1 _2 _3; _=sqrt(_1*_1+_2*_2+_3*_3); return _1/_ _2/_ _3/_ -sqrt: procedure; parse arg x; if x=0 then return 0; return .sqrt(x)/1 -.sqrt: d=digits(); numeric digits 11; g=.sqrtGuess() - do j=0 while p>9; m.j=p; p=p%2+1; end - do k=j+5 by -1 to 0; if m.k>11 then numeric digits m.k; g=.5*(g+x/g);end - return g -.sqrtGuess: numeric form; m.=11; p=d+d%4+2; v=format(x,2,1,,0) 'E0' - parse var v g 'E' _ .; return g*.5'E'_%2 +norm: parse arg _1 _2 _3; _=sqrt(_1**2+_2**2+_3**2); return _1/_ _2/_ _3/_ +/*─────────────────────────────────────SQRT subroutine────────────────────────*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); p=d+d%4+2; m.=11 + numeric digits m.;numeric form;parse value format(x,2,1,,0) 'E0' with g 'E' _ . + g=g*.5'E'_%2; 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 diff --git a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d index 3c40cddb56..afeef682f4 100644 --- a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d +++ b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-1.d @@ -2,7 +2,7 @@ import std.stdio, std.random, std.algorithm, std.traits, std.array; enum DutchColors { red, white, blue } -void dutchNationalFlagSort(DutchColors[] items) pure nothrow { +void dutchNationalFlagSort(DutchColors[] items) pure nothrow @nogc { int lo, mid, hi = items.length - 1; while (mid <= hi) @@ -22,10 +22,10 @@ void dutchNationalFlagSort(DutchColors[] items) pure nothrow { void main() { DutchColors[12] balls; foreach (ref ball; balls) - ball = [EnumMembers!DutchColors][uniform(0, $)]; + ball = uniform!DutchColors; writeln("Original Ball order:\n", balls); - balls.dutchNationalFlagSort(); + balls.dutchNationalFlagSort; writeln("\nSorted Ball Order:\n", balls); - assert(balls[].isSorted(), "Balls not sorted"); + assert(balls[].isSorted, "Balls not sorted."); } diff --git a/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-3.d b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-3.d new file mode 100644 index 0000000000..acdf3f2c25 --- /dev/null +++ b/Task/Dutch-national-flag-problem/D/dutch-national-flag-problem-3.d @@ -0,0 +1,93 @@ +import std.stdio, std.random, std.algorithm, std.traits, std.range; + +enum Color : ubyte { blue, white, red } + +immutable isMonochrome = (in Color[] a, in size_t i, in size_t j, in Color c) + pure nothrow @safe @nogc => iota(i, j).all!(k => a[k] == c); + +bool isPermutation(in Color[] a1, in Color[] a2) pure nothrow @safe @nogc { + size_t[EnumMembers!Color.length] counts1, counts2; + foreach (immutable x; a1) + counts1[x]++; + foreach (immutable x; a2) + counts2[x]++; + return counts1 == counts2; +} + + +void dutchNationalFlagSort(Color[] a) pure nothrow @safe @nogc + // This function is not @nogc in -debug builds. + /* + Scan of the array 'a' from left to right using 'i' and we + maintain this invariant, using indices 'b' and 'r': + + 0 b i r + +---------+----------+-----------+-------+ + | blue | white | ? | red | + +---------+----------+-----------+-------+ + */ +out { + // Find b and r. + immutable bRaw = a.countUntil!q{a != b}(Color.blue); + immutable size_t b = (bRaw == -1) ? a.length : bRaw; + immutable rRaw = a.retro.countUntil!q{a != b}(Color.red); + immutable size_t r = (rRaw == -1) ? 0 : (a.length - rRaw); + + assert(isMonochrome(a, 0, b, Color.blue)); + assert(isMonochrome(a, b, r, Color.white)); + assert(isMonochrome(a, r, a.length, Color.red)); + // debug assert(isPermutation(a, a.old)); +} body { + size_t b = 0, i = 0, r = a.length; + debug { + /*ghost*/ immutable aInit = a.idup; // For loop invariant. + /*ghost*/ size_t riPred = r - i; // For loop variant. + } + + while (i < r) { + /*invariant*/ assert(0 <= b && b <= i && i <= r && r <= a.length); + /*invariant*/ assert(isMonochrome(a, 0, b, Color.blue)); + /*invariant*/ assert(isMonochrome(a, b, i, Color.white)); + /*invariant*/ assert(isMonochrome(a, r, a.length, Color.red)); + /*invariant*/ debug assert(isPermutation(a, aInit)); + + final switch (a[i]) with (Color) { + case blue: + a[b].swap(a[i]); + b++; + i++; + break; + case white: + i++; + break; + case red: + r--; + a[r].swap(a[i]); + break; + } + + debug { + /*variant*/ assert((r - i) < riPred); + riPred = r - i; + } + } +} + +void main() { + Color[12] balls; + + // Test special cases. + foreach (immutable color; [EnumMembers!Color]) { + balls[] = color; + balls.dutchNationalFlagSort; + assert(balls[].isSorted, "Balls not sorted."); + } + + foreach (ref b; balls) + b = uniform!Color; + + writeln("Original Ball order:\n", balls); + balls.dutchNationalFlagSort; + writeln("\nSorted Ball Order:\n", balls); + assert(balls[].isSorted, "Balls not sorted."); +} diff --git a/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java new file mode 100644 index 0000000000..88b88fde61 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Java/dutch-national-flag-problem.java @@ -0,0 +1,46 @@ +import java.util.Arrays; +import java.util.Random; + +public class DutchNationalFlag { + enum DutchColors { + RED, WHITE, BLUE + } + + public static void main(String[] args) { + DutchColors[] balls = new DutchColors[12]; + + DutchColors[] values = DutchColors.values(); + Random rand = new Random(); + for (int i = 0; i < balls.length; i++) + balls[i] = values[rand.nextInt(values.length)]; + + System.out.println("Before: " + Arrays.toString(balls)); + + dutchNationalFlagSort(balls); + + System.out.println("After : " + Arrays.toString(balls)); + } + + private static void dutchNationalFlagSort(DutchColors[] items) { + int lo = 0, mid = 0, hi = items.length - 1; + + while (mid <= hi) + switch (items[mid]) { + case RED: + swap(items, lo++, mid++); + break; + case WHITE: + mid++; + break; + case BLUE: + swap(items, mid, hi--); + break; + } + } + + private static void swap(DutchColors[] arr, int a, int b) { + DutchColors tmp = arr[a]; + arr[a] = arr[b]; + arr[b] = tmp; + } +} diff --git a/Task/Dutch-national-flag-problem/Scala/dutch-national-flag-problem.scala b/Task/Dutch-national-flag-problem/Scala/dutch-national-flag-problem.scala new file mode 100644 index 0000000000..7ad0a41009 --- /dev/null +++ b/Task/Dutch-national-flag-problem/Scala/dutch-national-flag-problem.scala @@ -0,0 +1,11 @@ +object FlagColor extends Enumeration { + type FlagColor = Value + val Red, White, Blue = Value +} + +val genBalls = (1 to 10).map(i => FlagColor(scala.util.Random.nextInt(FlagColor.maxId))) +val sortedBalls = genBalls.sorted +val sorted = if (genBalls == sortedBalls) "sorted" else "not sorted" + +println(s"Generated balls (${genBalls mkString " "}) are $sorted.") +println(s"Sorted balls (${sortedBalls mkString " "}) are sorted.") diff --git a/Task/Dynamic-variable-names/Emacs-Lisp/dynamic-variable-names.l b/Task/Dynamic-variable-names/Emacs-Lisp/dynamic-variable-names.l new file mode 100644 index 0000000000..6275dbb6ab --- /dev/null +++ b/Task/Dynamic-variable-names/Emacs-Lisp/dynamic-variable-names.l @@ -0,0 +1 @@ +(set (intern (read-string "Enter variable name: ")) 123) diff --git a/Task/Dynamic-variable-names/Ruby/dynamic-variable-names.rb b/Task/Dynamic-variable-names/Ruby/dynamic-variable-names.rb index ed9005babd..7f0cb13e93 100644 --- a/Task/Dynamic-variable-names/Ruby/dynamic-variable-names.rb +++ b/Task/Dynamic-variable-names/Ruby/dynamic-variable-names.rb @@ -1,4 +1,4 @@ p "Enter a variable name" -x = gets.chomp! -instance_variable_set "@" + x, 42 -p "The value of #{x} is #{instance_variable_get "@" + x}" +x = "@" + gets.chomp! +instance_variable_set x, 42 +p "The value of #{x} is #{instance_variable_get x}" diff --git a/Task/Echo-server/Haskell/echo-server.hs b/Task/Echo-server/Haskell/echo-server-1.hs similarity index 100% rename from Task/Echo-server/Haskell/echo-server.hs rename to Task/Echo-server/Haskell/echo-server-1.hs diff --git a/Task/Echo-server/Haskell/echo-server-2.hs b/Task/Echo-server/Haskell/echo-server-2.hs new file mode 100644 index 0000000000..5c47216a77 --- /dev/null +++ b/Task/Echo-server/Haskell/echo-server-2.hs @@ -0,0 +1,18 @@ +global mlck, nCons + +procedure main() + mlck := mutex() + nCons := 0 + while f := open(":12321","na") do { + handle_client(f) + critical mlck: if nCons <= 0 then close(f) + } +end + +procedure handle_client(f) + critical mlck: nCons +:= 1 + thread { + select(f,1000) & repeat writes(f,reads(f)) + critical mlck: nCons -:= 1 + } +end diff --git a/Task/Echo-server/Java/echo-server.java b/Task/Echo-server/Java/echo-server.java index 12522c6f3d..a91b9fe617 100644 --- a/Task/Echo-server/Java/echo-server.java +++ b/Task/Echo-server/Java/echo-server.java @@ -56,7 +56,7 @@ class ClientHandler implements Runnable { String inputLine, outputLine; while((inputLine = in.readLine()) != null){ outputLine = inputLine; - System.out.println("recieved: " + outputLine); + System.out.println("received: " + outputLine); out.write(outputLine+"\n"); out.flush(); if (outputLine.equals("exit")) diff --git a/Task/Echo-server/REALbasic/echo-server.realbasic b/Task/Echo-server/REALbasic/echo-server.realbasic index 71d0dac9fe..27b3dc3079 100644 --- a/Task/Echo-server/REALbasic/echo-server.realbasic +++ b/Task/Echo-server/REALbasic/echo-server.realbasic @@ -29,5 +29,5 @@ Inherits ConsoleApplication DoEvents() 'pump the event loop Wend End Function - Private Listener As EchoListener + Private Listener As EchoServer End Class diff --git a/Task/Element-wise-operations/Haskell/element-wise-operations-1.hs b/Task/Element-wise-operations/Haskell/element-wise-operations-1.hs new file mode 100644 index 0000000000..94f8e0fa8b --- /dev/null +++ b/Task/Element-wise-operations/Haskell/element-wise-operations-1.hs @@ -0,0 +1,129 @@ +{-# OPTIONS_GHC -fno-warn-duplicate-constraints #-} +{-# LANGUAGE RankNTypes #-} + +import Data.Array (Array, Ix) +import Data.Array.Base + +-- | Element-wise combine the values of two arrays 'a' and 'b' with 'f'. +-- 'a' and 'b' must have the same bounds. +zipWithA :: (IArray arr a, IArray arr b, IArray arr c, Ix i) => + (a -> b -> c) -> arr i a -> arr i b -> arr i c +zipWithA f a b = + case bounds a of + ba -> + if ba /= bounds b + then error "elemwise: bounds mismatch" + else + let n = numElements a + in unsafeArray ba [ (i, f (unsafeAt a i) (unsafeAt b i)) + | i <- [0 .. n - 1]] + +-- Convenient aliases for matrix-matrix element-wise operations. +type ElemOp a b c = (IArray arr a, IArray arr b, IArray arr c, Ix i) => + arr i a -> arr i b -> arr i c +type ElemOp1 a = ElemOp a a a + +infixl 6 +:, -: +infixl 7 *:, /:, `divE` + +(+:), (-:), (*:) :: (Num a) => ElemOp1 a +(+:) = zipWithA (+) +(-:) = zipWithA (-) +(*:) = zipWithA (*) + +divE :: (Integral a) => ElemOp1 a +divE = zipWithA div + +(/:) :: (Fractional a) => ElemOp1 a +(/:) = zipWithA (/) + +infixr 8 ^:, **:, ^^: + +(^:) :: (Num a, Integral b) => ElemOp a b a +(^:) = zipWithA (^) + +(**:) :: (Floating a) => ElemOp1 a +(**:) = zipWithA (**) + +(^^:) :: (Fractional a, Integral b) => ElemOp a b a +(^^:) = zipWithA (^^) + +-- Convenient aliases for matrix-scalar element-wise operations. +type ScalarOp a b c = (IArray arr a, IArray arr c, Ix i) => + arr i a -> b -> arr i c +type ScalarOp1 a = ScalarOp a a a + +samap :: (IArray arr a, IArray arr c, Ix i) => + (a -> b -> c) -> arr i a -> b -> arr i c +samap f a s = amap (`f` s) a + +infixl 6 +., -. +infixl 7 *., /., `divS` + +(+.), (-.), (*.) :: (Num a) => ScalarOp1 a +(+.) = samap (+) +(-.) = samap (-) +(*.) = samap (*) + +divS :: (Integral a) => ScalarOp1 a +divS = samap div + +(/.) :: (Fractional a) => ScalarOp1 a +(/.) = samap (/) + +infixr 8 ^., **., ^^. + +(^.) :: (Num a, Integral b) => ScalarOp a b a +(^.) = samap (^) + +(**.) :: (Floating a) => ScalarOp1 a +(**.) = samap (**) + +(^^.) :: (Fractional a, Integral b) => ScalarOp a b a +(^^.) = samap (^^) + +main :: IO () +main = do + let m1, m2 :: (forall a. (Enum a, Num a) => Array (Int, Int) a) + m1 = listArray ((0, 0), (2, 3)) [1..] + m2 = listArray ((0, 0), (2, 3)) [10..] + s :: (forall a. Num a => a) + s = 99 + putStrLn "m1" + print m1 + putStrLn "m2" + print m2 + putStrLn "s" + print s + putStrLn "m1 + m2" + print $ m1 +: m2 + putStrLn "m1 - m2" + print $ m1 -: m2 + putStrLn "m1 * m2" + print $ m1 *: m2 + putStrLn "m1 `div` m2" + print $ m1 `divE` m2 + putStrLn "m1 / m2" + print $ m1 /: m2 + putStrLn "m1 ^ m2" + print $ m1 ^: m2 + putStrLn "m1 ** m2" + print $ m1 **: m2 + putStrLn "m1 ^^ m2" + print $ m1 ^^: m2 + putStrLn "m1 + s" + print $ m1 +. s + putStrLn "m1 - s" + print $ m1 -. s + putStrLn "m1 * s" + print $ m1 *. s + putStrLn "m1 `div` s" + print $ m1 `divS` s + putStrLn "m1 / s" + print $ m1 /. s + putStrLn "m1 ^ s" + print $ m1 ^. s + putStrLn "m1 ** s" + print $ m1 **. s + putStrLn "m1 ^^ s" + print $ m1 ^^. s diff --git a/Task/Element-wise-operations/Haskell/element-wise-operations-2.hs b/Task/Element-wise-operations/Haskell/element-wise-operations-2.hs new file mode 100644 index 0000000000..73b2811203 --- /dev/null +++ b/Task/Element-wise-operations/Haskell/element-wise-operations-2.hs @@ -0,0 +1,37 @@ +procedure main() + a := [[1,2,3],[4,5,6],[7,8,9]] + b := [[9,8,7],[6,5,4],[3,2,1]] + showMat(" a: ",a) + showMat(" b: ",b) + showMat("a+b: ",mmop("+",a,b)) + showMat("a-b: ",mmop("-",a,b)) + showMat("a*b: ",mmop("*",a,b)) + showMat("a/b: ",mmop("/",a,b)) + showMat("a^b: ",mmop("^",a,b)) + showMat("a+2: ",msop("+",a,2)) + showMat("a-2: ",msop("-",a,2)) + showMat("a*2: ",msop("*",a,2)) + showMat("a/2: ",msop("/",a,2)) + showMat("a^2: ",msop("^",a,2)) +end + +procedure mmop(op,A,B) + if (*A = *B) & (*A[1] = *B[1]) then { + C := [: |list(*A[1])\*A[1] :] + a1 := create !!A + b1 := create !!B + every (!!C) := op(@a1,@b1) + return C + } +end + +procedure msop(op,A,s) + C := [: |list(*A[1])\*A[1] :] + a1 := create !!A + every (!!C) := op(@a1,s) + return C +end + +procedure showMat(label, m) + every writes(label | right(!!m,5) | "\n") +end diff --git a/Task/Element-wise-operations/MATLAB/element-wise-operations.m b/Task/Element-wise-operations/MATLAB/element-wise-operations.m new file mode 100644 index 0000000000..7ed7aa83f7 --- /dev/null +++ b/Task/Element-wise-operations/MATLAB/element-wise-operations.m @@ -0,0 +1,4 @@ +a = rand; +b = rand(10,10); +scalar_matrix = a * b; +component_wise = b .* b; diff --git a/Task/Empty-directory/00DESCRIPTION b/Task/Empty-directory/00DESCRIPTION index 283749e811..f4751b37aa 100644 --- a/Task/Empty-directory/00DESCRIPTION +++ b/Task/Empty-directory/00DESCRIPTION @@ -1,3 +1,4 @@ Starting with a path to some directory, determine whether the directory is empty. -An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries. +An empty directory contains no files nor subdirectories. +With [[Unix]] or [[Windows]] systems, every directory contains an entry for “.” and almost every directory contains “..” (except for a root directory); an empty directory contains no other entries. diff --git a/Task/Empty-directory/C-sharp/empty-directory.cs b/Task/Empty-directory/C-sharp/empty-directory.cs new file mode 100644 index 0000000000..9a7063fbd8 --- /dev/null +++ b/Task/Empty-directory/C-sharp/empty-directory.cs @@ -0,0 +1,19 @@ +using System; +using System.IO; + +class Program +{ + static void Main( string[] args ) + { + foreach ( string dir in args ) + { + Console.WriteLine( "'{0}' {1} empty", dir, IsDirectoryEmpty( dir ) ? "is" : "is not" ); + } + } + + private static bool IsDirectoryEmpty( string dir ) + { + return ( Directory.GetFiles( dir ).Length == 0 && + Directory.GetDirectories( dir ).Length == 0 ); + } +} diff --git a/Task/Empty-directory/Ruby/empty-directory.rb b/Task/Empty-directory/Ruby/empty-directory.rb new file mode 100644 index 0000000000..c224faf05f --- /dev/null +++ b/Task/Empty-directory/Ruby/empty-directory.rb @@ -0,0 +1 @@ +Dir.entries("testdir").empty? diff --git a/Task/Empty-program/00META.yaml b/Task/Empty-program/00META.yaml index 659c8686af..3548159ac8 100644 --- a/Task/Empty-program/00META.yaml +++ b/Task/Empty-program/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Basic language learning diff --git a/Task/Empty-program/360-Assembly/empty-program.360 b/Task/Empty-program/360-Assembly/empty-program.360 new file mode 100644 index 0000000000..cdc8559139 --- /dev/null +++ b/Task/Empty-program/360-Assembly/empty-program.360 @@ -0,0 +1,2 @@ + BR 14 + END diff --git a/Task/Empty-program/ALGOL-60/empty-program.alg b/Task/Empty-program/ALGOL-60/empty-program.alg new file mode 100644 index 0000000000..6bfd008ca8 --- /dev/null +++ b/Task/Empty-program/ALGOL-60/empty-program.alg @@ -0,0 +1 @@ +'BEGIN' 'END' diff --git a/Task/Empty-program/AWK/empty-program.awk b/Task/Empty-program/AWK/empty-program-1.awk similarity index 100% rename from Task/Empty-program/AWK/empty-program.awk rename to Task/Empty-program/AWK/empty-program-1.awk diff --git a/Task/Empty-program/AWK/empty-program-2.awk b/Task/Empty-program/AWK/empty-program-2.awk new file mode 100644 index 0000000000..105010154c --- /dev/null +++ b/Task/Empty-program/AWK/empty-program-2.awk @@ -0,0 +1 @@ +// {print} diff --git a/Task/Empty-program/BASIC/empty-program-1.basic b/Task/Empty-program/BASIC/empty-program-1.basic index a90900f0a9..e69de29bb2 100644 --- a/Task/Empty-program/BASIC/empty-program-1.basic +++ b/Task/Empty-program/BASIC/empty-program-1.basic @@ -1 +0,0 @@ -10 END diff --git a/Task/Empty-program/OOC/empty-program.ooc b/Task/Empty-program/OOC/empty-program.ooc new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/Oz/empty-program-1.oz b/Task/Empty-program/Oz/empty-program-1.oz index e69de29bb2..47b23a20fc 100644 --- a/Task/Empty-program/Oz/empty-program-1.oz +++ b/Task/Empty-program/Oz/empty-program-1.oz @@ -0,0 +1 @@ +unit diff --git a/Task/Empty-program/Oz/empty-program-2.oz b/Task/Empty-program/Oz/empty-program-2.oz index 47b23a20fc..ea82901629 100644 --- a/Task/Empty-program/Oz/empty-program-2.oz +++ b/Task/Empty-program/Oz/empty-program-2.oz @@ -1 +1,4 @@ -unit +functor +define + skip +end diff --git a/Task/Empty-program/REXX/empty-program-1.rexx b/Task/Empty-program/REXX/empty-program-1.rexx index a23f9fdc47..e69de29bb2 100644 --- a/Task/Empty-program/REXX/empty-program-1.rexx +++ b/Task/Empty-program/REXX/empty-program-1.rexx @@ -1 +0,0 @@ -/*comment*/ diff --git a/Task/Empty-program/REXX/empty-program-2.rexx b/Task/Empty-program/REXX/empty-program-2.rexx index 9d6f459ad8..a23f9fdc47 100644 --- a/Task/Empty-program/REXX/empty-program-2.rexx +++ b/Task/Empty-program/REXX/empty-program-2.rexx @@ -1 +1 @@ -/**/ +/*comment*/ diff --git a/Task/Empty-program/REXX/empty-program-3.rexx b/Task/Empty-program/REXX/empty-program-3.rexx index 76138cf7f3..9d6f459ad8 100644 --- a/Task/Empty-program/REXX/empty-program-3.rexx +++ b/Task/Empty-program/REXX/empty-program-3.rexx @@ -1 +1 @@ -/*REXX*/ +/**/ diff --git a/Task/Empty-program/REXX/empty-program-4.rexx b/Task/Empty-program/REXX/empty-program-4.rexx index 7893e47dd7..76138cf7f3 100644 --- a/Task/Empty-program/REXX/empty-program-4.rexx +++ b/Task/Empty-program/REXX/empty-program-4.rexx @@ -1 +1 @@ -/*this REXX program calculates if a date is a workday for the XYZ Company.*/ +/*REXX*/ diff --git a/Task/Empty-program/REXX/empty-program-5.rexx b/Task/Empty-program/REXX/empty-program-5.rexx new file mode 100644 index 0000000000..7893e47dd7 --- /dev/null +++ b/Task/Empty-program/REXX/empty-program-5.rexx @@ -0,0 +1 @@ +/*this REXX program calculates if a date is a workday for the XYZ Company.*/ diff --git a/Task/Empty-program/Scilab/empty-program.scilab b/Task/Empty-program/Scilab/empty-program.scilab new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Empty-program/Simula/empty-program.simula b/Task/Empty-program/Simula/empty-program.simula new file mode 100644 index 0000000000..26f0d47567 --- /dev/null +++ b/Task/Empty-program/Simula/empty-program.simula @@ -0,0 +1,2 @@ +BEGIN +END diff --git a/Task/Empty-program/Visual-Basic/empty-program.vb b/Task/Empty-program/Visual-Basic/empty-program.vb new file mode 100644 index 0000000000..70e1b53946 --- /dev/null +++ b/Task/Empty-program/Visual-Basic/empty-program.vb @@ -0,0 +1,2 @@ +Sub Main() +End Sub diff --git a/Task/Empty-string/00DESCRIPTION b/Task/Empty-string/00DESCRIPTION index 633767e476..d373144b4d 100644 --- a/Task/Empty-string/00DESCRIPTION +++ b/Task/Empty-string/00DESCRIPTION @@ -1,4 +1,5 @@ -Languages may have features for dealing specifically with empty strings (those containing no characters). +Languages may have features for dealing specifically with empty strings +(those containing no characters). The task is to: @@ -7,4 +8,4 @@ The task is to: * Demonstrate how to check that a string is empty. * Demonstrate how to check that a string is not empty. -[[Category:String manipulation]] +[[Category:String manipulation]] [[Category:Simple]] diff --git a/Task/Empty-string/Elixir/empty-string.elixir b/Task/Empty-string/Elixir/empty-string.elixir new file mode 100644 index 0000000000..3df71cabf7 --- /dev/null +++ b/Task/Empty-string/Elixir/empty-string.elixir @@ -0,0 +1,12 @@ +empty_string = "" +not_empty_string = "a" + +empty_string == "" +# => true +String.length(empty_string) == 0 +# => true + +not_empty_string == "" +# => false +String.length(not_empty_string) == 0 +# => false diff --git a/Task/Empty-string/Go/empty-string.go b/Task/Empty-string/Go/empty-string.go index 0f9f6f7541..da66e0ae6e 100644 --- a/Task/Empty-string/Go/empty-string.go +++ b/Task/Empty-string/Go/empty-string.go @@ -1,8 +1,14 @@ -// assign empty string to a variable +// define and initialize an empty string +var s string +s2 := "" + +// assign an empty string to a variable s = "" -// check that string is empty +// check that a string is empty, any of: s == "" +len(s) == 0 -// check that string is not empty -s > "" +// check that a string is not empty, any of: +s != "" +len(s) != 0 // or > 0 diff --git a/Task/Empty-string/JavaScript/empty-string-1.js b/Task/Empty-string/JavaScript/empty-string-1.js new file mode 100644 index 0000000000..c426f81c91 --- /dev/null +++ b/Task/Empty-string/JavaScript/empty-string-1.js @@ -0,0 +1,2 @@ +var s = ""; +var s = new String(); diff --git a/Task/Empty-string/JavaScript/empty-string-2.js b/Task/Empty-string/JavaScript/empty-string-2.js new file mode 100644 index 0000000000..6f3bb9b6b6 --- /dev/null +++ b/Task/Empty-string/JavaScript/empty-string-2.js @@ -0,0 +1,4 @@ +s == "" +s.length == 0 +!s +!Boolean(s) diff --git a/Task/Empty-string/JavaScript/empty-string-3.js b/Task/Empty-string/JavaScript/empty-string-3.js new file mode 100644 index 0000000000..8f5743c550 --- /dev/null +++ b/Task/Empty-string/JavaScript/empty-string-3.js @@ -0,0 +1,4 @@ +s != "" +s.length != 0 +s.length > 0 +Boolean(s) diff --git a/Task/Empty-string/Maple/empty-string.maple b/Task/Empty-string/Maple/empty-string.maple new file mode 100644 index 0000000000..a3ddcf9a34 --- /dev/null +++ b/Task/Empty-string/Maple/empty-string.maple @@ -0,0 +1,3 @@ +s := ""; # Create an empty string +evalb(s = ""); # test if the string is empty +evalb(s <> ""); # test if the string is not empty diff --git a/Task/Empty-string/Prolog/empty-string.pro b/Task/Empty-string/Prolog/empty-string.pro new file mode 100644 index 0000000000..26e04e70e7 --- /dev/null +++ b/Task/Empty-string/Prolog/empty-string.pro @@ -0,0 +1,4 @@ +assign_empty_string(Variable) :- Variable = "". + +is_empty_string(String) :- String == "". +not_empty_string(String) :- String \== "". diff --git a/Task/Empty-string/Smalltalk/empty-string.st b/Task/Empty-string/Smalltalk/empty-string.st new file mode 100644 index 0000000000..d0b9a849ed --- /dev/null +++ b/Task/Empty-string/Smalltalk/empty-string.st @@ -0,0 +1,8 @@ +"Assign empty string to a variable" +str := ''. + +"Check that string is empty" +str isEmpty. + +"Check that string is not empty" +str isEmpty not. diff --git a/Task/Empty-string/Standard-ML/empty-string.ml b/Task/Empty-string/Standard-ML/empty-string.ml new file mode 100644 index 0000000000..5616482a93 --- /dev/null +++ b/Task/Empty-string/Standard-ML/empty-string.ml @@ -0,0 +1,6 @@ +(* Assign empty string to a variable *) +val s = "" +(* Check that a string is empty*) +s = "" +(* Check that a string is nonempty *) +s <> "" diff --git a/Task/Enforced-immutability/00DESCRIPTION b/Task/Enforced-immutability/00DESCRIPTION index b326ba0841..aa909bdb14 100644 --- a/Task/Enforced-immutability/00DESCRIPTION +++ b/Task/Enforced-immutability/00DESCRIPTION @@ -1,2 +1 @@ Demonstrate any means your language has to prevent the modification of values, or to create objects that cannot be modified after they have been created. -{{omit from|MUMPS}} diff --git a/Task/Enforced-immutability/00META.yaml b/Task/Enforced-immutability/00META.yaml new file mode 100644 index 0000000000..0bb2150890 --- /dev/null +++ b/Task/Enforced-immutability/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Initialization +note: Enforced immutability diff --git a/Task/Enforced-immutability/Fortran/enforced-immutability-1.f b/Task/Enforced-immutability/Fortran/enforced-immutability-1.f new file mode 100644 index 0000000000..264cbfc9d6 --- /dev/null +++ b/Task/Enforced-immutability/Fortran/enforced-immutability-1.f @@ -0,0 +1 @@ +real, parameter :: pi = 3.141593 diff --git a/Task/Enforced-immutability/Fortran/enforced-immutability-2.f b/Task/Enforced-immutability/Fortran/enforced-immutability-2.f new file mode 100644 index 0000000000..461effebee --- /dev/null +++ b/Task/Enforced-immutability/Fortran/enforced-immutability-2.f @@ -0,0 +1,2 @@ +subroutine sub1(n) + real, intent(in) :: n diff --git a/Task/Enforced-immutability/PL-I/enforced-immutability.pli b/Task/Enforced-immutability/PL-I/enforced-immutability.pli new file mode 100644 index 0000000000..90d9341c22 --- /dev/null +++ b/Task/Enforced-immutability/PL-I/enforced-immutability.pli @@ -0,0 +1,6 @@ +*process source attributes xref; + constants: Proc Options(main); + Dcl three Bin Fixed(15) Value(3); + Put Skip List(1/three); + Put Skip List(1/3); + End; diff --git a/Task/Enforced-immutability/Perl-6/enforced-immutability-3.pl6 b/Task/Enforced-immutability/Perl-6/enforced-immutability-3.pl6 index 901bff99f0..6c00a1e465 100644 --- a/Task/Enforced-immutability/Perl-6/enforced-immutability-3.pl6 +++ b/Task/Enforced-immutability/Perl-6/enforced-immutability-3.pl6 @@ -1,2 +1 @@ -my $pi is readonly = 3 + rand; -my $pi ::= 3 + rand; # same thing, SSA-ish form +my $pi ::= 3 + rand; diff --git a/Task/Enforced-immutability/Ruby/enforced-immutability.rb b/Task/Enforced-immutability/Ruby/enforced-immutability-1.rb similarity index 85% rename from Task/Enforced-immutability/Ruby/enforced-immutability.rb rename to Task/Enforced-immutability/Ruby/enforced-immutability-1.rb index 011f80f05c..f3722ad7f0 100644 --- a/Task/Enforced-immutability/Ruby/enforced-immutability.rb +++ b/Task/Enforced-immutability/Ruby/enforced-immutability-1.rb @@ -1,4 +1,4 @@ -puts msg = "Hello World" +msg = "Hello World" msg << "!" puts msg #=> Hello World! @@ -12,10 +12,9 @@ rescue => e end puts msg #=> Hello World! - msg2 = msg -# An object is frozen and it is not a variable. +# The object is frozen, not the variable. msg = "hello world" # A new object was assigned to the variable. puts msg.frozen? #=> false diff --git a/Task/Enforced-immutability/Ruby/enforced-immutability-2.rb b/Task/Enforced-immutability/Ruby/enforced-immutability-2.rb new file mode 100644 index 0000000000..99aa7a9042 --- /dev/null +++ b/Task/Enforced-immutability/Ruby/enforced-immutability-2.rb @@ -0,0 +1,8 @@ +# There are two methods in the copy of the object. +msg = "Hello World!".freeze +msg2 = msg.clone # Copies the frozen and tainted state of obj. +msg3 = msg.dup # It doesn't copy the status (frozen, tainted) of obj. +puts msg2 #=> Hello World! +puts msg3 #=> Hello World! +puts msg2.frozen? #=> true +puts msg3.frozen? #=> false diff --git a/Task/Entropy/00DESCRIPTION b/Task/Entropy/00DESCRIPTION index 70ec8e6324..d1a71afbc6 100644 --- a/Task/Entropy/00DESCRIPTION +++ b/Task/Entropy/00DESCRIPTION @@ -1,9 +1,13 @@ Calculate the [[wp:Entropy (information theory)|information entropy]] (Shannon entropy) of a given input string. -Entropy is the [[wp:Expected value|expected value]] of the measure of [[wp:Self-information|information]] content in a system. In general, the Shannon entropy of a variable X is defined as: +Entropy is the [[wp:Expected value|expected value]] of the measure of [[wp:Self-information|information]] content in a system. +In general, the Shannon entropy of a variable X is defined as: :H(X) = \sum_{x\in\Omega} P(x) I(x) -where the information content I(x) = -\log_{b} P(x). If the base of the logarithm b = 2, the result is expressed in ''bits'', a [[wp:Units of information|unit of information]]. Therefore, given a string S of length n where P(s_i) is the relative frequency of each character, the entropy of a string in bits is: +where the information content I(x) = -\log_{b} P(x). +If the base of the logarithm b = 2, the result is expressed in ''bits'', a [[wp:Units of information|unit of information]]. +Therefore, given a string S of length n where P(s_i) is the relative frequency of each character, the entropy of a string in bits is: :H(S) = -\sum_{i=0}^n P(s_i) \log_2 (P(s_i)) -For this task, use "1223334444" as an example. The result should be around 1.84644 bits. +For this task, use "1223334444" as an example. +The result should be around 1.84644 bits. Related Task: [[Fibonacci_word]] diff --git a/Task/Entropy/ALGOL-68/entropy.alg b/Task/Entropy/ALGOL-68/entropy.alg new file mode 100644 index 0000000000..15cacf08d4 --- /dev/null +++ b/Task/Entropy/ALGOL-68/entropy.alg @@ -0,0 +1,43 @@ +# calculate the shannon entropy of a string # + +PROC shannon entropy = ( STRING s )REAL: + BEGIN + + INT string length = ( UPB s - LWB s ) + 1; + + # count the occurances of each character # + + [ 0 : max abs char ]INT char count; + + FOR char pos FROM LWB char count TO UPB char count DO + char count[ char pos ] := 0 + OD; + + FOR char pos FROM LWB s TO UPB s DO + char count[ ABS s[ char pos ] ] +:= 1 + OD; + + # calculate the entropy, we use log base 10 and then convert # + # to log base 2 after calculating the sum # + + REAL entropy := 0; + + FOR char pos FROM LWB char count TO UPB char count DO + IF char count[ char pos ] /= 0 + THEN + # have a character that occurs in the string # + REAL probability = char count[ char pos ] / string length; + entropy -:= probability * log( probability ) + FI + OD; + + entropy / log( 2 ) + END; # shannon entropy # + + + +main: +( + # test the shannon entropy routine # + print( ( shannon entropy( "1223334444" ), newline ) ) +) diff --git a/Task/Entropy/C-sharp/entropy-1.cs b/Task/Entropy/C-sharp/entropy-1.cs new file mode 100644 index 0000000000..fc5f931056 --- /dev/null +++ b/Task/Entropy/C-sharp/entropy-1.cs @@ -0,0 +1,39 @@ +using System; +using System.Collections.Generic; +namespace Entropy +{ + class Program + { + public static double logtwo(double num) + { + return Math.Log(num)/Math.Log(2); + } + public static void Main(string[] args) + { + label1: + string input = Console.ReadLine(); + double infoC=0; + Dictionary table = new Dictionary(); + + + foreach (char c in input) + { + if (table.ContainsKey(c)) + table[c]++; + else + table.Add(c,1); + + } + double freq; + foreach (KeyValuePair letter in table) + { + freq=letter.Value/input.Length; + infoC+=freq*logtwo(freq); + } + infoC*=-1; + Console.WriteLine("The Entropy of {0} is {1}",input,infoC); + goto label1; + + } + } +} diff --git a/Task/Entropy/C-sharp/entropy-2.cs b/Task/Entropy/C-sharp/entropy-2.cs new file mode 100644 index 0000000000..9513d309ef --- /dev/null +++ b/Task/Entropy/C-sharp/entropy-2.cs @@ -0,0 +1,43 @@ +using System; +namespace Entropy +{ + class Program + { + public static double logtwo(double num) + { + return Math.Log(num)/Math.Log(2); + } + static double Contain(string x,char k) + { + double count=0; + foreach (char Y in x) + { + if(Y.Equals(k)) + count++; + } + return count; + } + public static void Main(string[] args) + { + label1: + string input = Console.ReadLine(); + double infoC=0; + double freq; + string k=""; + foreach (char c1 in input) + { + if (!(k.Contains(c1.ToString()))) + k+=c1; + } + foreach (char c in k) + { + freq=Contain(input,c)/(double)input.Length; + infoC+=freq*logtwo(freq); + } + infoC/=-1; + Console.WriteLine("The Entropy of {0} is {1}",input,infoC); + goto label1; + + } + } +} diff --git a/Task/Entropy/Clojure/entropy-1.clj b/Task/Entropy/Clojure/entropy-1.clj index 5b9b3e21e7..c179fcb6c4 100644 --- a/Task/Entropy/Clojure/entropy-1.clj +++ b/Task/Entropy/Clojure/entropy-1.clj @@ -1,9 +1,7 @@ (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))))) + (let [len (count s), log-2 (Math/log 2)] + (->> (frequencies s) + (map (fn [[_ v]] + (let [rf (/ v len)] + (-> (Math/log rf) (/ log-2) (* rf) Math/abs)))) (reduce +)))) diff --git a/Task/Entropy/Clojure/entropy-2.clj b/Task/Entropy/Clojure/entropy-2.clj index 833889f537..f930c7250b 100644 --- a/Task/Entropy/Clojure/entropy-2.clj +++ b/Task/Entropy/Clojure/entropy-2.clj @@ -1,2 +1,2 @@ -(H "1223334444") +(entropy "1223334444") 1.8464393446710154 diff --git a/Task/Entropy/D/entropy.d b/Task/Entropy/D/entropy.d index 1caad78b15..b7959640fb 100644 --- a/Task/Entropy/D/entropy.d +++ b/Task/Entropy/D/entropy.d @@ -1,11 +1,12 @@ import std.stdio, std.algorithm, std.math; double entropy(T)(T[] s) -/*pure nothrow*/ if (__traits(compiles, s.sort())) { +pure nothrow if (__traits(compiles, s.sort())) { + immutable sLen = s.length; return s .sort() .group - .map!(g => g[1] / double(s.length)) + .map!(g => g[1] / double(sLen)) .map!(p => -p * p.log2) .sum; } diff --git a/Task/Entropy/Haskell/entropy.hs b/Task/Entropy/Haskell/entropy.hs index dd24f6b75e..e022cfbf10 100644 --- a/Task/Entropy/Haskell/entropy.hs +++ b/Task/Entropy/Haskell/entropy.hs @@ -5,4 +5,4 @@ main = print $ entropy "1223334444" entropy s = sum . map lg' . fq' . map (fromIntegral.length) . group . sort $ s where lg' c = (c * ) . logBase 2 $ 1.0 / c - fq' c = map (\x -> x / (sum c)) c + fq' c = let sc = sum c in map (/ sc) c diff --git a/Task/Entropy/JavaScript/entropy.js b/Task/Entropy/JavaScript/entropy.js new file mode 100644 index 0000000000..cea8cb0019 --- /dev/null +++ b/Task/Entropy/JavaScript/entropy.js @@ -0,0 +1,31 @@ +(function(shannon) { + // Create a dictionary of character frequencies and iterate over it. + function process(s, evaluator) { + var h = Object.create(null), k; + s.split('').forEach(function(c) { + h[c] && h[c]++ || (h[c] = 1); }); + if (evaluator) for (k in h) evaluator(k, h[k]); + return h; + }; + // Measure the entropy of a string in bits per symbol. + shannon.entropy = function(s) { + var sum = 0,len = s.length; + process(s, function(k, f) { + var p = f/len; + sum -= p * Math.log(p) / Math.log(2); + }); + return sum; + }; +})(window.shannon = window.shannon || {}); + +// Log the Shannon entropy of a string. +function logEntropy(s) { + console.log('Entropy of "' + s + '" in bits per symbol:', shannon.entropy(s)); +} + +logEntropy('1223334444'); +logEntropy('0'); +logEntropy('01'); +logEntropy('0123'); +logEntropy('01234567'); +logEntropy('0123456789abcdef'); diff --git a/Task/Entropy/Julia/entropy.julia b/Task/Entropy/Julia/entropy.julia new file mode 100644 index 0000000000..24fbd05391 --- /dev/null +++ b/Task/Entropy/Julia/entropy.julia @@ -0,0 +1 @@ +entropy(s)=-sum(x->x*log(2,x), [count(x->x==c,s)/length(s) for c in unique(s)]) diff --git a/Task/Entropy/OCaml/entropy.ocaml b/Task/Entropy/OCaml/entropy.ocaml new file mode 100644 index 0000000000..121197f209 --- /dev/null +++ b/Task/Entropy/OCaml/entropy.ocaml @@ -0,0 +1,30 @@ +(* generic OCaml, using a mutable Hashtbl *) + +(* pre-bake & return an inner-loop function to bin & assemble a character frequency map *) +let get_fproc (m: (char, int) Hashtbl.t) :(char -> unit) = + (fun (c:char) -> try + Hashtbl.replace m c ( (Hashtbl.find m c) + 1) + with Not_found -> Hashtbl.add m c 1) + + +(* pre-bake and return an inner-loop function to do the actual entropy calculation *) +let get_calc (slen:int) :(float -> float) = + let slen_float = float_of_int slen in + let log_2 = log 2.0 in + + (fun v -> let pt = v /. slen_float in + pt *. ((log pt) /. log_2) ) + + +(* main function, given a string argument it: + builds a (mutable) frequency map (initial alphabet size of 255, but it's auto-expanding), + extracts the relative probability values into a list, + folds-in the basic entropy calculation and returns the result. *) +let shannon (s:string) :float = + let freq_hash = Hashtbl.create 255 in + String.iter (get_fproc freq_hash) s; + + let relative_probs = Hashtbl.fold (fun k v b -> (float v)::b) freq_hash [] in + let calc = get_calc (String.length s) in + + -1.0 *. List.fold_left (fun b x -> b +. calc x) 0.0 relative_probs diff --git a/Task/Entropy/PL-I/entropy.pli b/Task/Entropy/PL-I/entropy.pli new file mode 100644 index 0000000000..2905c3b46d --- /dev/null +++ b/Task/Entropy/PL-I/entropy.pli @@ -0,0 +1,34 @@ +*process source xref attributes or(!); + /*-------------------------------------------------------------------- + * 08.08.2014 Walter Pachl translated from REXX version 1 + *-------------------------------------------------------------------*/ + ent: Proc Options(main); + Dcl (index,length,log2,substr) Builtin; + Dcl sysprint Print; + Dcl occ(100) Bin fixed(31) Init((100)0); + Dcl (n,cn,ci,i,pos) Bin fixed(31) Init(0); + Dcl chars Char(100) Var Init(''); + Dcl s Char(100) Var Init('1223334444'); + Dcl c Char(1); + Dcl (occf,p(100)) Dec Float(18); + Dcl e Dec Float(18) Init(0); + Do i=1 To length(s); + c=substr(s,i,1); + pos=index(chars,c); + If pos=0 Then Do; + pos=length(chars)+1; + cn+=1; + chars=chars!!c; + End; + occ(pos)+=1; + n+=1; + End; + do ci=1 To cn; + occf=occ(ci); + p(ci)=occf/n; + End; + Do ci=1 To cn; + e=e+p(ci)*log2(p(ci)); + End; + Put Edit('s='''!!s!!''' Entropy=',-e)(Skip,a,f(15,12)); + End; diff --git a/Task/Entropy/Pascal/entropy.pascal b/Task/Entropy/Pascal/entropy.pascal new file mode 100644 index 0000000000..ffc4f25624 --- /dev/null +++ b/Task/Entropy/Pascal/entropy.pascal @@ -0,0 +1,50 @@ +PROGRAM entropytest; + +USES StrUtils, Math; + +TYPE FArray = ARRAY of CARDINAL; + +VAR strng: STRING = '1223334444'; + +// list unique characters in a string +FUNCTION uniquechars(str: STRING): STRING; + VAR n: CARDINAL; + BEGIN + uniquechars := ''; + FOR n := 1 TO length(str) DO + IF (PosEx(str[n],str,n)>0) + AND (PosEx(str[n],uniquechars,1)=0) + THEN uniquechars += str[n]; + END; + +// obtain a list of character-frequencies for a string +// given a string containing its unique characters +FUNCTION frequencies(str,ustr: STRING): FArray; + VAR u,s,p,o: CARDINAL; + BEGIN + SetLength(frequencies, Length(ustr)+1); + p := 0; + FOR u := 1 TO length(ustr) DO + FOR s := 1 TO length(str) DO BEGIN + o := p; p := PosEx(ustr[u],str,s); + IF (p>o) THEN INC(frequencies[u]); + END; + END; + +// Obtain the Shannon entropy of a string +FUNCTION entropy(s: STRING): EXTENDED; + VAR pf : FArray; + us : STRING; + i,l: CARDINAL; + BEGIN + us := uniquechars(s); + pf := frequencies(s,us); + l := length(s); + entropy := 0.0; + FOR i := 1 TO length(us) DO + entropy -= pf[i]/l * log2(pf[i]/l); + END; + +BEGIN + Writeln('Entropy of "',strng,'" is ',entropy(strng):2:5, ' bits.'); +END. diff --git a/Task/Enumerations/C++/enumerations.cpp b/Task/Enumerations/C++/enumerations-1.cpp similarity index 100% rename from Task/Enumerations/C++/enumerations.cpp rename to Task/Enumerations/C++/enumerations-1.cpp diff --git a/Task/Enumerations/C++/enumerations-2.cpp b/Task/Enumerations/C++/enumerations-2.cpp new file mode 100644 index 0000000000..9d17e2e308 --- /dev/null +++ b/Task/Enumerations/C++/enumerations-2.cpp @@ -0,0 +1,3 @@ +enum class fruits { apple, banana, cherry }; + +enum class fruits { apple = 0, banana = 1, cherry = 2 }; diff --git a/Task/Enumerations/C++/enumerations-3.cpp b/Task/Enumerations/C++/enumerations-3.cpp new file mode 100644 index 0000000000..fed127a04c --- /dev/null +++ b/Task/Enumerations/C++/enumerations-3.cpp @@ -0,0 +1 @@ +enum class fruits : unsigned int { apple, banana, cherry }; diff --git a/Task/Enumerations/C++/enumerations-4.cpp b/Task/Enumerations/C++/enumerations-4.cpp new file mode 100644 index 0000000000..643b5e3682 --- /dev/null +++ b/Task/Enumerations/C++/enumerations-4.cpp @@ -0,0 +1 @@ +enum fruits : unsigned int { apple, banana, cherry }; diff --git a/Task/Enumerations/C/enumerations.c b/Task/Enumerations/C/enumerations-1.c similarity index 100% rename from Task/Enumerations/C/enumerations.c rename to Task/Enumerations/C/enumerations-1.c diff --git a/Task/Enumerations/C/enumerations-2.c b/Task/Enumerations/C/enumerations-2.c new file mode 100644 index 0000000000..4a65d4e9be --- /dev/null +++ b/Task/Enumerations/C/enumerations-2.c @@ -0,0 +1,3 @@ +typedef enum { apple, banana, cherry } fruits; + +typedef enum { apple = 0, banana = 1, cherry = 2 } fruits; diff --git a/Task/Enumerations/D/enumerations.d b/Task/Enumerations/D/enumerations.d index 6b9d4e9bfb..10e8197042 100644 --- a/Task/Enumerations/D/enumerations.d +++ b/Task/Enumerations/D/enumerations.d @@ -1,17 +1,50 @@ -// Named (commonly used enum in D) (int). -enum Fruits1 { apple, banana, cherry } - -// Anonymous, as in C. -enum { APPLE, BANANA, CHERRY } - -// Named with specified values (int). -enum Fruits2 { apple = 0, banana = 10, cherry = 20 } - -// Named, typed and with specified values. -enum Fruits3 : ubyte { apple = 0, banana = 100, cherry = 200 } - void main() { + // Named enumeration (commonly used enum in D). + // The underlying type is a 32 bit int. + enum Fruits1 { apple, banana, cherry } + + // You can assign an enum to the general type, but not the opposite: + int f1 = Fruits1.banana; // No error. + // Fruits1 f2 = 1; // Error: cannot implicitly convert. + + // Anonymous enumeration, as in C, of type 32 bit int. + enum { APPLE, BANANA, CHERRY } static assert(CHERRY == 2); - int f1 = Fruits2.banana; // No error. - // Fruits2 f2 = 1; // Error: cannot implicitly convert. + + // Named enumeration with specified values (int). + enum Fruits2 { apple = 0, banana = 10, cherry = 20 } + + // Named enumeration, typed and with specified values. + enum Fruits3 : ubyte { apple = 0, banana = 100, cherry = 200 } + + // Named enumeration, typed and with partially specified values. + enum Test : ubyte { A = 2, B, C = 3 } + static assert(Test.B == 3); // Uses the next ubyte, duplicated value. + + // This raises a compile-time error for overflow. + // enum Fruits5 : ubyte { apple = 254, banana = 255, cherry } + + enum Component { + none, + red = 2 ^^ 0, + green = 2 ^^ 1, + blue = 2 ^^ 2 + } + + // Phobos BitFlags support all the most common operations on flags. + // Some of the operations are shown below. + import std.typecons: BitFlags; + + alias ComponentFlags = BitFlags!Component; + immutable ComponentFlags flagsEmpty; + + // Value can be set with the | operator. + immutable flagsRed = flagsEmpty | Component.red; + + immutable flagsGreen = ComponentFlags(Component.green); + immutable flagsRedGreen = ComponentFlags(Component.red, Component.green); + immutable flagsBlueGreen = ComponentFlags(Component.blue, Component.green); + + // Use the & operator between BitFlags for intersection. + assert (flagsGreen == (flagsRedGreen & flagsBlueGreen)); } diff --git a/Task/Enumerations/Go/enumerations-1.go b/Task/Enumerations/Go/enumerations-1.go index 56f02cc2ed..faadb22af4 100644 --- a/Task/Enumerations/Go/enumerations-1.go +++ b/Task/Enumerations/Go/enumerations-1.go @@ -1,5 +1,5 @@ const ( - apple = iota - banana - cherry + apple = iota + banana + cherry ) diff --git a/Task/Enumerations/Go/enumerations-2.go b/Task/Enumerations/Go/enumerations-2.go index 774d58cda0..e42f8e3c09 100644 --- a/Task/Enumerations/Go/enumerations-2.go +++ b/Task/Enumerations/Go/enumerations-2.go @@ -1,5 +1,5 @@ const ( - apple = 0 - banana = 1 - cherry = 2 + apple = 0 + banana = 1 + cherry = 2 ) diff --git a/Task/Enumerations/Go/enumerations-3.go b/Task/Enumerations/Go/enumerations-3.go new file mode 100644 index 0000000000..1aec411dd6 --- /dev/null +++ b/Task/Enumerations/Go/enumerations-3.go @@ -0,0 +1,7 @@ +type fruit int + +const ( + apple fruit = iota + banana + cherry +) diff --git a/Task/Enumerations/Go/enumerations-4.go b/Task/Enumerations/Go/enumerations-4.go new file mode 100644 index 0000000000..d2cc67c465 --- /dev/null +++ b/Task/Enumerations/Go/enumerations-4.go @@ -0,0 +1,7 @@ +type fruit int + +const ( + apple fruit = 0 + banana fruit = 1 + cherry fruit = 2 +) diff --git a/Task/Enumerations/Objective-C/enumerations.m b/Task/Enumerations/Objective-C/enumerations.m new file mode 100644 index 0000000000..a0e232301b --- /dev/null +++ b/Task/Enumerations/Objective-C/enumerations.m @@ -0,0 +1,3 @@ +typedef NS_ENUM(NSInteger, fruits) { apple, banana, cherry }; + +typedef NS_ENUM(NSInteger, fruits) { apple = 0, banana = 1, cherry = 2 }; diff --git a/Task/Enumerations/Python/enumerations-1.py b/Task/Enumerations/Python/enumerations-1.py index 5b33ed298e..e6f766b516 100644 --- a/Task/Enumerations/Python/enumerations-1.py +++ b/Task/Enumerations/Python/enumerations-1.py @@ -1 +1,15 @@ -FIRST_NAME, LAST_NAME, PHONE = range(3) +>>> from enum import Enum +>>> Contact = Enum('Contact', 'FIRST_NAME, LAST_NAME, PHONE') +>>> Contact.__members__ +mappingproxy(OrderedDict([('FIRST_NAME', ), ('LAST_NAME', ), ('PHONE', )])) +>>> +>>> # Explicit +>>> class Contact2(Enum): + FIRST_NAME = 1 + LAST_NAME = 2 + PHONE = 3 + + +>>> Contact2.__members__ +mappingproxy(OrderedDict([('FIRST_NAME', ), ('LAST_NAME', ), ('PHONE', )])) +>>> diff --git a/Task/Enumerations/Python/enumerations-2.py b/Task/Enumerations/Python/enumerations-2.py index d24c6cc086..5b33ed298e 100644 --- a/Task/Enumerations/Python/enumerations-2.py +++ b/Task/Enumerations/Python/enumerations-2.py @@ -1 +1 @@ -vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE"))) +FIRST_NAME, LAST_NAME, PHONE = range(3) diff --git a/Task/Enumerations/Python/enumerations-3.py b/Task/Enumerations/Python/enumerations-3.py new file mode 100644 index 0000000000..d24c6cc086 --- /dev/null +++ b/Task/Enumerations/Python/enumerations-3.py @@ -0,0 +1 @@ +vars().update((key,val) for val,key in enumerate(("FIRST_NAME","LAST_NAME","PHONE"))) diff --git a/Task/Enumerations/Ruby/enumerations-1.rb b/Task/Enumerations/Ruby/enumerations-1.rb new file mode 100644 index 0000000000..159cfd1e88 --- /dev/null +++ b/Task/Enumerations/Ruby/enumerations-1.rb @@ -0,0 +1,11 @@ +module Fruits + APPLE = 0 + BANANA = 1 + CHERRY = 2 +end + +# It is possible to use a symbol if the value is unrelated. + +FRUITS = [:apple, :banana, :cherry] +val = :banana +FRUITS.include?(val) #=> true diff --git a/Task/Enumerations/Ruby/enumerations-2.rb b/Task/Enumerations/Ruby/enumerations-2.rb new file mode 100644 index 0000000000..20efd0407e --- /dev/null +++ b/Task/Enumerations/Ruby/enumerations-2.rb @@ -0,0 +1,12 @@ +module Card + # constants + SUITS = %i(Clubs Hearts Spades Diamonds) + SUIT_VALUE = SUITS.each_with_index.to_h # version 2.1+ +# SUIT_VALUE = Hash[ SUITS.each_with_index.to_a ] # before it + #=> {:Clubs=>0, :Hearts=>1, :Spades=>2, :Diamonds=>3} + + PIPS = %i(2 3 4 5 6 7 8 9 10 Jack Queen King Ace) + PIP_VALUE = PIPS.each.with_index(2).to_h # version 2.1+ +# PIP_VALUE = Hash[ PIPS.each.with_index(2).to_a ] # before it + #=> {:"2"=>2, :"3"=>3, :"4"=>4, :"5"=>5, :"6"=>6, :"7"=>7, :"8"=>8, :"9"=>9, :"10"=>10, :Jack=>11, :Queen=>12, :King=>13, :Ace=>14} +end diff --git a/Task/Enumerations/Ruby/enumerations.rb b/Task/Enumerations/Ruby/enumerations.rb deleted file mode 100644 index f47963cfd0..0000000000 --- a/Task/Enumerations/Ruby/enumerations.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Fruits -APPLE = 0 -BANANA = 1 -CHERRY = 2 -end diff --git a/Task/Environment-variables/00DESCRIPTION b/Task/Environment-variables/00DESCRIPTION index 105e0e423e..e651b16152 100644 --- a/Task/Environment-variables/00DESCRIPTION +++ b/Task/Environment-variables/00DESCRIPTION @@ -1 +1,6 @@ -Show how to get one of your process's [[wp:Environment variable|environment variables]]. The available variables vary by system; some of the common ones available on Unix include PATH, HOME, USER. +{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} +{{omit from|M4}} +{{omit from|Unlambda|Does not provide access to environment variables.}} +{{task|Programming environment operations}} +Show how to get one of your process's [[wp:Environment variable|environment variables]]. +The available variables vary by system; some of the common ones available on Unix include PATH, HOME, USER. diff --git a/Task/Environment-variables/00META.yaml b/Task/Environment-variables/00META.yaml index 45cd327e07..8f2d61dd8a 100644 --- a/Task/Environment-variables/00META.yaml +++ b/Task/Environment-variables/00META.yaml @@ -2,4 +2,4 @@ category: - Environment variables - Initialization -note: Programming environment operations +note: Environment variables diff --git a/Task/Environment-variables/Make/environment-variables-1.make b/Task/Environment-variables/Make/environment-variables-1.make new file mode 100644 index 0000000000..cd9c713f6f --- /dev/null +++ b/Task/Environment-variables/Make/environment-variables-1.make @@ -0,0 +1,3 @@ +TARGET = $(HOME)/some/thing.txt +foo: + echo $(TARGET) diff --git a/Task/Environment-variables/Make/environment-variables-2.make b/Task/Environment-variables/Make/environment-variables-2.make new file mode 100644 index 0000000000..b9fb5f6503 --- /dev/null +++ b/Task/Environment-variables/Make/environment-variables-2.make @@ -0,0 +1,2 @@ +bar: + echo "$$HOME" diff --git a/Task/Environment-variables/Make/environment-variables-3.make b/Task/Environment-variables/Make/environment-variables-3.make new file mode 100644 index 0000000000..8e01d59d21 --- /dev/null +++ b/Task/Environment-variables/Make/environment-variables-3.make @@ -0,0 +1,5 @@ +H = oops ... +bar: + echo $HOME + +# prints oops ... OME diff --git a/Task/Environment-variables/Perl/environment-variables.pl b/Task/Environment-variables/Perl/environment-variables-1.pl similarity index 100% rename from Task/Environment-variables/Perl/environment-variables.pl rename to Task/Environment-variables/Perl/environment-variables-1.pl diff --git a/Task/Environment-variables/Perl/environment-variables-2.pl b/Task/Environment-variables/Perl/environment-variables-2.pl new file mode 100644 index 0000000000..be9480ddb4 --- /dev/null +++ b/Task/Environment-variables/Perl/environment-variables-2.pl @@ -0,0 +1,2 @@ +use POSIX 'getenv'; +print getenv("HOME"),"\n"; diff --git a/Task/Environment-variables/Scala/environment-variables.scala b/Task/Environment-variables/Scala/environment-variables.scala index 2cf8d75d4c..a9c71f70cc 100644 --- a/Task/Environment-variables/Scala/environment-variables.scala +++ b/Task/Environment-variables/Scala/environment-variables.scala @@ -1,9 +1,8 @@ object Environment_variables extends App { - val variablesToUse = List("PATH", "HOME", "HOMEPATH", "USERNAME") - println((for { - y <- sys.env - x <- variablesToUse - if y._1 == x - } yield y).sorted.toMap.mkString("\n")) + def variablesToUse = Seq("USERPROFILE", "java.library.path", "PATH", "HOME", "HOMEPATH", "USERNAME") + println(sys.env.filter(p => variablesToUse contains p._1).toMap.mkString("\n")) + println + println (System.getProperty("java.library.path").split(";").mkString("\n")) + } diff --git a/Task/Environment-variables/Smalltalk/environment-variables.st b/Task/Environment-variables/Smalltalk/environment-variables.st new file mode 100644 index 0000000000..c637464a73 --- /dev/null +++ b/Task/Environment-variables/Smalltalk/environment-variables.st @@ -0,0 +1,3 @@ +OSProcess thisOSProcess environment at: #HOME. +OSProcess thisOSProcess environment at: #PATH. +OSProcess thisOSProcess environment at: #USER. diff --git a/Task/Equilibrium-index/D/equilibrium-index-1.d b/Task/Equilibrium-index/D/equilibrium-index-1.d index 4040d82b1d..a09fb1b106 100644 --- a/Task/Equilibrium-index/D/equilibrium-index-1.d +++ b/Task/Equilibrium-index/D/equilibrium-index-1.d @@ -1,7 +1,7 @@ import std.stdio, std.algorithm, std.range, std.functional; -auto equilibrium(Range)(Range r) pure nothrow { - return r.length.iota.filter!(i => r[0..i].sum == r[i+1 .. $].sum); +auto equilibrium(Range)(Range r) pure nothrow @safe /*@nogc*/ { + return r.length.iota.filter!(i => r[0 .. i].sum == r[i + 1 .. $].sum); } void main() { diff --git a/Task/Equilibrium-index/Prolog/equilibrium-index-1.pro b/Task/Equilibrium-index/Prolog/equilibrium-index-1.pro new file mode 100644 index 0000000000..950115ac54 --- /dev/null +++ b/Task/Equilibrium-index/Prolog/equilibrium-index-1.pro @@ -0,0 +1,6 @@ +equilibrium_index(List, Index) :- + append(Front, [_|Back], List), + sumlist(Front, Sum), + sumlist(Back, Sum), + length(Front, Len), + Index is Len. diff --git a/Task/Equilibrium-index/Prolog/equilibrium-index-2.pro b/Task/Equilibrium-index/Prolog/equilibrium-index-2.pro new file mode 100644 index 0000000000..6d35c523f4 --- /dev/null +++ b/Task/Equilibrium-index/Prolog/equilibrium-index-2.pro @@ -0,0 +1,4 @@ +?- equilibrium_index([-7, 1, 5, 2, -4, 3, 0], Index). +Index = 3 ; +Index = 6 ; +false. diff --git a/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx new file mode 100644 index 0000000000..40334f7f28 --- /dev/null +++ b/Task/Equilibrium-index/REXX/equilibrium-index-1.rexx @@ -0,0 +1,30 @@ +/*REXX program finds the equilibrium index for a numeric array (list).*/ +parse arg x /*get array's numbers from the CL*/ +if x='' then x=copies(' 7 -7',50) 7 /*Nothing given? Generate a list*/ +say ' array list: ' space(x) /*echo the array list to screen. */ +n=words(x) /*the number of words in the list*/ + do j=0 for n /*0─start is for zero─based array*/ + A.j=word(x,j+1) /*define the array element. */ + end /*j*/ /* [↑] assign A.0 A.1 A.3 ···*/ +say /*··· and also show a blank line.*/ +ans=equilibriumIndex(n) /*calculate the equilibrium Index*/ +@indexes=word('indices index',1+(ans==1)) /*adjust for single index?*/ +say 'equilibrium' @indexes": " ans /*show equilibrium index/indices.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────EQUILIBRIUMINDEX subroutine─────────*/ +equilibriumIndex: procedure expose A. /*have the array A. be exposed.*/ +parse arg top; high=top-1 /*stemmed array A. starts at 0*/ +q= /*equilibrium indexes (so far). */ + do e=0 to high /*find various sums (top/bot). */ + sumB=0 /*sum of bottom part of the list*/ + do b=0 to e-1 /*add the " " " " " */ + sumB=sumB + A.b /*add this array element to sumB.*/ + end /*b*/ /* [↑] summation of bottom part.*/ + sumT=0 /*sum of top part of the list*/ + do t=e+1 to high /*add the " " " " " */ + sumT=sumT + A.t /*add this array element to sumT.*/ + end /*t*/ /* [↑] summation of the top part*/ + if sumB==sumT then q=q e /*if both sums equal, found one. */ + end /*e*/ /* [↑] add quilibrium to E list.*/ +if q=='' then q="(none)" /*adjust if no indices are found.*/ +return strip(q) /*return the equilibrium list. */ diff --git a/Task/Equilibrium-index/REXX/equilibrium-index-2.rexx b/Task/Equilibrium-index/REXX/equilibrium-index-2.rexx new file mode 100644 index 0000000000..ecd16f00e0 --- /dev/null +++ b/Task/Equilibrium-index/REXX/equilibrium-index-2.rexx @@ -0,0 +1,33 @@ +/* REXX --------------------------------------------------------------- +* 30.06.2014 Walter Pachl +*--------------------------------------------------------------------*/ +parse arg l +say ' array list:' strip(l) +x.=0 +Do i=1 To words(l) + x.i=word(l,i) + End +n=i-1 +ans=strip(equilibriumIndices()) +n=words(ans) +Select + When n=0 Then Say 'There''s no equilibrium index' + When n=1 Then Say 'equilibrium index :' ans + Otherwise Say 'equilibrium indices:' ans + End +Say '---' +exit +equilibriumIndices: procedure expose x. n +sum.=0 +sum=0 +eil='' +Do i=1 To n + sum=sum+x.i + sum.i=sum + End +Do i=1 To n + im1=i-1 + If sum.im1=(sum.n-x.i)/2 Then + eil=eil im1 + End +Return eil diff --git a/Task/Equilibrium-index/REXX/equilibrium-index.rexx b/Task/Equilibrium-index/REXX/equilibrium-index.rexx deleted file mode 100644 index 9d3378c2ac..0000000000 --- a/Task/Equilibrium-index/REXX/equilibrium-index.rexx +++ /dev/null @@ -1,33 +0,0 @@ -/*REXX program finds the equalibrium index for an numeric array (list).*/ -parse arg x /*get the array's numbers. */ -say ' array list: ' x /*echo the array list to screen. */ -say /* ... and a blank line. */ -k=0 /*needed for array list counter. */ - do j=0 /*start J at 1 for 1-based arrays*/ - k=k+1 /*bump counter of array numbers. */ - _=word(x,k) /*get the number from the list. */ - if _=='' then leave /*if null, then we are done. */ - A.j=_ /*define the array element. */ - end /*j*/ -j=j-1 /*fudge DO index for the real cnt*/ -ans=equalibriumIndex(0,j) /*calculate the equalibrium Index*/ -@indexes='indices'; if ans==1 then @indexes='index' /*singular adj.*/ -say 'equalibrium' @indexes": " ans /*show equalibrium index/indices.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────EQUALIBRIUMINDEX subroutine─────────*/ -equalibriumIndex: procedure expose A. /*have the array A. be exposed.*/ -parse arg start,many /*start is most likely 0 or 1 */ -q= /*equalibrium indexes (so far). */ - do e=start to many /*find various sums (top/bot). */ - sumB=0 /*sum of bottom part of a list. */ - do b=start to e-1 /*add the bottom part of a list. */ - sumB=sumB + A.b /*add this array element to sumB.*/ - end /*b*/ - sumT=0 /*sum of top part of a list. */ - do t=e+1 to many /*add the top part of a list. */ - sumT=sumT + A.t /*add this array element to sumT.*/ - end /*t*/ - - if sumB=sumT then q=q e /*if both sums equal, found one. */ - end /*e*/ -return strip(q) /*return the equalibrium list. */ diff --git a/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication.as b/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication.as new file mode 100644 index 0000000000..d76c91f540 --- /dev/null +++ b/Task/Ethiopian-multiplication/ActionScript/ethiopian-multiplication.as @@ -0,0 +1,31 @@ +function Divide(a:Number):Number { + return ((a-(a%2))/2); +} +function Multiply(a:Number):Number { + return (a *= 2); +} +function isEven(a:Number):Boolean { + if (a%2 == 0) { + return (true); + } else { + return (false); + } +} +function Ethiopian(left:Number, right:Number) { + var r:Number = 0; + trace(left+" "+right); + while (left != 1) { + var State:String = "Keep"; + if (isEven(Divide(left))) { + State = "Strike"; + } + trace(Divide(left)+" "+Multiply(right)+" "+State); + left = Divide(left); + right = Multiply(right); + if (State == "Keep") { + r += right; + } + } + trace("="+" "+r); +} +} diff --git a/Task/Ethiopian-multiplication/Aime/ethiopian-multiplication.aime b/Task/Ethiopian-multiplication/Aime/ethiopian-multiplication.aime index 6cae6475ed..bad28a2405 100644 --- a/Task/Ethiopian-multiplication/Aime/ethiopian-multiplication.aime +++ b/Task/Ethiopian-multiplication/Aime/ethiopian-multiplication.aime @@ -1,4 +1,4 @@ -oid +void halve(integer &x) { x >>= 1; @@ -24,27 +24,17 @@ ethiopian(integer plier, integer plicand, integer tutor) result = 0; if (tutor) { - o_text("ethiopian multiplication of "); - o_integer(plier); - o_text(" by "); - o_integer(plicand); - o_text("\n"); + o_form("ethiopian multiplication of ~ by ~\n", plier, plicand); } while (plier >= 1) { if (iseven(plier)) { if (tutor) { - o_winteger(4, plier); - o_space(1); - o_winteger(6, plicand); - o_text(" struck\n"); + o_form("/w4/ /w6/ struck\n", plier, plicand); } } else { if (tutor) { - o_winteger(4, plier); - o_space(1); - o_winteger(6, plicand); - o_text(" kept\n"); + o_form("/w4/ /w6/ kept\n", plier, plicand); } result += plicand; diff --git a/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d b/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d index cb1311edf2..5753d98487 100644 --- a/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d +++ b/Task/Ethiopian-multiplication/D/ethiopian-multiplication.d @@ -1,10 +1,10 @@ -int ethiopian(int n1, int n2) pure nothrow +int ethiopian(int n1, int n2) pure nothrow @nogc in { assert(n1 >= 0, "Multiplier can't be negative"); } body { - static enum doubleNum = (in int n) pure nothrow => n * 2; - static enum halveNum = (in int n) pure nothrow => n / 2; - static enum isEven = (in int n) pure nothrow => !(n & 1); + static enum doubleNum = (in int n) pure nothrow @nogc => n * 2; + static enum halveNum = (in int n) pure nothrow @nogc => n / 2; + static enum isEven = (in int n) pure nothrow @nogc => !(n & 1); int result; while (n1 >= 1) { diff --git a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e new file mode 100644 index 0000000000..8a2f1cc43c --- /dev/null +++ b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-1.e @@ -0,0 +1,41 @@ +class + ETHIOPIAN_MULTIPLICATION +feature{NONE} + double_int(n: INTEGER): INTEGER + do + Result:= n*2 + end + + halve_int(n: INTEGER) : INTEGER + do + Result:= n//2 + end + + even_int(n: INTEGER): BOOLEAN + do + Result:= n\\2=0 + end +feature + ethiopian_mult(a,b: INTEGER): INTEGER + require + a_positive: a>0 + b_positive: b>0 + local + new_a, new_b: INTEGER + do + new_a:= a + new_b:= b + from + until + new_a<=0 + loop + if even_int(new_a)= FALSE then + Result:= Result+new_b + end + new_a:= halve_int(new_a) + new_b:= double_int(new_b) + end + ensure + Result_correct: Result= a*b + end +end diff --git a/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e new file mode 100644 index 0000000000..35f653935e --- /dev/null +++ b/Task/Ethiopian-multiplication/Eiffel/ethiopian-multiplication-2.e @@ -0,0 +1,15 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + make + local + do + create mult + io.put_integer ( mult.ethiopian_mult (17,34)) + end + mult: ETHIOPIAN_MULTIPLICATION +end diff --git a/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l b/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l index 28a704958f..dddb792bc0 100644 --- a/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l +++ b/Task/Ethiopian-multiplication/Emacs-Lisp/ethiopian-multiplication.l @@ -5,10 +5,10 @@ (defun double (n) (* n 2)) (defun ethiopian-multiplication (l r) - (setq sum 0) - (while (>= l 1) - (unless (even-p l) - (setq sum (+ r sum))) - (setq l (halve l)) - (setq r (double r))) - (print sum)) + (let ((sum 0)) + (while (>= l 1) + (unless (even-p l) + (setq sum (+ r sum))) + (setq l (halve l)) + (setq r (double r))) + sum)) diff --git a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-2.j b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-2.j index 3d935ae6fb..ab3e3cbb6a 100644 --- a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-2.j +++ b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-2.j @@ -1,2 +1 @@ - 17 ethiop 34 -578 +ethio=: *@] * (ethiop |) diff --git a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-3.j b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-3.j index 7c036ad767..4c0275e7be 100644 --- a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-3.j +++ b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-3.j @@ -1,2 +1 @@ - (<5) double 17 -17 34 68 136 272 +ethio=: *@] -@]^:(0 > [) (ethiop |) diff --git a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-4.j b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-4.j index ab3e3cbb6a..ac489587c8 100644 --- a/Task/Ethiopian-multiplication/J/ethiopian-multiplication-4.j +++ b/Task/Ethiopian-multiplication/J/ethiopian-multiplication-4.j @@ -1 +1,8 @@ -ethio=: *@] * (ethiop |) + 7 ethio 11 +77 + 7 ethio _11 +_77 + _7 ethio 11 +_77 + _7 ethio _11 +77 diff --git a/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-3.java b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-3.java index 8e618a5121..108818b5e0 100644 --- a/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-3.java +++ b/Task/Ethiopian-multiplication/Java/ethiopian-multiplication-3.java @@ -17,11 +17,8 @@ var eth = { if( !eth.isEven( a[i] ) ){ sum += b[i]; } - } - + } return sum + b[0]; - } } - // eth.mult(17,34) returns 578 diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia new file mode 100644 index 0000000000..a453d4287a --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-1.julia @@ -0,0 +1,8 @@ +# bit shifting, equivalent to div(x, 2) +halve(x::Int) = x >> 1 + +# preserves the type +double(x::Int) = 2*x + +# could just use iseven(x), but that feels like cheating +even(x::Int) = (mod(x, 2) == 0 ? true : false) diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia new file mode 100644 index 0000000000..0d3bcc02e4 --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-2.julia @@ -0,0 +1,9 @@ +function ethopian_multiplication(a::Int, b::Int) + res = 0 + while a > 0 + res += even(a) ? 0 : b + a = halve(a) + b = double(b) + end + return res +end diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia new file mode 100644 index 0000000000..07c2b0bc43 --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-3.julia @@ -0,0 +1,9 @@ +function ethopian_multiplication_arr(a::Int, b::Int) + A = [a] + B = [b] + while A[end] > 1 + push!(A, halve(A[end])) + push!(B, double(B[end])) + end + return sum(B[!map(even, A)]) +end diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-4.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-4.julia new file mode 100644 index 0000000000..ecb5e13d53 --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-4.julia @@ -0,0 +1,4 @@ +>> ethopian_multiplication(17, 34) +578 +>> ethopian_multiplication_arr(44, 71) +3124 diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia new file mode 100644 index 0000000000..1ea4761dee --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-5.julia @@ -0,0 +1 @@ +def pairs: while( .[0] > 0; [ (.[0] | halve), (.[1] | double) ]); diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia new file mode 100644 index 0000000000..8cef496ce6 --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-6.julia @@ -0,0 +1,15 @@ +def halve: (./2) | floor; + +def double: 2 * .; + +def isEven: . % 2 == 0; + +def ethiopian_multiply(a;b): + def pairs: recurse( if .[0] > 0 + then [ (.[0] | halve), (.[1] | double) ] + else empty + end ); + reduce ([a,b] | pairs + | select( .[0] | isEven | not) + | .[1] ) as $i + (0; . + $i) ; diff --git a/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia new file mode 100644 index 0000000000..e89ad806a5 --- /dev/null +++ b/Task/Ethiopian-multiplication/Julia/ethiopian-multiplication-7.julia @@ -0,0 +1 @@ +ethiopian_multiply(17;34) # => 578 diff --git a/Task/Ethiopian-multiplication/PHP/ethiopian-multiplication-2.php b/Task/Ethiopian-multiplication/PHP/ethiopian-multiplication-2.php index 624f39af49..bc6bf83b2e 100644 --- a/Task/Ethiopian-multiplication/PHP/ethiopian-multiplication-2.php +++ b/Task/Ethiopian-multiplication/PHP/ethiopian-multiplication-2.php @@ -42,5 +42,4 @@ class ethiopian_multiply { } echo ethiopian_multiply::init(17, 34); - ?> diff --git a/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-1.pro b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-1.pro new file mode 100644 index 0000000000..8492d2ba49 --- /dev/null +++ b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-1.pro @@ -0,0 +1,23 @@ +halve(X,Y) :- Y is X // 2. +double(X,Y) :- Y is 2*X. +is_even(X) :- 0 is X mod 2. + +% columns(First,Second,Left,Right) is true if integers First and Second +% expand into the columns Left and Right, respectively +columns(1,Second,[1],[Second]). +columns(First,Second,[First|Left],[Second|Right]) :- + halve(First,Halved), + double(Second,Doubled), + columns(Halved,Doubled,Left,Right). + +% contribution(Left,Right,Amount) is true if integers Left and Right, +% from their respective columns contribute Amount to the final sum. +contribution(Left,_Right,0) :- + is_even(Left). +contribution(Left,Right,Right) :- + \+ is_even(Left). + +ethiopian(First,Second,Product) :- + columns(First,Second,Left,Right), + maplist(contribution,Left,Right,Contributions), + sumlist(Contributions,Product). diff --git a/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-2.pro b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-2.pro new file mode 100644 index 0000000000..58e3c19cd1 --- /dev/null +++ b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-2.pro @@ -0,0 +1,12 @@ +:- use_module(library(func)). + +% halve/2, double/2, is_even/2 definitions go here + +ethiopian(First,Second,Product) :- + ethiopian(First,Second,0,Product). + +ethiopian(1,Second,Sum0,Sum) :- + Sum is Sum0 + Second. +ethiopian(First,Second,Sum0,Sum) :- + Sum1 is Sum0 + Second*(First mod 2), + ethiopian(halve $ First, double $ Second, Sum1, Sum). diff --git a/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-3.pro b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-3.pro new file mode 100644 index 0000000000..b77f2fb4a1 --- /dev/null +++ b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-3.pro @@ -0,0 +1,25 @@ +:- module(ethiopia, [test/0, mul/3]). + +:- use_module(library(chr)). + +:- chr_constraint mul/3, halve/2, double/2, even/1, add_odd/4. + +mul(1, Y, S) <=> S = Y. +mul(X, Y, S) <=> X \= 1 | halve(X, X1), + double(Y, Y1), + mul(X1, Y1, S1), + add_odd(X, Y, S1, S). + +halve(X, Y) <=> Y is X // 2. + +double(X, Y) <=> Y is X * 2. + +even(X) <=> 0 is X mod 2 | true. +even(X) <=> 1 is X mod 2 | false. + +add_odd(X, _, A, S) <=> even(X) | S is A. +add_odd(X, Y, A, S) <=> \+ even(X) | S is A + Y. + +test :- + mul(17, 34, Z), !, + writeln(Z). diff --git a/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-4.pro b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-4.pro new file mode 100644 index 0000000000..e5789358a1 --- /dev/null +++ b/Task/Ethiopian-multiplication/Prolog/ethiopian-multiplication-4.pro @@ -0,0 +1,21 @@ +:- module(ethiopia, [test/0, mul/3]). + +:- use_module(library(chr)). + +:- chr_constraint mul/3, even/1, add_if_odd/4. + +mul(1, Y, S) <=> S = Y. +mul(X, Y, S) <=> X \= 1 | X1 is X // 2, + Y1 is Y * 2, + mul(X1, Y1, S1), + add_if_odd(X, Y, S1, S). + +even(X) <=> 0 is X mod 2 | true. +even(X) <=> 1 is X mod 2 | false. + +add_if_odd(X, _, A, S) <=> even(X) | S is A. +add_if_odd(X, Y, A, S) <=> \+ even(X) | S is A + Y. + +test :- + mul(17, 34, Z), + writeln(Z). diff --git a/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust b/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust new file mode 100644 index 0000000000..53bac168c3 --- /dev/null +++ b/Task/Ethiopian-multiplication/Rust/ethiopian-multiplication.rust @@ -0,0 +1,28 @@ +fn double(a : int) -> int{ + a << 1 +} + +fn halve(a : int) -> int{ + a >> 1 +} + +fn is_even(a : int) -> bool{ + a & 1 == 0 +} + +fn ethiopian_multiplication(mut x : int, mut y : int) -> int{ + let mut sum = 0; + + while x >= 1 { + print!("{} \t {}", x, y); + if is_even(x) { + println!("\t Not Kept"); + } else { + sum = sum + y; + println!("\t Kept"); + } + x = halve(x); + y = double(y); + } + sum +} diff --git a/Task/Ethiopian-multiplication/Scala/ethiopian-multiplication.scala b/Task/Ethiopian-multiplication/Scala/ethiopian-multiplication.scala index b6891a249a..3a36d356ea 100644 --- a/Task/Ethiopian-multiplication/Scala/ethiopian-multiplication.scala +++ b/Task/Ethiopian-multiplication/Scala/ethiopian-multiplication.scala @@ -11,6 +11,8 @@ def ethiopian3(i:Int, j:Int):Int= res } +def ethiopian4(i: Int, j: Int): Int = if (i == 1) j else ethiopian(halve(i), double(j)) + (if (isEven(i)) 0 else j) + def isEven(x:Int)=(x&1)==0 def halve(x:Int)=x>>>1 def double(x:Int)=x<<1 diff --git a/Task/Euler-method/D/euler-method.d b/Task/Euler-method/D/euler-method.d index e88bc47a46..3b4fc880b4 100644 --- a/Task/Euler-method/D/euler-method.d +++ b/Task/Euler-method/D/euler-method.d @@ -1,26 +1,22 @@ -import std.stdio, std.range; +import std.stdio, std.range, std.traits; -/** -Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and -t=a..b and the step size h. -*/ -void euler(F)(in F f, in double y0, - in double a, in double b, in double h) { +/// Approximates y(t) in y'(t)=f(t,y) with y(a)=y0 and t=a..b and the step size h. +void euler(F)(in F f, in double y0, in double a, in double b, in double h) @safe +if (isCallable!F && __traits(compiles, { real r = f(0.0, 0.0); })) { double y = y0; - foreach (t; iota(a, b, h)) { + foreach (immutable t; iota(a, b, h)) { writefln("%.3f %.3f", t, y); y += h * f(t, y); } - writeln("done"); + "done".writeln; } void main() { - /// Example: Newton's cooling law - static newtonCoolingLaw(in double time, in double t) { - return -0.07 * (t - 20); - } + /// Example: Newton's cooling law. + enum newtonCoolingLaw = (in double time, in double t) + pure nothrow @safe @nogc => -0.07 * (t - 20); - euler(&newtonCoolingLaw, 100, 0, 100, 2); - euler(&newtonCoolingLaw, 100, 0, 100, 5); - euler(&newtonCoolingLaw, 100, 0, 100, 10); + euler(newtonCoolingLaw, 100, 0, 100, 2); + euler(newtonCoolingLaw, 100, 0, 100, 5); + euler(newtonCoolingLaw, 100, 0, 100, 10); } diff --git a/Task/Euler-method/JavaScript/euler-method.js b/Task/Euler-method/JavaScript/euler-method.js new file mode 100644 index 0000000000..69666fe2e1 --- /dev/null +++ b/Task/Euler-method/JavaScript/euler-method.js @@ -0,0 +1,29 @@ +// Function that takes differential-equation, initial condition, +// ending x, and step size as parameters +function eulersMethod(f, x1, y1, x2, h) { + // Header + console.log("\tX\t|\tY\t"); + console.log("------------------------------------"); + + // Initial Variables + var x=x1, y=y1; + + // While we're not done yet + // Both sides of the OR let you do Euler's Method backwards + while ((xx2 && x1>x2)) { + // Print what we have + console.log("\t" + x + "\t|\t" + y); + + // Calculate the next values + y += h*f(x, y) + x += h; + } + + return y; +} + +function cooling(x, y) { + return -0.07 * (y-20); +} + +eulersMethod(cooling, 0, 100, 100, 10); diff --git a/Task/Euler-method/R/euler-method.r b/Task/Euler-method/R/euler-method.r new file mode 100644 index 0000000000..2843f1f653 --- /dev/null +++ b/Task/Euler-method/R/euler-method.r @@ -0,0 +1,17 @@ +euler <- function(f, y0, a, b, h) +{ + t <- a + y <- y0 + + while (t < b) + { + cat(sprintf("%6.3f %6.3f\n", t, y)) + t <- t + h + y <- y + h*f(t, y) + } +} + +newtoncooling <- function(time, temp) + return(-0.07*(temp-20)) + +euler(newtoncooling, 100, 0, 100, 10) diff --git a/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients.c b/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients.c new file mode 100644 index 0000000000..61d9baadd5 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/C/evaluate-binomial-coefficients.c @@ -0,0 +1,43 @@ +#include +#include + +/* We go to some effort to handle overflow situations */ + +static unsigned long gcd_ui(unsigned long x, unsigned long y) { + unsigned long t; + if (y < x) { t = x; x = y; y = t; } + while (y > 0) { + t = y; y = x % y; x = t; /* y1 <- x0 % y0 ; x1 <- y0 */ + } + return x; +} + +unsigned long binomial(unsigned long n, unsigned long k) { + unsigned long d, g, r = 1; + if (k == 0) return 1; + if (k == 1) return n; + if (k >= n) return (k == n); + if (k > n/2) k = n-k; + for (d = 1; d <= k; d++) { + if (r >= ULONG_MAX/n) { /* Possible overflow */ + unsigned long nr, dr; /* reduced numerator / denominator */ + g = gcd_ui(n, d); nr = n/g; dr = d/g; + g = gcd_ui(r, dr); r = r/g; dr = dr/g; + if (r >= ULONG_MAX/nr) return 0; /* Unavoidable overflow */ + r *= nr; + r /= dr; + n--; + } else { + r *= n--; + r /= d; + } + } + return r; +} + +int main() { + printf("%lu\n", binomial(5, 3)); + printf("%lu\n", binomial(40, 19)); + printf("%lu\n", binomial(67, 31)); + return 0; +} diff --git a/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients.coffee b/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients.coffee new file mode 100644 index 0000000000..025c550049 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/CoffeeScript/evaluate-binomial-coefficients.coffee @@ -0,0 +1,9 @@ +binomial_coefficient = (n, k) -> + result = 1 + for i in [0...k] + result *= (n - i) / (i + 1) + result + +n = 5 +for k in [0..n] + console.log "binomial_coefficient(#{n}, #{k}) = #{binomial_coefficient(n,k)}" diff --git a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d index 7fb8e2cb4f..4af1479e1d 100644 --- a/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d +++ b/Task/Evaluate-binomial-coefficients/D/evaluate-binomial-coefficients.d @@ -1,8 +1,8 @@ -T binomial(T)(in T n, T k) pure /*nothrow*/ { +T binomial(T)(in T n, T k) pure nothrow { if (k > (n / 2)) k = n - k; T bc = 1; - foreach (T i; cast(T)2 .. k + 1) + foreach (T i; T(2) .. k + 1) bc = (bc * (n - k + i)) / i; return bc; } @@ -10,7 +10,7 @@ T binomial(T)(in T n, T k) pure /*nothrow*/ { void main() { import std.stdio, std.bigint; - foreach (d; [[5, 3], [100, 2], [100, 98]]) + foreach (const d; [[5, 3], [100, 2], [100, 98]]) writefln("(%3d %3d) = %s", d[0], d[1], binomial(d[0], d[1])); writeln("(100 50) = ", binomial(100.BigInt, 50.BigInt)); } diff --git a/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f new file mode 100644 index 0000000000..de43ce23b8 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Fortran/evaluate-binomial-coefficients.f @@ -0,0 +1,31 @@ +program test_choose + + implicit none + + write (*, '(i0)') choose (5, 3) + +contains + + function factorial (n) result (res) + + implicit none + integer, intent (in) :: n + integer :: res + integer :: i + + res = product ((/(i, i = 1, n)/)) + + end function factorial + + function choose (n, k) result (res) + + implicit none + integer, intent (in) :: n + integer, intent (in) :: k + integer :: res + + res = factorial (n) / (factorial (k) * factorial (n - k)) + + end function choose + +end program test_choose diff --git a/Task/Evaluate-binomial-coefficients/Haskell/evaluate-binomial-coefficients-4.hs b/Task/Evaluate-binomial-coefficients/Haskell/evaluate-binomial-coefficients-4.hs new file mode 100644 index 0000000000..7f8e4c2aef --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Haskell/evaluate-binomial-coefficients-4.hs @@ -0,0 +1,5 @@ +coeffs = iterate next [1] + where + next ns = zipWith (+) (0:ns) $ ns ++ [0] + +main = print $ coeffs !! 5 !! 3 diff --git a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java index 61720ea8a6..dd16e2015d 100644 --- a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java +++ b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-1.java @@ -1,17 +1,18 @@ -public class Binom { +public class Binomial +{ + private static long binomial(int n, int k) + { + if (k>n-k) + k=n-k; - static long combinations(int n, int k) { - long coeff = 1; - for (int i = n - k + 1; i <= n; i++) { - coeff *= i; - } - for (int i = 1; i <= k; i++) { - coeff /= i; - } - return coeff; - } + long b=1; + for (int i=1, m=n; i<=k; i++, m--) + b=b*m/i; + return b; + } - public static void main(String[] args){ - System.out.println(combinations(5, 3)); + public static void main(String[] args) + { + System.out.println(binomial(5, 3)); } } diff --git a/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-3.java b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-3.java new file mode 100644 index 0000000000..7cdb3118a1 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Java/evaluate-binomial-coefficients-3.java @@ -0,0 +1,17 @@ +public class Binomial +{ + private static long binom(int n, int k) + { + if (k==0) + return 1; + else if (k>n-k) + return binom(n, n-k); + else + return binom(n-1, k-1)*n/k; + } + + public static void main(String[] args) + { + System.out.println(binom(5, 3)); + } +} diff --git a/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients.pli b/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients.pli new file mode 100644 index 0000000000..915ada747d --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/PL-I/evaluate-binomial-coefficients.pli @@ -0,0 +1,22 @@ +binomial_coefficients: + procedure options (main); + declare (n, k) fixed; + + get (n, k); + put (coefficient(n, k)); + +coefficient: procedure (n, k) returns (fixed decimal (15)); + declare (n, k) fixed; + return (fact(n)/ (fact(n-k) * fact(k)) ); +end coefficient; + +fact: procedure (n) returns (fixed decimal (15)); + declare n fixed; + declare i fixed, f fixed decimal (15); + f = 1; + do i = 1 to n; + f = f * i; + end; + return (f); +end fact; +end binomial_coefficients; diff --git a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 index 0c0bb0da3e..6d6b1b7797 100644 --- a/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 +++ b/Task/Evaluate-binomial-coefficients/Perl-6/evaluate-binomial-coefficients.pl6 @@ -1,3 +1,2 @@ -sub infix:($n, $k) { ([*] $n-$k+1 .. $n) / [*] 2 .. $k } - +sub infix: { [*] ($^n ... 0) Z/ 1 .. $^p } say 5 choose 3; diff --git a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-1.pl b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-1.pl new file mode 100644 index 0000000000..715d9f4562 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-1.pl @@ -0,0 +1,8 @@ +sub binomial { + use bigint; + my ($r, $n, $k) = (1, @_); + for (1 .. $k) { $r *= $n--; $r /= $_ } + $r; +} + +print binomial(5, 3); diff --git a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-2.pl b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-2.pl new file mode 100644 index 0000000000..4041e6c8e8 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-2.pl @@ -0,0 +1,5 @@ +sub binomial { + use bigint; + my($n,$k) = @_; + (0+$n)->bnok($k); +} diff --git a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-3.pl b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-3.pl new file mode 100644 index 0000000000..e5241ffb1e --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients-3.pl @@ -0,0 +1,2 @@ +use ntheory qw/binomial/; +print length(binomial(100000,50000)), "\n"; diff --git a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl b/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl deleted file mode 100644 index 821299185f..0000000000 --- a/Task/Evaluate-binomial-coefficients/Perl/evaluate-binomial-coefficients.pl +++ /dev/null @@ -1,8 +0,0 @@ -sub binomial { - use bigint; - my ($r, $n, $k) = (1, @_); - for (1 .. $k) { $r *= $n + 1 - $_; $r /= $_ } - $r; -} - -print binomial(30, 13); diff --git a/Task/Evaluate-binomial-coefficients/PicoLisp/evaluate-binomial-coefficients.l b/Task/Evaluate-binomial-coefficients/PicoLisp/evaluate-binomial-coefficients.l index 2b817128ee..4b1362e7ac 100644 --- a/Task/Evaluate-binomial-coefficients/PicoLisp/evaluate-binomial-coefficients.l +++ b/Task/Evaluate-binomial-coefficients/PicoLisp/evaluate-binomial-coefficients.l @@ -1,3 +1,7 @@ (de binomial (N K) - (let f '((N) (apply * (range 1 N))) - (/ (f N) (* (f (- N K)) (f K))) ) ) + (let f + '((N) + (if (=0 N) 1 (apply * (range 1 N))) ) + (/ + (f N) + (* (f (- N K)) (f K)) ) ) ) diff --git a/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients.r b/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients.r new file mode 100644 index 0000000000..77351d6616 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/R/evaluate-binomial-coefficients.r @@ -0,0 +1 @@ +choose(5,3) diff --git a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients.rexx b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx similarity index 58% rename from Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients.rexx rename to Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx index 9b757625f0..b99e7362dc 100644 --- a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients.rexx +++ b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-1.rexx @@ -1,12 +1,9 @@ /*REXX program calculates binomial coefficients (aka, combinations). */ - -numeric digits 100000 -parse arg n k . -say 'combinations('n","k') =' comb(n,k) +numeric digits 100000 /*allow some gihugeic numbers. */ +parse arg n k . /*get N and K from the C.L.*/ +say 'combinations('n","k')=' comb(n,k) /*display the result to terminal.*/ exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────COMB subroutine─────────────────────*/ -comb: procedure; parse arg x,y; return fact(x) / (fact(x-y) * fact(y)) - +comb: procedure; parse arg x,y; return fact(x) % (fact(x-y) * fact(y)) /*──────────────────────────────────FACT subroutine─────────────────────*/ -fact: procedure; parse arg z; !=1; do j=2 to z; !=!*j; end; return ! +fact: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! diff --git a/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx new file mode 100644 index 0000000000..d9444e4b48 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/REXX/evaluate-binomial-coefficients-2.rexx @@ -0,0 +1,9 @@ +/*REXX program calculates binomial coefficients (aka, combinations). */ +numeric digits 100000 /*allow some gihugeic numbers. */ +parse arg n k . /*get N and K from the C.L.*/ +say 'combinations('n","k')=' comb(n,k) /*display the result to terminal.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────COMB subroutine─────────────────────*/ +comb: procedure; parse arg x,y; return pfact(x-y+1,x) % pfact(2,y) +/*──────────────────────────────────PFACT subroutine────────────────────*/ +pfact: procedure; !=1; do j=arg(1) to arg(2); !=!*j; end; return ! diff --git a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-2.scala b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-2.scala index 96ed2661b5..c7b522d493 100644 --- a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-2.scala +++ b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-2.scala @@ -1 +1,8 @@ -The Binomial Coefficient of 5 and 3 equals 10. +object Binomial extends App { + def binomialCoefficient(n: Int, k: Int) = + (BigInt(n - k + 1) to n).product / + (BigInt(1) to k).product + + val Array(n, k) = args.map(_.toInt) + println("The Binomial Coefficient of %d and %d equals %,3d.".format(n, k, binomialCoefficient(n, k))) +} diff --git a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-3.scala b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-3.scala index c7b522d493..7d60043fd9 100644 --- a/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-3.scala +++ b/Task/Evaluate-binomial-coefficients/Scala/evaluate-binomial-coefficients-3.scala @@ -1,8 +1,6 @@ -object Binomial extends App { - def binomialCoefficient(n: Int, k: Int) = - (BigInt(n - k + 1) to n).product / - (BigInt(1) to k).product - - val Array(n, k) = args.map(_.toInt) - println("The Binomial Coefficient of %d and %d equals %,3d.".format(n, k, binomialCoefficient(n, k))) -} + def bico(n: Long, k: Long): Long = (n, k) match { + case (n, 0) => 1 + case (0, k) => 0 + case (n, k) => bico(n - 1, k - 1) + bico(n - 1, k) + } + println("bico(5,3) = " + bico(5, 3)) diff --git a/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss new file mode 100644 index 0000000000..7cb1067ef0 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Scheme/evaluate-binomial-coefficients.ss @@ -0,0 +1,12 @@ +(define (factorial n) + (define (*factorial n acc) + (if (zero? n) + acc + (*factorial (- n 1) (* acc n)))) + (*factorial n 1)) + +(define (choose n k) + (/ (factorial n) (* (factorial k) (factorial (- n k))))) + +(display (choose 5 3)) +(newline) diff --git a/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-1.seed7 b/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-1.seed7 new file mode 100644 index 0000000000..49e606f2cd --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-1.seed7 @@ -0,0 +1,14 @@ +$ include "seed7_05.s7i"; + +const proc: main is func + local + var integer: n is 0; + var integer: k is 0; + begin + for n range 0 to 66 do + for k range 0 to n do + write(n ! k <& " "); + end for; + writeln; + end for; + end func; diff --git a/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-2.seed7 b/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-2.seed7 new file mode 100644 index 0000000000..ebe973aed8 --- /dev/null +++ b/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients-2.seed7 @@ -0,0 +1,26 @@ +const func bigInteger: (in bigInteger: n) ! (in var bigInteger: k) is func + result + var bigInteger: binom is 0_; + local + var bigInteger: numerator is 0_; + var bigInteger: denominator is 0_; + begin + if n >= 0_ and k > n >> 1 then + k := n - k; + end if; + if k < 0_ then + binom := 0_; + elsif k = 0_ then + binom := 1_; + else + binom := n; + numerator := pred(n); + denominator := 2_; + while denominator <= k do + binom *:= numerator; + binom := binom div denominator; + decr(numerator); + incr(denominator); + end while; + end if; + end func; diff --git a/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients.seed7 b/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients.seed7 deleted file mode 100644 index a81ca38b8b..0000000000 --- a/Task/Evaluate-binomial-coefficients/Seed7/evaluate-binomial-coefficients.seed7 +++ /dev/null @@ -1,26 +0,0 @@ -$ include "seed7_05.s7i"; - -const func integer: binomial (in integer: n, in var integer: k) is func - result - var integer: binomial is 0; - local - var integer: l is 0; - begin - if n >= k then - if k > n - k then - k := n - k; # Optimization - end if; - binomial := 1; - l := 0; - while l < k do - binomial *:= n - l; - incr(l); - binomial := binomial div l; - end while; - end if; - end func; - -const proc: main is func - begin - writeln("binomial coefficient of (5, 3) is " <& binomial(5, 3)); - end func; diff --git a/Task/Even-or-odd/6502-Assembly/even-or-odd.6502 b/Task/Even-or-odd/6502-Assembly/even-or-odd.6502 new file mode 100644 index 0000000000..da1312486a --- /dev/null +++ b/Task/Even-or-odd/6502-Assembly/even-or-odd.6502 @@ -0,0 +1,48 @@ + .lf evenodd6502.lst + .cr 6502 + .tf evenodd6502.obj,ap1 +;------------------------------------------------------ +; Even or Odd for the 6502 by barrym95838 2014.12.10 +; Thanks to sbprojects.com for a very nice assembler! +; The target for this assembly is an Apple II with +; mixed-case output capabilities. Apple IIs like to +; work in '+128' ascii, and this version is tailored +; to that preference. +; Tested and verified on AppleWin 1.20.0.0 +;------------------------------------------------------ +; Constant Section +; +CharIn = $fd0c ;Specific to the Apple II +CharOut = $fded ;Specific to the Apple II +;------------------------------------------------------ +; The main program +; +main ldy #sIntro-sbase + jsr puts ;Print Intro +loop jsr CharIn ;Get a char from stdin + cmp #$83 ;Ctrl-C? + beq done ; yes: end program + jsr CharOut ;Echo char + ldy #sOdd-sbase ;Pre-load odd string + lsr ;LSB of char to carry flag + bcs isodd + ldy #sEven-sbase +isodd jsr puts ;Print appropriate response + beq loop ;Always taken +; Output NUL-terminated string @ offset Y +; +puts lda sbase,y ;Get string char + beq done ;Done if NUL + jsr CharOut ;Output the char + iny ;Point to next char + bne puts ;Loop up to 255 times +done rts ;Return to caller +;------------------------------------------------------ +; String Constants (in '+128' ascii, Apple II style) +; +sbase: ;String base address +sIntro .az -"Hit any key (Ctrl-C to quit):",-#13 +sEven .az -" is even.",-#13 +sOdd .az -" is odd.",-#13 +;------------------------------------------------------ + .en diff --git a/Task/Even-or-odd/ALGOL-68/even-or-odd.alg b/Task/Even-or-odd/ALGOL-68/even-or-odd.alg new file mode 100644 index 0000000000..3139bfcd3e --- /dev/null +++ b/Task/Even-or-odd/ALGOL-68/even-or-odd.alg @@ -0,0 +1,8 @@ +# Algol 68 has a standard operator: ODD which returns TRUE if it's integer # +# operand is odd and FALSE if it is even # +# E.g.: # + +INT n; +print( ( "Enter an integer: " ) ); +read( ( n ) ); +print( ( whole( n, 0 ), " is ", IF ODD n THEN "odd" ELSE "even" FI, newline ) ) diff --git a/Task/Even-or-odd/C++/even-or-odd.cpp b/Task/Even-or-odd/C++/even-or-odd.cpp index 9ade0cfe0c..fea9b2dd48 100644 --- a/Task/Even-or-odd/C++/even-or-odd.cpp +++ b/Task/Even-or-odd/C++/even-or-odd.cpp @@ -1,6 +1,3 @@ -bool isEven(int Value){ - if((x % 2) == 0){ - return true; - } - return false; +bool isEven(int x) { + return x % 2; } diff --git a/Task/Even-or-odd/ColdFusion/even-or-odd.cfm b/Task/Even-or-odd/ColdFusion/even-or-odd.cfm new file mode 100644 index 0000000000..ed68067fb7 --- /dev/null +++ b/Task/Even-or-odd/ColdFusion/even-or-odd.cfm @@ -0,0 +1,5 @@ + + She's even + + He's odd + diff --git a/Task/Even-or-odd/D/even-or-odd.d b/Task/Even-or-odd/D/even-or-odd.d index c934cb72fd..866653f6ec 100644 --- a/Task/Even-or-odd/D/even-or-odd.d +++ b/Task/Even-or-odd/D/even-or-odd.d @@ -1,6 +1,6 @@ -import std.stdio, std.bigint; - void main() { - foreach (i; -5 .. 6) - writeln(i, " ", i & 1, " ", i % 2, " ", BigInt(i) % 2); + import std.stdio, std.bigint; + + foreach (immutable i; -5 .. 6) + writeln(i, " ", i & 1, " ", i % 2, " ", i.BigInt % 2); } diff --git a/Task/Even-or-odd/JavaScript/even-or-odd-1.js b/Task/Even-or-odd/JavaScript/even-or-odd-1.js new file mode 100644 index 0000000000..5203f84464 --- /dev/null +++ b/Task/Even-or-odd/JavaScript/even-or-odd-1.js @@ -0,0 +1,3 @@ +function isEven( i ) { + return (i & 1) === 0; +} diff --git a/Task/Even-or-odd/JavaScript/even-or-odd.js b/Task/Even-or-odd/JavaScript/even-or-odd-2.js similarity index 100% rename from Task/Even-or-odd/JavaScript/even-or-odd.js rename to Task/Even-or-odd/JavaScript/even-or-odd-2.js diff --git a/Task/Even-or-odd/M4/even-or-odd.m4 b/Task/Even-or-odd/M4/even-or-odd.m4 new file mode 100644 index 0000000000..2f24e03748 --- /dev/null +++ b/Task/Even-or-odd/M4/even-or-odd.m4 @@ -0,0 +1,8 @@ +define(`even', `ifelse(eval(`$1'%2),0,True,False)') +define(`odd', `ifelse(eval(`$1'%2),0,False,True)') + +even(13) +even(8) + +odd(5) +odd(0) diff --git a/Task/Even-or-odd/Maple/even-or-odd.maple b/Task/Even-or-odd/Maple/even-or-odd.maple new file mode 100644 index 0000000000..918da0c7d7 --- /dev/null +++ b/Task/Even-or-odd/Maple/even-or-odd.maple @@ -0,0 +1,8 @@ +EvenOrOdd := proc( x::integer ) + if x mod 2 = 0 then + print("Even"): + else + print("Odd"): + end if: +end proc: +EvenOrOdd(9); diff --git a/Task/Even-or-odd/NewLISP/even-or-odd.newlisp b/Task/Even-or-odd/NewLISP/even-or-odd.newlisp new file mode 100644 index 0000000000..dc546ba245 --- /dev/null +++ b/Task/Even-or-odd/NewLISP/even-or-odd.newlisp @@ -0,0 +1,2 @@ +(odd? 1) +(even? 2) diff --git a/Task/Even-or-odd/OOC/even-or-odd.ooc b/Task/Even-or-odd/OOC/even-or-odd.ooc new file mode 100644 index 0000000000..6f3ea197ca --- /dev/null +++ b/Task/Even-or-odd/OOC/even-or-odd.ooc @@ -0,0 +1,9 @@ +// Using the modulo operator +even: func (n: Int) -> Bool { + (n % 2) == 0 +} + +// Using bitwise and +odd: func (n: Int) -> Bool { + (n & 1) == 1 +} diff --git a/Task/Even-or-odd/REXX/even-or-odd.rexx b/Task/Even-or-odd/REXX/even-or-odd.rexx index 86e258fc39..d98d400ae9 100644 --- a/Task/Even-or-odd/REXX/even-or-odd.rexx +++ b/Task/Even-or-odd/REXX/even-or-odd.rexx @@ -2,30 +2,28 @@ numeric digits 1000 /*handle most big 'uns from the CL*/ parse arg x _ . /*get arg(s) from the command line*/ if x=='' then call terr 'no input' -if _\=='' | arg()\==1 then call terr 'too many arguments:' arg(1) -if \datatype(x,'N') then call terr x "isn't numeric" -if \datatype(x,'W') then call terr x "isn't an integer" -y=abs(x) /*just in case X is negative, */ - /*(modulus of neg # might be -1), */ -/*══════════════════════════════════════════════════════════════════════*/ - say center('test using modulo method',40,'─') +if _\=='' | arg()\==1 then call terr 'too many arguments: ' arg(1) +if \datatype(x,'N') then call terr x " isn't numeric" +if \datatype(x,'W') then call terr x " isn't an integer" +y=abs(x)/1 /*just in case X is negative, */ + /*(remainder of neg # might be -1)*/ + /*══════════════════════════════════════════════════*/ + say center('test using remainder)method',40,'─') if y//2 then say x 'is odd' else say x 'is even' -/*══════════════════════════════════════════════════════════════════════*/ + /*══════════════════════════════════════════════════*/ say; say center('test rightmost digit for evenness',40,'─') _=right(y,1) if pos(_,02468)==0 then say x 'is odd' else say x 'is even' -/*══════════════════════════════════════════════════════════════════════*/ + /*══════════════════════════════════════════════════*/ say; say center('test rightmost digit for oddness',40,'─') if pos(right(y,1),13579)==0 then say x 'is even' else say x 'is odd' -/*══════════════════════════════════════════════════════════════════════*/ + /*══════════════════════════════════════════════════*/ say; say center('test rightmost (binary) bit',40,'─') - /*Note: some REXX's don't have a D2B bif.*/ if right(x2b(d2x(y)),1) then say x 'is odd' else say x 'is even' -/*══════════════════════════════════════════════════════════════════════*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────TERR subroutine─────────────────────*/ terr: say; say '***error!***'; say; say arg(1); say; exit 13 diff --git a/Task/Even-or-odd/Rust/even-or-odd-1.rust b/Task/Even-or-odd/Rust/even-or-odd-1.rust new file mode 100644 index 0000000000..4668146ced --- /dev/null +++ b/Task/Even-or-odd/Rust/even-or-odd-1.rust @@ -0,0 +1,2 @@ +let isodd = |x: int| x & 1 == 1; +let iseven = |x: int| x & 1 == 0; diff --git a/Task/Even-or-odd/Rust/even-or-odd-2.rust b/Task/Even-or-odd/Rust/even-or-odd-2.rust new file mode 100644 index 0000000000..ffd0ef47b2 --- /dev/null +++ b/Task/Even-or-odd/Rust/even-or-odd-2.rust @@ -0,0 +1,2 @@ +let isodd = |x: int| x % 2 == 1; +let iseven = |x: int| x % 2 == 0; diff --git a/Task/Events/Perl-6/events.pl6 b/Task/Events/Perl-6/events.pl6 new file mode 100644 index 0000000000..bfc18e460b --- /dev/null +++ b/Task/Events/Perl-6/events.pl6 @@ -0,0 +1,14 @@ +note now, " program start"; +my $event = Channel.new; + +my $todo = start { + note now, " task start"; + $event.receive; + note now, " event reset by task"; +} + +note now, " program sleeping"; +sleep 1; +note now, " program signaling event"; +$event.send(0); +await $todo; diff --git a/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime index 1ea1d782f5..c88586454a 100644 --- a/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime +++ b/Task/Evolutionary-algorithm/Aime/evolutionary-algorithm.aime @@ -8,7 +8,7 @@ fitness(data t, data b) i = b_length(t); while (i) { i -= 1; - f += sign(b_character(t, i) ^ b_character(b, i)); + f += sign(t[i] ^ b[i]); } return f; @@ -23,9 +23,9 @@ mutate(data c, data b, data u) i = 0; while (i < l) { if (drand(15)) { - b_append(c, b_character(b, i)); + b_append(c, b[i]); } else { - b_append(c, b_character(u, drand(26))); + b_append(c, u[drand(26)]); } i += 1; } @@ -45,7 +45,7 @@ main(void) i = l; while (i) { i -= 1; - b_append(b, b_character(u, drand(26))); + b_append(b, u[drand(26)]); } f = fitness(t, b); @@ -53,9 +53,7 @@ main(void) data n; integer a; - o_winteger(-4, f); - o_text(b_string(b)); - o_newline(); + o_form("/lw4/~\n", f, b_string(b)); n = b; @@ -75,9 +73,7 @@ main(void) b = n; } - o_winteger(-4, f); - o_text(b_string(b)); - o_newline(); + o_form("/lw4/~\n", f, b_string(b)); return 0; } diff --git a/Task/Evolutionary-algorithm/ColdFusion/evolutionary-algorithm.cfm b/Task/Evolutionary-algorithm/ColdFusion/evolutionary-algorithm.cfm new file mode 100644 index 0000000000..335e36c687 --- /dev/null +++ b/Task/Evolutionary-algorithm/ColdFusion/evolutionary-algorithm.cfm @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ###counter# #numberformat(fitness*100, 99)#% fit: #parent#
+
+ +
diff --git a/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d b/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d index ccd4a6e646..984c1fe4b1 100644 --- a/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d +++ b/Task/Evolutionary-algorithm/D/evolutionary-algorithm.d @@ -5,7 +5,7 @@ enum C = 100; // Number of children in each generation. enum P = 0.05; // Mutation probability. enum fitness = (dchar[] s) => target.zip(s).count!q{ a[0] != a[1] }; dchar rnd() { return (uppercase ~ " ")[uniform(0, $)]; } -enum mut= (dchar[] s) => s.map!(a=> uniform(0,1.) < P ? rnd : a).array; +enum mut = (dchar[] s) => s.map!(a => uniform01 < P ? rnd : a).array; void main() { auto parent = target.length.iota.map!(_ => rnd).array; diff --git a/Task/Evolutionary-algorithm/Octave/evolutionary-algorithm.octave b/Task/Evolutionary-algorithm/Octave/evolutionary-algorithm.octave index c1e6eceeb3..a0d0650d7e 100644 --- a/Task/Evolutionary-algorithm/Octave/evolutionary-algorithm.octave +++ b/Task/Evolutionary-algorithm/Octave/evolutionary-algorithm.octave @@ -2,27 +2,26 @@ global target; target = split("METHINKS IT IS LIKE A WEASEL", ""); charset = ["A":"Z", " "]; p = ones(length(charset), 1) ./ length(charset); -parent = discrete_rnd(length(target), charset, p)'; -mutaterate = 0.01; +parent = discrete_rnd(charset, p, length(target), 1); +mutaterate = 0.1; -C = 100; +C = 1000; -function r = fitness(parent, thetarget) - r = sum(parent == thetarget) ./ length(thetarget); +function r = fitness(parent, target) + r = sum(parent == target) ./ length(target); endfunction -function r = mutate(parent, therate, charset) +function r = mutate(parent, mutaterate, charset) r = parent; p = unifrnd(0, 1, length(parent), 1); - nmutants = sum( p < therate ); + nmutants = sum( p < mutaterate ); if (nmutants) - s = discrete_rnd(nmutants, charset, ones(length(charset), 1) ./ length(charset))'; - r( p < therate ) = s; + s = discrete_rnd(charset, ones(length(charset), 1) ./ length(charset),nmutants,1); + r( p < mutaterate ) = s; endif endfunction -function r = evolve(parent, mutatefunc, fitnessfunc, C, mutaterate, \ - charset) +function r = evolve(parent, mutatefunc, fitnessfunc, C, mutaterate, charset) global target; children = []; for i = 1:C @@ -42,10 +41,11 @@ function printgen(p, t, i) endfunction i = 0; + while( !all(parent == target) ) i++; parent = evolve(parent, @mutate, @fitness, C, mutaterate, charset); - if ( mod(i, 20) == 0 ) + if ( mod(i, 1) == 0 ) printgen(parent, target, i); endif endwhile diff --git a/Task/Evolutionary-algorithm/OoRexx/evolutionary-algorithm.rexx b/Task/Evolutionary-algorithm/OoRexx/evolutionary-algorithm.rexx new file mode 100644 index 0000000000..56e274a750 --- /dev/null +++ b/Task/Evolutionary-algorithm/OoRexx/evolutionary-algorithm.rexx @@ -0,0 +1,54 @@ +/* Weasel.rex - Me thinks thou art a weasel. - G,M.D. - 2/25/2011 */ +arg C M +/* C is the number of children parent produces each generation. */ +/* M is the mutation rate of each gene (character) */ + +call initialize +generation = 0 +do until parent = target + most_fitness = fitness(parent) + most_fit = parent + do C + child = mutate(parent, M) + child_fitness = fitness(child) + if child_fitness > most_fitness then + do + most_fitness = child_fitness + most_fit = child + say "Generation" generation": most fit='"most_fit"', fitness="left(most_fitness,4) + end + end + parent = most_fit + generation = generation + 1 +end +exit + +initialize: + target = "METHINKS IT IS LIKE A WEASEL" + alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ " + c_length_target = length(target) + parent = mutate(copies(" ", c_length_target), 1.0) + do i = 1 to c_length_target + target_ch.i = substr(target,i,1) + end +return + +fitness: procedure expose target_ch. c_length_target + arg parm_string + fitness = 0 + do i_target = 1 to c_length_target + if substr(parm_string,i_target,1) = target_ch.i_target then + fitness = fitness + 1 + end +return fitness + +mutate:procedure expose alphabet +arg string, parm_mutation_rate + result = "" + do istr = 1 to length(string) + if random(1,1000)/1000 <= parm_mutation_rate then + result = result || substr(alphabet,random(1,length(alphabet)),1) + else + result = result || substr(string,istr,1) + end +return result diff --git a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 index 0f1e6295da..47446132e3 100644 --- a/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 +++ b/Task/Evolutionary-algorithm/Perl-6/evolutionary-algorithm.pl6 @@ -10,4 +10,4 @@ loop ( my $parent = alphabet.roll(target.chars).join; $parent ne target; $parent = max :by(&fitness), mutate($parent) xx C -) { printf "%6d: '%s'\n", (state $)++, $parent } +) { printf "%6d: '%s'\n", $++, $parent } diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION index 103f4e8562..8aaed74d82 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00DESCRIPTION @@ -1,8 +1,16 @@ -Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away. +{{omit from|C}} +{{omit from|GUISS}} +{{omit from|M4}} +{{omit from|Retro}} +{{omit from|Swift}} + +Show how to create a user-defined exception and +show how to catch an exception raised from several nested calls away. # Create two user-defined exceptions, U0 and U1. # Have function foo call function bar twice. # Have function bar call function baz. # Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second. # Function foo should catch only exception U0, not U1. + Show/describe what happens when the program is run. diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00META.yaml b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00META.yaml new file mode 100644 index 0000000000..8af673b2be --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Control Structures 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 index fa5cf75806..6aadf60109 100644 --- 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 @@ -1,14 +1,13 @@ void -baz(integer i, text &exception) +baz(integer i) { - exception = cat("U", itoa(i)); - error(exception); + error(cat("U", itoa(i))); } void -bar(integer i, text &exception) +bar(integer i) { - baz(i, exception); + baz(i); } void @@ -18,13 +17,11 @@ foo(void) i = 0; while (i < 2) { - text e; + text e; - if (trap(bar, i, e)) { - o_text("Exception `"); - o_text(e); - o_text("' thrown\n"); - if (!compare(e, "U1")) { + if (trap_d(e, bar, i)) { + o_form("Exception `~' thrown\n", e); + if (e != "U0") { o_text("will not catch exception\n"); error(e); } diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call.c b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call.c new file mode 100644 index 0000000000..0a6cb92611 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/C/exceptions-catch-an-exception-thrown-in-a-nested-call.c @@ -0,0 +1,119 @@ +#include +#include + +typedef struct exception { + int extype; + char what[128]; +} exception; + +typedef struct exception_ctx { + exception * exs; + int size; + int pos; +} exception_ctx; + +exception_ctx * Create_Ex_Ctx(int length) { + const int safety = 8; // alignment precaution. + char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); + if (! tmp) return NULL; + exception_ctx * ctx = (exception_ctx*)tmp; + ctx->size = length; + ctx->pos = -1; + ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); + return ctx; +} + +void Free_Ex_Ctx(exception_ctx * ctx) { + free(ctx); +} + +int Has_Ex(exception_ctx * ctx) { + return (ctx->pos >= 0) ? 1 : 0; +} + +int Is_Ex_Type(exception_ctx * exctx, int extype) { + return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; +} + +void Pop_Ex(exception_ctx * ctx) { + if (ctx->pos >= 0) --ctx->pos; +} + +const char * Get_What(exception_ctx * ctx) { + if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; + return NULL; +} + +int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { + if (++exctx->pos == exctx->size) { + // Use last slot and report error. + --exctx->pos; + fprintf(stderr, "*** Error: Overflow in exception context.\n"); + } + snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg); + exctx->exs[exctx->pos].extype = extype; + return -1; +} + +////////////////////////////////////////////////////////////////////// + +exception_ctx * GLOBALEX = NULL; +enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR }; + +void baz(int n) { + if (! n) { + Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz."); + return; + } + else { + Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz."); + return; + } +} + +void bar(int n) { + fprintf(stdout, "Bar door is open.\n"); + baz(n); + if (Has_Ex(GLOBALEX)) goto bar_cleanup; + fprintf(stdout, "Baz has been called without errors.\n"); +bar_cleanup: + fprintf(stdout, "Bar door is closed.\n"); +} + +void foo() { + fprintf(stdout, "Foo entering bar.\n"); + bar(0); + while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { + fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); + Pop_Ex(GLOBALEX); + } + if (Has_Ex(GLOBALEX)) return; + fprintf(stdout, "Foo left the bar.\n"); + fprintf(stdout, "Foo entering bar again.\n"); + bar(1); + while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { + fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); + Pop_Ex(GLOBALEX); + } + if (Has_Ex(GLOBALEX)) return; + fprintf(stdout, "Foo left the bar.\n"); +} + + +int main(int argc, char ** argv) { + exception_ctx * ctx = Create_Ex_Ctx(5); + GLOBALEX = ctx; + + foo(); + if (Has_Ex(ctx)) goto main_ex; + + fprintf(stdout, "No errors encountered.\n"); + +main_ex: + while (Has_Ex(ctx)) { + fprintf(stderr, "*** Error: %s\n", Get_What(ctx)); + Pop_Ex(ctx); + } + Free_Ex_Ctx(ctx); + return 0; +} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call.go b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-1.go similarity index 100% rename from Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call.go rename to Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-1.go diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-2.go b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-2.go new file mode 100644 index 0000000000..7b8e1734bf --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Go/exceptions-catch-an-exception-thrown-in-a-nested-call-2.go @@ -0,0 +1,59 @@ +package main + +import "fmt" + +type U0 struct { + error + s string +} +type U1 int + +func foo2() { + defer func() { + // We can't just "catch" U0 and ignore U1 directly but ... + if e := recover(); e != nil { + // e can be of any type, check for type U0 + if x, ok := e.(*U0); ok { + // we can only execute code here, + // not return to the body of foo2 + fmt.Println("Recovered U0:", x.s) + // We could cheat and call bar the second time + // from here, if it paniced again (even with U0) + // it wouldn't get recovered. + // Instead we've split foo into two calls to foo2. + } else { + // ... if we don't want to handle it we can + // pass it along. + fmt.Println("passing on:", e) + panic(e) // like a "re-throw" + } + } + }() + bar() +} + +func foo() { + // Call bar twice via foo2 + foo2() + foo2() + fmt.Println("not reached") +} + +func bar() int { + return baz() +} + +var done bool + +func baz() int { + if !done { + done = true + panic(&U0{nil, "a message"}) + } + panic(U1(42)) +} + +func main() { + foo() + fmt.Println("No panic") +} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/REXX/exceptions-catch-an-exception-thrown-in-a-nested-call.rexx b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/REXX/exceptions-catch-an-exception-thrown-in-a-nested-call.rexx index 15f7f309fe..7b7d9da2db 100644 --- a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/REXX/exceptions-catch-an-exception-thrown-in-a-nested-call.rexx +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/REXX/exceptions-catch-an-exception-thrown-in-a-nested-call.rexx @@ -2,22 +2,20 @@ call foo /*invoke the FOO function. */ say 'mainline program is done.' /*indicate that Elroy was here. */ exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────FOO function────────────────────────*/ foo: call bar; call bar /*invoke BAR function twice. */ return 0 /*return a zero to invoker. */ U0: say 'exception U0 caught in FOO' /*handle the U0 exception. */ return -2 /*return to the invoker. */ - /*──────────────────────────────────BAR function────────────────────────*/ bar: call baz /*have BAR invoke BAZ function. */ return 0 /*return a zero to invoker. */ - /*──────────────────────────────────BAZ function────────────────────────*/ baz: if symbol('BAZ#')=='LIT' then baz#=0 /*initialize BAZ invocation#*/ baz# = baz#+1 /*bump the BAZ invocation # by 1.*/ if baz#==1 then signal U0 /*if first invocation, raise U0 */ if baz#==2 then signal U1 /* " second " " U1 */ - return 0 /*return a zero to invoker. */ -U0: return -1 /*handle exception if not caught.*/ -U1: return -1 /* " " " " " */ + return 0 /*return a 0 (zero) to invoker.*/ + /* [↓] this U0 sub is ignored.*/ +U0: return -1 /*handle exception if not caught.*/ +U1: return -1 /* " " " " " */ diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb new file mode 100644 index 0000000000..56f5163e92 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Ruby/exceptions-catch-an-exception-thrown-in-a-nested-call.rb @@ -0,0 +1,25 @@ +def foo + begin + bar + rescue U0 + puts "captured exception U0" + end +end + +def bar + baz +end + +def baz + @bazcount = @bazcount.to_i + 1 + raise @bazcount == 1 ? U0 : U1 +end + +class U0 < StandardError +end + +class U1 < StandardError +end + +foo +foo diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Scala/exceptions-catch-an-exception-thrown-in-a-nested-call.scala b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Scala/exceptions-catch-an-exception-thrown-in-a-nested-call.scala new file mode 100644 index 0000000000..b6a2fc64ca --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Scala/exceptions-catch-an-exception-thrown-in-a-nested-call.scala @@ -0,0 +1,19 @@ +object ExceptionsTest extends App { + class U0 extends Exception + class U1 extends Exception + + def foo { + for (i <- 0 to 1) + try { + bar(i) + } catch { case e: U0 => println("Function foo caught exception U0") } + } + + def bar(i: Int) { + def baz(i: Int) = { if (i == 0) throw new U0 else throw new U1 } + + baz(i) // Nest those calls + } + + foo +} diff --git a/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Seed7/exceptions-catch-an-exception-thrown-in-a-nested-call.seed7 b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Seed7/exceptions-catch-an-exception-thrown-in-a-nested-call.seed7 new file mode 100644 index 0000000000..ee84b9e5d9 --- /dev/null +++ b/Task/Exceptions-Catch-an-exception-thrown-in-a-nested-call/Seed7/exceptions-catch-an-exception-thrown-in-a-nested-call.seed7 @@ -0,0 +1,36 @@ +$ include "seed7_05.s7i"; + +const EXCEPTION: U0 is enumlit; +const EXCEPTION: U1 is enumlit; + +const proc: baz (in integer: num) is func + begin + if num = 1 then + raise U0; + else + raise U1; + end if; + end func; + +const proc: bar (in integer: num) is func + begin + baz(num); + end func; + +const proc: foo is func + local + var integer: num is 0; + begin + for num range 1 to 2 do + block + bar(num); + exception + catch U0: writeln("U0 catched"); + end block; + end for; + end func; + +const proc: main is func + begin + foo; + end func; diff --git a/Task/Exceptions/00DESCRIPTION b/Task/Exceptions/00DESCRIPTION index 8216313ff9..011dfa6f12 100644 --- a/Task/Exceptions/00DESCRIPTION +++ b/Task/Exceptions/00DESCRIPTION @@ -1,4 +1,10 @@ {{Control Structures}} -This task is to give an example of an exception handling routine and to "throw" a new exception. +{{omit from|Euphoria}} +{{omit from|M4}} +{{omit from|Retro}} +{{omit from|Swift|[Swift does not support exception handling]}} + +This task is to give an example of an exception handling routine +and to "throw" a new exception. Cf. [[Exceptions Through Nested Calls]] diff --git a/Task/Exceptions/Go/exceptions.go b/Task/Exceptions/Go/exceptions.go index 1472eacc57..6465ea7930 100644 --- a/Task/Exceptions/Go/exceptions.go +++ b/Task/Exceptions/Go/exceptions.go @@ -2,18 +2,21 @@ package main import "fmt" -func foo() { - fmt.Println("let's foo...") - defer func() { - if err := recover(); err != nil { - fmt.Printf("Error: %v\n", err) - } - }() - panic("FAIL!") - fmt.Println("there's no point in going on.") +func foo() int { + fmt.Println("let's foo...") + defer func() { + if e := recover(); e != nil { + fmt.Println("Recovered from", e) + } + }() + var a []int + a[12] = 0 + fmt.Println("there's no point in going on.") + panic("never reached") + panic(fmt.Scan) // Can use any value, here a function! } func main() { - foo() - fmt.Println("glad that's over.") + foo() + fmt.Println("glad that's over.") } diff --git a/Task/Exceptions/Logtalk/exceptions.logtalk b/Task/Exceptions/Logtalk/exceptions.logtalk new file mode 100644 index 0000000000..af5ff6800f --- /dev/null +++ b/Task/Exceptions/Logtalk/exceptions.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/Scala/exceptions.scala b/Task/Exceptions/Scala/exceptions.scala new file mode 100644 index 0000000000..1690c10983 --- /dev/null +++ b/Task/Exceptions/Scala/exceptions.scala @@ -0,0 +1,62 @@ +//Defining exceptions +class AccountBlockException extends Exception +class InsufficientFundsException(val amount: Double) extends Exception + +class CheckingAccount(number: Int, var blocked: Boolean = false, var balance: Double = 0.0) { + def deposit(amount: Double) { // Throwing an exception 1 + if (blocked) throw new AccountBlockException + balance += amount + } + + def withdraw(amount: Double) { // Throwing an exception 2 + if (blocked) throw new AccountBlockException + if (amount <= balance) balance -= amount + else throw new InsufficientFundsException(amount - balance) + } +} + +object CheckingAccount extends App { + + class ExampleException1 extends Exception + + val c = new CheckingAccount(101) + println("Depositing $500...") + try { + c.deposit(500.00) + println("\nWithdrawing $100...") + c.withdraw(100.00) + println("\nWithdrawing $600...") + c.withdraw(600.00) + } catch { // Exception handler + case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}") + case ac: AccountBlockException => println("Account blocked.") + + ///////////////////////////// An example of multiple exception handler //////////////////////// + case e@(_: ExampleException1 | + _: InterruptedException) => println(s"Out of memory or something else.") + + case e: Exception => e.printStackTrace() + case _: Throwable => // Exception cached without any action + } finally println("Have a nice day") +} + +object CheckingBlockingAccount extends App { + val c = new CheckingAccount(102, true) + println("Depositing $500...") + try { + c.deposit(500.00) + println("\nWithdrawing $100...") + c.withdraw(100.00) + println("\nWithdrawing $600...") + c.withdraw(600.00) + } catch { // Exception handler + case ac: InsufficientFundsException => println(s"Sorry, but you are short ${'$'} ${ac.amount}") + case ac: AccountBlockException => println("Account blocked.") + case e: Exception => e.printStackTrace() + case _: Throwable => + } finally println("Have a nice day") +} + +object NotImplementedErrorTest extends App { + ??? // Throws scala.NotImplementedError: an implementation is missing +} diff --git a/Task/Executable-library/00DESCRIPTION b/Task/Executable-library/00DESCRIPTION index a49f5699fb..0d25c18585 100644 --- a/Task/Executable-library/00DESCRIPTION +++ b/Task/Executable-library/00DESCRIPTION @@ -1,4 +1,11 @@ -The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. +{{omit from|Go}} +{{omit from|GUISS}} +{{omit from|Maxima}} + +The general idea behind an executable library is to create a library +that when used as a library does one thing; +but has the ability to be run directly via command line. +Thus the API comes with a CLI in the very same source code file. '''Task detail''' diff --git a/Task/Execute-Brain----/00DESCRIPTION b/Task/Execute-Brain----/00DESCRIPTION index 4123238f82..8bcb6c63cf 100644 --- a/Task/Execute-Brain----/00DESCRIPTION +++ b/Task/Execute-Brain----/00DESCRIPTION @@ -1,13 +1,26 @@ -{{implementation|Brainf***}}RCBF is a set of [[Brainf***]] compilers and interpreters written for Rosetta Code in a variety of languages. Below are links to each of the versions of RCBF. +{{implementation|Brainf***}}RCBF is a set of [[Brainf***]] compilers and interpreters written for Rosetta Code in a variety of languages.
+Below are links to each of the versions of RCBF. An implementation need only properly implement the following instructions: -* [     (left bracket) -* ]     (right bracket) -* +     (plus sign) -* -     (minus sign) -* <     (less than sign) -* >     (greater than sign) -* ,     (comma) -* .     (period) +{| class="wikitable" +!Command +!Description +|- +| style="text-align:center"| > || Move the pointer to the right +|- +| style="text-align:center"| < || Move the pointer to the left +|- +| style="text-align:center"| + || Increment the memory cell under the pointer +|- +| style="text-align:center"| - || Decrement the memory cell under the pointer +|- +| style="text-align:center"| . || Output the character signified by the cell at the pointer +|- +| style="text-align:center"| , || Input a character and store it in the cell at the pointer +|- +| style="text-align:center"| [ || Jump past the matching ] if the cell under the pointer is 0 +|- +| style="text-align:center"| ] || Jump back to the matching [ if the cell under the pointer is nonzero +|} Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
diff --git a/Task/Execute-Brain----/PicoLisp/execute-brain----.l b/Task/Execute-Brain----/PicoLisp/execute-brain-----1.l similarity index 100% rename from Task/Execute-Brain----/PicoLisp/execute-brain----.l rename to Task/Execute-Brain----/PicoLisp/execute-brain-----1.l diff --git a/Task/Execute-Brain----/PicoLisp/execute-brain-----2.l b/Task/Execute-Brain----/PicoLisp/execute-brain-----2.l new file mode 100644 index 0000000000..f50bda3aa1 --- /dev/null +++ b/Task/Execute-Brain----/PicoLisp/execute-brain-----2.l @@ -0,0 +1,58 @@ +(de brackets (Lst) + (let S NIL + (make + (for (I . X) Lst + (case X + ("[" (push 'S I)) + ("]" + (unless S (quit "Unbalanced '['")) + (link (list (pop 'S) I)) ) ) ) + (when S (quit "Unbalanced ']'")) ) ) ) + +(de lupbra (Lst N) + (find + '((I) + (or + (= (car I) N) + (= (cadr I) N) ) ) + Lst ) ) + +(de brain (L) + (let + (D (0) + DH 1 + DL 1 + CH 1 + CL (length L) + B (brackets L) ) + (loop + (case (get L CH) + (> + (inc 'DH) + (when (> DH DL) + (setq D (insert DH D 0)) + (inc 'DL) ) ) + (< + (dec 'DH) + (when (< DH 1) + (setq D (insert DH D 0)) + (inc 'DL) + (one DH) ) ) + (+ (inc (nth D DH))) + (- (dec (nth D DH))) + (. (prin (char (get D DH)))) + ("," (set (nth D DH) (char (key)))) + ("[" + (when (=0 (get D DH)) + (setq CH (cadr (lupbra B CH))) ) ) + ("]" + (when (n0 (get D DH)) + (setq CH (car (lupbra B CH))) ) ) ) + (inc 'CH) + (T (> CH CL)) ) ) ) + +(brain (chop ">+++++++++[<++++++++>-]<.>+++++++[<++++>-]<+.+++++++..+++.[-] +>++++++++[<++++>-] <.>+++++++++++[<++++++++>-]<-.--------.+++.------.--- +-----.[-]>++++++++[<++++>- ]<+.[-]++++++++++." ) ) + +(bye) diff --git a/Task/Execute-HQ9+/Haxe/execute-hq9+.haxe b/Task/Execute-HQ9+/Haxe/execute-hq9+.haxe new file mode 100644 index 0000000000..7cd3a16600 --- /dev/null +++ b/Task/Execute-HQ9+/Haxe/execute-hq9+.haxe @@ -0,0 +1,21 @@ +// live demo: http://try.haxe.org/#2E7D4 +static function hq9plus(code:String):String { + var out:String = ""; + var acc:Int = 0; + for (position in 0 ... code.length) switch (code.charAt(position)) { + case "H", "h": out += "Hello, World!\n"; + case "Q", "q": out += '$code\n'; + case "9": + var quantity:Int = 99; + while (quantity > 1) { + out += '$quantity bottles of beer on the wall, $quantity bottles of beer.\n'; + out += 'Take one down and pass it around, ${--quantity} bottles of beer.\n'; + } + out += "1 bottle of beer on the wall, 1 bottle of beer.\n" + + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + + "No more bottles of beer on the wall, no more bottles of beer.\n" + + "Go to the store and buy some more, 99 bottles of beer on the wall.\n"; + case "+": acc++; + } + return out; +} diff --git a/Task/Execute-HQ9+/Inform-7/execute-hq9+.inf b/Task/Execute-HQ9+/Inform-7/execute-hq9+.inf index 2ccf888765..ef7534f55e 100644 --- a/Task/Execute-HQ9+/Inform-7/execute-hq9+.inf +++ b/Task/Execute-HQ9+/Inform-7/execute-hq9+.inf @@ -14,10 +14,10 @@ To interpret (code - indexed text): say "[code][line break]"; otherwise if C is "9": repeat with iteration running from 1 to 99: - let N be 100 - iteration; - say "[N] bottle[s] of beer on the wall[line break]"; - say "[N] bottle[s] of beer[line break]"; + let M be 100 - iteration; + say "[M] bottle[s] of beer on the wall[line break]"; + say "[M] bottle[s] of beer[line break]"; say "Take one down, pass it around[line break]"; - say "[N - 1] bottle[s] of beer on the wall[paragraph break]"; + say "[M - 1] bottle[s] of beer on the wall[paragraph break]"; otherwise if C is "+": increase accumulator by 1. diff --git a/Task/Execute-SNUSP/J/execute-snusp-1.j b/Task/Execute-SNUSP/J/execute-snusp-1.j new file mode 100644 index 0000000000..d33a1c16e9 --- /dev/null +++ b/Task/Execute-SNUSP/J/execute-snusp-1.j @@ -0,0 +1,53 @@ +Note 'snusp' + + Without $ character the program counter starts at top left (0 0) moving to the right (0 1) + + > increment the pointer (to point to the next cell to the right). + < decrement the pointer (to point to the next cell to the left). + + increment (increase by one) the cell at the pointer. + - decrement (decrease by one) the cell at the pointer. + . output the value of the cell at the pointer as a character. + , accept one character of input, storing its value in the cell at the pointer. + \/ mirrors + ? skip if memory pointer is 0 + ! skip + $ optional start program here (also heading to the right) + +) + +smoutput 'Toroidal programs run forever. Use ^C to interrupt.' + +main =: 3 : 0 NB. use: main 'program.snusp' + PROGRAM =: [;._2 LF ,~ 1!:1 boxopen y + SHAPE =: $PROGRAM + PC =: SHAPE#:(,PROGRAM) i.'$' + PCSTEP =: 0 1 + CELL =: 0 + CELLS =: ,0 + while. 1 do. NB. for_i. i.400 do. + INSTRUCTION =: (' do. + CELL =: >: CELL + if. CELL >: # CELLS do. + CELLS =: CELLS , 0 + end. + case. ;/'-+' do. CELLS =: CELL ((<:'- +'i.INSTRUCTION)+{)`[`]} CELLS + case. '.' do. 1!:2&4 (CELL{CELLS){a. + case. ',' do. CELLS =: (1!:1<1) CELL } CELLS + fcase. '/' do. STEP =: - STEP + case. '\' do. STEP =: PCSTEP =: |. STEP + case. '?' do. STEP =: +:^:(0 = CELL{CELLS) STEP + case. '!' do. STEP =: +: STEP + end. + PC =: (| (PC + STEP + ])) SHAPE NB. toroidal + NB. smoutput PC;CELL;CELLS NB. debug + end. +) diff --git a/Task/Execute-SNUSP/J/execute-snusp-2.j b/Task/Execute-SNUSP/J/execute-snusp-2.j new file mode 100644 index 0000000000..da6f92225b --- /dev/null +++ b/Task/Execute-SNUSP/J/execute-snusp-2.j @@ -0,0 +1,5 @@ +\ display JJ and linefeed, then loop forever +\ +++++++++++++++++++++++++++++++++++++\ + ! /+++++++++++++++++++++++++++++++++++++/ + / \..<+++++\ + \ . +++++/ diff --git a/Task/Execute-a-Markov-algorithm/00DESCRIPTION b/Task/Execute-a-Markov-algorithm/00DESCRIPTION index afdc11b4d3..9c2da90b4b 100644 --- a/Task/Execute-a-Markov-algorithm/00DESCRIPTION +++ b/Task/Execute-a-Markov-algorithm/00DESCRIPTION @@ -96,7 +96,11 @@ should generate the output: : 11111111111111111111 ==Ruleset 5== -A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. +A simple [http://en.wikipedia.org/wiki/Turing_machine Turing machine], +implementing a three-state [http://en.wikipedia.org/wiki/Busy_beaver busy beaver]. + +The tape consists of 0s and 1s, the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. +All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
diff --git a/Task/Execute-a-Markov-algorithm/Java/execute-a-markov-algorithm.java b/Task/Execute-a-Markov-algorithm/Java/execute-a-markov-algorithm.java
new file mode 100644
index 0000000000..c60dab27c7
--- /dev/null
+++ b/Task/Execute-a-Markov-algorithm/Java/execute-a-markov-algorithm.java
@@ -0,0 +1,63 @@
+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 java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class Markov {
+
+    public static void main(String[] args) throws IOException {
+
+        List rules = readRules("markov_rules.txt");
+        List tests = readTests("markov_tests.txt");
+
+        Pattern pattern = Pattern.compile("^([^#]*?)\\s+->\\s+(\\.?)(.*)");
+
+        for (int i = 0; i < tests.size(); i++) {
+            String origTest = tests.get(i);
+
+            List captures = new ArrayList<>();
+            for (String rule : rules.get(i)) {
+                Matcher m = pattern.matcher(rule);
+                if (m.find()) {
+                    String[] groups = new String[m.groupCount()];
+                    for (int j = 0; j < groups.length; j++)
+                        groups[j] = m.group(j + 1);
+                    captures.add(groups);
+                }
+            }
+
+            String test = origTest;
+            String copy = test;
+            for (int j = 0; j < captures.size(); j++) {
+                String[] c = captures.get(j);
+                test = test.replace(c[0], c[2]);
+                if (c[1].equals("."))
+                    break;
+                if (!test.equals(copy)) {
+                    j = -1; // redo loop
+                    copy = test;
+                }
+            }
+            System.out.printf("%s\n%s\n\n", origTest, test);
+        }
+    }
+
+    private static List readTests(String path)
+            throws IOException {
+        return Files.readAllLines(Paths.get(path), StandardCharsets.UTF_8);
+    }
+
+    private static List readRules(String path)
+            throws IOException {
+        String ls = System.lineSeparator();
+        String lines = new String(Files.readAllBytes(Paths.get(path)), "UTF-8");
+        List rules = new ArrayList<>();
+        for (String line : lines.split(ls + ls))
+            rules.add(line.split(ls));
+        return rules;
+    }
+}
diff --git a/Task/Execute-a-system-command/AWK/execute-a-system-command.awk b/Task/Execute-a-system-command/AWK/execute-a-system-command.awk
index 87c981a1ed..633416a511 100644
--- a/Task/Execute-a-system-command/AWK/execute-a-system-command.awk
+++ b/Task/Execute-a-system-command/AWK/execute-a-system-command.awk
@@ -1,3 +1,4 @@
 BEGIN {
-  system("ls")
+  system("ls")		# Unix
+ #system("dir")		# DOS/MS-Windows
 }
diff --git a/Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria b/Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria
new file mode 100644
index 0000000000..d76fc775f0
--- /dev/null
+++ b/Task/Execute-a-system-command/Euphoria/execute-a-system-command.euphoria
@@ -0,0 +1,32 @@
+ -- system --
+-- the simplest way --
+-- system spawns a new shell so I/O redirection is possible --
+
+system( "dir /w c:\temp\ " ) -- Microsoft --
+
+system( "/bin/ls -l /tmp" ) -- Linux BSD OSX --
+
+----
+
+ -- system_exec() --
+ -- system_exec does not spawn a new shell --
+ -- ( like bash or cmd.exe ) --
+
+integer exit_code = 0
+sequence ls_command = ""
+
+ifdef UNIX or LINUX or OSX then
+    ls_command = "/bin/ls -l "
+elsifdef WINDOWS then
+    ls_command = "dir /w "
+end ifdef
+
+exit_code = system_exec( ls_command )
+
+if exit_code = -1 then
+    puts( STDERR, " could not execute " & ls_command & "\n" )
+elsif exit_code = 0 then
+    puts( STDERR, ls_command & " succeeded\n")
+else
+    printf( STDERR, "command %s failed with code %d\n", ls_command, exit_code)
+end if
diff --git a/Task/Execute-a-system-command/Go/execute-a-system-command.go b/Task/Execute-a-system-command/Go/execute-a-system-command.go
index c6fee0de78..8575bdb5be 100644
--- a/Task/Execute-a-system-command/Go/execute-a-system-command.go
+++ b/Task/Execute-a-system-command/Go/execute-a-system-command.go
@@ -1,13 +1,16 @@
 package main
-import "fmt"
-import "os/exec"
+
+import (
+    "log"
+    "os"
+    "os/exec"
+)
 
 func main() {
-  cmd := exec.Command("ls", "-l")
-  output, err := cmd.Output()
-  if (err != nil) {
-    fmt.Println(err)
-    return
-  }
-  fmt.Print(string(output))
+    cmd := exec.Command("ls", "-l")
+    cmd.Stdout = os.Stdout
+    cmd.Stderr = os.Stderr
+    if err := cmd.Run(); err != nil {
+        log.Fatal(err)
+    }
 }
diff --git a/Task/Execute-a-system-command/NewLISP/execute-a-system-command.newlisp b/Task/Execute-a-system-command/NewLISP/execute-a-system-command.newlisp
new file mode 100644
index 0000000000..bbeec022d8
--- /dev/null
+++ b/Task/Execute-a-system-command/NewLISP/execute-a-system-command.newlisp
@@ -0,0 +1 @@
+(exec "ls")
diff --git a/Task/Exponentiation-operator/00META.yaml b/Task/Exponentiation-operator/00META.yaml
index 8644b2ad9b..15104c6b92 100644
--- a/Task/Exponentiation-operator/00META.yaml
+++ b/Task/Exponentiation-operator/00META.yaml
@@ -1,2 +1,4 @@
 ---
+category:
+- Arithmetic
 note: Arithmetic operations
diff --git a/Task/Exponentiation-operator/C/exponentiation-operator.c b/Task/Exponentiation-operator/C/exponentiation-operator-1.c
similarity index 100%
rename from Task/Exponentiation-operator/C/exponentiation-operator.c
rename to Task/Exponentiation-operator/C/exponentiation-operator-1.c
diff --git a/Task/Exponentiation-operator/C/exponentiation-operator-2.c b/Task/Exponentiation-operator/C/exponentiation-operator-2.c
new file mode 100644
index 0000000000..eaa87b9b40
--- /dev/null
+++ b/Task/Exponentiation-operator/C/exponentiation-operator-2.c
@@ -0,0 +1,13 @@
+#define generic_pow(base, exp)\
+    _Generic((base),\
+            double: dpow,\
+            int: ipow)\
+    (base, exp)
+
+int main()
+{
+    printf("2^6 = %d\n", generic_pow(2,6));
+    printf("2^-6 = %d\n", generic_pow(2,-6));
+    printf("2.71^6 = %lf\n", generic_pow(2.71,6));
+    printf("2.71^-6 = %lf\n", generic_pow(2.71,-6));
+}
diff --git a/Task/Exponentiation-operator/D/exponentiation-operator.d b/Task/Exponentiation-operator/D/exponentiation-operator.d
index f5f6dbc6cd..fefb75193e 100644
--- a/Task/Exponentiation-operator/D/exponentiation-operator.d
+++ b/Task/Exponentiation-operator/D/exponentiation-operator.d
@@ -1,12 +1,12 @@
 import std.stdio, std.conv;
 
 struct Number(T) {
-    T x; // Base.
+    T x; // base
     alias x this;
     string toString() const { return text(x); }
 
     Number opBinary(string op)(in int exponent)
-    const pure nothrow if (op == "^^") in {
+    const pure nothrow @nogc if (op == "^^") in {
         if (exponent < 0)
             assert (x != 0, "Division by zero");
     } body {
@@ -16,7 +16,7 @@ struct Number(T) {
         T factor;
         if (exponent < 0) {
             zerodir = +1;
-            factor = (cast(T)1) / x;
+            factor = T(1) / x;
         } else {
             zerodir = -1;
             factor = x;
diff --git a/Task/Exponentiation-operator/Perl/exponentiation-operator.pl b/Task/Exponentiation-operator/Perl/exponentiation-operator-1.pl
similarity index 100%
rename from Task/Exponentiation-operator/Perl/exponentiation-operator.pl
rename to Task/Exponentiation-operator/Perl/exponentiation-operator-1.pl
diff --git a/Task/Exponentiation-operator/Perl/exponentiation-operator-2.pl b/Task/Exponentiation-operator/Perl/exponentiation-operator-2.pl
new file mode 100644
index 0000000000..1832ad73ec
--- /dev/null
+++ b/Task/Exponentiation-operator/Perl/exponentiation-operator-2.pl
@@ -0,0 +1,13 @@
+sub ex {
+  my($base,$exp) = @_;
+  die "Exponent '$exp' must be an integer!" if $exp != int($exp);
+  return 1 if $exp == 0;
+  ($base, $exp) = (1/$base, -$exp)  if $exp < 0;
+  my $c = 1;
+  while ($exp > 1) {
+    $c *= $base if $exp % 2;
+    $base *= $base;
+    $exp >>= 1;
+  }
+  $base * $c;
+}
diff --git a/Task/Exponentiation-operator/Prolog/exponentiation-operator-1.pro b/Task/Exponentiation-operator/Prolog/exponentiation-operator-1.pro
new file mode 100644
index 0000000000..dd6154a1fc
--- /dev/null
+++ b/Task/Exponentiation-operator/Prolog/exponentiation-operator-1.pro
@@ -0,0 +1,2 @@
+:- arithmetic_function((^^)/2).
+:- op(200, xfy, user:(^^)).
diff --git a/Task/Exponentiation-operator/Prolog/exponentiation-operator-2.pro b/Task/Exponentiation-operator/Prolog/exponentiation-operator-2.pro
new file mode 100644
index 0000000000..3328258c95
--- /dev/null
+++ b/Task/Exponentiation-operator/Prolog/exponentiation-operator-2.pro
@@ -0,0 +1,24 @@
+%% ^^/3
+%
+%   True if Power is Base ^ Exp.
+
+^^(Base, Exp, Power) :-
+    ( Exp < 0   ->  Power is 1 / (Base ^^ (Exp * -1))            % If exponent is negative, then ...
+
+    ; Exp > 0   ->  length(Powers, Exp),                         % If exponent is positive, then
+                    foldl( exp_folder(Base), Powers, 1, Power )  %    Powers is a list of free variables with length Exp
+                                                                 %    and Power is Powers folded with exp_folder/4
+
+    ; Power = 1                                                  % otherwise Exp must be 0, so
+    ).
+
+%% exp_folder/4
+%
+%       True when Power is the product of Base and Powers.
+%
+%       This predicate is designed to work with foldl and a list of free variables.
+%       It passes the result of each evaluation to the next application through its
+%       fourth argument, instantiating the elements of Powers to each successive Power of the Base.
+
+exp_folder(Base, Power, Powers, Power) :-
+    Power is Base * Powers.
diff --git a/Task/Exponentiation-operator/Prolog/exponentiation-operator-3.pro b/Task/Exponentiation-operator/Prolog/exponentiation-operator-3.pro
new file mode 100644
index 0000000000..d09cd1b9d8
--- /dev/null
+++ b/Task/Exponentiation-operator/Prolog/exponentiation-operator-3.pro
@@ -0,0 +1,11 @@
+?- X is 2 ^^ 3.
+X = 8.
+
+?- X is 2 ^^ -3.
+X = 0.125.
+
+?- X is 2.5 ^^ -3.
+X = 0.064.
+
+?- X is 2.5 ^^ 3.
+X = 15.625.
diff --git a/Task/Exponentiation-operator/Prolog/exponentiation-operator-4.pro b/Task/Exponentiation-operator/Prolog/exponentiation-operator-4.pro
new file mode 100644
index 0000000000..2ecc67f192
--- /dev/null
+++ b/Task/Exponentiation-operator/Prolog/exponentiation-operator-4.pro
@@ -0,0 +1,16 @@
+exp_recursive(Base, NegExp, NegPower) :-
+    NegExp < 0,
+    Exp is NegExp * -1,
+    exp_recursive_(Base, Exp, Base, Power),
+    NegPower is 1 / Power.
+exp_recursive(Base, Exp, Power) :-
+    Exp > 0,
+    exp_recursive_(Base, Exp, Base, Power).
+exp_recursive(_, 0, 1).
+
+exp_recursive_(_,    1,   Power, Power).
+exp_recursive_(Base, Exp, Acc,   Power)   :-
+    Exp > 1,
+    NewAcc is Base * Acc,
+    NewExp is Exp  - 1,
+    exp_recursive_(Base, NewExp, NewAcc, Power).
diff --git a/Task/Exponentiation-operator/Seed7/exponentiation-operator-2.seed7 b/Task/Exponentiation-operator/Seed7/exponentiation-operator-2.seed7
index ae5d75fca3..016f353f85 100644
--- a/Task/Exponentiation-operator/Seed7/exponentiation-operator-2.seed7
+++ b/Task/Exponentiation-operator/Seed7/exponentiation-operator-2.seed7
@@ -1,44 +1,32 @@
 const func float: fltIPow (in var float: base, in var integer: exponent) is func
   result
-    var float: result is 0.0;
+    var float: power is 1.0;
   local
-    var boolean: neg_exp is FALSE;
+    var integer: stop is 0;
   begin
     if base = 0.0 then
       if exponent < 0 then
-        result := Infinity;
-      elsif exponent = 0 then
-        result := 1.0;
-      else
-        result := 0.0;
+        power := Infinity;
+      elsif exponent > 0 then
+        power := 0.0;
       end if;
     else
       if exponent < 0 then
-        exponent := -exponent;
-        neg_exp := TRUE;
+        stop := -1;
       end if;
-      # In the twos complement representation the most
-      # negative number is the only one where both the
-      # number and its negation are negative. When the
-      # exponent is proven to be to the most negative
-      # number fltIPow returns 0.0 .
-      if exponent >= 0 then
+      if odd(exponent) then
+        power := base;
+      end if;
+      exponent >>:= 1;
+      while exponent <> stop do
+        base *:= base;
         if odd(exponent) then
-          result := base;
-        else
-          result := 1.0;
+          power *:= base;
         end if;
         exponent >>:= 1;
-        while exponent <> 0 do
-          base *:= base;
-          if odd(exponent) then
-            result *:= base;
-          end if;
-          exponent >>:= 1;
-        end while;
-        if neg_exp then
-          result := 1.0 / result;
-        end if;
+      end while;
+      if stop = -1 then
+        power := 1.0 / power;
       end if;
     end if;
   end func;
diff --git a/Task/Extend-your-language/00DESCRIPTION b/Task/Extend-your-language/00DESCRIPTION
index 4f00a8898a..c830736c5e 100644
--- a/Task/Extend-your-language/00DESCRIPTION
+++ b/Task/Extend-your-language/00DESCRIPTION
@@ -29,4 +29,4 @@ This can be improved by introducing a new keyword '''if2'''. It is similar to ''
    else
       noConditionIsTrue();
 
-Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analog to the language's built-in 'if' statement.
+Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
diff --git a/Task/Extend-your-language/Ada/extend-your-language.ada b/Task/Extend-your-language/Ada/extend-your-language.ada
new file mode 100644
index 0000000000..49860ecdf7
--- /dev/null
+++ b/Task/Extend-your-language/Ada/extend-your-language.ada
@@ -0,0 +1,20 @@
+with Ada.Text_IO; use Ada.Text_IO;
+
+procedure Test_If_2 is
+
+   type Two_Bool is range 0 .. 3;
+
+   function If_2(Cond_1, Cond_2: Boolean) return Two_Bool is
+      (Two_Bool(2*Boolean'Pos(Cond_1)) + Two_Bool(Boolean'Pos(Cond_2)));
+
+begin
+   for N in 10 .. 20 loop
+      Put(Integer'Image(N) & " is ");
+      case If_2(N mod 2 = 0, N mod 3 = 0) is
+	 when 2#11# => Put_Line("divisible by both two and three.");
+	 when 2#10# => Put_Line("divisible by two, but not by three.");
+	 when 2#01# => Put_Line("divisible by three, but not by two.");
+	 when 2#00# => Put_Line("neither divisible by two, nor by three.");
+      end case;
+   end loop;
+end Test_If_2;
diff --git a/Task/Extend-your-language/Mathematica/extend-your-language-1.math b/Task/Extend-your-language/Mathematica/extend-your-language-1.math
new file mode 100644
index 0000000000..f991c334f3
--- /dev/null
+++ b/Task/Extend-your-language/Mathematica/extend-your-language-1.math
@@ -0,0 +1,9 @@
+If2[test1_, test2_, condBoth_, cond1_, cond2_, condNone_] := With[
+   {result1 = test1,
+    result2 = test2},
+   Which[
+    result1 && result2, condBoth,
+    result1, cond1,
+    result2, cond2,
+    True, condNone]];
+SetAttributes[If2, HoldAll];
diff --git a/Task/Extend-your-language/Mathematica/extend-your-language-2.math b/Task/Extend-your-language/Mathematica/extend-your-language-2.math
new file mode 100644
index 0000000000..111de4b5ad
--- /dev/null
+++ b/Task/Extend-your-language/Mathematica/extend-your-language-2.math
@@ -0,0 +1,5 @@
+x = 0;
+If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
+If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
+If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
+If2[Mod[(++x), 2] == 0, Mod[x, 3] == 1, Print["Both: ", x], Print["First: ", x], Print["Second: ", x], Print["Neither: ", x]];
diff --git a/Task/Extend-your-language/Mathematica/extend-your-language.math b/Task/Extend-your-language/Mathematica/extend-your-language.math
deleted file mode 100644
index e0bc0bd27c..0000000000
--- a/Task/Extend-your-language/Mathematica/extend-your-language.math
+++ /dev/null
@@ -1,5 +0,0 @@
-if2[c1_,c2_]:=Which[
-          c1&&c2, bothConditionsAreTrue[],
-          c1, firstConditionIsTrue[],
-          c2, secondConditionIsTrue[],
-          True,noConditionIsTrue]
diff --git a/Task/Extend-your-language/REXX/extend-your-language-1.rexx b/Task/Extend-your-language/REXX/extend-your-language-1.rexx
new file mode 100644
index 0000000000..2d638900b8
--- /dev/null
+++ b/Task/Extend-your-language/REXX/extend-your-language-1.rexx
@@ -0,0 +1,8 @@
+if2(  some expression that results in a boolean value,  some other expression that results in a boolean value.)
+
+    select
+    when if.11  {condition 1 & 2  are true}   then  perform-a-REXX-statement.
+    when if.10  {condition 1       is true}     "      "    "   "      "
+    when if.01  {condition 2       is true}     "      "    "   "      "
+    when if.00  {no condition      is true}     "      "    "   "      "
+    end
diff --git a/Task/Extend-your-language/REXX/extend-your-language-2.rexx b/Task/Extend-your-language/REXX/extend-your-language-2.rexx
new file mode 100644
index 0000000000..436a8f7b50
--- /dev/null
+++ b/Task/Extend-your-language/REXX/extend-your-language-2.rexx
@@ -0,0 +1,20 @@
+/*REXX program introduces   IF2,   a type of four-way compound  IF:     */
+
+  do n=10  to 20                       /*put DO loop through it's paces.*/
+                                       /* [↓]  divisible by 2 and/or 3? */
+  if2( n//2==0, n//3==0)               /*use the four-way  IF statement.*/
+      select                           /*now, test the 4 possible cases.*/
+      when if.11  then say n  "is divisible by both two and three."
+      when if.10  then say n  "is divisible by two, but not by three."
+      when if.01  then say n  "is divisible by three, but not by two."
+      when if.00  then say n  "is neither divisible by two, nor by three."
+      otherwise nop                    /* ◄─┬─this statement is optional*/
+      end   /*select*/                 /*   ├─ and only exists in case  */
+  end       /*n*/                      /*   ├─ one or more WHENs (above)*/
+                                       /*   └─ are omitted.             */
+exit                                   /*stick a fork in it, we're done.*/
+/*──────────────────────────────────IF2 routine─────────────────────────*/
+if2: parse arg if.10, if.01            /*assign the cases  10  and  01  */
+               if.11= if.10 & if.01    /*   "    "  case   11           */
+               if.00= \(if.10 | if.01) /*   "    "    "    00           */
+return ''                              /*return to the invoker of  IF2. */
diff --git a/Task/Extend-your-language/Ruby/extend-your-language-1.rb b/Task/Extend-your-language/Ruby/extend-your-language-1.rb
index 9801283f58..4ed3975718 100644
--- a/Task/Extend-your-language/Ruby/extend-your-language-1.rb
+++ b/Task/Extend-your-language/Ruby/extend-your-language-1.rb
@@ -1,23 +1,23 @@
 # Define a class which always returns itself for everything
 class HopelesslyEgocentric
-  def method_missing what, *args; self; end;
+  def method_missing(what, *args) self end
 end
 
-def if2 cond1, cond2
+def if2(cond1, cond2)
   if cond1 and cond2
     yield
     HopelesslyEgocentric.new
   elsif cond1
     Class.new(HopelesslyEgocentric) do
-      def else1; yield; HopelesslyEgocentric.new; end
+      def else1; yield; HopelesslyEgocentric.new end
     end.new
   elsif cond2
     Class.new(HopelesslyEgocentric) do
-      def else2; yield; HopelesslyEgocentric.new; end
+      def else2; yield; HopelesslyEgocentric.new end
     end.new
   else
     Class.new(HopelesslyEgocentric) do
-      def neither; yield; end
+      def neither; yield end
     end.new
   end
 end
diff --git a/Task/Extend-your-language/Ruby/extend-your-language-2.rb b/Task/Extend-your-language/Ruby/extend-your-language-2.rb
index e9000dbc8a..443ee5befa 100644
--- a/Task/Extend-your-language/Ruby/extend-your-language-2.rb
+++ b/Task/Extend-your-language/Ruby/extend-your-language-2.rb
@@ -1,9 +1,12 @@
-if2(5 < x, x < 7) do
-  puts "both true"
-end.else1 do
-  puts "first is true"
-end.else2 do
-  puts "second is true"
-end.neither do
-  puts "neither is true"
+[true,false].product([true,false]).each do |cond1, cond2|
+  print "%5s, %5s => " % [cond1, cond2]
+  if2(cond1, cond2) do
+    puts "both true"
+  end.else1 do
+    puts "first is true"
+  end.else2 do
+    puts "second is true"
+  end.neither do
+    puts "neither is true"
+  end
 end
diff --git a/Task/Extreme-floating-point-values/00DESCRIPTION b/Task/Extreme-floating-point-values/00DESCRIPTION
index a7b00f20b2..e920843f9a 100644
--- a/Task/Extreme-floating-point-values/00DESCRIPTION
+++ b/Task/Extreme-floating-point-values/00DESCRIPTION
@@ -1,7 +1,11 @@
 {{omit from|BBC BASIC}}
+{{omit from|Golfscript}}
+{{omit from|Retro}}
+
 The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity.
 
-The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it.
+The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables.
+Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it.
 
 
C.f: * [http://www.cl.cam.ac.uk/teaching/1011/FPComp/floatingmath.pdf What Every Computer Scientist Should Know About Floating-Point Arithmetic] diff --git a/Task/Extreme-floating-point-values/00META.yaml b/Task/Extreme-floating-point-values/00META.yaml new file mode 100644 index 0000000000..234794984a --- /dev/null +++ b/Task/Extreme-floating-point-values/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Irrational numbers diff --git a/Task/Extreme-floating-point-values/AWK/extreme-floating-point-values.awk b/Task/Extreme-floating-point-values/AWK/extreme-floating-point-values.awk index 0e437f2b62..7f6e1768a1 100644 --- a/Task/Extreme-floating-point-values/AWK/extreme-floating-point-values.awk +++ b/Task/Extreme-floating-point-values/AWK/extreme-floating-point-values.awk @@ -1,7 +1,7 @@ BEGIN { # This requires 1e400 to overflow to infinity. nzero = -0 - nan = 0 * 1e400 + nan = 0 * 1e400 pinf = 1e400 ninf = -1e400 diff --git a/Task/Extreme-floating-point-values/Clojure/extreme-floating-point-values.clj b/Task/Extreme-floating-point-values/Clojure/extreme-floating-point-values.clj new file mode 100644 index 0000000000..36325fd744 --- /dev/null +++ b/Task/Extreme-floating-point-values/Clojure/extreme-floating-point-values.clj @@ -0,0 +1,11 @@ +(def neg-inf (/ -1.0 0.0)) ; Also Double/NEGATIVE_INFINITY +(def inf (/ 1.0 0.0)) ; Also Double/POSITIVE_INFINITY +(def nan (/ 0.0 0.0)) ; Also Double/NaN +(def neg-zero (/ -2.0 Double/POSITIVE_INFINITY)) ; Also -0.0 +(println " Negative inf: " neg-inf) +(println " Positive inf: " inf) +(println " NaN: " nan) +(println " Negative 0: " neg-zero) +(println " inf + -inf: " (+ inf neg-inf)) +(println " NaN == NaN: " (= Double/NaN Double/NaN)) +(println "NaN equals NaN: " (.equals Double/NaN Double/NaN)) diff --git a/Task/Extreme-floating-point-values/Eiffel/extreme-floating-point-values.e b/Task/Extreme-floating-point-values/Eiffel/extreme-floating-point-values.e new file mode 100644 index 0000000000..953bec616d --- /dev/null +++ b/Task/Extreme-floating-point-values/Eiffel/extreme-floating-point-values.e @@ -0,0 +1,33 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + negInf, posInf, negZero, nan: REAL_64 + do + negInf := -1. / 0. -- also {REAL_64}.negative_infinity + posInf := 1. / 0. -- also {REAL_64}.positive_infinity + negZero := -1. / posInf + nan := 0. / 0. -- also {REAL_64}.nan + + print("Negative Infinity: ") print(negInf) print("%N") + print("Positive Infinity: ") print(posInf) print("%N") + print("Negative Zero: ") print(negZero) print("%N") + print("NaN: ") print(nan) print("%N%N") + + print("1.0 + Infinity = ") print((1.0 + posInf)) print("%N") + print("1.0 - Infinity = ") print((1.0 - posInf)) print("%N") + print("-Infinity + Infinity = ") print((negInf + posInf)) print("%N") + print("-0.0 * Infinity = ") print((negZero * posInf)) print("%N") + print("NaN + NaN = ") print((nan + nan)) print("%N") + print("(NaN = NaN) = ") print((nan = nan)) print("%N") + print("(0.0 = -0.0) = ") print((0.0 = negZero)) print("%N") + end +end diff --git a/Task/Factorial/00DESCRIPTION b/Task/Factorial/00DESCRIPTION index 9b7a896e69..3827a02adf 100644 --- a/Task/Factorial/00DESCRIPTION +++ b/Task/Factorial/00DESCRIPTION @@ -1,3 +1,5 @@ The '''Factorial Function''' of a positive integer, ''n'', is defined as the product of the sequence ''n'', ''n''-1, ''n''-2, ...1 and the factorial of zero, 0, is [[wp:Factorial#Definition|defined]] as being 1. -Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative n errors is optional. +Write a function to return the factorial of a number. +Solutions can be iterative or recursive. +Support for trapping negative n errors is optional. diff --git a/Task/Factorial/00META.yaml b/Task/Factorial/00META.yaml index f759feccfd..1d3d5a5d15 100644 --- a/Task/Factorial/00META.yaml +++ b/Task/Factorial/00META.yaml @@ -4,4 +4,5 @@ category: - Memoization - Classic CS problems and programs - Arithmetic +- Simple note: Arithmetic operations diff --git a/Task/Factorial/360-Assembly/factorial.360 b/Task/Factorial/360-Assembly/factorial.360 new file mode 100644 index 0000000000..ba796f2260 --- /dev/null +++ b/Task/Factorial/360-Assembly/factorial.360 @@ -0,0 +1,64 @@ +FACTO CSECT + USING FACTO,R13 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'FACTO' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 base register and savearea pointer + ZAP N,=P'1' n=1 +LOOPN CP N,NN if n>nn + BH ENDLOOPN then goto endloop + LA R1,PARMLIST + L R15,=A(FACT) + BALR R14,R15 call fact(n) + ZAP F,0(L'R,R1) f=fact(n) +DUMP EQU * + MVC S,MASK + ED S,N + MVC WTOBUF+5(2),S+30 + MVC S,MASK + ED S,F + MVC WTOBUF+9(32),S + WTO MF=(E,WTOMSG) + AP N,=P'1' n=n+1 + B LOOPN +ENDLOOPN EQU * +RETURN EQU * + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +FACT EQU * function FACT(l) + L R2,0(R1) + L R3,12(R2) + ZAP L,0(L'N,R2) l=n + ZAP R,=P'1' r=1 + ZAP I,=P'2' i=2 +LOOP CP I,L if i>l + BH ENDLOOP then goto endloop + MP R,I r=r*i + AP I,=P'1' i=i+1 + B LOOP +ENDLOOP EQU * + LA R1,R return r + BR R14 end function FACT + DS 0D +NN DC PL16'29' +N DS PL16 +F DS PL16 +C DS CL16 +II DS PL16 +PARMLIST DC A(N) +S DS CL33 +MASK DC X'40',29X'20',X'212060' CL33 +WTOMSG DS 0F + DC H'80',XL2'0000' +WTOBUF DC CL80'FACT(..)=................................ ' +L DS PL16 +R DS PL16 +I DS PL16 + LTORG + YREGS + END FACTO diff --git a/Task/Factorial/Babel/factorial-1.pb b/Task/Factorial/Babel/factorial-1.pb new file mode 100644 index 0000000000..e684649cbe --- /dev/null +++ b/Task/Factorial/Babel/factorial-1.pb @@ -0,0 +1,10 @@ +((main + {(0 1 2 3 4 5 6 7 8 9 10) + {fact ! %d nl <<} + each}) + +(fact + {({dup 0 =}{ zap 1 } + {dup 1 =}{ zap 1 } + {1 }{ <- 1 {iter 1 + *} -> 1 - times }) + cond})) diff --git a/Task/Factorial/Babel/factorial-2.pb b/Task/Factorial/Babel/factorial-2.pb new file mode 100644 index 0000000000..4b931af5a0 --- /dev/null +++ b/Task/Factorial/Babel/factorial-2.pb @@ -0,0 +1,10 @@ +((main + {(0 1 2 3 4 5 6 7 8 9 10) + {fact ! %d nl <<} + each}) + +(fact + {({dup 0 =}{ zap 1 } + {dup 1 =}{ zap 1 } + {1 }{ dup 1 - fact ! *}) + cond})) diff --git a/Task/Factorial/Babel/factorial.pb b/Task/Factorial/Babel/factorial.pb deleted file mode 100644 index f02ae2a0fc..0000000000 --- a/Task/Factorial/Babel/factorial.pb +++ /dev/null @@ -1,16 +0,0 @@ -main: - { argv 0 th $d - fac - %d cr << } - -fac!: - { dup zero? - { dup one? - { cp 1 - fac * } - { zap 1 } - if } - { zap 1 } - if } - -one?! : { 1 = } -zero?!: { 0 = } diff --git a/Task/Factorial/D/factorial-1.d b/Task/Factorial/D/factorial-1.d index f0f9610c22..3e58873cac 100644 --- a/Task/Factorial/D/factorial-1.d +++ b/Task/Factorial/D/factorial-1.d @@ -1,4 +1,4 @@ -uint factorial(in uint n) pure nothrow +uint factorial(in uint n) pure nothrow @nogc in { assert(n <= 12); } body { diff --git a/Task/Factorial/D/factorial-2.d b/Task/Factorial/D/factorial-2.d index 7e74d3753f..050cca05c8 100644 --- a/Task/Factorial/D/factorial-2.d +++ b/Task/Factorial/D/factorial-2.d @@ -1,4 +1,4 @@ -uint factorial(in uint n) pure nothrow +uint factorial(in uint n) pure nothrow @nogc in { assert(n <= 12); } body { diff --git a/Task/Factorial/D/factorial-3.d b/Task/Factorial/D/factorial-3.d index 727b101df2..d05cc7ff19 100644 --- a/Task/Factorial/D/factorial-3.d +++ b/Task/Factorial/D/factorial-3.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range; -uint factorial(in uint n) pure nothrow +uint factorial(in uint n) pure nothrow @nogc in { assert(n <= 12); } body { diff --git a/Task/Factorial/D/factorial-4.d b/Task/Factorial/D/factorial-4.d index 3acddea41a..e02a87ca11 100644 --- a/Task/Factorial/D/factorial-4.d +++ b/Task/Factorial/D/factorial-4.d @@ -2,7 +2,7 @@ uint factorial(in uint n) pure nothrow in { assert(n <= 12); } body { - static uint inner(uint n, uint acc) pure nothrow { + static uint inner(uint n, uint acc) pure nothrow @nogc { if (n < 1) return acc; else diff --git a/Task/Factorial/Elixir/factorial.elixir b/Task/Factorial/Elixir/factorial.elixir new file mode 100644 index 0000000000..7ff6cee4ac --- /dev/null +++ b/Task/Factorial/Elixir/factorial.elixir @@ -0,0 +1,14 @@ +defmodule Factorial do + # Simple recursive function + def fac(0), do: 1 + def fac(n) when n > 0, do: n * fac(n - 1) + + # Tail recursive function + def fac_tail(n), do: fac_tail(n, 1) + def fac_tail(0, acc), do: acc + def fac_tail(n, acc) when n > 0, do: fac_tail(n - 1, acc * n) + + # Using Enumeration features + def fac_reduce(0), do: 0 + def fac_reduce(n) when n > 0, do: Enum.reduce(1..n, 1, &*/2) +end diff --git a/Task/Factorial/Forth/factorial.fth b/Task/Factorial/Forth/factorial-1.fth similarity index 100% rename from Task/Factorial/Forth/factorial.fth rename to Task/Factorial/Forth/factorial-1.fth diff --git a/Task/Factorial/Forth/factorial-2.fth b/Task/Factorial/Forth/factorial-2.fth new file mode 100644 index 0000000000..eee3ad0561 --- /dev/null +++ b/Task/Factorial/Forth/factorial-2.fth @@ -0,0 +1,14 @@ +: factorial ( n -- d ) + dup 33 u> -24 and throw + dup 2 < IF + drop 1. + ELSE + 1. + rot 1+ 2 DO + i 1 m*/ + LOOP + THEN ; + +33 factorial d. 8683317618811886495518194401280000000 ok +-5 factorial d. +:2: Invalid numeric argument diff --git a/Task/Factorial/Haskell/factorial-2.hs b/Task/Factorial/Haskell/factorial-2.hs index 4a9556a5a8..0dac8da641 100644 --- a/Task/Factorial/Haskell/factorial-2.hs +++ b/Task/Factorial/Haskell/factorial-2.hs @@ -1 +1 @@ -factorial n = foldl (*) 1 [1..n] +factorial = product . enumFromTo 1 diff --git a/Task/Factorial/Haskell/factorial-3.hs b/Task/Factorial/Haskell/factorial-3.hs index 1536f72670..4a9556a5a8 100644 --- a/Task/Factorial/Haskell/factorial-3.hs +++ b/Task/Factorial/Haskell/factorial-3.hs @@ -1 +1 @@ -factorials = scanl (*) 1 [1..] +factorial n = foldl (*) 1 [1..n] diff --git a/Task/Factorial/Haskell/factorial-4.hs b/Task/Factorial/Haskell/factorial-4.hs index 6b76b69b6e..1536f72670 100644 --- a/Task/Factorial/Haskell/factorial-4.hs +++ b/Task/Factorial/Haskell/factorial-4.hs @@ -1,3 +1 @@ -factorial :: Integral -> Integral -factorial 0 = 1 -factorial n = n * factorial (n-1) +factorials = scanl (*) 1 [1..] diff --git a/Task/Factorial/Haskell/factorial-5.hs b/Task/Factorial/Haskell/factorial-5.hs index baef906bf8..6b76b69b6e 100644 --- a/Task/Factorial/Haskell/factorial-5.hs +++ b/Task/Factorial/Haskell/factorial-5.hs @@ -1,5 +1,3 @@ -fac n - | n >= 0 = go 1 n - | otherwise = error "Negative factorial!" - where go acc 0 = acc - go acc n = go (acc * n) (n - 1) +factorial :: Integral -> Integral +factorial 0 = 1 +factorial n = n * factorial (n-1) diff --git a/Task/Factorial/Haskell/factorial-6.hs b/Task/Factorial/Haskell/factorial-6.hs new file mode 100644 index 0000000000..baef906bf8 --- /dev/null +++ b/Task/Factorial/Haskell/factorial-6.hs @@ -0,0 +1,5 @@ +fac n + | n >= 0 = go 1 n + | otherwise = error "Negative factorial!" + where go acc 0 = acc + go acc n = go (acc * n) (n - 1) diff --git a/Task/Factorial/Haskell/factorial-7.hs b/Task/Factorial/Haskell/factorial-7.hs new file mode 100644 index 0000000000..fc1e9a1e70 --- /dev/null +++ b/Task/Factorial/Haskell/factorial-7.hs @@ -0,0 +1,8 @@ +{-# LANGUAGE PostfixOperators #-} + +(!) 0 = 1 +(!) n = n * ((n-1)!) + +main = do + print (5!) + print ((4!)!) diff --git a/Task/Factorial/Mercury/factorial-1.mercury b/Task/Factorial/Mercury/factorial-1.mercury new file mode 100644 index 0000000000..19d860d3ab --- /dev/null +++ b/Task/Factorial/Mercury/factorial-1.mercury @@ -0,0 +1,16 @@ +:- module factorial. + +:- interface. +:- import_module integer. + +:- func factorial(integer) = integer. + +:- implementation. + +:- pragma memo(factorial/1). + +factorial(N) = + ( N =< integer(0) + -> integer(1) + ; factorial(N - integer(1)) * N + ). diff --git a/Task/Factorial/Mercury/factorial-2.mercury b/Task/Factorial/Mercury/factorial-2.mercury new file mode 100644 index 0000000000..8cf4529439 --- /dev/null +++ b/Task/Factorial/Mercury/factorial-2.mercury @@ -0,0 +1,18 @@ +:- module test_factorial. +:- interface. +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module factorial. +:- import_module char, integer, list, string. + +main(!IO) :- + command_line_arguments(Args, !IO), + filter(is_all_digits, Args, CleanArgs), + Arg1 = list.det_index0(CleanArgs, 0), + Number = integer.det_from_string(Arg1), + Result = factorial(Number), + Fmt = integer.to_string, + io.format("factorial(%s) = %s\n", [s(Fmt(Number)), s(Fmt(Result))], !IO). diff --git a/Task/Factorial/Mercury/factorial-3.mercury b/Task/Factorial/Mercury/factorial-3.mercury new file mode 100644 index 0000000000..5e5d67065d --- /dev/null +++ b/Task/Factorial/Mercury/factorial-3.mercury @@ -0,0 +1 @@ +factorial(100) = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 diff --git a/Task/Factorial/PARI-GP/factorial-3.pari b/Task/Factorial/PARI-GP/factorial-3.pari index 859d67a051..125fb5c492 100644 --- a/Task/Factorial/PARI-GP/factorial-3.pari +++ b/Task/Factorial/PARI-GP/factorial-3.pari @@ -1 +1 @@ -fact(n)=prod(k=2,n,k) +fact(n)=factorback([2..n]) diff --git a/Task/Factorial/Perl/factorial-4.pl b/Task/Factorial/Perl/factorial-4.pl new file mode 100644 index 0000000000..134339c5bf --- /dev/null +++ b/Task/Factorial/Perl/factorial-4.pl @@ -0,0 +1,3 @@ +use ntheory qw/factorial/; +# factorial returns a UV (native unsigned int) or Math::BigInt depending on size +say length( factorial(10000) ); diff --git a/Task/Factorial/Perl/factorial-5.pl b/Task/Factorial/Perl/factorial-5.pl new file mode 100644 index 0000000000..8cabdc7ebe --- /dev/null +++ b/Task/Factorial/Perl/factorial-5.pl @@ -0,0 +1,2 @@ +use bigint; +say length( 10000->bfac ); diff --git a/Task/Factorial/Perl/factorial-6.pl b/Task/Factorial/Perl/factorial-6.pl new file mode 100644 index 0000000000..db386f3a12 --- /dev/null +++ b/Task/Factorial/Perl/factorial-6.pl @@ -0,0 +1,2 @@ +use Math::GMP; +say length( Math::GMP->new(10000)->bfac ); diff --git a/Task/Factorial/Perl/factorial-7.pl b/Task/Factorial/Perl/factorial-7.pl new file mode 100644 index 0000000000..bbd6007911 --- /dev/null +++ b/Task/Factorial/Perl/factorial-7.pl @@ -0,0 +1,2 @@ +use Math::Pari qw/ifact/; +say length( ifact(10000) ); diff --git a/Task/Factorial/PicoLisp/factorial-2.l b/Task/Factorial/PicoLisp/factorial-2.l index 1e8b545cc6..72ff296aa5 100644 --- a/Task/Factorial/PicoLisp/factorial-2.l +++ b/Task/Factorial/PicoLisp/factorial-2.l @@ -1,2 +1,2 @@ (de fact (N) - (apply * (range 1 N) ) + (apply * (range 1 N) ) ) diff --git a/Task/Factorial/Python/factorial-3.py b/Task/Factorial/Python/factorial-3.py index 4c0d73302c..53defba5aa 100644 --- a/Task/Factorial/Python/factorial-3.py +++ b/Task/Factorial/Python/factorial-3.py @@ -1,4 +1,5 @@ from operator import mul +from functools import reduce def factorial(n): - return reduce(mul, xrange(1,n+1), 1) + return reduce(mul, range(1,n+1), 1) diff --git a/Task/Factorial/Python/factorial-4.py b/Task/Factorial/Python/factorial-4.py index e440a26db6..2e8331bac3 100644 --- a/Task/Factorial/Python/factorial-4.py +++ b/Task/Factorial/Python/factorial-4.py @@ -1,10 +1,27 @@ ->>> for i in range(6): - print i, factorial(i) +from cmath import * -0 1 -1 1 -2 2 -3 6 -4 24 -5 120 ->>> +# Coefficients used by the GNU Scientific Library +g = 7 +p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7] + +def gamma(z): + z = complex(z) + # Reflection formula + if z.real < 0.5: + return pi / (sin(pi*z)*gamma(1-z)) + else: + z -= 1 + x = p[0] + for i in range(1, g+2): + x += p[i]/(z+i) + t = z + g + 0.5 + return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x + +def factorial(n): + return gamma(n+1) + +print "factorial(-0.5)**2=",factorial(-0.5)**2 +for i in range(10): + print "factorial(%d)=%s"%(i,factorial(i)) diff --git a/Task/Factorial/Python/factorial-5.py b/Task/Factorial/Python/factorial-5.py index 2e8331bac3..5bf8836512 100644 --- a/Task/Factorial/Python/factorial-5.py +++ b/Task/Factorial/Python/factorial-5.py @@ -1,27 +1,5 @@ -from cmath import * - -# Coefficients used by the GNU Scientific Library -g = 7 -p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, - 771.32342877765313, -176.61502916214059, 12.507343278686905, - -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7] - -def gamma(z): - z = complex(z) - # Reflection formula - if z.real < 0.5: - return pi / (sin(pi*z)*gamma(1-z)) - else: - z -= 1 - x = p[0] - for i in range(1, g+2): - x += p[i]/(z+i) - t = z + g + 0.5 - return sqrt(2*pi) * t**(z+0.5) * exp(-t) * x - def factorial(n): - return gamma(n+1) - -print "factorial(-0.5)**2=",factorial(-0.5)**2 -for i in range(10): - print "factorial(%d)=%s"%(i,factorial(i)) + z=1 + if n>1: + z=n*factorial(n-1) + return z diff --git a/Task/Factorial/REXX/factorial-3.rexx b/Task/Factorial/REXX/factorial-3.rexx index 7957839124..33103af367 100644 --- a/Task/Factorial/REXX/factorial-3.rexx +++ b/Task/Factorial/REXX/factorial-3.rexx @@ -1,34 +1,27 @@ -/*REXX program computes the factorial of a non-negative integer, and */ -/* automatically adjusts the number of digits to accommodate the answer.*/ - -/*This version allows for faster multiplying of #s (no trailing zeros).*/ -numeric digits 100 /*start with 100 digits. */ -numeric form /*indicates we want scientric form*/ -parse arg n .; if n=='' then n=0 /*get argument from command line. */ - -/*════════════════════════════════════where the rubber meets the road. */ -!=1 /*define factorial product so far.*/ - do j=2 to n /*compute factorial the hard way. */ - o!=! /*save old ! in case of overflow. */ - !=!*j /*multiple the factorial with J, */ - /* and strip all trailing zeroes. */ - if pos('E',!)\==0 then do /*is ! in exponential notation? */ - d=digits() /*D is current digs*/ - numeric digits d+d%10 /*add ten percent. */ - !=o!*j /*recalculate for the lost digit. */ - end - !=strip(!,'tail-end',0) /*kill some electrons, strip 0's. */ - end /*(above) only 1st letter is used.*/ - /*let's perform some housekeeping.*/ -if pos('E',!)\==0 then !=strip(!/1,"T",0) /*! in exponential notation?*/ -v=5; tz=0 - do while v<=n /*calculate # of trailing zeroes. */ - tz=tz+n%v - v=v*5 - end /*while v≤n*/ -!=! || copies(0,tz) /*add some water to rehydrate !. */ +/*REXX program computes the factorial of a number, striping trailing 0's*/ +numeric digits 200 /*start with two hundred digits. */ +parse arg N .; if N=='' then N=0 /*get argument from command line.*/ +!=1 /*define factorial produce so far*/ +/*═══════════════════════════════════════where the rubber meets the road*/ + do j=2 to N /*compute factorial the hard way.*/ + old!=! /*save old ! in case of overflow.*/ + !=!*j /*multiple old factorial with J.*/ + if pos('E',!)\==0 then do /*is ! in exponential notation?*/ + d=digits() /*D temporarly stores # digits.*/ + numeric digits d+d%10 /*add 10% do digits.*/ + !=old!*j /*recalculate for the lost digits*/ + end /*IFF ≡ if and only if. [↓] */ + if right(!,1)==0 then !=strip(!,,0) /*strip trailing zeroes IFF the*/ + end /*j*/ /* [↑] right-most digit is zero.*/ +z=0 /*the number of trailing zeroes. */ + do v=5 by 0 while v<=N /*calculate # of trailing zeroes.*/ + z=z+N%v /*bump Z if multiple power of 5. */ + v=v*5 /*calculate the next power of 5. */ + end /*while v≤N*/ /* [↑] advance V by ourselves.*/ /*══════════════════════════════════════════════════════════════════════*/ - -say n'! is ['length(!) "digits]:" /*display # of digits in factorial*/ -say /*add some whitespace to output, */ -say ! /* ... and display the ! product.*/ +!=! || copies(0,z) /*add water to rehydrate the !. */ +if z==0 then z='no' /*use gooder English for message.*/ +say N'! is ['length(!) " digits with " z ' trailing zeroes]:' +say /*display blank line (whitespace)*/ +say ! /* ··· and display the ! product.*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Factorial/Rascal/factorial-3.rascal b/Task/Factorial/Rascal/factorial-3.rascal index b8d33750cf..ac0fc94a25 100644 --- a/Task/Factorial/Rascal/factorial-3.rascal +++ b/Task/Factorial/Rascal/factorial-3.rascal @@ -1,5 +1,4 @@ -rascal>factorial_iter(10) -int: 3628800 - -rascal>factorial_iter2(10) -int: 3628800 +public int factorial_rec(int n){ + if(n>1) return n*factorial_rec(n-1); + else return 1; +} diff --git a/Task/Factorial/Scilab/factorial.scilab b/Task/Factorial/Scilab/factorial-1.scilab similarity index 100% rename from Task/Factorial/Scilab/factorial.scilab rename to Task/Factorial/Scilab/factorial-1.scilab diff --git a/Task/Factorial/Scilab/factorial-2.scilab b/Task/Factorial/Scilab/factorial-2.scilab new file mode 100644 index 0000000000..3ba3c7b827 --- /dev/null +++ b/Task/Factorial/Scilab/factorial-2.scilab @@ -0,0 +1,6 @@ +function f=factoriter(n) + f=1 + for i=2:n + f=f*i + end +endfunction diff --git a/Task/Factorial/Scilab/factorial-3.scilab b/Task/Factorial/Scilab/factorial-3.scilab new file mode 100644 index 0000000000..aa5633f2c2 --- /dev/null +++ b/Task/Factorial/Scilab/factorial-3.scilab @@ -0,0 +1,5 @@ +function f=factorrec(n) + if n==0 then f=1 + else f=n*factorrec(n-1) + end +endfunction diff --git a/Task/Factorial/TI-83-BASIC/factorial.ti-83 b/Task/Factorial/TI-83-BASIC/factorial.ti-83 new file mode 100644 index 0000000000..01306e963c --- /dev/null +++ b/Task/Factorial/TI-83-BASIC/factorial.ti-83 @@ -0,0 +1,3 @@ +10→N +N! ---> 362880 +prod(seq(I,I,1,N)) ---> 362880 diff --git a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION index 5f89db5f47..07672ca7e3 100644 --- a/Task/Factors-of-a-Mersenne-number/00DESCRIPTION +++ b/Task/Factors-of-a-Mersenne-number/00DESCRIPTION @@ -1,6 +1,22 @@ -A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, [[Lucas-Lehmer test]]. There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). Some languages already have built-in implementations of this exponent-and-mod operation (called ''modPow'' or similar). The following is how to implement this ''modPow'' yourself: +{{omit from|GUISS}} + +A Mersenne number is a number in the form of 2P-1. + +If P is prime, the Mersenne number may be a Mersenne prime +(if P is not prime, the Mersenne number is also not prime). + +In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, [[Lucas-Lehmer test]]. + +There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1). +Some languages already have built-in implementations of this exponent-and-mod operation (called ''modPow'' or similar). + +The following is how to implement this ''modPow'' yourself: + +For example, let's compute 223 mod 47. +Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. +Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. +Use the result of the modulo from the last step as the initial value of square in the next step: -For example, let's compute 223 mod 47. Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it. Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47. Use the result of the modulo from the last step as the initial value of square in the next step: Remove Optional square top bit multiply by 2 mod 47 ------------ ------- ------------- ------ @@ -10,8 +26,18 @@ For example, let's compute 223 mod 47. Convert the exponent 23 to bin 32*32 = 1024 1 1 1024*2 = 2048 27 27*27 = 729 1 729*2 = 1458 1 -Since 223 mod 47 = 1, 47 is a factor of 2P-1. (To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) Since we've shown that 47 is a factor, 223-1 is not prime. Further properties of Mersenne numbers allow us to refine the process even more. Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. Finally any potential factor q must be [[Primality by Trial Division|prime]]. As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). +Since 223 mod 47 = 1, 47 is a factor of 2P-1. +(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.) +Since we've shown that 47 is a factor, 223-1 is not prime. +Further properties of Mersenne numbers allow us to refine the process even more. +Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8. +Finally any potential factor q must be [[Primality by Trial Division|prime]]. +As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N). These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1. -'''Task:''' Using the above method find a factor of 2929-1 (aka M929) +;Task: +Using the above method find a factor of 2929-1 (aka M929) + +;See also: +* [https://www.youtube.com/watch?v=SNwvJ7psoow Computers in 1948: 2¹²⁷-1]
diff --git a/Task/Factors-of-a-Mersenne-number/00META.yaml b/Task/Factors-of-a-Mersenne-number/00META.yaml index fdeafd347e..c4edec6fe3 100644 --- a/Task/Factors-of-a-Mersenne-number/00META.yaml +++ b/Task/Factors-of-a-Mersenne-number/00META.yaml @@ -1,4 +1,5 @@ --- category: +- Arithmetic - Arithmetic operations note: Prime Numbers diff --git a/Task/Factors-of-a-Mersenne-number/Bracmat/factors-of-a-mersenne-number.bracmat b/Task/Factors-of-a-Mersenne-number/Bracmat/factors-of-a-mersenne-number.bracmat new file mode 100644 index 0000000000..d0114898ae --- /dev/null +++ b/Task/Factors-of-a-Mersenne-number/Bracmat/factors-of-a-mersenne-number.bracmat @@ -0,0 +1,62 @@ +( ( modPow + = square P divisor highbit log 2pow + . !arg:(?P.?divisor) + & 1:?square + & 2\L!P:#%?log+? + & 2^!log:?2pow + & whl + ' ( mod + $ ( ( div$(!P.!2pow):1&2 + | 1 + ) + * !square^2 + . !divisor + ) + : ?square + & mod$(!P.!2pow):?P + & 1/2*!2pow:~/:?2pow + ) + & !square + ) +& ( isPrime + = incs nextincs primeCandidate nextPrimeCandidate quotient + . 1 1 2 2 (4 2 4 2 4 6 2 6:?incs) + : ?nextincs + & 1:?primeCandidate + & ( nextPrimeCandidate + = ( !nextincs:&!incs:?nextincs + | + ) + & !nextincs:%?inc ?nextincs + & !inc+!primeCandidate:?primeCandidate + ) + & whl + ' ( (!nextPrimeCandidate:?divisor)^2:~>!arg + & !arg*!divisor^-1:?quotient:/ + ) + & !quotient:/ + ) +& ( Factors-of-a-Mersenne-Number + = P k candidate bignum + . !arg:?P + & 2^!P+-1:?bignum + & 0:?k + & whl + ' ( 2*(1+!k:?k)*!P+1:?candidate + & !candidate^2:~>!bignum + & ( ~(mod$(!candidate.8):(1|7)) + | ~(isPrime$!candidate) + | modPow$(!P.!candidate):?mp:~1 + ) + ) + & !mp:1 + & (!candidate.(2^!P+-1)*!candidate^-1) + ) +& ( Factors-of-a-Mersenne-Number$929:(?divisorA.?divisorB) + & out + $ ( str + $ ("found some divisors of 2^" !P "-1 : " !divisorA " and " !divisorB) + ) + | out$"no divisors found" + ) +); diff --git a/Task/Factors-of-a-Mersenne-number/Common-Lisp/factors-of-a-mersenne-number-2.lisp b/Task/Factors-of-a-Mersenne-number/Common-Lisp/factors-of-a-mersenne-number-2.lisp index d233bc737b..55b2ea2dcc 100644 --- a/Task/Factors-of-a-Mersenne-number/Common-Lisp/factors-of-a-mersenne-number-2.lisp +++ b/Task/Factors-of-a-Mersenne-number/Common-Lisp/factors-of-a-mersenne-number-2.lisp @@ -1,11 +1,3 @@ -(defun primep (a) - (cond ((= a 2) T) - ((or (<= a 1) (= (mod a 2) 0)) nil) - ((loop for i from 3 to (sqrt a) by 2 do - (if (= (mod a i) 0) - (return nil))) nil) - (T T))) - (defun primep (n) "Is N prime?" (and (> n 1) diff --git a/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d b/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d index 0a6cca326c..a9c00b0fa2 100644 --- a/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d +++ b/Task/Factors-of-a-Mersenne-number/D/factors-of-a-mersenne-number.d @@ -1,7 +1,7 @@ import std.stdio, std.math, std.traits; -ulong mersenneFactor(in ulong p) pure nothrow { - static bool isPrime(T)(in T n) pure nothrow { +ulong mersenneFactor(in ulong p) pure nothrow @nogc { + static bool isPrime(T)(in T n) pure nothrow @nogc { if (n < 2 || n % 2 == 0) return n == 2; for (Unqual!T i = 3; i ^^ 2 <= n; i += 2) @@ -10,7 +10,8 @@ ulong mersenneFactor(in ulong p) pure nothrow { return true; } - static long modPow(in long cb, in long ce,in long m) pure nothrow { + static long modPow(in long cb, in long ce,in long m) + pure nothrow @nogc { long b = cb; long result = 1; for (long e = ce; e > 0; e >>= 1) { diff --git a/Task/Factors-of-a-Mersenne-number/Perl/factors-of-a-mersenne-number-2.pl b/Task/Factors-of-a-Mersenne-number/Perl/factors-of-a-mersenne-number-2.pl index bc44baf888..695416c8d0 100644 --- a/Task/Factors-of-a-Mersenne-number/Perl/factors-of-a-mersenne-number-2.pl +++ b/Task/Factors-of-a-Mersenne-number/Perl/factors-of-a-mersenne-number-2.pl @@ -1,11 +1,30 @@ -M2 = 3 is prime -M2 = 3 is prime -M3 = 7 is prime -M5 = 31 is prime -M7 = 127 is prime -M11 = 2047 = 23 × 89 -M13 = 8191 is prime -... -M53 = 9007199254740991 = 6361 × 1416003655831 -M59 = 576460752303423487 = 179951 × 3203431780337 -M929 = 4538....8911 = 13007 × 348890....84273 +use Math::GMP; + +# Use GMP's simple probable prime test. +sub is_prime { Math::GMP->new(shift)->probab_prime(20); } + +# Lucas-Lehmer test, deterministic for 2^p-1 given p +sub is_mersenne_prime { + my($p, $mp, $s) = ($_[0], Math::GMP->new(2)**$_[0]-1, Math::GMP->new(4)); + return 1 if $p == 2; + $s = ($s * $s - 2) % $mp for 3 .. $p; + $s == 0; +} + +for my $p (2 .. 100, 929) { + next unless is_prime($p); + my $mp = Math::GMP->new(2) ** $p - 1; + my $lim = $mp->bsqrt(); + $lim = 1000000 if $lim > 1000000; # We're using it as a pre-test + my $factor; + for (my $q = Math::GMP->new(2*$p+1); $q <= $lim && !$factor; $q += 2*$p) { + next unless ($q & 7) == 1 || ($q & 7) == 7; + next unless is_prime($q); + $factor = $q if Math::GMP->new(2)->powm_gmp($p,$q) == 1; # $mp % $q == 0 + } + if ($factor) { + print "M$p = $factor * ",$mp/$factor,"\n"; + } else { + print "M$p is ", is_mersenne_prime($p) ? "prime" : "composite", "\n"; + } +} diff --git a/Task/Factors-of-an-integer/Befunge/factors-of-an-integer.bf b/Task/Factors-of-an-integer/Befunge/factors-of-an-integer.bf new file mode 100644 index 0000000000..874b7ceb3f --- /dev/null +++ b/Task/Factors-of-an-integer/Befunge/factors-of-an-integer.bf @@ -0,0 +1,4 @@ +10:p&v: >:0:g%#v_0:g\:0:g/\v + >:0:g:*`| > >0:g1+0:p + >:0:g:*-#v_0:g\>$>:!#@_.v + > ^ ^ ," "< 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 c4c52105e6..e855d51db7 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[] factors(T)(in T n) /*pure nothrow*/ { +T[] factors(T)(in T n) pure nothrow { if (n == 1) return [n]; diff --git a/Task/Factors-of-an-integer/Frink/factors-of-an-integer.frink b/Task/Factors-of-an-integer/Frink/factors-of-an-integer.frink new file mode 100644 index 0000000000..f7675b415a --- /dev/null +++ b/Task/Factors-of-an-integer/Frink/factors-of-an-integer.frink @@ -0,0 +1 @@ +allFactors[n] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs new file mode 100644 index 0000000000..767d88c834 --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-6.hs @@ -0,0 +1,3 @@ +import Data.List +factors n = lows ++ (reverse $ map (div n) lows) + where lows = filter ((== 0) . mod n) [1..truncate . sqrt $ fromIntegral n] diff --git a/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs new file mode 100644 index 0000000000..25781a43b2 --- /dev/null +++ b/Task/Factors-of-an-integer/Haskell/factors-of-an-integer-7.hs @@ -0,0 +1,4 @@ +*Main> :set +s +*Main> factors 120 +[1,2,3,4,5,6,8,10,12,15,20,24,30,40,60,120] +(0.01 secs, 7578656 bytes) diff --git a/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-1.max b/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-1.max new file mode 100644 index 0000000000..c02af0969a --- /dev/null +++ b/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-1.max @@ -0,0 +1,4 @@ +fn factors n = +( + return (for i = 1 to n+1 where mod n i == 0 collect i) +) diff --git a/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-2.max b/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-2.max new file mode 100644 index 0000000000..89ffd6087e --- /dev/null +++ b/Task/Factors-of-an-integer/MAXScript/factors-of-an-integer-2.max @@ -0,0 +1,10 @@ +factors 3 +#(1, 3) +factors 7 +#(1, 7) +factors 14 +#(1, 2, 7, 14) +factors 60 +#(1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30, 60) +factors 54 +#(1, 2, 3, 6, 9, 18, 27, 54) diff --git a/Task/Factors-of-an-integer/Pascal/factors-of-an-integer.pascal b/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-1.pascal similarity index 100% rename from Task/Factors-of-an-integer/Pascal/factors-of-an-integer.pascal rename to Task/Factors-of-an-integer/Pascal/factors-of-an-integer-1.pascal diff --git a/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal b/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal new file mode 100644 index 0000000000..a700739132 --- /dev/null +++ b/Task/Factors-of-an-integer/Pascal/factors-of-an-integer-2.pascal @@ -0,0 +1,36 @@ +program factors; +{Looking for extreme composite numbers: +http://wwwhomes.uni-bielefeld.de/achim/highly.txt} + +const + MAXFACTORCNT = 1920; //number := 3491888400; + +var + FaktorList : array[0..MAXFACTORCNT] of LongWord; + i, number,quot,cnt: LongWord; +begin + writeln('Enter a number between 1 and 4294967295: '); + write('3491888400 is a nice choice '); + readln(number); + + cnt := 0; + i := 1; + repeat + quot := number div i; + if quot *i-number = 0 then + begin + FaktorList[cnt] := i; + FaktorList[MAXFACTORCNT-cnt] := quot; + inc(cnt); + end; + inc(i); + until i> quot; + writeln(number,' has ',2*cnt,' factors'); + dec(cnt); + For i := 0 to cnt do + write(FaktorList[i],' ,'); + For i := cnt downto 1 do + write(FaktorList[MAXFACTORCNT-i],' ,'); +{ the last without ','} + writeln(FaktorList[MAXFACTORCNT]); +end. 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 f9f4ef9aa4..1b78cd3c33 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 @@ -sub factors (Int $n) { - sort uniq - map { $^x, $n div $^x }, - grep { $n %% $^x }, - 1 .. sqrt $n; -} +sub factors (Int $n) { squish sort ($_, $n div $_ if $n %% $_ for 1 .. sqrt $n) } diff --git a/Task/Factors-of-an-integer/Perl/factors-of-an-integer.pl b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-1.pl similarity index 71% rename from Task/Factors-of-an-integer/Perl/factors-of-an-integer.pl rename to Task/Factors-of-an-integer/Perl/factors-of-an-integer-1.pl index a2f4f485ac..d46ffbd6ba 100644 --- a/Task/Factors-of-an-integer/Perl/factors-of-an-integer.pl +++ b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-1.pl @@ -3,4 +3,4 @@ sub factors my($n) = @_; return grep { $n % $_ == 0 }(1 .. $n); } -print join ' ',factors(64); +print join ' ',factors(64), "\n"; diff --git a/Task/Factors-of-an-integer/Perl/factors-of-an-integer-2.pl b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-2.pl new file mode 100644 index 0000000000..f8569767a2 --- /dev/null +++ b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-2.pl @@ -0,0 +1,11 @@ +sub factors { + my $n = shift; + $n = -$n if $n < 0; + my @divisors; + for (1 .. int(sqrt($n))) { # faster and less memory than map/grep + push @divisors, $_ unless $n % $_; + } + # Return divisors including top half, without duplicating a square + @divisors, map { $_*$_ == $n ? () : int($n/$_) } reverse @divisors; +} +print join " ", factors(64), "\n"; diff --git a/Task/Factors-of-an-integer/Perl/factors-of-an-integer-3.pl b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-3.pl new file mode 100644 index 0000000000..21e463d716 --- /dev/null +++ b/Task/Factors-of-an-integer/Perl/factors-of-an-integer-3.pl @@ -0,0 +1,3 @@ +use ntheory qw/divisors/; +print join " ", divisors(12345678), "\n"; +# Alternately something like: fordivisors { say } 12345678; diff --git a/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-1.pro b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-1.pro new file mode 100644 index 0000000000..8dfc60d29c --- /dev/null +++ b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-1.pro @@ -0,0 +1,5 @@ +brute_force_factors( N , Fs ) :- + integer(N) , + N > 0 , + setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs ) + . diff --git a/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-2.pro b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-2.pro new file mode 100644 index 0000000000..04fef90dfa --- /dev/null +++ b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-2.pro @@ -0,0 +1,12 @@ +smart_factors(N,Fs) :- + integer(N) , + N > 0 , + setof( F , factor(N,F) , Fs ) + . + +factor(N,F) :- + L is floor(sqrt(N)) , + between(1,L,X) , + 0 =:= N mod X , + ( F = X ; F is N // X ) + . diff --git a/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-3.pro b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-3.pro new file mode 100644 index 0000000000..a3b17cd801 --- /dev/null +++ b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer-3.pro @@ -0,0 +1,15 @@ +between(X,Y,Z) :- + integer(X) , + integer(Y) , + X =< Z , + between1(X,Y,Z) + . + +between1(X,Y,X) :- + X =< Y + . +between1(X,Y,Z) :- + X < Y , + X1 is X+1 , + between1(X1,Y,Z) + . diff --git a/Task/Factors-of-an-integer/Prolog/factors-of-an-integer.pro b/Task/Factors-of-an-integer/Prolog/factors-of-an-integer.pro deleted file mode 100644 index a9279ebfe1..0000000000 --- a/Task/Factors-of-an-integer/Prolog/factors-of-an-integer.pro +++ /dev/null @@ -1,26 +0,0 @@ -factor(N, L) :- - factor(N, 1, [], L). - -factor(N, X, LC, L) :- - 0 is N mod X, - !, - Q is N / X, - (Q = X -> - sort([Q | LC], L) - ; - (Q > X -> - X1 is X+1, - factor(N, X1, [X, Q|LC], L) - ; - sort(LC, L) - ) - ). - -factor(N, X, LC, L) :- - Q is N / X, - (Q > X -> - X1 is X+1, - factor(N, X1, LC, L) - ; - sort(LC, L) - ). diff --git a/Task/Factors-of-an-integer/Python/factors-of-an-integer-4.py b/Task/Factors-of-an-integer/Python/factors-of-an-integer-4.py index 2104905adb..5c26450771 100644 --- a/Task/Factors-of-an-integer/Python/factors-of-an-integer-4.py +++ b/Task/Factors-of-an-integer/Python/factors-of-an-integer-4.py @@ -1,13 +1,18 @@ -def factor(n): - a, r = 1, [1] - while a * a < n: - a += 1 - if n % a: continue - b, f = 1, [] - while n % a == 0: - n //= a - b *= a - f += [i * b for i in r] - r += f - if n > 1: r += [i * n for i in r] - return r +from itertools import chain, cycle, accumulate # last of which is Python 3 only + +def factors(n): + def prime_powers(n): + # c goes through 2, 3, 5, then the infinite (6n+1, 6n+5) series + for c in accumulate(chain([2, 1, 2], cycle([2,4]))): + if c*c > n: break + if n%c: continue + d,p = (), c + while not n%c: + n,p,d = n//c, p*c, d + (p,) + yield(d) + if n > 1: yield((n,)) + + r = [1] + for e in prime_powers(n): + r += [a*b for a in r for b in e] + return r 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 68fe00ea39..d90e12635c 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,21 +1,23 @@ -/*REXX program displays (in order) the divisors of positive integer(s).*/ +/*REXX pgm displays divisors of any (negative/zero/positive) integers.*/ @.=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 // ?*/ +parse arg low high inc . /*get optional args. */ +high=word(high low 20,1); low=word(low 1,1); inc=word(inc 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.*/ +say copies('─',1+w) '─────────' copies('─' ,60) /*separator.*/ - do n=low to high by step; divs=divisors(n); #=words(divs) - say right(n,w)" " center('('#")",9) "──► " @.# ' ' divs - end /*n*/ + do n=low to high by inc; divs=divisors(n); #=words(divs); p=@.# + if divs=='infinite' then #='∞'; if n<1 then p=@.. /*handle N<1*/ + say right(n,w)" " center('['#"]",9) "──► " p ' ' divs + end /*n*/ /* [↑] process a range of ints.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────DIVISORS subroutine─────────────────*/ -divisors: procedure; parse arg x 1 b; if x=1 then return 1; odd=x//2 -a=1 /* [↓] use only EVEN or ODD ints.*/ +divisors: procedure; parse arg x; x=abs(x); if x==1 then return 1; b=x +if x==0 then return 'infinite'; odd=x//2 +a=1 /* [↓] use only EVEN|ODD integers*/ do j=2+odd by 1+odd while j*j +The most general case allows for complex numbers at the input +and results in a sequence of equal length, again of complex numbers. +If you need to restrict yourself to real numbers, the output should +be the magnitude (i.e. sqrt(re²+im²)) of the complex result. + +The classic version is the recursive Cooley–Tukey FFT. [http://en.wikipedia.org/wiki/Cooley–Tukey_FFT_algorithm Wikipedia] has pseudocode for that. +Further optimizations are possible but not required. diff --git a/Task/Fast-Fourier-transform/C/fast-fourier-transform.c b/Task/Fast-Fourier-transform/C/fast-fourier-transform.c new file mode 100644 index 0000000000..72d8ca2a80 --- /dev/null +++ b/Task/Fast-Fourier-transform/C/fast-fourier-transform.c @@ -0,0 +1,50 @@ +#include +#include +#include + +double PI; +typedef double complex cplx; + +void _fft(cplx buf[], cplx out[], int n, int step) +{ + if (step < n) { + _fft(out, buf, n, step * 2); + _fft(out + step, buf + step, n, step * 2); + + for (int i = 0; i < n; i += 2 * step) { + cplx t = cexp(-I * PI * i / n) * out[i + step]; + buf[i / 2] = out[i] + t; + buf[(i + n)/2] = out[i] - t; + } + } +} + +void fft(cplx buf[], int n) +{ + cplx out[n]; + for (int i = 0; i < n; i++) out[i] = buf[i]; + + _fft(buf, out, n, 1); +} + + +void show(const char * s, cplx buf[]) { + printf("%s", s); + for (int i = 0; i < 8; i++) + if (!cimag(buf[i])) + printf("%g ", creal(buf[i])); + else + printf("(%g, %g) ", creal(buf[i]), cimag(buf[i])); +} + +int main() +{ + PI = atan2(1, 1) * 4; + cplx buf[] = {1, 1, 1, 1, 0, 0, 0, 0}; + + show("Data: ", buf); + fft(buf, 8); + show("\nFFT : ", buf); + + return 0; +} diff --git a/Task/Fast-Fourier-transform/D/fast-fourier-transform-1.d b/Task/Fast-Fourier-transform/D/fast-fourier-transform-1.d index 78f39d361b..9d74699dbb 100644 --- a/Task/Fast-Fourier-transform/D/fast-fourier-transform-1.d +++ b/Task/Fast-Fourier-transform/D/fast-fourier-transform-1.d @@ -1,5 +1,5 @@ -import std.stdio, std.numeric; - void main() { + import std.stdio, std.numeric; + [1.0, 1, 1, 1, 0, 0, 0, 0].fft.writeln; } 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 af02ce26a3..0ac4a73dfe 100644 --- a/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d +++ b/Task/Fast-Fourier-transform/D/fast-fourier-transform-2.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range, std.math; -const(creal)[] fft(in creal[] x) /*pure nothrow*/ { +const(creal)[] fft(in creal[] x) pure /*nothrow*/ @safe { immutable N = x.length; if (N <= 1) return x; const ev = x.stride(2).array.fft; @@ -10,6 +10,6 @@ const(creal)[] fft(in creal[] x) /*pure nothrow*/ { return l.chain(r).array; } -void main() { +void main() @safe { [1.0L+0i, 1, 1, 1, 0, 0, 0, 0].fft.writeln; } diff --git a/Task/Fast-Fourier-transform/D/fast-fourier-transform-3.d b/Task/Fast-Fourier-transform/D/fast-fourier-transform-3.d index d52bbcbff5..53e24cf7ff 100644 --- a/Task/Fast-Fourier-transform/D/fast-fourier-transform-3.d +++ b/Task/Fast-Fourier-transform/D/fast-fourier-transform-3.d @@ -1,13 +1,13 @@ import std.stdio, std.algorithm, std.range, std.math, std.complex; -auto fft(T)(in T[] x) /*pure nothrow*/ { +auto fft(T)(in T[] x) pure /*nothrow @safe*/ { immutable N = x.length; if (N <= 1) return x; const ev = x.stride(2).array.fft; const od = x[1 .. $].stride(2).array.fft; alias E = std.complex.expi; - auto l = iota(N / 2).map!(k=> ev[k] + cast(T)E(-2*PI*k/N) * od[k]); - auto r = iota(N / 2).map!(k=> ev[k] - cast(T)E(-2*PI*k/N) * od[k]); + auto l = iota(N / 2).map!(k => ev[k] + T(E(-2* PI * k/N)) * od[k]); + auto r = iota(N / 2).map!(k => ev[k] - T(E(-2* PI * k/N)) * od[k]); return l.chain(r).array; } diff --git a/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-1.js b/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-1.js new file mode 100644 index 0000000000..50db973bf0 --- /dev/null +++ b/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-1.js @@ -0,0 +1,66 @@ +/* +complex fast fourier transform and inverse from +http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B +*/ +function icfft(amplitudes) +{ + var N = amplitudes.length; + var iN = 1 / N; + + //conjugate if imaginary part is not 0 + for(var i = 0 ; i < N; ++i) + if(amplitudes[i] instanceof Complex) + amplitudes[i].im = -amplitudes[i].im; + + //apply fourier transform + amplitudes = cfft(amplitudes) + + for(var i = 0 ; i < N; ++i) + { + //conjugate again + amplitudes[i].im = -amplitudes[i].im; + //scale + amplitudes[i].re *= iN; + amplitudes[i].im *= iN; + } + return amplitudes; +} + +function cfft(amplitudes) +{ + var N = amplitudes.length; + if( N <= 1 ) + return amplitudes; + + var hN = N / 2; + var even = []; + var odd = []; + even.length = hN; + odd.length = hN; + for(var i = 0; i < hN; ++i) + { + even[i] = amplitudes[i*2]; + odd[i] = amplitudes[i*2+1]; + } + even = cfft(even); + odd = cfft(odd); + + var a = -2*Math.PI; + for(var k = 0; k < hN; ++k) + { + if(!(even[k] instanceof Complex)) + even[k] = new Complex(even[k], 0); + if(!(odd[k] instanceof Complex)) + odd[k] = new Complex(odd[k], 0); + var p = k/N; + var t = new Complex(0, a * p); + t.cexp(t).mul(odd[k], t); + amplitudes[k] = even[k].add(t, odd[k]); + amplitudes[k + hN] = even[k].sub(t, even[k]); + } + return amplitudes; +} + +//test code +//console.log( cfft([1,1,1,1,0,0,0,0]) ); +//console.log( icfft(cfft([1,1,1,1,0,0,0,0])) ); diff --git a/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-2.js b/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-2.js new file mode 100644 index 0000000000..530bf5112b --- /dev/null +++ b/Task/Fast-Fourier-transform/JavaScript/fast-fourier-transform-2.js @@ -0,0 +1,50 @@ +/* +basic complex number arithmetic from +http://rosettacode.org/wiki/Fast_Fourier_transform#Scala +*/ +function Complex(re, im) +{ + this.re = re; + this.im = im || 0.0; +} +Complex.prototype.add = function(other, dst) +{ + dst.re = this.re + other.re; + dst.im = this.im + other.im; + return dst; +} +Complex.prototype.sub = function(other, dst) +{ + dst.re = this.re - other.re; + dst.im = this.im - other.im; + return dst; +} +Complex.prototype.mul = function(other, dst) +{ + //cache re in case dst === this + var r = this.re * other.re - this.im * other.im; + dst.im = this.re * other.im + this.im * other.re; + dst.re = r; + return dst; +} +Complex.prototype.cexp = function(dst) +{ + var er = Math.exp(this.re); + dst.re = er * Math.cos(this.im); + dst.im = er * Math.sin(this.im); + return dst; +} +Complex.prototype.log = function() +{ + /* + although 'It's just a matter of separating out the real and imaginary parts of jw.' is not a helpful quote + the actual formula I found here and the rest was just fiddling / testing and comparing with correct results. + http://cboard.cprogramming.com/c-programming/89116-how-implement-complex-exponential-functions-c.html#post637921 + */ + if( !this.re ) + console.log(this.im.toString()+'j'); + else if( this.im < 0 ) + console.log(this.re.toString()+this.im.toString()+'j'); + else + console.log(this.re.toString()+'+'+this.im.toString()+'j'); +} 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 a829282448..e044fe05dd 100644 --- a/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 +++ b/Task/Fast-Fourier-transform/Perl-6/fast-fourier-transform.pl6 @@ -1,9 +1,8 @@ sub fft { return @_ if @_ == 1; - my @evn = fft( @_[0,2...^* >= @_] ); - my @odd = fft( @_[1,3...^* >= @_] ); - my $twd = 2i * pi / @_; # twiddle factor - @odd[$_] *= exp( $_ * $twd ) for ^@odd; + my @evn = fft( @_[0, 2 ... *] ); + my @odd = fft( @_[1, 3 ... *] ) Z* + (1, * * cis( 2 * pi / @_ ) ... *); return @evn »+« @odd, @evn »-« @odd; } diff --git a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl index c95f81965f..6e03ad7e35 100644 --- a/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl +++ b/Task/Fast-Fourier-transform/Perl/fast-fourier-transform.pl @@ -4,13 +4,13 @@ use Math::Complex; sub fft { return @_ if @_ == 1; - my @evn = fft(@_[grep { not $_ % 2 } 0 .. @_ - 1]); - my @odd = fft(@_[grep { $_ % 2 } 1 .. @_ - 1]); + my @evn = fft(@_[grep { not $_ % 2 } 0 .. $#_ ]); + my @odd = fft(@_[grep { $_ % 2 } 1 .. $#_ ]); my $twd = 2*i* pi / @_; - $odd[$_] *= exp( $_ * $twd ) for 0 .. @odd - 1; + $odd[$_] *= exp( $_ * $twd ) for 0 .. $#odd; return - (map { $evn[$_] + $odd[$_] } 0 .. @evn-1 ), - (map { $evn[$_] - $odd[$_] } 0 .. @evn-1 ); + (map { $evn[$_] + $odd[$_] } 0 .. $#evn ), + (map { $evn[$_] - $odd[$_] } 0 .. $#evn ); } diff --git a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py index fc0151d1d4..ded43e91aa 100644 --- a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py +++ b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-1.py @@ -3,9 +3,11 @@ from cmath import exp, pi def fft(x): N = len(x) if N <= 1: return x - even = fft(x[0::2]) - odd = fft(x[1::2]) - return [even[k] + exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] + \ - [even[k] - exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] + even = fft2(x[0::2]) + odd = fft2(x[1::2]) + T= [exp(-2j*pi*k/N)*odd[k] for k in xrange(N/2)] + return [even[k] + T[k] for k in xrange(N/2)] + \ + [even[k] - T[k] for k in xrange(N/2)] -print fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]) +print( ' '.join("%5.3f" % abs(f) + for f in fft([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0])) ) diff --git a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-2.py b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-2.py index 33534e7988..bdad2108b3 100644 --- a/Task/Fast-Fourier-transform/Python/fast-fourier-transform-2.py +++ b/Task/Fast-Fourier-transform/Python/fast-fourier-transform-2.py @@ -1,5 +1,5 @@ >>> from numpy.fft import fft >>> from numpy import array ->>> a = array((0.0, 0.924, 0.707, -0.383, -1.0, -0.383, 0.707, 0.924, 0.0, -0.924, -0.707, 0.383, 1.0, 0.383, -0.707, -0.924)) +>>> a = array([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0]) >>> print( ' '.join("%5.3f" % abs(f) for f in fft(a)) ) -0.000 0.001 0.000 8.001 0.000 0.001 0.000 0.001 0.000 0.001 0.000 0.001 0.000 8.001 0.000 0.001 +4.000 2.613 0.000 1.082 0.000 1.082 0.000 2.613 diff --git a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx index 524b15aba4..44c9c6177e 100644 --- a/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx +++ b/Task/Fast-Fourier-transform/REXX/fast-fourier-transform.rexx @@ -1,56 +1,60 @@ /*REXX pgm does a fast Fourier transform (FFT) on a set of complex nums.*/ numeric digits length( pi() ) - 1 /*limited by PI function result. */ -arg data; if data='' then data='1 1 1 1 0' /*no data? Then use default*/ -data=translate(data, 'J', "I") /*allow use of i as well as j */ +arg data /*the ARG verb uppercases DATA */ +if data='' then data=1 1 1 1 0 /*No data? Then use the default.*/ +data=translate(data, 'J', "I") /*allow use of I as well as J */ size=words(data); pad=left('',6) /*PAD: for indenting/padding SAYs*/ - do sig=0 until 2**sig>=size ;end /* # args exactly a power of 2?*/ - do j=size+1 to 2**sig;data=data 0;end /*add zeroes until a power of 2.*/ -size=words(data); call hdr /*┌─────────────────────────────┐*/ + do p=0 until 2**p>=size ; end /* # args exactly a power of 2? */ + do j=size+1 to 2**p;data=data 0; end /*add zeroes until a power of 2. */ +size=words(data); ph=p%2; call hdr /*┌─────────────────────────────┐*/ /*│ Numbers in data can be in │*/ do j=0 for size /*│ 7 formats: real │*/ _=word(data,j+1) /*│ real,imag │*/ - parse var _ #.1.j ',' #.2.j /*│ ,imag │*/ - if right(#.1.j,1)=='J' then /*│ nnnJ │*/ - parse var #.1.j #2.j "J" @.1.j /*│ nnnj │*/ - do p=1 for 2 /*omitted?*/ /*│ nnnI │*/ - #.p.j=word(#.p.j 0, 1) /*│ nnni │*/ - end /*p*/ /*└─────────────────────────────┘*/ + parse var _ #.1.j ',' #.2.j /*│ ,imag │*/ + if right(#.1.j,1)=='J' then parse , /*│ nnnJ │*/ + var #.1.j #2.j "J" @.1.j /*│ nnnj │*/ + do m=1 for 2 /*omitted?*/ /*│ nnnI │*/ + #.m.j=word(#.m.j 0, 1) /*│ nnni │*/ + end /*m*/ /*└─────────────────────────────┘*/ + say pad " FFT in " center(j+1,7) pad nice(#.1.j) nice(#.2.j,'i') end /*j*/ -say; say; tran=2*pi()/2**sig; !.=0 -hsig=2**sig%2; counterA=2**(sig-sig%2); pointer=counterA; doubler=1 +say; say; tran=2*pi()/2**p; !.=0 +hp=2**p%2; counterA=2**(p-ph); pointer=counterA; doubler=1 + + do p-ph; halfpointer=pointer%2 - do sig-sig%2; halfpointer=pointer%2 do i=halfpointer by pointer to counterA-halfpointer - _=i-halfpointer; !.i=!._+doubler + _=i-halfpointer; !.i=!._+doubler end /*i*/ - doubler=doubler*2; pointer=halfpointer - end /*sig-sig%2*/ - do j=0 to 2**sig%4; cmp.j=cos(j*tran); _m=hsig-j; cmp._m=-cmp.j - _p=hsig+j; cmp._p=-cmp.j - end /*j*/ + doubler=doubler*2; pointer=halfpointer + end /*p-ph*/ -counterB=2**(sig%2) + do j=0 to 2**p%4; cmp.j=cos(j*tran); _m=hp-j; cmp._m=-cmp.j + _p=hp+j; cmp._p=-cmp.j + end /*j*/ - do i=0 for counterA; p=i*counterB - do j=0 for counterB; h=p+j; _=!.j*counterB+!.i; if _<=h then iterate +counterB=2**ph + + do i=0 for counterA; q=i *counterB + do j=0 for counterB; h=q+j; _=!.j*counterB+!.i; if _<=h then iterate parse value #.1._ #.1.h #.2._ #.2.h with #.1.h #.1._ #.2.h #.2._ - end /*j*/ /* [↓] switch two sets of values*/ + end /*j*/ /* [↑] switch two sets of values*/ end /*i*/ -double=1; do sig ; w=2**sig%2%double - do k=0 for double ; lb=w*k ; lh=lb+2**sig%4 - do j=0 for w ; a=j*double*2+k ; b=a+double - r=#.1.a; i=#.2.a ; c1=cmp.lb*#.1.b ; c4=cmp.lb*#.2.b - c2=cmp.lh*#.2.b ; c3=cmp.lh*#.1.b - #.1.a=r+c1-c2 ; #.2.a=i+c3+c4 - #.1.b=r-c1+c2 ; #.2.b=i-c3-c4 +double=1; do p ; w=hp%double + do k=0 for double; lb=w*k ; lh=lb+2**p%4 + do j=0 for w ; a=j*double*2+k ; b=a+double + r=#.1.a; i=#.2.a ; c1=cmp.lb*#.1.b ; c4=cmp.lb*#.2.b + c2=cmp.lh*#.2.b ; c3=cmp.lh*#.1.b + #.1.a=r+c1-c2 ; #.2.a=i+c3+c4 + #.1.b=r-c1+c2 ; #.2.b=i-c3-c4 end /*j*/ end /*k*/ double=double+double - end /*sig*/ + end /*p*/ call hdr do i=0 for size say pad " FFT out " center(i+1,7) pad nice(#.1.i) nice(#.2.i,'j') diff --git a/Task/Fast-Fourier-transform/Racket/fast-fourier-transform.rkt b/Task/Fast-Fourier-transform/Racket/fast-fourier-transform.rkt new file mode 100644 index 0000000000..69c72874ad --- /dev/null +++ b/Task/Fast-Fourier-transform/Racket/fast-fourier-transform.rkt @@ -0,0 +1,3 @@ +#lang racket +(require math) +(array-fft (array #[1. 1. 1. 1. 0. 0. 0. 0.])) diff --git a/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb b/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb index ae7723d4c8..05d3bd1c26 100644 --- a/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb +++ b/Task/Fast-Fourier-transform/Ruby/fast-fourier-transform.rb @@ -3,8 +3,8 @@ def fft(vec) evens_odds = vec.partition.with_index{|_,i| i.even?} evens, odds = evens_odds.map{|even_odd| fft(even_odd)*2} evens.zip(odds).map.with_index do |(even, odd),i| - even + odd * Math::E ** Complex(0, 2 * Math::PI * (-i)/ vec.size) + even + odd * Math::E ** Complex(0, -2 * Math::PI * i / vec.size) end end -fft([1,1,1,1,0,0,0,0]).each{|c| p c} +fft([1,1,1,1,0,0,0,0]).each{|c| puts "%9.6f %+9.6fi" % c.rect} diff --git a/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-1.scala b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-1.scala new file mode 100644 index 0000000000..d96a64f995 --- /dev/null +++ b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-1.scala @@ -0,0 +1,25 @@ +import scala.math.{ Pi, cos, sin, cosh, sinh, abs } + +case class Complex(re: Double, im: Double) { + def +(x: Complex): Complex = Complex(re + x.re, im + x.im) + def -(x: Complex): Complex = Complex(re - x.re, im - x.im) + def *(x: Double): Complex = Complex(re * x, im * x) + def *(x: Complex): Complex = Complex(re * x.re - im * x.im, re * x.im + im * x.re) + def /(x: Double): Complex = Complex(re / x, im / x) + + override def toString(): String = { + val a = "%1.3f" format re + val b = "%1.3f" format abs(im) + (a,b) match { + case (_, "0.000") => a + case ("0.000", _) => b + "i" + case (_, _) if im > 0 => a + " + " + b + "i" + case (_, _) => a + " - " + b + "i" + } + } +} + +def exp(c: Complex) : Complex = { + val r = (cosh(c.re) + sinh(c.re)) + Complex(cos(c.im), sin(c.im)) * r +} diff --git a/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-2.scala b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-2.scala new file mode 100644 index 0000000000..390a79fca5 --- /dev/null +++ b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-2.scala @@ -0,0 +1,25 @@ +def _fft(cSeq: Seq[Complex], direction: Complex, scalar: Int): Seq[Complex] = { + if (cSeq.length == 1) { + return cSeq + } + val n = cSeq.length + assume(n % 2 == 0, "The Cooley-Tukey FFT algorithm only works when the length of the input is even.") + + val evenOddPairs = cSeq.grouped(2).toSeq + val evens = _fft(evenOddPairs map (_(0)), direction, scalar) + val odds = _fft(evenOddPairs map (_(1)), direction, scalar) + + def leftRightPair(k: Int): Pair[Complex, Complex] = { + val base = evens(k) / scalar + val offset = exp(direction * (Pi * k / n)) * odds(k) / scalar + (base + offset, base - offset) + } + + val pairs = (0 until n/2) map leftRightPair + val left = pairs map (_._1) + val right = pairs map (_._2) + left ++ right +} + +def fft(cSeq: Seq[Complex]): Seq[Complex] = _fft(cSeq, Complex(0, 2), 1) +def rfft(cSeq: Seq[Complex]): Seq[Complex] = _fft(cSeq, Complex(0, -2), 2) diff --git a/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-3.scala b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-3.scala new file mode 100644 index 0000000000..88a8eb7bb5 --- /dev/null +++ b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform-3.scala @@ -0,0 +1,5 @@ +val data = Seq(Complex(1,0), Complex(1,0), Complex(1,0), Complex(1,0), + Complex(0,0), Complex(0,2), Complex(0,0), Complex(0,0)) + +println(fft(data)) +println(rfft(fft(data))) diff --git a/Task/Fast-Fourier-transform/Scala/fast-fourier-transform.scala b/Task/Fast-Fourier-transform/Scala/fast-fourier-transform.scala deleted file mode 100644 index 08ae1d4449..0000000000 --- a/Task/Fast-Fourier-transform/Scala/fast-fourier-transform.scala +++ /dev/null @@ -1,32 +0,0 @@ -object FFT extends App { - import scala.math._ - - case class Complex(re: Double, im: Double = 0.0) { - def +(x: Complex): Complex = Complex((this.re+x.re),(this.im+x.im)) - def -(x: Complex): Complex = Complex((this.re-x.re),(this.im-x.im)) - def *(x: Complex): Complex = Complex(this.re*x.re-this.im*x.im,this.re*x.im+this.im*x.re) - } - - def fft(f: List[Complex]): List[Complex] = { - import Stream._ - require((f.size==0)||(from(0) map {x=>pow(2,x).toInt}).takeWhile(_<2*f.size).toList.exists(_==f.size)==true,"list size "+f.size+" not allowed!") - f.size match { - case 0 => Nil - case 1 => f - case n => { - val cis: Double => Complex = phi => Complex(cos(phi),sin(phi)) - val e = fft(f.zipWithIndex.filter(_._2%2==0).map(_._1)) - val o = fft(f.zipWithIndex.filter(_._2%2!=0).map(_._1)) - import scala.collection.mutable.ListBuffer - val lb = new ListBuffer[Pair[Int, Complex]]() - for (k <- 0 to n/2-1) { - lb += Pair(k,e(k)+o(k)*cis(-2*Pi*k/n)) - lb += Pair(k+n/2,e(k)-o(k)*cis(-2*Pi*k/n)) - } - lb.toList.sortWith((x,y)=>x._1 +#include + +// This class forms a simple 'generator', where operator() returns the next +// element in the series. It uses a small sliding window buffer to minimize +// storage overhead. +class nacci_t +{ + std::vector< int > history; + unsigned windex; // sliding window index + unsigned rindex; // result index + int running_sum; // sum of values in sliding window + + public: + + nacci_t( unsigned int order, int a0 = 1, int a1 = 1 ) + : history( order + 1 ), windex( 0 ), rindex( order - 1 ), + running_sum( a0 + a1 ) + { + // intialize sliding window + history[order - 1] = a0; + history[order - 0] = a1; + } + + int operator()() + { + int result = history[ rindex ]; // get 'nacci number to return + running_sum -= history[ windex ]; // old 'nacci falls out of window + + history[ windex ] = running_sum; // new 'nacci enters the window + running_sum += running_sum; // new 'nacci added to the sum + + if ( ++windex == history.size() ) windex = 0; + if ( ++rindex == history.size() ) rindex = 0; + + return result; + } +}; + +int main() +{ + for ( unsigned int i = 2; i <= 10; ++i ) + { + nacci_t nacci( i ); // fibonacci sequence + + std::cout << "nacci( " << i << " ): "; + + for ( int j = 0; j < 10; ++j ) + std::cout << " " << nacci(); + + std::cout << std::endl; + } + + for ( unsigned int i = 2; i <= 10; ++i ) + { + nacci_t lucas( i, 2, 1 ); // Lucas sequence + + std::cout << "lucas( " << i << " ): "; + + for ( int j = 0; j < 10; ++j ) + std::cout << " " << lucas(); + + std::cout << std::endl; + } +} diff --git a/Task/Fibonacci-n-step-number-sequences/C-sharp/fibonacci-n-step-number-sequences.cs b/Task/Fibonacci-n-step-number-sequences/C-sharp/fibonacci-n-step-number-sequences.cs new file mode 100644 index 0000000000..2d483cbdbb --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/C-sharp/fibonacci-n-step-number-sequences.cs @@ -0,0 +1,84 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Fibonacci +{ + class Program + { + static void Main(string[] args) + { + PrintNumberSequence("Fibonacci", GetNnacciNumbers(2, 10)); + PrintNumberSequence("Lucas", GetLucasNumbers(10)); + PrintNumberSequence("Tribonacci", GetNnacciNumbers(3, 10)); + PrintNumberSequence("Tetranacci", GetNnacciNumbers(4, 10)); + Console.ReadKey(); + } + + private static IList GetLucasNumbers(int length) + { + IList seedSequence = new List() { 2, 1 }; + return GetFibLikeSequence(seedSequence, length); + } + + private static IList GetNnacciNumbers(int seedLength, int length) + { + return GetFibLikeSequence(GetNacciSeed(seedLength), length); + } + + private static IList GetNacciSeed(int seedLength) + { + IList seedSquence = new List() { 1 }; + + for (uint i = 0; i < seedLength - 1; i++) + { + seedSquence.Add((ulong)Math.Pow(2, i)); + } + + return seedSquence; + } + + private static IList GetFibLikeSequence(IList seedSequence, int length) + { + IList sequence = new List(); + + int count = seedSequence.Count(); + + if (length <= count) + { + sequence = seedSequence.Take((int)length).ToList(); + } + else + { + sequence = seedSequence; + + for (int i = count; i < length; i++) + { + ulong num = 0; + + for (int j = 0; j < count; j++) + { + num += sequence[sequence.Count - 1 - j]; + } + + sequence.Add(num); + } + } + + return sequence; + } + + private static void PrintNumberSequence(string Title, IList numbersequence) + { + StringBuilder output = new StringBuilder(Title).Append(" "); + + foreach (long item in numbersequence) + { + output.AppendFormat("{0}, ", item); + } + + Console.WriteLine(output.ToString()); + } + } +} diff --git a/Task/Fibonacci-n-step-number-sequences/Common-Lisp/fibonacci-n-step-number-sequences.lisp b/Task/Fibonacci-n-step-number-sequences/Common-Lisp/fibonacci-n-step-number-sequences.lisp new file mode 100644 index 0000000000..941e99739f --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Common-Lisp/fibonacci-n-step-number-sequences.lisp @@ -0,0 +1,18 @@ +(defun gen-fib (lst m) + "Return the first m members of a generalized Fibonacci sequence using lst as initial values + and the length of lst as step." + (let ((l (- (length lst) 1))) + (do* ((fib-list (reverse lst) (cons (loop for i from 0 to l sum (nth i fib-list)) fib-list)) + (c (+ l 2) (+ c 1))) + ((> c m) (reverse fib-list))))) + +(defun initial-values (n) + "Return the initial values of the Fibonacci n-step sequence" + (cons 1 + (loop for i from 0 to (- n 2) + collect (expt 2 i)))) + +(defun start () + (format t "Lucas series: ~a~%" (gen-fib '(2 1) 10)) + (loop for i from 2 to 4 + do (format t "Fibonacci ~a-step sequence: ~a~%" i (gen-fib (initial-values i) 10)))) diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d index 3ff57095b5..2792ed2f16 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-1.d @@ -4,12 +4,12 @@ void main() { const(int)[] memo; size_t addNum; - void setHead(int[] head) nothrow { + void setHead(int[] head) nothrow @safe { memo = head; addNum = head.length; } - int fibber(in size_t n) nothrow { + int fibber(in size_t n) nothrow @safe { if (n >= memo.length) memo ~= iota(n - addNum, n).map!fibber.sum; return memo[n]; @@ -21,8 +21,7 @@ void main() { 10.iota.map!fibber.writeln; const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - //foreach (immutable n, const name; prefixes.split.enumerate(2)) { - foreach (immutable n, name; iota(2, 11).zip(prefixes.split)) { + foreach (immutable n, const name; prefixes.split.enumerate(2)) { setHead(1 ~ iota(n - 1).map!q{2 ^^ a}.array); writefln("n=%2d, %5snacci -> %(%d %) ...", n, name, 15.iota.map!fibber); diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d index a353bc2e94..c483d1422d 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-2.d @@ -4,12 +4,12 @@ struct fiblike(T) { const(T)[] memo; immutable size_t addNum; - this(in T[] start) /*nothrow*/ { + this(in T[] start) nothrow @safe { this.memo = start.dup; this.addNum = start.length; } - T opCall(in size_t n) /*nothrow*/ { + T opCall(in size_t n) nothrow @safe { if (n >= memo.length) memo ~= iota(n - addNum, n) .map!(i => opCall(i)) @@ -27,8 +27,7 @@ void main() { iota(10).map!lucas.writeln; const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - //foreach (immutable n, const name; prefixes.split.enumerate(2)) { - foreach (immutable n, name; iota(2, 11).zip(prefixes.split)) { + foreach (immutable n, const name; prefixes.split.enumerate(2)) { auto fib = fiblike!int(1 ~ iota(n - 1).map!q{2 ^^ a}.array); writefln("n=%2d, %5snacci -> %(%d %) ...", n, name, 15.iota.map!fib); diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d index eb519cb273..1890da363c 100644 --- a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-3.d @@ -11,7 +11,7 @@ struct Fiblike(T) { return result; } foreach (immutable i; tail.length.iota.cycle) { - immutable x = cast(int)tail.sum; + immutable x = tail.sum; result = dg(x); if (result) break; @@ -37,8 +37,7 @@ void main() { Fiblike!int([2, 1]).takeApply(10).writeln; const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; - //foreach (immutable n, const name; prefixes.split.enumerate(2)) { - foreach (const n, name; iota(2, 11).zip(prefixes.split)) { + foreach (immutable n, const name; prefixes.split.enumerate(2)) { auto fib = Fiblike!int(1 ~ iota(n - 1).map!q{2 ^^ a}.array); writefln("n=%2d, %5snacci -> %s", n, name, fib.takeApply(15)); } diff --git a/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-4.d b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-4.d new file mode 100644 index 0000000000..6254e6c847 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/D/fibonacci-n-step-number-sequences-4.d @@ -0,0 +1,19 @@ +void main() { + import std.stdio, std.algorithm, std.range, std.concurrency; + + immutable fibLike = (int[] tail) => new Generator!int({ + foreach (x; tail) + yield(x); + foreach (immutable i; tail.length.iota.cycle) + yield(tail[i] = tail.sum); + }); + + foreach (seed; [[1, 1], [2, 1]]) + fibLike(seed).take(10).writeln; + + immutable prefixes = "fibo tribo tetra penta hexa hepta octo nona deca"; + foreach (immutable n, const name; prefixes.split.enumerate(2)) { + auto fib = fibLike(1 ~ iota(n - 1).map!q{2 ^^ a}.array); + writefln("n=%2d, %5snacci -> %(%s, %), ...", n, name, fib.take(15)); + } +} diff --git a/Task/Fibonacci-n-step-number-sequences/Fortran/fibonacci-n-step-number-sequences.f b/Task/Fibonacci-n-step-number-sequences/Fortran/fibonacci-n-step-number-sequences.f new file mode 100644 index 0000000000..210376c9be --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Fortran/fibonacci-n-step-number-sequences.f @@ -0,0 +1,64 @@ +! save this program as file f.f08 +! gnu-linux command to build and test +! $ a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e 2\\n5\\n\\n | $a + +! -*- mode: compilation; default-directory: "/tmp/" -*- +! Compilation started at Fri Apr 4 23:20:27 +! +! a=./f && gfortran -Wall -std=f2008 $a.f08 -o $a && echo -e 2\\n8\\ny\\n | $a +! Enter the number of terms to sum: Show the the first how many terms of the sequence? Accept this initial sequence (y/n)? +! 1 1 +! 1 1 2 3 5 8 13 21 +! +! Compilation finished at Fri Apr 4 23:20:27 + +program f + implicit none + integer :: n, terms + integer, allocatable, dimension(:) :: sequence + integer :: i + character :: answer + write(6,'(a)',advance='no')'Enter the number of terms to sum: ' + read(5,*) n + if ((n < 2) .or. (29 < n)) stop'Unreasonable! Exit.' + write(6,'(a)',advance='no')'Show the the first how many terms of the sequence? ' + read(5,*) terms + if (terms < 1) stop'Lazy programmer has not implemented backward sequences.' + n = min(n, terms) + allocate(sequence(1:terms)) + sequence(1) = 1 + do i = 0, n - 2 + sequence(i+2) = 2**i + end do + write(6,*)'Accept this initial sequence (y/n)?' + write(6,*) sequence(:n) + read(5,*) answer + if (answer .eq. 'n') then + write(6,*) 'Fine. Enter the initial terms.' + do i=1, n + write(6, '(i2,a2)', advance = 'no') i, ': ' + read(5, *) sequence(i) + end do + end if + call nacci(n, sequence) + write(6,*) sequence(:terms) + deallocate(sequence) + +contains + + subroutine nacci(n, s) + ! nacci =: (] , +/@{.)^:(-@#@]`(-#)`]) + integer, intent(in) :: n + integer, intent(inout), dimension(:) :: s + integer :: i, terms + terms = size(s) +! do i = n+1, terms + ! s(i) = sum(s(i-n:i-1)) + ! end do + i = n+1 + if (n+1 .le. terms) s(i) = sum(s(i-n:i-1)) + do i = n + 2, terms + s(i) = 2*s(i-1) - s(i-(n+1)) + end do + end subroutine nacci +end program f diff --git a/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-1.icon b/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-1.icon new file mode 100644 index 0000000000..9a4970f05a --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-1.icon @@ -0,0 +1,15 @@ +procedure main(A) + every writes("F2:\t"|right((fnsGen(1,1))\14,5) | "\n") + every writes("F3:\t"|right((fnsGen(1,1,2))\14,5) | "\n") + every writes("F4:\t"|right((fnsGen(1,1,2,4))\14,5) | "\n") + every writes("Lucas:\t"|right((fnsGen(2,1))\14,5) | "\n") + every writes("F?:\t"|right((fnsGen!A)\14,5) | "\n") +end + +procedure fnsGen(cache[]) + n := *cache + every i := seq() do { + if i > *cache then every (put(cache,0),cache[i] +:= cache[i-n to i-1]) + suspend cache[i] + } +end diff --git a/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-2.icon b/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-2.icon new file mode 100644 index 0000000000..d1d8410261 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Icon/fibonacci-n-step-number-sequences-2.icon @@ -0,0 +1,10 @@ +procedure fnsGen(cache[]) + every i := seq() do { + if i := (i > *cache, *cache) then { + every (sum := 0) +:= !cache + put(cache, sum) # cache only 'just enough' + pop(cache) + } + suspend cache[i] + } +end diff --git a/Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences.pascal b/Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-1.pascal similarity index 100% rename from Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences.pascal rename to Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-1.pascal diff --git a/Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-2.pascal b/Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-2.pascal new file mode 100644 index 0000000000..f3aa68e8db --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Pascal/fibonacci-n-step-number-sequences-2.pascal @@ -0,0 +1,113 @@ +program FibbonacciN (output); +{$IFNDEF FPC} + {$APPTYPE CONSOLE} +{$ENDIF} +const + MAX_Nacci = 10; + + No_of_examples = 11;// max 90; (golden ratio)^No < 2^64 + Name: array[2..11] of string = ('Fibonacci: ', + 'Tribonacci: ', + 'Tetranacci: ', + 'Pentanacci: ', + 'Hexanacci: ', + 'Heptanacci: ', + 'Octonacci: ', + 'Nonanacci: ', + 'Decanacci: ', + 'Lucas: ' + ); + +type + tfibIdx = 0..MAX_Nacci; + tNacVal = Uint64;// longWord + tNacci = record + ncSum : tNacVal; + ncLastFib : array[tFibIdx] of tNacVal; + ncNextIdx : array[tFibIdx] of tFibIdx; + ncIdx : tFibIdx; + ncValue : tFibIdx; + end; + + +function CreateNacci(n: tFibIdx): TNacci; +var + i : tFibIdx; + sum :tNacVal; +begin + //With result do + with CreateNacci do + begin + ncLastFib[0] := 1; + ncLastFib[1] := 1; + For i := 2 to n-1 do + ncLastFib[i] := ncLastFib[i-1] * 2; + + Sum := 0; + For i := 0 to n-1 do + sum := sum +ncLastFib[i]; + ncSum := Sum; + //No need to do a compare + //inc(idx); + //if idx>= n then + // idx := 0; + //idx := nextIdx[idx] + For i := 0 to n-2 do + ncNextIdx[i] := i+1; + ncNextIdx[n-1] := 0; + ncIdx := 0; + end; +end; + +function LehmerCreate:TNacci; +begin + with LehmerCreate do + begin + ncLastFib[0] := 2; + ncLastFib[1] := 1; + ncSum := 3; + ncNextIdx[0] := 1; + ncNextIdx[1] := 0; + ncIdx := 0; + end; +end; + +function NextNacci(var Nacci:tNacci):tNacVal; +var + NewSum :tNacVal; +begin + with Nacci do + begin + NewSum := 2*ncSum- ncLastFib[ncIdx]; + ncLastFib[ncIdx] := ncSum; + ncIdx := ncNextIdx[ncIdx]; + NextNacci := ncSum; + ncSum := NewSum; + end; +end; + +var + Nacci : tNacci; + j, k: integer; + +BEGIN + for j := 2 to 10 do + begin + Nacci := CreateNacci(j); + write (Name[j]); + For k := 0 to j-1 do + write(Nacci.ncLastFib[k],' '); + For k := j to No_of_examples-1 do + write(NextNacci(Nacci),' '); + writeln; + end; + + write (Name[11]); + j := 2; + Nacci := LehmerCreate; + For k := 0 to j-1 do + write(Nacci.ncLastFib[k],' '); + For k := j to No_of_examples-1 do + write(NextNacci(Nacci),' '); + writeln; +END. diff --git a/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 b/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 index 6bde5302af..8f21ed5012 100644 --- a/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 +++ b/Task/Fibonacci-n-step-number-sequences/Perl-6/fibonacci-n-step-number-sequences-1.pl6 @@ -4,7 +4,7 @@ sub fibo ($n) { } sub nacci (*@starter) { - my &fun = eval join '+', '*' xx @starter; + my &fun = EVAL join '+', '*' xx @starter; @starter, &fun ... *; } diff --git a/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-1.rust b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-1.rust new file mode 100644 index 0000000000..8c5e6a8bd1 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-1.rust @@ -0,0 +1,41 @@ +struct GenFibonacci { + buf: Vec, + sum: u64, + idx: usize, +} + +impl Iterator for GenFibonacci { + type Item = u64; + fn next(&mut self) -> Option { + let result = Some(self.sum); + self.sum -= self.buf[self.idx]; + self.buf[self.idx] += self.sum; + self.sum += self.buf[self.idx]; + self.idx = (self.idx + 1) % self.buf.len(); + result + } +} + +fn print(buf: Vec, len: usize) { + let mut sum = 0; + for &elt in buf.iter() { sum += elt; print!("\t{}", elt); } + let iter = GenFibonacci { buf: buf, sum: sum, idx: 0 }; + for x in iter.take(len) { + print!("\t{}", x); + } +} + + +fn main() { + print!("Fib2:"); + print(vec![1,1], 10 - 2); + + print!("\nFib3:"); + print(vec![1,1,2], 10 - 3); + + print!("\nFib4:"); + print(vec![1,1,2,4], 10 - 4); + + print!("\nLucas:"); + print(vec![2,1], 10 - 2); +} diff --git a/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-2.rust b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-2.rust new file mode 100644 index 0000000000..46e178b807 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences-2.rust @@ -0,0 +1,4 @@ +Fib2: 1 1 2 3 5 8 13 21 34 55 +Fib3: 1 1 2 4 7 13 24 44 81 149 +Fib4: 1 1 2 4 8 15 29 56 108 208 +Lucas: 2 1 3 4 7 11 18 29 47 76 diff --git a/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust b/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust deleted file mode 100644 index 0497fda1aa..0000000000 --- a/Task/Fibonacci-n-step-number-sequences/Rust/fibonacci-n-step-number-sequences.rust +++ /dev/null @@ -1,21 +0,0 @@ - // Works with 0.9 -fn fibonacci(max: uint, mut list: ~[int]) -> ~[int] { - if list.len() == 0 { - list = ~[0,1]; // If the list is empty, give it 0 and 1 as first to items - } else if list.len() == max { - return list; - } - - // Get the last two items on the list - let n1 = list.len() - 1; // Last item - let n2 = list.len() - 2; // Second-to-last item - - let f1 = *list.iter().nth(n1).unwrap(); // Get the (n-1)th item - let f2 = *list.iter().nth(n2).unwrap(); // get the (n-2)th item - - // Add them together and push the sum onto the list! - list.push(f1 + f2); - - // Get the next number with the new list - return fibonacci(max, list) -} diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala new file mode 100644 index 0000000000..c8d6cb76d2 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-1.scala @@ -0,0 +1,7 @@ +//we rely on implicit conversion from Int to BigInt. +//BigInt is preferable since the numbers get very big, very fast. +//(though for a small example of the first few numbers it's not needed) +def fibStream(init: BigInt*): Stream[BigInt] = { + def inner(prev: Vector[BigInt]): Stream[BigInt] = prev.head #:: inner(prev.tail :+ prev.sum) + inner(init.toVector) +} diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala new file mode 100644 index 0000000000..c48fb45336 --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-2.scala @@ -0,0 +1,10 @@ +//in the optimized version we don't compute values until it's needed. +//the unoptimized version, computed k elements ahead, where k being +//the number of elements to sum (fibonacci: k=2, tribonacci: k=3, ...). +def fibStream(init: BigInt*): Stream[BigInt] = { + def inner(prev: Vector[BigInt]): Stream[BigInt] = { + val sum = prev.sum + sum #:: inner(prev.tail :+ sum) + } + init.toStream #::: inner(init.toVector) +} diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala new file mode 100644 index 0000000000..94871fc0ad --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-3.scala @@ -0,0 +1,11 @@ +//instead of summing k elements each phase, we exploit the fact +//that the last element is already the sum of all k preceding elements +def fib2Stream(init: BigInt*): Stream[BigInt] = { + def inner(prev: Vector[BigInt]): Stream[BigInt] = { + val n = prev.last * 2 - prev.head + n #:: inner(prev.tail :+ n) + } + //last element must be the sum of k preceding elements, vector size should be k+1 + val v = init.toVector :+ init.sum + v.toStream #::: inner(v) +} diff --git a/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-4.scala b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-4.scala new file mode 100644 index 0000000000..9b42e4fe2d --- /dev/null +++ b/Task/Fibonacci-n-step-number-sequences/Scala/fibonacci-n-step-number-sequences-4.scala @@ -0,0 +1,4 @@ +println(s"Fibonacci: ${fibStream(1,1).take(10).mkString(",")}") +println(s"Tribonacci: ${fibStream(1,1,2).take(10).mkString(",")}") +println(s"Tetranacci: ${fibStream(1,1,2,4).take(10).mkString(",")}") +println(s"Lucas: ${fibStream(2,1).take(10).mkString(",")}") diff --git a/Task/Fibonacci-sequence/00DESCRIPTION b/Task/Fibonacci-sequence/00DESCRIPTION index 58010a6249..9600144067 100644 --- a/Task/Fibonacci-sequence/00DESCRIPTION +++ b/Task/Fibonacci-sequence/00DESCRIPTION @@ -3,7 +3,8 @@ The '''Fibonacci sequence''' is a sequence Fn of natural numbers defi F1 = 1 Fn = Fn-1 + Fn-2, if n>1 -Write a function to generate the nth Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). +Write a function to generate the nth Fibonacci number. +Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: diff --git a/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 new file mode 100644 index 0000000000..5b6b23f2fa --- /dev/null +++ b/Task/Fibonacci-sequence/360-Assembly/fibonacci-sequence.360 @@ -0,0 +1,49 @@ +FIBONACC CSECT + USING FIBONACC,R12 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'FIBONACC' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R12,R15 +* ---- CODE + LA R1,0 f1=0 + LA R2,1 f2=1 + LA R4,1 i=1 + LA R6,1 + LH R7,N +LOOP BXH R4,R6,ENDLOOP for i=2 to n + LR R3,R2 + AR R3,R1 f3=f1+f2 + CVD R4,P i + UNPK Z,P + MVC C,Z + OI C+L'C-1,X'F0' + MVC WTOBUF+5(5),C+11 + CVD R3,P f3 + UNPK Z,P + MVC C,Z + OI C+L'C-1,X'F0' + MVC WTOBUF+12(10),C+6 + WTO MF=(E,WTOMSG) + LR R1,R2 f1=f2 + LR R2,R3 f2=f3 + B LOOP next i +ENDLOOP EQU * +* ---- END CODE +RETURN EQU * + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +* ---- DATA +N DC H'46' max i +P DS PL8 +Z DS ZL16 +C DS CL16 +WTOMSG DS 0F + DC H'80' + DC H'0' +WTOBUF DC CL80'fibo(12345)=1234567890 ' + YREGS + END FIBONACC diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl new file mode 100644 index 0000000000..5b4caf7c2d --- /dev/null +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-1.apl @@ -0,0 +1 @@ +↑+.×/N/⊂2 2⍴1 1 1 0 diff --git a/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl b/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl new file mode 100644 index 0000000000..a30ddaceb7 --- /dev/null +++ b/Task/Fibonacci-sequence/APL/fibonacci-sequence-2.apl @@ -0,0 +1 @@ +↑0 1↓↑+.×/N/⊂2 2⍴1 1 1 0 diff --git a/Task/Fibonacci-sequence/ATS/fibonacci-sequence-1.ats b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-1.ats new file mode 100644 index 0000000000..4fe0d51f3c --- /dev/null +++ b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-1.ats @@ -0,0 +1,2 @@ +fun fib_rec(n: int): int = + if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n diff --git a/Task/Fibonacci-sequence/ATS/fibonacci-sequence-2.ats b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-2.ats new file mode 100644 index 0000000000..9a5abb53e0 --- /dev/null +++ b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-2.ats @@ -0,0 +1,9 @@ +(* +** This one is also referred to as being tail-recursive +*) +fun +fib_trec(n: int): int = +if +n > 0 +then (fix loop (i:int, r0:int, r1:int): int => if i > 1 then loop (i-1, r1, r0+r1) else r1)(n, 0, 1) +else 0 diff --git a/Task/Fibonacci-sequence/ATS/fibonacci-sequence-3.ats b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-3.ats new file mode 100644 index 0000000000..7deee66245 --- /dev/null +++ b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-3.ats @@ -0,0 +1,27 @@ +(* +** This implementation is verified! +*) + +dataprop FIB (int, int) = + | FIB0 (0, 0) | FIB1 (1, 1) + | {n:nat} {r0,r1:int} FIB2 (n+2, r0+r1) of (FIB (n, r0), FIB (n+1, r1)) +// end of [FIB] // end of [dataprop] + +fun +fibats{n:nat} + (n: int (n)) +: [r:int] (FIB (n, r) | int r) = let + fun loop + {i:nat | i <= n}{r0,r1:int} + ( + pf0: FIB (i, r0), pf1: FIB (i+1, r1) + | ni: int (n-i), r0: int r0, r1: int r1 + ) : [r:int] (FIB (n, r) | int r) = + if (ni > 0) + then loop{i+1}(pf1, FIB2 (pf0, pf1) | ni - 1, r1, r0 + r1) + else (pf0 | r0) + // end of [if] + // end of [loop] +in + loop {0} (FIB0 (), FIB1 () | n, 0, 1) +end // end of [fibats] diff --git a/Task/Fibonacci-sequence/ATS/fibonacci-sequence-4.ats b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-4.ats new file mode 100644 index 0000000000..c24e6646e6 --- /dev/null +++ b/Task/Fibonacci-sequence/ATS/fibonacci-sequence-4.ats @@ -0,0 +1,79 @@ +(* ****** ****** *) +// +// How to compile: +// patscc -o fib fib.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) +// +abst@ype +int3_t0ype = + (int, int, int) +// +typedef int3 = int3_t0ype +// +(* ****** ****** *) + +extern +fun int3 : (int, int, int) -<> int3 +extern +fun int3_1 : int3 -<> int +extern +fun mul_int3_int3: (int3, int3) -<> int3 + +(* ****** ****** *) + +local + +assume +int3_t0ype = (int, int, int) + +in (* in-of-local *) +// +implement +int3 (x, y, z) = @(x, y, z) +// +implement int3_1 (xyz) = xyz.1 +// +implement +mul_int3_int3 +( + @(a,b,c), @(d,e,f) +) = + (a*d + b*e, a*e + b*f, b*e + c*f) +// +end // end of [local] + +(* ****** ****** *) +// +implement +gnumber_int (n) = int3(n, 0, n) +// +implement gmul_val = mul_int3_int3 +// +(* ****** ****** *) +// +fun +fib (n: intGte(0)): int = + int3_1(gpow_int_val (n, int3(1, 1, 0))) +// +(* ****** ****** *) + +implement +main0 () = +{ +// +val N = 10 +val () = println! ("fib(", N, ") = ", fib(N)) +val N = 20 +val () = println! ("fib(", N, ") = ", fib(N)) +val N = 30 +val () = println! ("fib(", N, ") = ", fib(N)) +val N = 40 +val () = println! ("fib(", N, ") = ", fib(N)) +// +} (* end of [main0] *) diff --git a/Task/Fibonacci-sequence/Babel/fibonacci-sequence.pb b/Task/Fibonacci-sequence/Babel/fibonacci-sequence.pb index 7f87b4a452..670a093465 100644 --- a/Task/Fibonacci-sequence/Babel/fibonacci-sequence.pb +++ b/Task/Fibonacci-sequence/Babel/fibonacci-sequence.pb @@ -1,17 +1,20 @@ -main: - { argv 0 th $d - fib - %d cr << } +((main + {{iter fib !} + 20 times -fib!: - { dup zero? - { dup one? - { cp <- 2 - fib -> 1 - fib + } - { zap 1 } - if } - { zap 1 } - if } + collect ! + rev -zero?!: { 0 = } + {%d " " . <<} + each}) -one?!: { 1 = } +(collect { -1 take }) + +(fib + {{dup 2 <} + {fnord} + {dup + <- 2 - fib ! -> + 1 - fib ! + + } + ifte})) diff --git a/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-7.clj b/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-7.clj new file mode 100644 index 0000000000..be1fd133ff --- /dev/null +++ b/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-7.clj @@ -0,0 +1,6 @@ +(defn fib [n] + (case n + 0 0 + 1 1 + (+ (fib (- n 1)) + (fib (- n 2))))) diff --git a/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-8.clj b/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-8.clj new file mode 100644 index 0000000000..5c73f55f7e --- /dev/null +++ b/Task/Fibonacci-sequence/Clojure/fibonacci-sequence-8.clj @@ -0,0 +1,8 @@ +(def fib + (memoize + (fn [n] + (case n + 0 0 + 1 1 + (+ (fib (- n 1)) + (fib (- n 2))))))) diff --git a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-2.coffee b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-2.coffee index 7061778dd1..199d77b18d 100644 --- a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-2.coffee +++ b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-2.coffee @@ -1,7 +1,5 @@ fib_iter = (n) -> - if n < 2 - return n - [prev, curr] = 0, 1 - for i in [1..n] - [prev, curr] = [curr, curr + prev] - return curr + return n if n < 2 + [prev, curr] = [0, 1] + [prev, curr] = [curr, curr + prev] for i in [1..n] + curr diff --git a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-3.coffee b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-3.coffee index 0d4f1f0571..66924e5d60 100644 --- a/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-3.coffee +++ b/Task/Fibonacci-sequence/CoffeeScript/fibonacci-sequence-3.coffee @@ -1,5 +1,2 @@ fib_rec = (n) -> - if n < 2 - return n - else - return fib_rec(n-1) + fib_rec(n-2) + if n < 2 then n else fib_rec(n-1) + fib_rec(n-2) diff --git a/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp new file mode 100644 index 0000000000..ab03fa12dd --- /dev/null +++ b/Task/Fibonacci-sequence/Common-Lisp/fibonacci-sequence-7.lisp @@ -0,0 +1,21 @@ +(defconstant +2x2-identity+ '(1 0 0 1)) +(defconstant +fib-seed+ '(1 1 1 0)) + +(defun multiply-2x2 (matrix-1 matrix-2) + (let* ((a (first matrix-1)) (b (second matrix-1)) (c (third matrix-1)) (d (fourth matrix-1)) + (e (first matrix-2)) (f (second matrix-2)) (g (third matrix-2)) (h (fourth matrix-2)) + (ae (* a e)) (bg (* b g)) (af (* a f)) (bh (* b h)) + (ce (* c e)) (dg (* d g)) (cf (* c f)) (dh (* d h))) + (list (+ ae bg) (+ af bh) (+ ce dg) (+ cf dh)))) + +(defun square-2x2 (matrix) + (multiply-2x2 matrix matrix)) + +(defun 2x2-exponentiation (matrix n) + (cond ((zerop n) +2x2-identity+) + ((eql n 1) matrix) + ((evenp n) (square-2x2 (2x2-exponentiation matrix (/ n 2)))) + (t (multiply-2x2 (square-2x2 (2x2-exponentiation matrix (/ (1- n) 2))) matrix)))) + +(defun fib (n) + (car (2x2-exponentiation +fib-seed+ (1- n)))) diff --git a/Task/Fibonacci-sequence/Dart/fibonacci-sequence.dart b/Task/Fibonacci-sequence/Dart/fibonacci-sequence.dart index e7e5afb66f..b11e5ffffb 100644 --- a/Task/Fibonacci-sequence/Dart/fibonacci-sequence.dart +++ b/Task/Fibonacci-sequence/Dart/fibonacci-sequence.dart @@ -1,18 +1,18 @@ int fib(int n) { - if(n==0 || n==1) { + if (n==0 || n==1) { return n; } - int prev=1; - int current=1; - for(int i=2;i n==0||n==1 ? n : fibRec(n-1)+fibRec(n-2); +int fibRec(int n) => n==0 || n==1 ? n : fibRec(n-1) + fibRec(n-2); main() { print(fib(11)); diff --git a/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl b/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl index 92d6a2ba6d..e2c3d9b940 100644 --- a/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl +++ b/Task/Fibonacci-sequence/Fexl/fibonacci-sequence.fexl @@ -1,26 +1,14 @@ -# fibonacci is the infinite list of all Fibonacci numbers. -# -# Note that this program uses the symbols "1" and "+". You can specify -# the definitions of those symbols however you like, allowing you to use -# any system of arithmetic you need. For example, you can use either the -# built-in long arithmetic, or infinite precision arithmetic, by simply -# defining "1" and "+" appropriately. - -\fibonacci = +# (fib n) = the nth Fibonacci number +\fib= ( - \fibonacci == (\x\y - item x; - \z = (+ x y) - fibonacci y z - ) - - fibonacci 1 1 + (@\loop\x\y\n + le n 0 x; + \z=(+ x y) + \n=(- n 1) + loop y z n + ) + 0 1 ) -# OK, so that's the list of *all* Fibonacci numbers. If you want the nth number, -# you can extract it with the fib function as follows. By the way, this *does* -# have the effect of caching, so once a particular point in the sequence is -# calculated, it doesn't have to be calculated again. - -# (fib n) is the nth fibonacci number, starting with n==0, or 1 if n is negative. -\fib = (\n list_at fibonacci n 1) +# Now test it: +for 0 20 (\n say (fib n)) diff --git a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-1.f b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-1.f index 66e77dd394..64e21be1ae 100644 --- a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-1.f +++ b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-1.f @@ -1,12 +1,24 @@ -module fibonacci -contains - recursive function fibR(n) result(fib) - integer, intent(in) :: n - integer :: fib - - select case (n) - case (:0); fib = 0 - case (1); fib = 1 - case default; fib = fibR(n-1) + fibR(n-2) - end select - end function fibR + FUNCTION IFIB(N) + IF (N.EQ.0) THEN + ITEMP0=0 + ELSE IF (N.EQ.1) THEN + ITEMP0=1 + ELSE IF (N.GT.1) THEN + ITEMP1=0 + ITEMP0=1 + DO 1 I=2,N + ITEMP2=ITEMP1 + ITEMP1=ITEMP0 + ITEMP0=ITEMP1+ITEMP2 + 1 CONTINUE + ELSE + ITEMP1=1 + ITEMP0=0 + DO 2 I=-1,N,-1 + ITEMP2=ITEMP1 + ITEMP1=ITEMP0 + ITEMP0=ITEMP2-ITEMP1 + 2 CONTINUE + END IF + IFIB=ITEMP0 + END diff --git a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-2.f b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-2.f index 6dcf24627b..a6dec42af8 100644 --- a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-2.f +++ b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-2.f @@ -1,20 +1,11 @@ - function fibI(n) - integer, intent(in) :: n - integer, parameter :: fib0 = 0, fib1 = 1 - integer :: fibI, back1, back2, i - - select case (n) - case (:0); fibI = fib0 - case (1); fibI = fib1 - - case default - fibI = fib1 - back1 = fib0 - do i = 2, n - back2 = back1 - back1 = fibI - fibI = back1 + back2 - end do - end select - end function fibI -end module fibonacci + EXTERNAL IFIB + CHARACTER*10 LINE + PARAMETER ( LINE = '----------' ) + WRITE(*,900) 'N', 'F[N]', 'F[-N]' + WRITE(*,900) LINE, LINE, LINE + DO 1 N = 0, 10 + WRITE(*,901) N, IFIB(N), IFIB(-N) + 1 CONTINUE + 900 FORMAT(3(X,A10)) + 901 FORMAT(3(X,I10)) + END diff --git a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-3.f b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-3.f index 6b7cb46101..66e77dd394 100644 --- a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-3.f +++ b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-3.f @@ -1,7 +1,12 @@ -program fibTest - use fibonacci +module fibonacci +contains + recursive function fibR(n) result(fib) + integer, intent(in) :: n + integer :: fib - do i = 0, 10 - print *, fibr(i), fibi(i) - end do -end program fibTest + select case (n) + case (:0); fib = 0 + case (1); fib = 1 + case default; fib = fibR(n-1) + fibR(n-2) + end select + end function fibR diff --git a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-4.f b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-4.f new file mode 100644 index 0000000000..6dcf24627b --- /dev/null +++ b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-4.f @@ -0,0 +1,20 @@ + function fibI(n) + integer, intent(in) :: n + integer, parameter :: fib0 = 0, fib1 = 1 + integer :: fibI, back1, back2, i + + select case (n) + case (:0); fibI = fib0 + case (1); fibI = fib1 + + case default + fibI = fib1 + back1 = fib0 + do i = 2, n + back2 = back1 + back1 = fibI + fibI = back1 + back2 + end do + end select + end function fibI +end module fibonacci diff --git a/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-5.f b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-5.f new file mode 100644 index 0000000000..6b7cb46101 --- /dev/null +++ b/Task/Fibonacci-sequence/Fortran/fibonacci-sequence-5.f @@ -0,0 +1,7 @@ +program fibTest + use fibonacci + + do i = 0, 10 + print *, fibr(i), fibi(i) + end do +end program fibTest diff --git a/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go b/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go new file mode 100644 index 0000000000..c9bcd60eff --- /dev/null +++ b/Task/Fibonacci-sequence/Go/fibonacci-sequence-3.go @@ -0,0 +1,16 @@ +func fibNumber() func() int { + fib1, fib2 := 0, 1 + return func() int { + fib1, fib2 = fib2, fib1 + fib2 + return fib1 + } +} + +func fibSequence(n int) int { + f := fibNumber() + fib := 0 + for i := 0; i < n; i++ { + fib = f() + } + return fib +} diff --git a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs index 8a73d176ff..ff9c2ccca8 100644 --- a/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs +++ b/Task/Fibonacci-sequence/Haskell/fibonacci-sequence-6.hs @@ -1,6 +1,6 @@ fibsteps (a,b) n - | n <= 0 = (a,b) - | True = fibsteps (b, a+b) (n-1) + | n <= 0 = (a,b) + | otherwise = fibsteps (b, a+b) (n-1) fibnums :: [Integer] fibnums = map fst $ iterate (`fibsteps` 1) (0,1) diff --git a/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java b/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java index 2a0d0e756d..91240d8318 100644 --- a/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java +++ b/Task/Fibonacci-sequence/Java/fibonacci-sequence-2.java @@ -1,4 +1,28 @@ -public static long recFibN(final int n) -{ - return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2); +/** + * O(log(n)) + */ +public static long fib(long n) { + if (n <= 0) + return 0; + + long i = (int) (n - 1); + long a = 1, b = 0, c = 0, d = 1, tmp1,tmp2; + + while (i > 0) { + if (i % 2 != 0) { + tmp1 = d * b + c * a; + tmp2 = d * (b + a) + c * b; + a = tmp1; + b = tmp2; + } + + tmp1 = (long) (Math.pow(c, 2) + Math.pow(d, 2)); + tmp2 = d * (2 * c + d); + + c = tmp1; + d = tmp2; + + i = i / 2; + } + return a + b; } diff --git a/Task/Fibonacci-sequence/Java/fibonacci-sequence-3.java b/Task/Fibonacci-sequence/Java/fibonacci-sequence-3.java index ca86e5a2aa..2a0d0e756d 100644 --- a/Task/Fibonacci-sequence/Java/fibonacci-sequence-3.java +++ b/Task/Fibonacci-sequence/Java/fibonacci-sequence-3.java @@ -1,6 +1,4 @@ -public static long anFibN(final long n) +public static long recFibN(final int n) { - double p = (1 + Math.sqrt(5)) / 2; - double q = 1 / p; - return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5)); + return (n < 2) ? n : recFibN(n - 1) + recFibN(n - 2); } diff --git a/Task/Fibonacci-sequence/Java/fibonacci-sequence-4.java b/Task/Fibonacci-sequence/Java/fibonacci-sequence-4.java index 3cb2baabc9..ca86e5a2aa 100644 --- a/Task/Fibonacci-sequence/Java/fibonacci-sequence-4.java +++ b/Task/Fibonacci-sequence/Java/fibonacci-sequence-4.java @@ -1,9 +1,6 @@ -public static long fibTailRec(final int n) +public static long anFibN(final long n) { - return fibInner(0, 1, n); -} - -private static long fibInner(final long a, final long b, final int n) -{ - return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1); + double p = (1 + Math.sqrt(5)) / 2; + double q = 1 / p; + return (long) ((Math.pow(p, n) + Math.pow(q, n)) / Math.sqrt(5)); } diff --git a/Task/Fibonacci-sequence/Java/fibonacci-sequence-5.java b/Task/Fibonacci-sequence/Java/fibonacci-sequence-5.java new file mode 100644 index 0000000000..3cb2baabc9 --- /dev/null +++ b/Task/Fibonacci-sequence/Java/fibonacci-sequence-5.java @@ -0,0 +1,9 @@ +public static long fibTailRec(final int n) +{ + return fibInner(0, 1, n); +} + +private static long fibInner(final long a, final long b, final int n) +{ + return n < 1 ? a : n == 1 ? b : fibInner(b, a + b, n - 1); +} diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js index 44e1e03185..74590caf0c 100644 --- a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-2.js @@ -1,18 +1,10 @@ -function fib(n) -{ - var - a = 0, - b = 1, - t; - while (n-- > 0) - { - t = a; - a = b; - b += t; - } - return a; +function fib(n) { + var a = 0, b = 1, t; + while (n-- > 0) { + t = a; + a = b; + b += t; + console.log(a); + } + return a; } - -var i; -for (i = 0; i < 10; ++i) - alert(fib(i)); diff --git a/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js new file mode 100644 index 0000000000..cbb9a58664 --- /dev/null +++ b/Task/Fibonacci-sequence/JavaScript/fibonacci-sequence-5.js @@ -0,0 +1,10 @@ +function* fibonacciGenerator() { + var prev = 0; + var curr = 1; + while (true) { + yield curr; + curr = curr + prev; + prev = curr - prev; + } +} +var fib = fibonacciGenerator(); diff --git a/Task/Fibonacci-sequence/Lush/fibonacci-sequence.lush b/Task/Fibonacci-sequence/Lush/fibonacci-sequence.lush new file mode 100644 index 0000000000..9653a1545a --- /dev/null +++ b/Task/Fibonacci-sequence/Lush/fibonacci-sequence.lush @@ -0,0 +1,4 @@ +(de fib-rec (n) + (if (< n 2) + n + (+ (fib-rec (- n 2)) (fib-rec (- n 1))))) diff --git a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m index a40d5e5cb7..ae02da25a9 100644 --- a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m +++ b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-1.m @@ -1,16 +1,6 @@ -function F = fibonacci(n) - - Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1} - F = 0; %F is F_{n} - - for i = (1:abs(n)) - Fn(2) = F; - F = sum(Fn); - Fn(1) = Fn(2); - end - - if n < 0 - F = F*((-1)^(n+1)); - end - +function f = fib(n) + + f = [1 1 ; 1 0]^(n-1); + f = f(1,1); + end diff --git a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-2.m b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-2.m index d9e46fb81d..a40d5e5cb7 100644 --- a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-2.m +++ b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-2.m @@ -1,13 +1,16 @@ -function number = fibonacci2(n) +function F = fibonacci(n) - if n == 1 - number = 1; - elseif n == 0 - number = 0; - elseif n < 0 - number = ((-1)^(n+1))*fibonacci2(-n);; - else - number = det(gallery('dramadah',n,3)); + Fn = [1 0]; %Fn(1) is F_{n-2}, Fn(2) is F_{n-1} + F = 0; %F is F_{n} + + for i = (1:abs(n)) + Fn(2) = F; + F = sum(Fn); + Fn(1) = Fn(2); + end + + if n < 0 + F = F*((-1)^(n+1)); end end diff --git a/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-3.m b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-3.m new file mode 100644 index 0000000000..d9e46fb81d --- /dev/null +++ b/Task/Fibonacci-sequence/MATLAB/fibonacci-sequence-3.m @@ -0,0 +1,13 @@ +function number = fibonacci2(n) + + if n == 1 + number = 1; + elseif n == 0 + number = 0; + elseif n < 0 + number = ((-1)^(n+1))*fibonacci2(-n);; + else + number = det(gallery('dramadah',n,3)); + end + +end diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-3.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-3.math new file mode 100644 index 0000000000..e7c19a65e8 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-3.math @@ -0,0 +1,3 @@ +fibi[prvprv_Integer, prv_Integer, rm_Integer] := + If[rm < 1, prvprv, fibi[prv, prvprv + prv, rm - 1]] +fib[n_Integer] := fibi[0, 1, n] diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-4.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-4.math new file mode 100644 index 0000000000..2143b46700 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-4.math @@ -0,0 +1,3 @@ +fib[n_Integer] := Block[{tmp, prvprv = 0, prv = 1}, + For[i = 0, i < n, i++, tmp = prv; prv += prvprv; prvprv = tmp]; + Return[prvprv]] diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-5.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-5.math new file mode 100644 index 0000000000..8afaa7f298 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-5.math @@ -0,0 +1,2 @@ +fibi[{prvprv_Integer, prv_Integer}] := {prv, prvprv + prv} +fibList[n_Integer] := Map[Take[#, 1] &, NestList[fibi, {0, 1}, n]] // Flatten diff --git a/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-6.math b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-6.math new file mode 100644 index 0000000000..698415daa9 --- /dev/null +++ b/Task/Fibonacci-sequence/Mathematica/fibonacci-sequence-6.math @@ -0,0 +1,21 @@ +{0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, \ +1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, \ +196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, \ +9227465, 14930352, 24157817, 39088169, 63245986, 102334155, \ +165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, \ +2971215073, 4807526976, 7778742049, 12586269025, 20365011074, \ +32951280099, 53316291173, 86267571272, 139583862445, 225851433717, \ +365435296162, 591286729879, 956722026041, 1548008755920, \ +2504730781961, 4052739537881, 6557470319842, 10610209857723, \ +17167680177565, 27777890035288, 44945570212853, 72723460248141, \ +117669030460994, 190392490709135, 308061521170129, 498454011879264, \ +806515533049393, 1304969544928657, 2111485077978050, \ +3416454622906707, 5527939700884757, 8944394323791464, \ +14472334024676221, 23416728348467685, 37889062373143906, \ +61305790721611591, 99194853094755497, 160500643816367088, \ +259695496911122585, 420196140727489673, 679891637638612258, \ +1100087778366101931, 1779979416004714189, 2880067194370816120, \ +4660046610375530309, 7540113804746346429, 12200160415121876738, \ +19740274219868223167, 31940434634990099905, 51680708854858323072, \ +83621143489848422977, 135301852344706746049, 218922995834555169026, \ +354224848179261915075} diff --git a/Task/Fibonacci-sequence/OPL/fibonacci-sequence.opl b/Task/Fibonacci-sequence/OPL/fibonacci-sequence.opl index c954e8f8ff..3e71a9a245 100644 --- a/Task/Fibonacci-sequence/OPL/fibonacci-sequence.opl +++ b/Task/Fibonacci-sequence/OPL/fibonacci-sequence.opl @@ -1,6 +1,5 @@ FIBON: REM Fibonacci sequence is generated to the Organiser II floating point variable limit. -REM This method was derived from (not copied...) the original OPL manual that came with the CM and XP in the mid 1980s. REM CLEAR/ON key quits. REM Mikesan - http://forum.psion2.org/ LOCAL A,B,C diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-10.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-10.pari index a8e222a86d..c40109afed 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-10.pari +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-10.pari @@ -1,11 +1,8 @@ fib(n)={ - if(n<0,return((-1)^(n+1)*fib(n))); - my(a=0,b=1,t); - while(n, - t=a+b; - a=b; - b=t; - n-- - ); - a + if(n<2, + n + , + my(s=self()); + s(n-2)+s(n-1) + ) }; diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-11.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-11.pari index 2f2e9ab577..a8e222a86d 100644 --- a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-11.pari +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-11.pari @@ -1 +1,11 @@ -fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k +fib(n)={ + if(n<0,return((-1)^(n+1)*fib(n))); + my(a=0,b=1,t); + while(n, + t=a+b; + a=b; + b=t; + n-- + ); + a +}; diff --git a/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-12.pari b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-12.pari new file mode 100644 index 0000000000..2f2e9ab577 --- /dev/null +++ b/Task/Fibonacci-sequence/PARI-GP/fibonacci-sequence-12.pari @@ -0,0 +1 @@ +fib(n)=my(k=0);while(n--,k++;while(!issquare(5*k^2+4)&&!issquare(5*k^2-4),k++));k diff --git a/Task/Fibonacci-sequence/PL-I/fibonacci-sequence.pli b/Task/Fibonacci-sequence/PL-I/fibonacci-sequence.pli index a6e2dd72d3..8055cc3e4f 100644 --- a/Task/Fibonacci-sequence/PL-I/fibonacci-sequence.pli +++ b/Task/Fibonacci-sequence/PL-I/fibonacci-sequence.pli @@ -1,9 +1,9 @@ /* Form the n-th Fibonacci number, n > 1. */ -get list (n); -f1 = 0; f2, f3 = 1; -do i = 1 to n-2; +get list(n); +f1 = 0; f2 = 1; +do i = 2 to n; f3 = f1 + f2; + put skip edit('fibo(',i,')=',f3)(a,f(5),a,f(5)); f1 = f2; f2 = f3; end; -put skip list (f3); diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pascal b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pascal index 857f37c7b4..e21b97c94d 100644 --- a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pascal +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-1.pascal @@ -1,8 +1,17 @@ -function fib(n: integer): integer; - begin - if (n = 0) or (n = 1) - then - fib := n - else - fib := fib(n-1) + fib(n-2) - end; +function fib(n: integer):longInt; +const + Sqrt5 = sqrt(5.0); + C1 = ln((Sqrt5+1.0)*0.5);//ln( 1.618..) +//C2 = ln((1.0-Sqrt5)*0.5);//ln(-0.618 )) tsetsetse + C2 = ln((Sqrt5-1.0)*0.5);//ln(+0.618 )) +begin + IF n>0 then + begin + IF odd(n) then + fib := round((exp(C1*n) + exp(C2*n) )/Sqrt5) + else + fib := round((exp(C1*n) - exp(C2*n) )/Sqrt5) + end + else + Fibdirekt := 0 +end; diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-2.pascal b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-2.pascal index 341c9f799e..857f37c7b4 100644 --- a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-2.pascal +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-2.pascal @@ -1,14 +1,8 @@ function fib(n: integer): integer; - var - f0, f1, f2, k: integer; begin - f0 := 0; - f1 := 1; - for k := 2 to n do - begin - f2:= f0 + f1; - f0 := f1; - f1 := f2; - end; - fib := f2; + if (n = 0) or (n = 1) + then + fib := n + else + fib := fib(n-1) + fib(n-2) end; diff --git a/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-3.pascal b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-3.pascal new file mode 100644 index 0000000000..c7090bd7da --- /dev/null +++ b/Task/Fibonacci-sequence/Pascal/fibonacci-sequence-3.pascal @@ -0,0 +1,22 @@ +function fib(n: integer): integer; +var + f0, f1, tmpf0, k: integer; +begin + f1 := n; + IF f1 >1 then + begin + k := f1-1; + f0 := 0; + f1 := 1; + repeat + tmpf0 := f0; + f0 := f1; + f1 := f1+tmpf0; + dec(k); + until k = 0; + end + else + IF f1 < 0 then + f1 := 0; + fib := f1; +end; diff --git a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 index 533b1a7bde..9f73216174 100644 --- a/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 +++ b/Task/Fibonacci-sequence/Perl-6/fibonacci-sequence-2.pl6 @@ -1,4 +1,4 @@ -proto fib (Int $n --> Int) {*} +proto fib (Int $n --> Int) is cached {*} multi fib (0) { 0 } multi fib (1) { 1 } multi fib ($n) { fib($n - 1) + fib($n - 2) } diff --git a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-1.pl b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-1.pl index 128befdde8..d1d0358f30 100644 --- a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-1.pl +++ b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-1.pl @@ -1,32 +1,7 @@ -# Iterative Fibonacci with bignum support. -# Multi-licensed under your choice of: -# 1. The GNU Free Documentation License (GFDL). -# 2. The MIT/X11 license. -# 3. The GNU General Publice License (GPL). -# 4. The Public Domain as understood by the CC-Zero public domain dedication. - -use strict; -use warnings; - -use Math::BigInt try => 'GMP'; - -sub fib_iter -{ - my ($n) = @_; - - my $this_fib = Math::BigInt->new(0); - my $next_fib = Math::BigInt->new(1); - - my $pos = 0; - - while ($pos < $n) - { - ($this_fib, $next_fib) = ($next_fib, $this_fib+$next_fib); - } - continue - { - $pos++; - } - - return $this_fib; +sub fib_iter { + my $n = shift; + use bigint try => "GMP,Pari"; + my ($v2,$v1) = (-1,1); + ($v2,$v1) = ($v1,$v2+$v1) for 0..$n; + $v1; } diff --git a/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl new file mode 100644 index 0000000000..0f9fe0a32f --- /dev/null +++ b/Task/Fibonacci-sequence/Perl/fibonacci-sequence-3.pl @@ -0,0 +1,20 @@ +# Binary ladder, GMP if available, Pure Perl otherwise +use ntheory qw/lucasu/; +say lucasu(1, -1, 10000); + +# Uses GMP internal method, so similar performance as above +use Math::GMP; +say Math::GMP::fibonacci(10000); + +# All Perl +use Math::NumSeq::Fibonacci; +my $seq = Math::NumSeq::Fibonacci->new; +say $seq->ith(10000); + +# All Perl +use Math::Big qw/fibonacci/; +say 0+fibonacci(10000); # Force scalar context + +# Perl, gives floating point *approximation* +use Math::Fibonacci qw/term/; +say term(10000); diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-10.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-10.py new file mode 100644 index 0000000000..dae759acba --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-10.py @@ -0,0 +1,10 @@ +def fib(): + """Yield fib[n+1] + fib[n]""" + yield 1 # have to start somewhere + lhs, rhs = fib(), fib() + yield next(lhs) # move lhs one iteration ahead + while True: + yield next(lhs)+next(rhs) + +f=fib() +print [next(f) for _ in range(9)] diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-5.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-5.py index cd9d70dde3..24eb4007fa 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-5.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-5.py @@ -1,5 +1,5 @@ -def fibGen(): - f0, f1 = 0, 1 - while True: - yield f0 - f0, f1 = f1, f0+f1 +def fibFastRec(n): + def fib(prvprv, prv, c): + if c < 1: return prvprv + else: return fib(prv, prvprv + prv, c - 1) + return fib(0, 1, n) diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-6.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-6.py index 88ef366fa7..b87bd1fba7 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-6.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-6.py @@ -1,14 +1,4 @@ ->>> fg = fibGen() ->>> for x in range(9): - print fg.next() - -0 -1 -1 -2 -3 -5 -8 -13 -21 ->>> +def fibGen(n,a=0,b=1): + while n>0: + yield a + a,b,n = b,a+b,n-1 diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py index 4bb8438a9e..c84cd923b1 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-7.py @@ -1,30 +1,3 @@ -def prevPowTwo(n): - 'Gets the power of two that is less than or equal to the given input' - if ((n & -n) == n): - return n - else: - n -= 1 - n |= n >> 1 - n |= n >> 2 - n |= n >> 4 - n |= n >> 8 - n |= n >> 16 - n += 1 - return (n/2) +>>> [i for i in fibGen(11)] -def crazyFib(n): - 'Crazy fast fibonacci number calculation' - powTwo = prevPowTwo(n) - - q = r = i = 1 - s = 0 - - while(i < powTwo): - i *= 2 - q, r, s = q*q + r*r, r * (q + s), (r*r + s*s) - - while(i < n): - i += 1 - q, r, s = q+r, q, r - - return q +[0,1,1,2,3,5,8,13,21,34,55] diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py index c3bd4903b0..4bb8438a9e 100644 --- a/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-8.py @@ -1,7 +1,30 @@ -def fib(n, c={0:1, 1:1}): - if n not in c: - x = n // 2 - c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) - return c[n] +def prevPowTwo(n): + 'Gets the power of two that is less than or equal to the given input' + if ((n & -n) == n): + return n + else: + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + n += 1 + return (n/2) -fib(10000000) # calculating it takes a few seconds, printing it takes eons +def crazyFib(n): + 'Crazy fast fibonacci number calculation' + powTwo = prevPowTwo(n) + + q = r = i = 1 + s = 0 + + while(i < powTwo): + i *= 2 + q, r, s = q*q + r*r, r * (q + s), (r*r + s*s) + + while(i < n): + i += 1 + q, r, s = q+r, q, r + + return q diff --git a/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py b/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py new file mode 100644 index 0000000000..c3bd4903b0 --- /dev/null +++ b/Task/Fibonacci-sequence/Python/fibonacci-sequence-9.py @@ -0,0 +1,7 @@ +def fib(n, c={0:1, 1:1}): + if n not in c: + x = n // 2 + c[n] = fib(x-1) * fib(n-x-1) + fib(x) * fib(n - x) + return c[n] + +fib(10000000) # calculating it takes a few seconds, printing it takes eons diff --git a/Task/Fibonacci-sequence/REXX/fibonacci-sequence.rexx b/Task/Fibonacci-sequence/REXX/fibonacci-sequence.rexx index d5762e28d2..95464561b8 100644 --- a/Task/Fibonacci-sequence/REXX/fibonacci-sequence.rexx +++ b/Task/Fibonacci-sequence/REXX/fibonacci-sequence.rexx @@ -1,23 +1,23 @@ /*REXX program calculates the Nth Fibonacci number, N can be zero or neg*/ -numeric digits 210000 /*prepare for some big 'uns. */ -parse arg x y . /*allow a single number or range.*/ -if x=='' then do; x=-40; y=abs(x); end /*No input? Use range -40 ──► +40*/ -if y=='' then y=x /*if only one number, show fib(n)*/ -w=max(length(x),length(y)) /*used for making output pretty. */ -fw=10 /*minmum maximum width. Ka-razy*/ - do j=x to y; q=fib(j) /*process each Fibonacci request.*/ - fw=max(fw,length(q)) /*fib# length or the max so far. */ +numeric digits 210000 /*be able to handle some big 'uns*/ +parse arg x y . /*allow a single number or range.*/ +if x=='' then do; x=-40; y=+40; end /*No input? Use range -40 ──► +40*/ +if y=='' then y=x /*if only one number, show fib(n)*/ +w=max(length(x), length(y)) /*used for making output pretty. */ +fw=10 /*minmum maximum width. Ka-razy.*/ + do j=x to y; q=fib(j) /*process each Fibonacci request.*/ + L=length(q) /*obtain the length (width) of Q.*/ + fw=max(fw, L) /*fib# length or the max so far. */ say 'Fibonacci('right(j,w)") = " right(q,fw) /*right justify Q.*/ - if length(q)>10 then say 'Fibonacci('right(j,w)") has a length of" l - end /*j*/ + if L>10 then say 'Fibonacci('right(j,w)") has a length of" L + end /*j*/ /* [↑] list a Fib seq. of x──►y */ exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────FIB subroutine (non-recursive)───*/ -fib: procedure; parse arg n; na=abs(n); a=0; b=1 -if na<2 then return na /*handle couple of special cases.*/ - - do k=2 to na; s=a+b /*sum the numbers up to │n│ */ - parse value b s with a b /*faster version of: a=b; s=b */ - end /*k*/ - -if n>0 | na//2==1 then return s /*if positive or odd negative ...*/ - return -s /* return a negative Fib number.*/ +/*──────────────────────────────────FIB subroutine──────────────────────*/ +fib: procedure; parse arg n; a=0; b=1; na=abs(n) /*use |n| */ +if na<2 then return na /*handle 3 special cases (-1,0,1)*/ + /* [↓] method is non-recursive.*/ + do k=2 to na; s=a+b; a=b; b=s /*sum the numbers up to │n│ */ + end /*k*/ /* [↑] (only positive Fibs used)*/ + /* [↓] na//2 [same as] na/2==1 */ +if n>0 | na//2 then return s /*if positive or odd negative ···*/ + return -s /*return a negative Fib number. */ diff --git a/Task/Fibonacci-sequence/Racket/fibonacci-sequence-1.rkt b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-1.rkt new file mode 100644 index 0000000000..9982c859d1 --- /dev/null +++ b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-1.rkt @@ -0,0 +1,5 @@ +(define (fib n) + (let loop ((cnt 0) (a 0) (b 1)) + (if (= n cnt) + a + (loop (+ cnt 1) b (+ a b))))) diff --git a/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt new file mode 100644 index 0000000000..a655d2441e --- /dev/null +++ b/Task/Fibonacci-sequence/Racket/fibonacci-sequence-2.rkt @@ -0,0 +1,11 @@ +#lang racket + +(require math/matrix) + +(define (fibmat n) (matrix-ref + (matrix-expt (matrix ([1 1] + [1 0])) + n) + 1 0)) + +(fibmat 1000) diff --git a/Task/Fibonacci-sequence/Racket/fibonacci-sequence.rkt b/Task/Fibonacci-sequence/Racket/fibonacci-sequence.rkt deleted file mode 100644 index 804059a2da..0000000000 --- a/Task/Fibonacci-sequence/Racket/fibonacci-sequence.rkt +++ /dev/null @@ -1,6 +0,0 @@ -(define (fibo number) - (define (fibo-rec number n i) - (if (<= number 0) - i - (fibo-rec (- number 1) (+ n i) n))) - (fibo-rec number 1 0)) diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb index 6bec0b623d..94298eecbc 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-1.rb @@ -1,6 +1,6 @@ -def fibIter(n) +def fib_iter(n) return 0 if n == 0 - fibPrev, fib = 1, 1 - (n.abs - 2).times { fibPrev, fib = fib, fib + fibPrev } - fib * (n<0 ? (-1)**(n+1) : 1) + fib_prev, fib = 1, 1 + (n.abs - 2).times { fib_prev, fib = fib, fib + fib_prev } + fib * (n < 0 ? (-1)**(n + 1) : 1) end diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb index 355da2190a..b47eecfae3 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-2.rb @@ -1,9 +1,9 @@ -def fibRec(n) +def fib_rec(n) if n <= -2 - (-1)**(n+1) * fibRec(n.abs) + (-1)**(n + 1) * fib_rec(n.abs) elsif n <= 1 n.abs else - fibRec(n-1) + fibRec(n-2) + fib_rec(n - 1) + fib_rec(n - 2) end end diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-3.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-3.rb index 13582e37d4..ace35a7f89 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-3.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-3.rb @@ -3,11 +3,11 @@ fib = Hash.new do |f, n| f[n] = if n <= -2 - (-1)**(n+1) * f[n.abs] + (-1)**(n + 1) * f[n.abs] elsif n <= 1 n.abs else - f[n-1] + f[n-2] + f[n - 1] + f[n - 2] end end # examples: fib[10] => 55, fib[-10] => (-55/1) diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-4.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-4.rb index 1e66c6b641..44634e9991 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-4.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-4.rb @@ -21,7 +21,7 @@ M = Matrix[[0, 1], [1,1]] # and then multiplying that by by M**(the remaining number of times). E.g., to compute # M**19, compute partial = ((M**2)**2) = M**16, and then compute partial*(M**3) = M**19. # That's only 5 matrix multiplications of M to compute M*19. -def self.fibMatrix(n) +def self.fib_matrix(n) return 0 if n <= 0 # F(0) return 1 if n == 1 # F(1) # To get F(n >= 2), compute M**(n - 1) and extract the lower right element. diff --git a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb index 497a79fe5c..044e3a789b 100644 --- a/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb +++ b/Task/Fibonacci-sequence/Ruby/fibonacci-sequence-5.rb @@ -1,11 +1,11 @@ require 'generator' -def fibGen +def fib_gen Generator.new do |g| f0, f1 = 0, 1 loop do g.yield f0 - f0, f1 = f1, f0+f1 + f0, f1 = f1, f0 + f1 end end end diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust index 2f8834d76f..49bbcee9ba 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-1.rust @@ -1,12 +1,17 @@ -fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) { +// Works with 0.13.0-dev (f673e9841) +fn fib(n: i64, f: F) -> (i64, i64) where F: Fn(i64) { if n < 0 { // Let these variables be mutated, otherwise too slow - let mut n1:i64 = 0, n2:i64 = -1, i:int = 0, tmp:i64; + let mut n1:i64 = 0; + let mut n2:i64 = -1; + let mut i:i64 = 0; + let mut tmp:i64; + while i > n { f(n1); tmp = n1-n2; - if (tmp > 0 && n2 > 0) { //Detect overflow - io::println("\nReached the limit of i64, halting"); + if tmp > 0 && n2 > 0 { //Detect overflow + println!("\nReached the limit of i64, halting"); return (n1, i); } n1 = n2; @@ -16,12 +21,16 @@ fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) { (n1+n2, n) } else if n > 0 { // And these variables - let mut n1:i64 = 0, n2:i64 = 1, i:int = 0, tmp:i64; + let mut n1:i64 = 0; + let mut n2:i64 = 1; + let mut i:i64 = 0; + let mut tmp:i64; + while i < n { f(n1); tmp = n1+n2; - if (tmp < 0) { //Detect overflow - io::println("\nReached the limit of i64, halting"); + if tmp < 0 { //Detect overflow + println!("\nReached the limit of i64, halting"); return (n1, i); } n1 = n2; @@ -36,21 +45,11 @@ fn fib(n: int, f: fn (num: i64) -> bool) -> (i64, int) { } fn main() { - let args = os::args(); - let n = if args.len() == 1 { - 10 - } else if args.len() > 1 { - // Convert from a string - match (int::from_str(args[1])) { - Some(num) => num, - None => 10 //Fall back to default - } - } else { - /* Required to use the if as an expression. - * We know that args.len() is always >= 1, the compiler - * does not. fail lets it know that we can't get past here. - */ - fail ~"No arguments given, somehow..."; + let args = std::os::args(); + let default_n = 10i64; + let n = match args.len() { + 1 => default_n, + _ => args[1].parse().unwrap_or(default_n) }; /* Use the loop protocol to be able to do things @@ -58,10 +57,10 @@ fn main() { * The loop itself returns a tuple with where it got to and * what the number is. */ - let (result, n) = for fib(n) |num| { + let (result, n) = fib(n, |num| { //print out the sequence - io::print(fmt!("%? ", num)); - }; + print!("{} ", num); + }); - io::println(fmt!("\nThe %dth fibonacci number is: %?", n, result)); + println!("\nThe {}th fibonacci number is: {}", n, result); } diff --git a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust index 1498e5f81b..7a60c2063e 100644 --- a/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust +++ b/Task/Fibonacci-sequence/Rust/fibonacci-sequence-2.rust @@ -1,19 +1,17 @@ +// Works with 0.13.0-dev (f673e9841) fn main() { + fn fib(n: int) -> int { + fn _fib(n: int, a: int, b: int) -> int { + match (n, a, b) { + (0, _, _) => a, + _ => _fib(n-1, a+b, a) + } + } - fn fib(n: int) -> int { + _fib(n, 0, 1) + } - fn _fib(n: int, a: int, b: int) -> int { - match (n, a, b) { - (0, _, _) => a, - _ => _fib(n-1, a+b, a) - } - } - - _fib(n, 0, 1) - - } - - for n in range(0,20) { - println(fmt!("%d", fib(n))) - } + for n in range(0, 20) { + println!("{}", fib(n)); + } } diff --git a/Task/Fibonacci-sequence/SQL/fibonacci-sequence.sql b/Task/Fibonacci-sequence/SQL/fibonacci-sequence.sql new file mode 100644 index 0000000000..f99cad4c99 --- /dev/null +++ b/Task/Fibonacci-sequence/SQL/fibonacci-sequence.sql @@ -0,0 +1,27 @@ +CREATE FUNCTION fib(n int) RETURNS numeric AS $$ + -- This recursive with generates endless list of Fibonacci numbers. + WITH RECURSIVE fibonacci(current, previous) AS ( + -- Initialize the current with 0, so the first value will be 0. + -- The previous value is set to 1, because its only goal is not + -- special casing the zero case, and providing 1 as the second + -- number in the sequence. + -- + -- The numbers end with dots to make them numeric type in + -- Postgres. Numeric type has almost arbitrary precision + -- (technically just 131,072 digits, but that's good enough for + -- most purposes, including calculating huge Fibonacci numbers) + SELECT 0., 1. + UNION ALL + -- To generate Fibonacci number, we need to add together two + -- previous Fibonacci numbers. Current number is saved in order + -- to be accessed in the next iteration of recursive function. + SELECT previous + current, current FROM fibonacci + ) + -- The user is only interested in current number, not previous. + SELECT current FROM fibonacci + -- We only need one number, so limit to 1 + LIMIT 1 + -- Offset the query by the requested argument to get the correct + -- position in the list. + OFFSET n +$$ LANGUAGE SQL RETURNS NULL ON NULL INPUT IMMUTABLE; diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala index e0a65a61e1..58f0cb96ba 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-3.scala @@ -1,4 +1,5 @@ -def fib(i:Int, a:Int=1, b:Int=0):Int = i match{ - case 1 => b - case _ => fib(i-1, b, a+b) -} +def fib(x:Int, prev: BigInt = 0, next: BigInt = 1):BigInt = x match { + case 0 => prev + case 1 => next + case _ => fib(x-1, next, (next + prev)) + } diff --git a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-5.scala b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-5.scala index 1dab8f56f0..6134d151a0 100644 --- a/Task/Fibonacci-sequence/Scala/fibonacci-sequence-5.scala +++ b/Task/Fibonacci-sequence/Scala/fibonacci-sequence-5.scala @@ -1,13 +1,3 @@ -// Fibonacci using BigInt with Stream.foldLeft optimized for GC (Scala v2.9 and above) -// Does not run out of memory for very large Fibonacci numbers -def fib(n:Int) = { - - def series(i:BigInt,j:BigInt):Stream[BigInt] = i #:: series(j, i+j) - - series(1,0).take(n).foldLeft(BigInt("0"))(_+_) -} - -// Small test -(0 to 13) foreach {n => print(fib(n).toString + " ")} - -// result: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 +val it = Iterator.iterate((0,1)){case (a,b) => (b,a+b)}.map(_._1) +//example: +println(it.take(13).mkString(",")) //prints: 0,1,1,2,3,5,8,13,21,34,55,89,144 diff --git a/Task/Fibonacci-sequence/Scilab/fibonacci-sequence.scilab b/Task/Fibonacci-sequence/Scilab/fibonacci-sequence.scilab new file mode 100644 index 0000000000..58893782c5 --- /dev/null +++ b/Task/Fibonacci-sequence/Scilab/fibonacci-sequence.scilab @@ -0,0 +1,11 @@ + clear + n=46 + f1=0; f2=1 + printf("fibo(%d)=%d\n",0,f1) + printf("fibo(%d)=%d\n",1,f2) + for i=2:n + f3=f1+f2 + printf("fibo(%d)=%d\n",i,f3) + f1=f2 + f2=f3 + end diff --git a/Task/Fibonacci-sequence/Visual-Basic/fibonacci-sequence.vb b/Task/Fibonacci-sequence/Visual-Basic/fibonacci-sequence.vb new file mode 100644 index 0000000000..16cad18674 --- /dev/null +++ b/Task/Fibonacci-sequence/Visual-Basic/fibonacci-sequence.vb @@ -0,0 +1,14 @@ +Sub fibonacci() + Const n = 139 + Dim i As Integer + Dim f1 As Variant, f2 As Variant, f3 As Variant 'for Decimal + f1 = CDec(0): f2 = CDec(1) 'for Decimal setting + Debug.Print "fibo("; 0; ")="; f1 + Debug.Print "fibo("; 1; ")="; f2 + For i = 2 To n + f3 = f1 + f2 + Debug.Print "fibo("; i; ")="; f3 + f1 = f2 + f2 = f3 + Next i +End Sub 'fibonacci diff --git a/Task/File-modification-time/00DESCRIPTION b/Task/File-modification-time/00DESCRIPTION index 6ea7b2d37f..81873a1f15 100644 --- a/Task/File-modification-time/00DESCRIPTION +++ b/Task/File-modification-time/00DESCRIPTION @@ -1 +1,11 @@ +{{omit from|Befunge|No filesystem support}} +{{omit from|HTML}} +{{omit from|Locomotive Basic|Does not have a real time clock.}} +{{omit from|M4}} +{{omit from|Maxima}} +{{omit from|PARI/GP}} +{{omit from|Retro}} +{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} +{{omit from|ZX Spectrum Basic|Does not have a real time clock.}} +{{task|File System Operations}} This task will attempt to get and set the modification time of a file. diff --git a/Task/File-modification-time/00META.yaml b/Task/File-modification-time/00META.yaml index 40458d9f21..d3da906d25 100644 --- a/Task/File-modification-time/00META.yaml +++ b/Task/File-modification-time/00META.yaml @@ -1,2 +1,4 @@ --- -note: File System Operations +category: +- Date and time +note: File modification time diff --git a/Task/File-modification-time/AWK/file-modification-time.awk b/Task/File-modification-time/AWK/file-modification-time.awk new file mode 100644 index 0000000000..c91696d69c --- /dev/null +++ b/Task/File-modification-time/AWK/file-modification-time.awk @@ -0,0 +1,34 @@ +#!/bin/awk -f +BEGIN { # file modification time on Unix, using stat + fn ="input.txt" + + cmd="stat " fn + print "#", cmd + system(cmd) # just execute cmd + + cmd="stat -c %Y " fn # seconds since the epoch + print "#", cmd + system(cmd) + + cmd="stat -c %y " fn # human-readable format + print "#", cmd + system(cmd) + + print "##" + cmd | getline x # get output from cmd + #print x + close(cmd) + + n=split(x,stat," ") + #for (i in stat) { print i, stat[i] } + print "file:", fn + print "date:", stat[1], "time:", stat[2] + +### change filetime with touch: + + cmd="touch -t 201409082359.59 " fn + print "#", cmd; system(cmd) + + cmd="stat " fn + print "#", cmd; system(cmd) +} diff --git a/Task/File-modification-time/Emacs-Lisp/file-modification-time.l b/Task/File-modification-time/Emacs-Lisp/file-modification-time.l new file mode 100644 index 0000000000..7ab9cd122b --- /dev/null +++ b/Task/File-modification-time/Emacs-Lisp/file-modification-time.l @@ -0,0 +1,5 @@ +(nth 5 (file-attributes "input.txt")) ;; mod date+time + +(set-file-times "input.txt") ;; to current-time +(set-file-times "input.txt" + (encode-time 0 0 0 1 1 2014)) ;; to given date+time diff --git a/Task/File-modification-time/NewLISP/file-modification-time.newlisp b/Task/File-modification-time/NewLISP/file-modification-time.newlisp new file mode 100644 index 0000000000..eafea8f4e1 --- /dev/null +++ b/Task/File-modification-time/NewLISP/file-modification-time.newlisp @@ -0,0 +1,5 @@ +;; print modification time +(println (date (file-info "input.txt" 6))) + +;; set modification time to now (Unix) +(! "touch -m input.txt") diff --git a/Task/File-modification-time/Run-BASIC/file-modification-time.run b/Task/File-modification-time/Run-BASIC/file-modification-time.run index 02903e8703..aceab3c3f7 100644 --- a/Task/File-modification-time/Run-BASIC/file-modification-time.run +++ b/Task/File-modification-time/Run-BASIC/file-modification-time.run @@ -1,4 +1,4 @@ -files #f, DefaultDir$ + "\*.*" ' all files in the defalt directory +files #f, DefaultDir$ + "\*.*" ' all files in the default directory print "hasanswer: ";#f HASANSWER() ' does it exist print "rowcount: ";#f ROWCOUNT() ' number of files in the directory @@ -16,7 +16,7 @@ if #f hasanswer() then ' or loop with while #f hasansw print "isdir: ";#f ISDIR() ' is it a directory or file name$ = #f NAME$() - shell$("touch -t 201002032359.59 ";name$;""") ' sell to os to set date + shell$("touch -t 201002032359.59 ";name$;""") ' shell to os to set date print end if diff --git a/Task/File-modification-time/Scala/file-modification-time.scala b/Task/File-modification-time/Scala/file-modification-time.scala new file mode 100644 index 0000000000..2ed2741af7 --- /dev/null +++ b/Task/File-modification-time/Scala/file-modification-time.scala @@ -0,0 +1,18 @@ +import java.io.File +import java.util.Date + +object FileModificationTime extends App { + def test(file: File) { + val (t, init) = (file.lastModified(), + s"The following ${if (file.isDirectory()) "directory" else "file"} called ${file.getPath()}") + + println(init + (if (t == 0) " does not exist." else " was modified at " + new Date(t).toInstant())) + println(init + + (if (file.setLastModified(System.currentTimeMillis())) " was modified to current time." else " does not exist.")) + println(init + + (if (file.setLastModified(t)) " was reset to previous time." else " does not exist.")) + } + + // main + List(new File("output.txt"), new File("docs")).foreach(test) +} diff --git a/Task/File-size/AWK/file-size.awk b/Task/File-size/AWK/file-size.awk new file mode 100644 index 0000000000..59a279bed1 --- /dev/null +++ b/Task/File-size/AWK/file-size.awk @@ -0,0 +1,17 @@ +# usage: awk -f filesize.awk -v fn=input.txt + +BEGIN { # Filesize on Unix, using ls + #system("ls -l") + + if(!fn) fn ="input.txt" + cmd="ls -l " fn + print "#", cmd + system(cmd) + + cmd | getline x + close(cmd) + #print x + n=split(x,stat," ") + #for (i in stat) {print i, stat[i] } + print "file:", stat[9], "size:", stat[5] +} diff --git a/Task/File-size/Lua/file-size-1.lua b/Task/File-size/Lua/file-size-1.lua new file mode 100644 index 0000000000..695a00ea58 --- /dev/null +++ b/Task/File-size/Lua/file-size-1.lua @@ -0,0 +1 @@ +FileTools:-Size( "input.txt" ) diff --git a/Task/File-size/Lua/file-size-2.lua b/Task/File-size/Lua/file-size-2.lua new file mode 100644 index 0000000000..4cf2ef9b67 --- /dev/null +++ b/Task/File-size/Lua/file-size-2.lua @@ -0,0 +1 @@ +FileTools:-Size( "/input.txt" ) diff --git a/Task/File-size/Lua/file-size.lua b/Task/File-size/Lua/file-size.lua deleted file mode 100644 index 0496ba10c3..0000000000 --- a/Task/File-size/Lua/file-size.lua +++ /dev/null @@ -1,9 +0,0 @@ -function GetFileSize( filename ) - local fp = io.open( filename ) - if fp == nil then - return nil - end - local filesize = fp:seek( "end" ) - fp:close() - return filesize -end diff --git a/Task/File-size/NewLISP/file-size.newlisp b/Task/File-size/NewLISP/file-size.newlisp new file mode 100644 index 0000000000..cbd18ad981 --- /dev/null +++ b/Task/File-size/NewLISP/file-size.newlisp @@ -0,0 +1,2 @@ +(println (first (file-info "input.txt"))) +(println (first (file-info "/input.txt"))) diff --git a/Task/File-size/Scala/file-size.scala b/Task/File-size/Scala/file-size.scala new file mode 100644 index 0000000000..58becd778b --- /dev/null +++ b/Task/File-size/Scala/file-size.scala @@ -0,0 +1,8 @@ +import java.io.File + +object FileSize extends App { + val name = "pg1661.txt" + + println(s"$name : ${new File(name).length()} bytes") + println(s"/$name : ${new File(s"${File.separator}$name").length()} bytes") +} diff --git a/Task/File-size/UNIX-Shell/file-size-2.sh b/Task/File-size/UNIX-Shell/file-size-2.sh index 4ee55dffda..d9eac22e88 100644 --- a/Task/File-size/UNIX-Shell/file-size-2.sh +++ b/Task/File-size/UNIX-Shell/file-size-2.sh @@ -1,2 +1,10 @@ -size1=$(wc -c < input.txt | tr -d ' ') -size2=$(wc -c < /input.txt | tr -d ' ') +echo "# ls:" +ls -la input.txt + +echo "# stat:" +stat input.txt + +echo "# Size:" +size1=$(ls -l input.txt | tr -s ' ' | cut -d ' ' -f 5) +size2=$(wc -c < input.txt | tr -d ' ') +echo $size1, $size2 diff --git a/Task/File-size/UNIX-Shell/file-size-3.sh b/Task/File-size/UNIX-Shell/file-size-3.sh index 9cc3ffdd9b..4ee55dffda 100644 --- a/Task/File-size/UNIX-Shell/file-size-3.sh +++ b/Task/File-size/UNIX-Shell/file-size-3.sh @@ -1,2 +1,2 @@ -size1=$(stat -f %z input.txt) -size2=$(stat -f %z /input.txt) +size1=$(wc -c < input.txt | tr -d ' ') +size2=$(wc -c < /input.txt | tr -d ' ') diff --git a/Task/File-size/UNIX-Shell/file-size-4.sh b/Task/File-size/UNIX-Shell/file-size-4.sh index 5ccea0f6ff..9cc3ffdd9b 100644 --- a/Task/File-size/UNIX-Shell/file-size-4.sh +++ b/Task/File-size/UNIX-Shell/file-size-4.sh @@ -1,5 +1,2 @@ -# from module 'zsh/stat', load builtin 'zstat' -zmodload -F zsh/stat b:zstat - -size1=$(zstat +size input.txt) -size2=$(zstat +size /input.txt) +size1=$(stat -f %z input.txt) +size2=$(stat -f %z /input.txt) diff --git a/Task/File-size/UNIX-Shell/file-size-5.sh b/Task/File-size/UNIX-Shell/file-size-5.sh new file mode 100644 index 0000000000..5ccea0f6ff --- /dev/null +++ b/Task/File-size/UNIX-Shell/file-size-5.sh @@ -0,0 +1,5 @@ +# from module 'zsh/stat', load builtin 'zstat' +zmodload -F zsh/stat b:zstat + +size1=$(zstat +size input.txt) +size2=$(zstat +size /input.txt) diff --git a/Task/Filter/00DESCRIPTION b/Task/Filter/00DESCRIPTION index b9c54df2db..505835948c 100644 --- a/Task/Filter/00DESCRIPTION +++ b/Task/Filter/00DESCRIPTION @@ -1,3 +1,5 @@ -Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. +Select certain elements from an Array into a new Array in a generic way. +To demonstrate, select all even numbers from an Array. -As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array. +As an option, give a second solution which filters destructively, +by modifying the original Array rather than creating a new Array. diff --git a/Task/Filter/AWK/filter.awk b/Task/Filter/AWK/filter-1.awk similarity index 91% rename from Task/Filter/AWK/filter.awk rename to Task/Filter/AWK/filter-1.awk index 031ef1b442..e58d188b61 100644 --- a/Task/Filter/AWK/filter.awk +++ b/Task/Filter/AWK/filter-1.awk @@ -1,2 +1 @@ $ awk 'BEGIN{split("1 2 3 4 5 6 7 8 9",a);for(i in a)if(!(a[i]%2))r=r" "a[i];print r}' -4 6 8 2 diff --git a/Task/Filter/AWK/filter-2.awk b/Task/Filter/AWK/filter-2.awk new file mode 100644 index 0000000000..31ea3cc2c5 --- /dev/null +++ b/Task/Filter/AWK/filter-2.awk @@ -0,0 +1,5 @@ +BEGIN { + split("1 2 3 4 5 6 7 8 9",a); + for(i in a) if( !(a[i]%2) ) r = r" "a[i]; + print r +} diff --git a/Task/Filter/CoffeeScript/filter.coffee b/Task/Filter/CoffeeScript/filter.coffee new file mode 100644 index 0000000000..d8ceb5bb0c --- /dev/null +++ b/Task/Filter/CoffeeScript/filter.coffee @@ -0,0 +1 @@ +[1..10].filter (x) -> not (x%2) diff --git a/Task/Filter/D/filter-1.d b/Task/Filter/D/filter-1.d index 7adb1596df..7f24a08806 100644 --- a/Task/Filter/D/filter-1.d +++ b/Task/Filter/D/filter-1.d @@ -1,9 +1,7 @@ -import std.algorithm; - void main() { + import std.algorithm: filter, equal; + immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; - - auto evens = data.filter!(x => x % 2 == 0)(); // lazy - + auto evens = data.filter!(x => x % 2 == 0); // Lazy. assert(evens.equal([2, 4, 6, 8, 10])); } diff --git a/Task/Filter/Julia/filter.julia b/Task/Filter/Julia/filter.julia index f3b73b1a0a..072deaaac3 100644 --- a/Task/Filter/Julia/filter.julia +++ b/Task/Filter/Julia/filter.julia @@ -5,5 +5,4 @@ julia> filter(iseven, [1,2,3,4,5,6,7,8,9]) 6 8 -julia> filter(isdigit, "distance: 150 000 000") -"150000000" +julia> diff --git a/Task/Filter/Lua/filter-1.lua b/Task/Filter/Lua/filter-1.lua new file mode 100644 index 0000000000..868026948b --- /dev/null +++ b/Task/Filter/Lua/filter-1.lua @@ -0,0 +1,11 @@ +function filter(t, func) + local ret = {} + for i, v in ipairs(t) do + ret[#ret+1] = func(v) and v or nil + end + return ret +end + +function even(a) return a % 2 == 0 end + +print(unpack(filter({1, 2, 3, 4 ,5, 6, 7, 8, 9, 10}, even))) diff --git a/Task/Filter/Lua/filter-2.lua b/Task/Filter/Lua/filter-2.lua new file mode 100644 index 0000000000..66c201f333 --- /dev/null +++ b/Task/Filter/Lua/filter-2.lua @@ -0,0 +1,11 @@ +function filter(t, func) + for i, v in ipairs(t) do + if not func(v) then table.remove(t, i) end + end +end + +function even(a) return a % 2 == 0 end + +local values = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} +filter(values, even) +print(unpack(values)) diff --git a/Task/Filter/Lua/filter.lua b/Task/Filter/Lua/filter.lua deleted file mode 100644 index f002180d82..0000000000 --- a/Task/Filter/Lua/filter.lua +++ /dev/null @@ -1,9 +0,0 @@ -function filter(t, func) - local ret = {} - for i, v in ipairs(t) do ret[#ret+1] = func(v) and v or nil end - return ret -end - -function even(a) return a % 2 == 0 end - -print(unpack(filter({1,2,3,4,5,6,7,8,9,10},even))) diff --git a/Task/Filter/Rust/filter.rust b/Task/Filter/Rust/filter.rust new file mode 100644 index 0000000000..5bb6d34750 --- /dev/null +++ b/Task/Filter/Rust/filter.rust @@ -0,0 +1,27 @@ +fn main() { + // Create a new vector, then use retain to filter what we want. + // Hopefully we will see .copy_iter() or .clone_iter() soon so + // we can write code like this: + + /* + let nums = range(1i32, 20i32).collect::>(); + let evens = nums.copy_iter().filter(|x| x % 2 == 0).collect::>(); + for i in evens.iter() { + println!("{}", i) + } + */ + println!("new vec filtered: "); + let nums = range(1i32, 20i32).collect::>(); + let evens = nums.iter().map(|x| x.clone()).filter(|x| x % 2 == 0).collect::>(); + for i in evens.iter() { + println!("{}", i) + } + + // Filter an already existing vector + println!("original vec filtered: "); + let mut nums = range(1i32, 20i32).collect::>(); + nums.retain(|x| x % 2 == 0); + for i in nums.iter() { + println!("{}", i) + } +} diff --git a/Task/Filter/XQuery/filter-1.xquery b/Task/Filter/XQuery/filter-1.xquery index d557c4f1a3..b616f0fdd4 100644 --- a/Task/Filter/XQuery/filter-1.xquery +++ b/Task/Filter/XQuery/filter-1.xquery @@ -13,5 +13,5 @@ let $long := for $value in $array return {$short} - {$short} + {$long} diff --git a/Task/Find-common-directory-path/00META.yaml b/Task/Find-common-directory-path/00META.yaml new file mode 100644 index 0000000000..ae625822b7 --- /dev/null +++ b/Task/Find-common-directory-path/00META.yaml @@ -0,0 +1,2 @@ +--- +note: String manipulation diff --git a/Task/Find-common-directory-path/Aime/find-common-directory-path.aime b/Task/Find-common-directory-path/Aime/find-common-directory-path.aime index 4e590ce497..82fd0fc396 100644 --- a/Task/Find-common-directory-path/Aime/find-common-directory-path.aime +++ b/Task/Find-common-directory-path/Aime/find-common-directory-path.aime @@ -19,18 +19,18 @@ cdp(...) r_last(r, v); i = 0; - while ((c = character(s, i)) == character(v, i) && c) { + while ((c = s[i]) == v[i] && c) { i += 1; } - if (!c && character(v, i) == '/') { + if (!c && v[i] == '/') { } else { - while (i && character(s, i - 1) != '/') { + while (i && s[i - 1] != '/') { i -= 1; } } - if (1 < i && character(s, i - 1) == '/') { + if (1 < i && s[i - 1] == '/') { i -= 1; } diff --git a/Task/Find-common-directory-path/Go/find-common-directory-path.go b/Task/Find-common-directory-path/Go/find-common-directory-path.go index 5863a0137b..6d65ae8db6 100644 --- a/Task/Find-common-directory-path/Go/find-common-directory-path.go +++ b/Task/Find-common-directory-path/Go/find-common-directory-path.go @@ -1,65 +1,59 @@ package main -import( +import ( "fmt" + "os" "path" - "strings" ) -func CommonPrefix(sep string, paths ...string) (string) { +func CommonPrefix(sep byte, paths ...string) string { // Handle special cases. switch len(paths) { - case 0: - return "" - case 1: - return path.Clean(paths[0]) + case 0: + return "" + case 1: + return path.Clean(paths[0]) } + // Note, we treat string as []byte, not []rune as is often + // done in Go. (And sep as byte, not rune). This is because + // most/all supported OS' treat paths as string of non-zero + // bytes. A filename may be displayed as a sequence of Unicode + // runes (typically encoded as UTF-8) but paths are + // not required to be valid UTF-8 or in any normalized form + // (e.g. "é" (U+00C9) and "é" (U+0065,U+0301) are different + // file names. c := []byte(path.Clean(paths[0])) - // Ignore the first path since it's already in c. - for _, v := range(paths[1:]) { - // Clean up each path before testing it. - v = path.Clean(v) + // We add a trailing sep to handle the case where the + // common prefix directory is included in the path list + // (e.g. /home/user1, /home/user1/foo, /home/user1/bar). + // path.Clean will have cleaned off trailing / separators with + // the exception of the root directory, "/" (in which case we + // make it "//", but this will get fixed up to "/" bellow). + c = append(c, sep) - // Get the length of the shorter slice. - shorter := len(v) - if len(v) > len(c) { - shorter = len(c) + // Ignore the first path since it's already in c + for _, v := range paths[1:] { + // Clean up each path before testing it + v = path.Clean(v) + string(sep) + + // Find the first non-common byte and truncate c + if len(v) < len(c) { + c = c[:len(v)] } - - // Find the first non-common character and copy up to it into c. - for i := 0; i < shorter; i++ { + for i := 0; i < len(c); i++ { if v[i] != c[i] { - c = c[0:i] + c = c[:i] break } } } - // Correct for problem caused by prepending the actual common path to the - // list of paths searched through. - for _, v := range(paths) { - if len(v) > len(c) { - if strings.HasPrefix(v, string(c)) { - if len(v) > len(c) + len(sep) { - if v[len(c):len(c)+len(sep)] == sep { - c = append(c, []byte(sep)...) - break - } - } - } - } - } - - // Remove trailing non-seperator characters. - for i := len(c)-1; i >= 0; i-- { - if i + len(sep) > len(c) { - continue - } - - if string(c[i:i+len(sep)]) == sep { - c = c[0:i] + // Remove trailing non-separator characters and the final separator + for i := len(c) - 1; i >= 0; i-- { + if c[i] == sep { + c = c[:i] break } } @@ -68,10 +62,18 @@ func CommonPrefix(sep string, paths ...string) (string) { } func main() { - c := CommonPrefix("/", + c := CommonPrefix(os.PathSeparator, + //"/home/user1/tmp", "/home/user1/tmp/coverage/test", "/home/user1/tmp/covert/operator", "/home/user1/tmp/coven/members", + "/home//user1/tmp/coventry", + "/home/user1/././tmp/covertly/foo", + "/home/bob/../user1/tmp/coved/bar", ) - fmt.Printf("%v\n", c) + if c == "" { + fmt.Println("No common path") + } else { + fmt.Println("Common path:", c) + } } diff --git a/Task/Find-common-directory-path/Perl/find-common-directory-path-1.pl b/Task/Find-common-directory-path/Perl/find-common-directory-path-1.pl new file mode 100644 index 0000000000..6275d21afa --- /dev/null +++ b/Task/Find-common-directory-path/Perl/find-common-directory-path-1.pl @@ -0,0 +1,6 @@ +sub common_prefix { + my $sep = shift; + my $paths = join "\0", map { $_.$sep } @_; + $paths =~ /^ ( [^\0]* ) $sep [^\0]* (?: \0 \1 $sep [^\0]* )* $/sx; + return $1; +} diff --git a/Task/Find-common-directory-path/Perl/find-common-directory-path-2.pl b/Task/Find-common-directory-path/Perl/find-common-directory-path-2.pl new file mode 100644 index 0000000000..d43450515f --- /dev/null +++ b/Task/Find-common-directory-path/Perl/find-common-directory-path-2.pl @@ -0,0 +1,12 @@ +use List::Util qw(first); + +sub common_prefix { + my ($sep, @paths) = @_; + my %prefixes; + + foreach (@paths) { + do { ++$prefixes{$_} } while s/$sep [^$sep]* $//g + } + + return first { $prefixes{$_} == @paths } reverse sort keys %prefixes; +} diff --git a/Task/Find-common-directory-path/Perl/find-common-directory-path-3.pl b/Task/Find-common-directory-path/Perl/find-common-directory-path-3.pl new file mode 100644 index 0000000000..47d0517325 --- /dev/null +++ b/Task/Find-common-directory-path/Perl/find-common-directory-path-3.pl @@ -0,0 +1,4 @@ +my @paths = qw(/home/user1/tmp/coverage/test + /home/user1/tmp/covert/operator + /home/user1/tmp/coven/members); +print common_prefix('/', @paths), "\n"; diff --git a/Task/Find-common-directory-path/Perl/find-common-directory-path.pl b/Task/Find-common-directory-path/Perl/find-common-directory-path.pl deleted file mode 100644 index daeb8cc518..0000000000 --- a/Task/Find-common-directory-path/Perl/find-common-directory-path.pl +++ /dev/null @@ -1,19 +0,0 @@ -use List::Util qw(max reduce); -sub compath { - my ($sep, @paths, %hash) = @_; - # Tokenize and tally subpaths - foreach (@paths) { - my @tok = split $sep, substr($_,1); - ++$hash{join $sep, @tok[0..$_]} for (0..$#tok); } - # Return max length subpath or null - my $max = max values %hash; - return '' unless $max == @paths; - my @res = grep {$hash{$_} == $max} keys %hash; - return $sep . reduce { length $a > length $b ? $a : $b } @res; -} - -# Test and display -my @paths = qw(/home/user1/tmp/coverage/test - /home/user1/tmp/covert/operator - /home/user1/tmp/coven/members); -print compath('/', @paths), "\n"; diff --git a/Task/Find-common-directory-path/Ruby/find-common-directory-path-1.rb b/Task/Find-common-directory-path/Ruby/find-common-directory-path-1.rb index 3868e92847..7aaf3367c7 100644 --- a/Task/Find-common-directory-path/Ruby/find-common-directory-path-1.rb +++ b/Task/Find-common-directory-path/Ruby/find-common-directory-path-1.rb @@ -3,4 +3,4 @@ require 'abbrev' dirs = %w( /home/user1/tmp/coverage/test /home/user1/tmp/covert/operator /home/user1/tmp/coven/members ) common_prefix = dirs.abbrev.keys.min_by {|key| key.length}.chop # => "/home/user1/tmp/cove" -common_directory = common_prefix.sub(%r{/[^/]*$}, '') # => "/home/user1/tmp" +common_directory = common_prefix.sub(%r{/[^/]*$}, '') # => "/home/user1/tmp" diff --git a/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb b/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb index efa556ad2a..fe95b04764 100644 --- a/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb +++ b/Task/Find-common-directory-path/Ruby/find-common-directory-path-2.rb @@ -1,4 +1,5 @@ separator = '/' paths = dirs.collect {|dir| dir.split(separator)} -uncommon_idx = paths.transpose.each_with_index.find {|dirnames, idx| dirnames.uniq.length > 1}.last -common_directory = paths[0][0 ... uncommon_idx].join(separator) # => "/home/user1/tmp" +uncommon_idx = paths[0].zip(*paths[1..-1]).index {|dirnames| dirnames.uniq.length > 1} +uncommon_idx = paths[0].length unless uncommon_idx # if uncommon_idx==nil +common_directory = paths[0][0...uncommon_idx].join(separator) # => "/home/user1/tmp" diff --git a/Task/Find-common-directory-path/Scala/find-common-directory-path-1.scala b/Task/Find-common-directory-path/Scala/find-common-directory-path-1.scala new file mode 100644 index 0000000000..ad3b443df8 --- /dev/null +++ b/Task/Find-common-directory-path/Scala/find-common-directory-path-1.scala @@ -0,0 +1,17 @@ +object FindCommonDirectoryPath extends App { + def commonPath(paths: List[String]): String = { + def common(a: List[String], b: List[String]): List[String] = (a, b) match { + case (a :: as, b :: bs) if a equals b => a :: common(as, bs) + case _ => Nil + } + if (paths.length < 2) paths.headOption.getOrElse("") + else paths.map(_.split("/").toList).reduceLeft(common).mkString("/") + } + + val test = List( + "/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members" + ) + println(commonPath(test)) +} diff --git a/Task/Find-common-directory-path/Scala/find-common-directory-path-2.scala b/Task/Find-common-directory-path/Scala/find-common-directory-path-2.scala new file mode 100644 index 0000000000..281228bebc --- /dev/null +++ b/Task/Find-common-directory-path/Scala/find-common-directory-path-2.scala @@ -0,0 +1,50 @@ +object FindCommonDirectoryPathRelative extends App { + def commonPath(paths: List[String]): String = { + val SEP = "/" + val BOUNDARY_REGEX = s"(?=[$SEP])(?<=[^$SEP])|(?=[^$SEP])(?<=[$SEP])" + def common(a: List[String], b: List[String]): List[String] = (a, b) match { + case (a :: as, b :: bs) if a equals b => a :: common(as, bs) + case _ => Nil + } + if (paths.length < 2) paths.headOption.getOrElse("") + else paths.map(_.split(BOUNDARY_REGEX).toList).reduceLeft(common).mkString + } + + val test = List( + "/home/user1/tmp/coverage/test", + "/home/user1/tmp/covert/operator", + "/home/user1/tmp/coven/members" + ) + println(commonPath(test).replaceAll("/$", "")) + + // test cases + assert(commonPath(test.take(1)) == test.head) + assert(commonPath(Nil) == "") + assert(commonPath(List("")) == "") + assert(commonPath(List("/")) == "/") + assert(commonPath(List("/", "")) == "") + assert(commonPath(List("/", "/a")) == "/") + assert(commonPath(List("/a", "/b")) == "/") + assert(commonPath(List("/a", "/a")) == "/a") + assert(commonPath(List("/a/a", "/b")) == "/") + assert(commonPath(List("/a/a", "/b")) == "/") + assert(commonPath(List("/a/a", "/a")) == "/a") + assert(commonPath(List("/a/a", "/a/b")) == "/a/") + assert(commonPath(List("/a/b", "/a/b")) == "/a/b") + assert(commonPath(List("a", "/a")) == "") + assert(commonPath(List("a/a", "/a")) == "") + assert(commonPath(List("a/a", "/b")) == "") + assert(commonPath(List("a", "a")) == "a") + assert(commonPath(List("a/a", "b")) == "") + assert(commonPath(List("a/a", "b")) == "") + assert(commonPath(List("a/a", "a")) == "a") + assert(commonPath(List("a/a", "a/b")) == "a/") + assert(commonPath(List("a/b", "a/b")) == "a/b") + assert(commonPath(List("/a/", "/b/")) == "/") + assert(commonPath(List("/a/", "/a/")) == "/a/") + assert(commonPath(List("/a/a/", "/b/")) == "/") + assert(commonPath(List("/a/a/", "/b/")) == "/") + assert(commonPath(List("/a/a/", "/a/")) == "/a/") + assert(commonPath(List("/a/a/", "/a/b/")) == "/a/") + assert(commonPath(List("/a/b/", "/a/b/")) == "/a/b/") +} diff --git a/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl/find-largest-left-truncatable-prime-in-a-given-base.pl b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl/find-largest-left-truncatable-prime-in-a-given-base.pl new file mode 100644 index 0000000000..3f978d518b --- /dev/null +++ b/Task/Find-largest-left-truncatable-prime-in-a-given-base/Perl/find-largest-left-truncatable-prime-in-a-given-base.pl @@ -0,0 +1,20 @@ +use ntheory qw/:all/; +use Math::GMPz; + +sub lltp { + my($n, $b, $best) = (shift, Math::GMPz->new(1)); + my @v = map { Math::GMPz->new($_) } @{primes($n-1)}; + while (@v) { + $best = vecmax(@v); + $b *= $n; + my @u; + foreach my $vi (@v) { + push @u, grep { is_prob_prime($_) } map { $vi + $_*$b } 1 .. $n-1; + } + @v = @u; + } + die unless is_provable_prime($best); + $best; +} + +printf "%2d %s\n", $_, lltp($_) for 3 .. 17; diff --git a/Task/Find-limit-of-recursion/00DESCRIPTION b/Task/Find-limit-of-recursion/00DESCRIPTION index dca806d9af..6b17c10eb9 100644 --- a/Task/Find-limit-of-recursion/00DESCRIPTION +++ b/Task/Find-limit-of-recursion/00DESCRIPTION @@ -1 +1,2 @@ -{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]][[Category:Programming environment operations]]Find the limit of recursion. +{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]][[Category:Programming environment operations]] [[Category:Simple]] +Find the limit of recursion. diff --git a/Task/Find-limit-of-recursion/Fortran/find-limit-of-recursion.f b/Task/Find-limit-of-recursion/Fortran/find-limit-of-recursion.f new file mode 100644 index 0000000000..fe3c1f7a52 --- /dev/null +++ b/Task/Find-limit-of-recursion/Fortran/find-limit-of-recursion.f @@ -0,0 +1,19 @@ +program recursion_depth + + implicit none + + call recurse (1) + +contains + + recursive subroutine recurse (i) + + implicit none + integer, intent (in) :: i + + write (*, '(i0)') i + call recurse (i + 1) + + end subroutine recurse + +end program recursion_depth diff --git a/Task/Find-limit-of-recursion/Go/find-limit-of-recursion.go b/Task/Find-limit-of-recursion/Go/find-limit-of-recursion.go index a83c85fa80..58049a8ba4 100644 --- a/Task/Find-limit-of-recursion/Go/find-limit-of-recursion.go +++ b/Task/Find-limit-of-recursion/Go/find-limit-of-recursion.go @@ -1,14 +1,23 @@ package main -import "fmt" +import ( + "flag" + "fmt" + "runtime/debug" +) func main() { - r(1) + stack := flag.Int("stack", 0, "maximum per goroutine stack size or 0 for the default") + flag.Parse() + if *stack > 0 { + debug.SetMaxStack(*stack) + } + r(1) } func r(l int) { - if l % 1000 == 0 { - fmt.Println(l) - } - r(l+1) + if l%1000 == 0 { + fmt.Println(l) + } + r(l + 1) } diff --git a/Task/Find-limit-of-recursion/J/find-limit-of-recursion.j b/Task/Find-limit-of-recursion/J/find-limit-of-recursion.j index 5c739605b8..41f5731541 100644 --- a/Task/Find-limit-of-recursion/J/find-limit-of-recursion.j +++ b/Task/Find-limit-of-recursion/J/find-limit-of-recursion.j @@ -1 +1 @@ - $:@>: ::] 0 +(recur=: verb def 'recur smoutput N=:N+1')N=:0 diff --git a/Task/Find-the-missing-permutation/00DESCRIPTION b/Task/Find-the-missing-permutation/00DESCRIPTION index 14272091a2..259e257666 100644 --- a/Task/Find-the-missing-permutation/00DESCRIPTION +++ b/Task/Find-the-missing-permutation/00DESCRIPTION @@ -1,8 +1,16 @@ -These are all of the permutations of the symbols A, B, C and D, except for one that's not listed. Find that missing permutation. +These are all of the permutations of the symbols A, B, C and D, +except for one that's not listed. +Find that missing permutation. (cf. [[Permutations]]) -There is an obvious method : enumerating all permutations of A, B, C, D, and looking for the missing one. There is an alternate method. Hint : if all permutations were here, how many times would A appear in each position ? What is the parity of this number ? +There is an obvious method : +enumerating all permutations of A, B, C, D, and looking for the missing one. + +There is an alternate method. +Hint : if all permutations were here, +how many times would A appear in each position ? +What is the parity of this number ?
ABCD
 CABD
diff --git a/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation.coffee b/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation.coffee
new file mode 100644
index 0000000000..5f8bf42fae
--- /dev/null
+++ b/Task/Find-the-missing-permutation/CoffeeScript/find-the-missing-permutation.coffee
@@ -0,0 +1,35 @@
+missing_permutation = (arr) ->
+  # Find the missing permutation in an array of N! - 1 permutations.
+
+  # We won't validate every precondition, but we do have some basic
+  # guards.
+  if arr.length == 0
+    throw Error "Need more data"
+  if arr.length == 1
+      return [arr[0][1] + arr[0][0]]
+
+  # Now we know that for each position in the string, elements should appear
+  # an even number of times (N-1 >= 2).  We can use a set to detect the element appearing
+  # an odd number of times.  Detect odd occurrences by toggling admission/expulsion
+  # to and from the set for each value encountered.  At the end of each pass one element
+  # will remain in the set.
+  result = ''
+  for pos in [0...arr[0].length]
+      set = {}
+      for permutation in arr
+          c = permutation[pos]
+          if set[c]
+            delete set[c]
+          else
+            set[c] = true
+      for c of set
+        result += c
+        break
+  result
+
+given = '''ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA
+  CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'''
+
+arr = (s for s in given.replace('\n', ' ').split ' ' when s != '')
+
+console.log missing_permutation(arr)
diff --git a/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d b/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d
index d153561138..7e57b99d1e 100644
--- a/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d
+++ b/Task/Find-the-missing-permutation/D/find-the-missing-permutation.d
@@ -1,35 +1,37 @@
 void main() {
     import std.stdio, std.string, std.algorithm, std.range, std.conv;
 
-    const perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
-                   BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
-                   BADC BDAC CBDA DBCA DCAB".split;
+    immutable perms = "ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC
+                       BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD
+                       BADC BDAC CBDA DBCA DCAB".split;
 
     // Version 1: test all permutations.
-    const permsSet = perms.zip(0.repeat).assocArray;
-    auto perm = cast(ubyte[])perms[0].dup;
+    immutable permsSet = perms
+                         .map!representation
+                         .zip(true.repeat)
+                         .assocArray;
+    auto perm = perms[0].dup.representation;
     do {
-        if (cast(char[])perm !in permsSet)
-            writeln(cast(char[])perm);
+        if (perm !in permsSet)
+            writeln(perm.map!(c => char(c)));
     } while (perm.nextPermutation);
 
-    // Version 2: XOR all the ASCII values, the uneven one gets
-    // flushed out. Based on Perl 6 (via Go).
-    enum int len = 4;
+    // Version 2: xor all the ASCII values, the uneven one
+    // gets flushed out. Based on Perl 6 (via Go).
+    enum len = 4;
     char[len] b = 0;
     foreach (immutable p; perms)
         b[] ^= p[];
     b.writeln;
 
-    // Version 3 : Sum ASCII values.
+    // Version 3: sum ASCII values.
     immutable rowSum = perms[0].sum;
     len
     .iota
     .map!(i => to!char(rowSum - perms.transversal(i).sum % rowSum))
     .writeln;
 
-    // Version 4: some sort of checksum, Java translation.
-    // maxCode will be 36.
+    // Version 4: a checksum, Java translation. maxCode will be 36.
     immutable maxCode = reduce!q{a * b}(len - 1, iota(3, len + 1));
 
     foreach (immutable i; 0 .. len) {
diff --git a/Task/Find-the-missing-permutation/R/find-the-missing-permutation.r b/Task/Find-the-missing-permutation/R/find-the-missing-permutation.r
new file mode 100644
index 0000000000..c3f591cc30
--- /dev/null
+++ b/Task/Find-the-missing-permutation/R/find-the-missing-permutation.r
@@ -0,0 +1,12 @@
+library(combinat)
+
+permute.me <- c("A", "B", "C", "D")
+perms  <- permn(permute.me)  # list of all permutations
+perms2 <- matrix(unlist(perms), ncol=length(permute.me), byrow=T)  # matrix of all permutations
+perms3 <- apply(perms2, 1, paste, collapse="")  # vector of all permutations
+
+incomplete <- c("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB",
+                "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA",
+                "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")
+
+setdiff(perms3, incomplete)
diff --git a/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx b/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
index ccad47f419..1b6e34067d 100644
--- a/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
+++ b/Task/Find-the-missing-permutation/REXX/find-the-missing-permutation.rexx
@@ -1,26 +1,30 @@
-/*REXX program finds a  missing permuation  from an internal list.      */
+/*REXX program finds (a)  missing permutation(s)  from an internal list.*/
+list = 'ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA',
+       'CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'
+@.=                                    /* [↓]  needs to be THINGS long. */
+@abcU  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'  /*an uppercase (Latin) alphabet. */
+things = 4                             /*# of unique letters to be used.*/
+bunch  = 4                             /*# letters to be used at a time.*/
+                 do j=1  for things
+                 $.j=substr(@abcU,j,1)
+                 end   /*j*/           /* [↑]  construct a letter array.*/
+call permset 1                         /*invoke  PERMSET  (recursively).*/
+exit                                   /*stick a fork in it, we're done.*/
+/*──────────────────────────────────PERMSET subroutine──────────────────*/
+permset: procedure expose $. @. bunch list things;   parse arg ?
+if ?>bunch  then do
+                 _=;         do m=1  for bunch       /*build permutation*/
+                             _=_ || @.m              /*add perm ──► list*/
+                             end   /*m*/
+                                                     /* [↓]  is in list?*/
+                 if wordpos(_,list)==0  then say _ ' is missing from the list.'
+                 end
+            else do x=1  for things                  /*build a new perm.*/
 
-list='ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA',
-     'CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB'
-
-@.=;   @abcU='ABCDEFGUIJKLMNOPQRSTUVWXYZ'
-things=4
-bunch=4
-                 do j=1 for things     /*build list of permutation obj. */
-                 $.j=substr(@abcu,j,1)
-                 end   /*j*/
-call permset 1
-exit
-/*─────────────────────────────────────PERMSET subroutine───────────────*/
-permset:procedure expose $. @. bunch list things;   parse arg ?
-if ?>bunch then do;   _=@.1;         do m=2 to bunch
-                                     _=_||@.m
-                                     end   /*m*/
-                if wordpos(_,list)==0 then say _ ' is missing from the list.'
-                end
-           else do x=1 for things      /*construction a new permuation. */
-                  do k=1 for ?-1;  if @.k==$.x then iterate x;  end  /*k*/
-                @.?=$.x
-                call permset ?+1
-                end   /*x*/
+                             do k=1  for ?-1
+                             if @.k==$.x  then iterate x   /*been built?*/
+                             end  /*k*/
+                 @.?=$.x                             /*define as built. */
+                 call permset ?+1                    /*call recursively.*/
+                 end   /*x*/
 return
diff --git a/Task/Find-the-missing-permutation/RapidQ/find-the-missing-permutation.rapidq b/Task/Find-the-missing-permutation/RapidQ/find-the-missing-permutation.rapidq
new file mode 100644
index 0000000000..6503391508
--- /dev/null
+++ b/Task/Find-the-missing-permutation/RapidQ/find-the-missing-permutation.rapidq
@@ -0,0 +1,24 @@
+Dim PList as QStringList
+PList.addItems "ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB"
+PList.additems "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA"
+PList.additems "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB"
+
+Dim NumChar(4, 65 to 68) as integer
+Dim MPerm as string
+
+'Create table with occurences
+For x = 0 to PList.Itemcount -1
+    for y = 1 to 4
+        Inc(NumChar(y, asc(PList.Item(x)[y])))
+    next
+next
+
+'When a char only occurs 5 times it's the missing one
+for x = 1 to 4
+    for y = 65 to 68
+        MPerm = MPerm + iif(NumChar(x, y)=5, chr$(y), "")
+    next
+next
+
+showmessage MPerm
+'= DBAC
diff --git a/Task/Find-the-missing-permutation/Ruby/find-the-missing-permutation.rb b/Task/Find-the-missing-permutation/Ruby/find-the-missing-permutation.rb
index 0821ec30d7..fce12b4925 100644
--- a/Task/Find-the-missing-permutation/Ruby/find-the-missing-permutation.rb
+++ b/Task/Find-the-missing-permutation/Ruby/find-the-missing-permutation.rb
@@ -3,6 +3,6 @@ given = %w{
   CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB
 }
 
-all = given[0].split(//).permutation.collect {|perm| perm.join('')}
+all = given[0].chars.permutation.collect(&:join)
 
-missing = all - given   # ["DBAC"]
+puts "missing: #{all - given}"
diff --git a/Task/Find-the-missing-permutation/Seed7/find-the-missing-permutation.seed7 b/Task/Find-the-missing-permutation/Seed7/find-the-missing-permutation.seed7
new file mode 100644
index 0000000000..137f46b231
--- /dev/null
+++ b/Task/Find-the-missing-permutation/Seed7/find-the-missing-permutation.seed7
@@ -0,0 +1,33 @@
+$ include "seed7_05.s7i";
+
+const func string: missingPermutation (in array string: perms) is func
+  result
+    var string: missing is "";
+  local
+    var integer: pos is 0;
+    var set of char: chSet is (set of char).EMPTY_SET;
+    var string: permutation is "";
+    var char: ch is ' ';
+  begin
+    if length(perms) <> 0 then
+      for key pos range perms[1] do
+        chSet := (set of char).EMPTY_SET;
+        for permutation range perms do
+          ch := permutation[pos];
+          if ch in chSet then
+            excl(chSet, ch);
+          else
+            incl(chSet, ch);
+          end if;
+        end for;
+        missing &:= min(chSet);
+      end for;
+    end if;
+  end func;
+
+const proc: main is func
+  begin
+    writeln(missingPermutation([] ("ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD",
+           "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC",
+           "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB")));
+  end func;
diff --git a/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION b/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION
index 0b084bd6cf..916a54bc79 100644
--- a/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION
+++ b/Task/First-class-functions-Use-numbers-analogously/00DESCRIPTION
@@ -1,6 +1,6 @@
 In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types.
 
-This tasks aim is to compare and contrast a languages implementation of First class functions, with its normal handling of numbers.
+This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers.
 
 
 Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections:
diff --git a/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-1.pl b/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-1.pl
new file mode 100644
index 0000000000..d3be6100a6
--- /dev/null
+++ b/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-1.pl
@@ -0,0 +1,20 @@
+sub multiplier {
+    my ( $n1, $n2 ) = @_;
+    sub {
+        $n1 * $n2 * $_[0];
+    };
+}
+
+my $x  = 2.0;
+my $xi = 0.5;
+my $y  = 4.0;
+my $yi = 0.25;
+my $z  = $x + $y;
+my $zi = 1.0 / ( $x + $y );
+
+my %zip;
+@zip{ $x, $y, $z } = ( $xi, $yi, $zi );
+
+while ( my ( $number, $inverse ) = each %zip ) {
+    print multiplier( $number, $inverse )->(0.5), "\n";
+}
diff --git a/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-2.pl b/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-2.pl
new file mode 100644
index 0000000000..d97e22033f
--- /dev/null
+++ b/Task/First-class-functions-Use-numbers-analogously/Perl/first-class-functions-use-numbers-analogously-2.pl
@@ -0,0 +1,9 @@
+sub compose {
+    my ($f, $g) = @_;
+
+    sub {
+        $f -> ($g -> (@_));
+    };
+}
+...
+compose($flist1[$_], $flist2[$_]) -> (0.5)
diff --git a/Task/First-class-functions/AppleScript/first-class-functions.applescript b/Task/First-class-functions/AppleScript/first-class-functions.applescript
new file mode 100644
index 0000000000..933a6dd38f
--- /dev/null
+++ b/Task/First-class-functions/AppleScript/first-class-functions.applescript
@@ -0,0 +1,56 @@
+-- Compose two functions, where each function is
+-- a script object with a call(x) handler.
+on compose(f, g)
+	script
+		on call(x)
+			f's call(g's call(x))
+		end call
+	end script
+end compose
+
+script increment
+	on call(n)
+		n + 1
+	end call
+end script
+
+script decrement
+	on call(n)
+		n - 1
+	end call
+end script
+
+script twice
+	on call(x)
+		x * 2
+	end call
+end script
+
+script half
+	on call(x)
+		x / 2
+	end call
+end script
+
+script cube
+	on call(x)
+		x ^ 3
+	end call
+end script
+
+script cuberoot
+	on call(x)
+		x ^ (1 / 3)
+	end call
+end script
+
+set functions to {increment, twice, cube}
+set inverses to {decrement, half, cuberoot}
+set answers to {}
+repeat with i from 1 to 3
+	set end of answers to ¬
+		compose(item i of inverses, ¬
+			item i of functions)'s ¬
+		call(0.5)
+end repeat
+answers -- Result: {0.5, 0.5, 0.5}
diff --git a/Task/First-class-functions/AutoHotkey/first-class-functions.ahk b/Task/First-class-functions/AutoHotkey/first-class-functions.ahk
index f05d3fc055..97c763ff42 100644
--- a/Task/First-class-functions/AutoHotkey/first-class-functions.ahk
+++ b/Task/First-class-functions/AutoHotkey/first-class-functions.ahk
@@ -1,31 +1,31 @@
-forward := "sin,cube,cos"
-inverse := "Asin,cuberoot,Acos"
-StringSplit, forward, forward, `,  ; store array length in forward0
-StringSplit, inverse, inverse, `,  ; array contents are in inverse1, inverse2...
-Loop, % forward0
-  MsgBox % map(compose(forward%A_Index%, inverse%A_Index%), 0.500)
-Return
-
-compose(f, g){
-  Return map(0, 0, f, g)
+#NoEnv
+; Set the floating-point precision
+SetFormat, Float, 0.15
+; Super-global variables for function objects
+Global F, G
+; User-defined functions
+Cube(X) {
+   Return X ** 3
 }
-
-map(ab = 0, x = 0 , a = 0, b = 0)
-{
-  Static
-  If (a And b)
-    Return a . "`n" . b
-  If ab
-  {
-    StringSplit, ab, ab, `n
-    Return %ab1%(%ab2%(x))
-  }
+CubeRoot(X) {
+   Return X ** (1/3)
 }
-
-cube(x){
-  Return x ** 3
+; Function arrays, Sin/ASin and Cos/ACos are built-in
+FuncArray1 := [Func("Sin"),  Func("Cos"),  Func("Cube")]
+FuncArray2 := [Func("ASin"), Func("ACos"), Func("CubeRoot")]
+; Compose
+Compose(FN1, FN2) {
+   Static FG := Func("ComposedFunction")
+   F := FN1, G:= FN2
+   Return FG
 }
-
-cuberoot(x){
-  Return x ** (1 / 3)
+ComposedFunction(X) {
+   Return F.(G.(X))
 }
+; Run
+X := 0.5 + 0
+Result := "Input:`n" . X . "`n`nOutput:"
+For Index In FuncArray1
+   Result .= "`n" . Compose(FuncArray1[Index], FuncArray2[Index]).(X)
+MsgBox, 0, First-Class Functions, % Result
+ExitApp
diff --git a/Task/First-class-functions/Bracmat/first-class-functions.bracmat b/Task/First-class-functions/Bracmat/first-class-functions.bracmat
new file mode 100644
index 0000000000..bcc0d00763
--- /dev/null
+++ b/Task/First-class-functions/Bracmat/first-class-functions.bracmat
@@ -0,0 +1,17 @@
+( (sqrt=.!arg^1/2)
+& (log=.e\L!arg)
+& (A=x2d (=.!arg^2) log (=.!arg*pi))
+& ( B
+  = d2x sqrt (=.e^!arg) (=.!arg*pi^-1)
+  )
+& ( compose
+  =   f g
+    .   !arg:(?f.?g)
+      & '(.($f)$(($g)$!arg))
+  )
+&   whl
+  ' ( !A:%?F ?A
+    & !B:%?G ?B
+    & out$((compose$(!F.!G))$3210)
+    )
+)
diff --git a/Task/First-class-functions/Groovy/first-class-functions-2.groovy b/Task/First-class-functions/Groovy/first-class-functions-2.groovy
index 80e0454df9..cd9021966d 100644
--- a/Task/First-class-functions/Groovy/first-class-functions-2.groovy
+++ b/Task/First-class-functions/Groovy/first-class-functions-2.groovy
@@ -4,5 +4,5 @@ def cubeRoot = { it ** (1/3) }
 funcList = [ Math.&sin, Math.&cos, cube ]
 inverseList = [ Math.&asin, Math.&acos, cubeRoot ]
 
-println [funcList, inverseList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) }
-println [inverseList, funcList].transpose().collect { compose(it[0],it[1]) }.collect{ it(0.5) }
+println ([funcList, inverseList].transpose().collect { f, finv -> compose(f, finv) }.collect{ it(0.5) })
+println ([inverseList, funcList].transpose().collect { finv, f -> compose(finv, f) }.collect{ it(0.5) })
diff --git a/Task/First-class-functions/Java/first-class-functions-2.java b/Task/First-class-functions/Java/first-class-functions-2.java
index a16b47c6e1..9e579ebcb5 100644
--- a/Task/First-class-functions/Java/first-class-functions-2.java
+++ b/Task/First-class-functions/Java/first-class-functions-2.java
@@ -3,16 +3,7 @@ import java.util.function.Function;
 
 public class FirstClass{
 	
-	public static  Function compose(
-			final Function f, final Function g) {
-		return new Function() {
-			@Override public C apply(A x) {
-				return f.apply(g.apply(x));
-			}
-		};
-	}
-	
-	public static void main(String[] args){
+	public static void main(String... arguments){
 		ArrayList> functions = new ArrayList<>();
 		
 		functions.add(Math::cos);
@@ -25,8 +16,8 @@ public class FirstClass{
 		inverse.add(Math::atan);
 		inverse.add(Math::sqrt);
 		System.out.println("Compositions:");
-		for(int i = 0; i < functions.size(); i++){
-			System.out.println(compose(functions.get(i), inverse.get(i)).apply(0.5));
+		for (int i = 0; i < functions.size(); i++){
+			System.out.println(functions.get(i).compose(inverse.get(i)).apply(0.5));
 		}
 		System.out.println("Hard-coded compositions:");
 		System.out.println(Math.cos(Math.acos(0.5)));
diff --git a/Task/First-class-functions/TXR/first-class-functions.txr b/Task/First-class-functions/TXR/first-class-functions.txr
new file mode 100644
index 0000000000..1c3c0afe87
--- /dev/null
+++ b/Task/First-class-functions/TXR/first-class-functions.txr
@@ -0,0 +1,11 @@
+@(do
+   (defvar funlist [list sin
+                         cos
+                         (op expt @1 3)])
+
+   (defvar invlist [list asin
+                         acos
+                         (op expt @1 (/ 1 3))])
+
+   (each ((f funlist) (i invlist))
+     (prinl [(chain f i) 0.5])))
diff --git a/Task/Five-weekends/00DESCRIPTION b/Task/Five-weekends/00DESCRIPTION
index e552710c6b..50d77bc3aa 100644
--- a/Task/Five-weekends/00DESCRIPTION
+++ b/Task/Five-weekends/00DESCRIPTION
@@ -12,3 +12,8 @@ The month of October in 2010 has five Fridays, five Saturdays, and five Sundays.
 '''Extra credit'''
 
 Count and/or show all of the years which do not have at least one five-weekend month (there should be 29).
+
+;See also
+* [[Day of the week]]
+* [[Last Friday of each month]]
+* [[Find last sunday of each month]]
diff --git a/Task/Five-weekends/00META.yaml b/Task/Five-weekends/00META.yaml
new file mode 100644
index 0000000000..2f9fac8f1f
--- /dev/null
+++ b/Task/Five-weekends/00META.yaml
@@ -0,0 +1,5 @@
+---
+category:
+- Date and time
+- Puzzles
+note: Five weekends
diff --git a/Task/Five-weekends/AWK/five-weekends.awk b/Task/Five-weekends/AWK/five-weekends.awk
new file mode 100644
index 0000000000..e7ad286b3f
--- /dev/null
+++ b/Task/Five-weekends/AWK/five-weekends.awk
@@ -0,0 +1,56 @@
+# usage:  awk -f 5weekends.awk  cal.txt
+
+# Filter a file of month-calendars, such as
+# ...
+##        January 1901
+##    Mo Tu We Th Fr Sa Su
+##        1  2  3  4  5  6
+##     7  8  9 10 11 12 13
+##    14 15 16 17 18 19 20
+##    21 22 23 24 25 26 27
+##    28 29 30 31
+# ...
+##         March 1901
+##    Mo Tu We Th Fr Sa Su
+##                 1  2  3
+##     4  5  6  7  8  9 10
+##    11 12 13 14 15 16 17
+##    18 19 20 21 22 23 24
+##    25 26 27 28 29 30 31
+# ...
+# This file is generated by a script for the unix-shell,
+# see http://rosettacode.org/wiki/Five_weekends#UNIX_Shell
+
+BEGIN   { print("# Month with 5 weekends:")
+          badYears = numW5 = 0;
+          lastW5 = -1
+        }
+
+0+$2>33 { if( $2>currYear ) {       # calendar-header: month, year
+            if( lastW5==numW5 ) {
+              badYears++; sep="\n"
+              if( badYears % 10 ) { sep=" " }
+              bY=bY currYear sep;   # collect years in string
+            ##print badYears,":", currYear
+            }
+            lastW5=numW5
+          }
+          WE=0; currYear=$2; currMY = $1 " " $2;
+        ##print currMY;
+          next
+        }
+
+/^Mo/   { next }                    # skip lines with weekday-names
+
+        { $0 = substr($0,13) }      # cut inputline, leave  Fr,Sa,Su only
+
+NF>2    { WE++;                     # 3 fields left => complete weekend found
+          if( WE>4 ) {
+            numW5++; printf("%4d : %s\n", numW5, currMY)
+          }
+        }
+
+END     { print("# Found", numW5, "month with 5 weekends.")
+          print("# Found", badYears, "years with no month having 5 weekends:")
+          print(bY)
+        }
diff --git a/Task/Five-weekends/D/five-weekends-2.d b/Task/Five-weekends/D/five-weekends-2.d
index 52c17664a8..a039ac9ce5 100644
--- a/Task/Five-weekends/D/five-weekends-2.d
+++ b/Task/Five-weekends/D/five-weekends-2.d
@@ -1,16 +1,16 @@
-import std.stdio, std.datetime, std.traits;
-
 void main() {
+    import std.stdio, std.datetime, std.traits;
+
     enum first_year = 1900;
     enum last_year = 2100;
 
-    int totalNo5Weekends;
-    const(Date)[] fiveWeekendMonths;
-    foreach (year; first_year .. last_year + 1) {
+    uint totalNo5Weekends;
+    immutable(Date)[] fiveWeekendMonths;
+    foreach (immutable year; first_year .. last_year + 1) {
         bool has5Weekends = false;
 
-        foreach (month; [EnumMembers!Month]) {
-            const firstDay = Date(year, month, 1);
+        foreach (immutable month; EnumMembers!Month) {
+            immutable firstDay = Date(year, month, 1);
             if (firstDay.daysInMonth == 31 &&
                 firstDay.dayOfWeek == DayOfWeek.fri) {
                 has5Weekends = true;
@@ -24,11 +24,11 @@ void main() {
 
     writefln("Total 5-weekend months between %d and %d: %d",
              first_year, last_year, fiveWeekendMonths.length);
-    foreach (date; fiveWeekendMonths[0 .. 5])
-        writeln(date.month, " ", date.year);
-    writeln("...");
-    foreach (date; fiveWeekendMonths[$ - 5 .. $])
-        writeln(date.month, " ", date.year);
+    foreach (immutable date; fiveWeekendMonths[0 .. 5])
+        writeln(date.month, ' ', date.year);
+    "...".writeln;
+    foreach (immutable date; fiveWeekendMonths[$ - 5 .. $])
+        writeln(date.month, ' ', date.year);
 
     writeln("\nTotal number of years with no 5-weekend months: ",
             totalNo5Weekends);
diff --git a/Task/Five-weekends/Racket/five-weekends.rkt b/Task/Five-weekends/Racket/five-weekends.rkt
new file mode 100644
index 0000000000..31dcecae17
--- /dev/null
+++ b/Task/Five-weekends/Racket/five-weekends.rkt
@@ -0,0 +1,26 @@
+#lang racket
+(require srfi/19)
+
+(define long-months '(1 3 5 7 8 10 12))
+(define days #(sun mon tue wed thu fri sat))
+
+(define (week-day date)
+  (vector-ref days (date-week-day date)))
+
+(define (five-weekends-a-month start end)
+  (for*/list ([year (in-range start (+ end 1))]
+              [month long-months]
+              [date (in-value (make-date 0 0 0 0 31 month year 0))]
+              #:when (eq? (week-day date) 'sun))
+    date))
+
+(define weekends (five-weekends-a-month 1900 2100))
+(define count (length weekends))
+
+(displayln (~a "There are " count " weeks with five weekends."))
+(displayln "The first five are: ")
+(for ([w (take weekends 5)])
+  (displayln (date->string w "~b ~Y")))
+(displayln "The last five are: ")
+(for ([w (drop weekends (- count 5))])
+  (displayln (date->string w "~b ~Y")))
diff --git a/Task/Five-weekends/Ruby/five-weekends.rb b/Task/Five-weekends/Ruby/five-weekends.rb
index 0dd048ebfa..403ea78c65 100644
--- a/Task/Five-weekends/Ruby/five-weekends.rb
+++ b/Task/Five-weekends/Ruby/five-weekends.rb
@@ -1,11 +1,13 @@
 require 'date'
+# The only case where the month has 5 weekends is when the last day
+# of the month falls on a Sunday and the month has 31 days.
 
-# if the last day of the month falls on a Sunday and the month has 31 days,
-# this is the only case where the month has 5 weekends.
-start = Date.parse("1900-01-01")
-stop  = Date.parse("2100-12-31")
-dates = (start..stop).find_all do |day|
-  day.mday == 31 and day.wday == 0 # Ruby 1.9: and day.sunday?
+dates = []
+1900.upto(2100) do |year|
+  1.upto(12) do |month|
+    d = Date.new(year, month, -1) # -1 is last day of month
+    dates << d if d.sunday? && d.day == 31
+  end
 end
 
 puts "There are #{dates.size} months with 5 weekends from 1900 to 2100:"
diff --git a/Task/Five-weekends/UNIX-Shell/five-weekends.sh b/Task/Five-weekends/UNIX-Shell/five-weekends.sh
new file mode 100644
index 0000000000..aab6ce040f
--- /dev/null
+++ b/Task/Five-weekends/UNIX-Shell/five-weekends.sh
@@ -0,0 +1,12 @@
+echo "Creating cal-file..."
+echo > cal.txt
+for ((y=1900; y <= 2100; y++)); do
+  for ((m=1; m <= 12; m++)); do
+   #echo $m $y
+    cal -m $m $y >> cal.txt
+  done
+done
+ls -la cal.txt
+
+echo "Looking for month with 5 weekends:"
+awk -f 5weekends.awk  cal.txt
diff --git a/Task/Five-weekends/XPL0/five-weekends.xpl0 b/Task/Five-weekends/XPL0/five-weekends.xpl0
index babd9c1c7c..c65f18ca26 100644
--- a/Task/Five-weekends/XPL0/five-weekends.xpl0
+++ b/Task/Five-weekends/XPL0/five-weekends.xpl0
@@ -1,7 +1,7 @@
 include c:\cxpl\codes;                  \intrinsic 'code' declarations
 
 
-proc    WeekDay(Year, Month, Day);      \Return day of week (0=Sat 1=Sun..6=Fri)
+func    WeekDay(Year, Month, Day);      \Return day of week (0=Sat 1=Sun..6=Fri)
 int     Year, Month, Day;
 [if Month<=2 then [Month:= Month+12;  Year:= Year-1];
 return rem((Day + (Month+1)*26/10 + Year + Year/4 + Year/100*6 + Year/400) / 7);
diff --git a/Task/FizzBuzz/00DESCRIPTION b/Task/FizzBuzz/00DESCRIPTION
index ba52dad10f..a9e8e1af66 100644
--- a/Task/FizzBuzz/00DESCRIPTION
+++ b/Task/FizzBuzz/00DESCRIPTION
@@ -1,3 +1,8 @@
-Write a program that prints the integers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". [http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html]
+Write a program that prints the integers from 1 to 100.
 
-FizzBuzz was presented as the lowest level of comprehension required to illustrate adequacy. [http://www.codinghorror.com/blog/archives/000804.html]
+But for multiples of three print "Fizz" instead of the number,
+and for the multiples of five print "Buzz". 
+For numbers which are multiples of both three and five print "FizzBuzz". [http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html] + +FizzBuzz was presented as the lowest level of comprehension +required to illustrate adequacy. [http://blog.codinghorror.com/fizzbuzz-the-programmers-stairway-to-heaven/] diff --git a/Task/FizzBuzz/00META.yaml b/Task/FizzBuzz/00META.yaml index 71d70b5414..e3088e0d06 100644 --- a/Task/FizzBuzz/00META.yaml +++ b/Task/FizzBuzz/00META.yaml @@ -2,4 +2,5 @@ category: - Iteration - Recursion +- Simple note: Classic CS problems and programs diff --git a/Task/FizzBuzz/APL/fizzbuzz.apl b/Task/FizzBuzz/APL/fizzbuzz-1.apl similarity index 100% rename from Task/FizzBuzz/APL/fizzbuzz.apl rename to Task/FizzBuzz/APL/fizzbuzz-1.apl diff --git a/Task/FizzBuzz/APL/fizzbuzz-2.apl b/Task/FizzBuzz/APL/fizzbuzz-2.apl new file mode 100644 index 0000000000..e2fbf6f312 --- /dev/null +++ b/Task/FizzBuzz/APL/fizzbuzz-2.apl @@ -0,0 +1 @@ +A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100] diff --git a/Task/FizzBuzz/C++/fizzbuzz-1.cpp b/Task/FizzBuzz/C++/fizzbuzz-1.cpp index cedbea43a2..406d65ef40 100644 --- a/Task/FizzBuzz/C++/fizzbuzz-1.cpp +++ b/Task/FizzBuzz/C++/fizzbuzz-1.cpp @@ -1,18 +1,18 @@ #include using namespace std; -int main () { - - int i; - for (i = 0; i <= 100; i++) { +int main () +{ + for (int i = 1; i <= 100; i++) + { if ((i % 15) == 0) - cout << "FizzBuzz" << endl; + cout << "FizzBuzz\n"; else if ((i % 3) == 0) - cout << "Fizz" << endl; + cout << "Fizz\n"; else if ((i % 5) == 0) - cout << "Buzz" << endl; + cout << "Buzz\n"; else - cout << i << endl; + cout << i << "\n"; } return 0; } diff --git a/Task/FizzBuzz/C++/fizzbuzz-2.cpp b/Task/FizzBuzz/C++/fizzbuzz-2.cpp index 3688c21605..ce8c3ae26f 100644 --- a/Task/FizzBuzz/C++/fizzbuzz-2.cpp +++ b/Task/FizzBuzz/C++/fizzbuzz-2.cpp @@ -13,7 +13,7 @@ int main() cout << "Buzz"; if (!fizz && !buzz) cout << i; - cout << endl; + cout << "\n"; } return 0; } diff --git a/Task/FizzBuzz/C++/fizzbuzz-3.cpp b/Task/FizzBuzz/C++/fizzbuzz-3.cpp index 0acaa25aab..a555a867d1 100644 --- a/Task/FizzBuzz/C++/fizzbuzz-3.cpp +++ b/Task/FizzBuzz/C++/fizzbuzz-3.cpp @@ -1,25 +1,16 @@ #include -#include -#include int main() { - std::vector range(100); - std::iota(range.begin(), range.end(), 1); + int i, f = 2, b = 4; - std::vector values; - values.resize(range.size()); + for ( i = 1 ; i <= 100 ; ++i, --f, --b ) + { + if ( f && b ) { std::cout << i; } + if ( !f ) { std::cout << "Fizz"; f = 3; } + if ( !b ) { std::cout << "Buzz"; b = 5; } + std::cout << std::endl; + } - auto fizzbuzz = [](int i) -> std::string { - if ((i%15) == 0) return "FizzBuzz"; - if ((i%5) == 0) return "Buzz"; - if ((i%3) == 0) return "Fizz"; - return std::to_string(i); - }; - - std::transform(range.begin(), range.end(), values.begin(), fizzbuzz); - - for (auto& str: values) std::cout << str << std::endl; - - return 0; + return 0; } diff --git a/Task/FizzBuzz/C++/fizzbuzz-4.cpp b/Task/FizzBuzz/C++/fizzbuzz-4.cpp index d9974c72f9..0acaa25aab 100644 --- a/Task/FizzBuzz/C++/fizzbuzz-4.cpp +++ b/Task/FizzBuzz/C++/fizzbuzz-4.cpp @@ -1,48 +1,25 @@ #include - -template -struct fizzbuzz : fizzbuzz -{ - fizzbuzz() - { std::cout << n << std::endl; } -}; - -template -struct fizzbuzz : fizzbuzz -{ - fizzbuzz() - { std::cout << "FizzBuzz" << std::endl; } -}; - -template -struct fizzbuzz : fizzbuzz -{ - fizzbuzz() - { std::cout << "Fizz" << std::endl; } -}; - -template -struct fizzbuzz : fizzbuzz -{ - fizzbuzz() - { std::cout << "Buzz" << std::endl; } -}; - -template <> -struct fizzbuzz<0,0,0> -{ - fizzbuzz() - { std::cout << 0 << std::endl; } -}; - -template -struct fb_run -{ - fizzbuzz fb; -}; +#include +#include int main() { - fb_run<100> fb; + std::vector range(100); + std::iota(range.begin(), range.end(), 1); + + std::vector values; + values.resize(range.size()); + + auto fizzbuzz = [](int i) -> std::string { + if ((i%15) == 0) return "FizzBuzz"; + if ((i%5) == 0) return "Buzz"; + if ((i%3) == 0) return "Fizz"; + return std::to_string(i); + }; + + std::transform(range.begin(), range.end(), values.begin(), fizzbuzz); + + for (auto& str: values) std::cout << str << std::endl; + return 0; } diff --git a/Task/FizzBuzz/C++/fizzbuzz-5.cpp b/Task/FizzBuzz/C++/fizzbuzz-5.cpp index d00cefbbe2..d9974c72f9 100644 --- a/Task/FizzBuzz/C++/fizzbuzz-5.cpp +++ b/Task/FizzBuzz/C++/fizzbuzz-5.cpp @@ -1,164 +1,48 @@ #include -#include -#include -#include -#include -#include -using namespace std; -using namespace boost; - -/////////////////////////////////////////////////////////////////////////////// -// exponentiation calculations -template struct POWER_CORE : POWER_CORE{}; - -template -struct POWER_CORE +template +struct fizzbuzz : fizzbuzz { - enum : int { val = accum }; + fizzbuzz() + { std::cout << n << std::endl; } }; -template struct POWER : POWER_CORE<1, base, exp>{}; - -/////////////////////////////////////////////////////////////////////////////// -// # of digit calculations -template struct NUM_DIGITS_CORE : NUM_DIGITS_CORE{}; - -template -struct NUM_DIGITS_CORE +template +struct fizzbuzz : fizzbuzz { - enum : int { val = depth}; + fizzbuzz() + { std::cout << "FizzBuzz" << std::endl; } }; -template struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{}; - -template <> -struct NUM_DIGITS<0> +template +struct fizzbuzz : fizzbuzz { - enum : int { val = 1 }; + fizzbuzz() + { std::cout << "Fizz" << std::endl; } }; -/////////////////////////////////////////////////////////////////////////////// -// Convert digit to character (1 -> '1') -template -struct DIGIT_TO_CHAR +template +struct fizzbuzz : fizzbuzz { - enum : char{ val = i + 48 }; -}; - -/////////////////////////////////////////////////////////////////////////////// -// Find the digit at a given offset into a number of the form 0000000017 -template // place -> [0 .. 10] -struct DIGIT_AT -{ - enum : char{ val = (i / POWER<10, place>::val) % 10 }; -}; - -struct NULL_CHAR -{ - enum : char{ val = '\0' }; -}; - -/////////////////////////////////////////////////////////////////////////////// -// Convert the digit at a given offset into a number of the form '0000000017' to a character -template // place -> [0 .. 9] - struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT::val >{}; - -/////////////////////////////////////////////////////////////////////////////// -// Convert the digit at a given offset into a number of the form '17' to a character - -// Template description, with specialization to generate null characters for out of range offsets -template - struct OFFSET_CHAR_CORE_CHECKED{}; -template - struct OFFSET_CHAR_CORE_CHECKED : NULL_CHAR{}; -template - struct OFFSET_CHAR_CORE_CHECKED : ALT_CHAR{}; - -// Perform the range check and pass it on -template - struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED{}; - -// Calc the number of digits and pass it on -template - struct OFFSET_CHAR : OFFSET_CHAR_CORE::val>{}; - -/////////////////////////////////////////////////////////////////////////////// -// Integer to char* template. Works on unsigned ints. -template -struct IntToStr -{ - const static char str[]; - typedef typename mpl::string< - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - /*OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val,*/ - NULL_CHAR::val>::type type; -}; - -template -const char IntToStr::str[] = -{ - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - OFFSET_CHAR::val, - NULL_CHAR::val -}; - -template -struct IF -{ - typedef Then RET; -}; - -template -struct IF -{ - typedef Else RET; -}; - - -template < typename Str1, typename Str2 > -struct concat : mpl::insert_range::type, Str2> {}; -template -struct concat3 : mpl::insert_range::type, typename concat::type > {}; - -typedef typename mpl::string<'f','i','z','z'>::type fizz; -typedef typename mpl::string<'b','u','z','z'>::type buzz; -typedef typename mpl::string<'\r', '\n'>::type mpendl; -typedef typename concat::type fizzbuzz; - -// discovered boost mpl limitation on some length - -template -struct FizzBuzz -{ - typedef typename concat3::type, typename IF::type >::RET >::RET >::RET, typename mpendl::type>::type type; + fizzbuzz() + { std::cout << "Buzz" << std::endl; } }; template <> -struct FizzBuzz<1> +struct fizzbuzz<0,0,0> { - typedef mpl::string<'1','\r','\n'>::type type; + fizzbuzz() + { std::cout << 0 << std::endl; } }; -int main(int argc, char** argv) +template +struct fb_run { - const int n = 7; - std::cout << mpl::c_str::type>::value << std::endl; - return 0; + fizzbuzz fb; +}; + +int main() +{ + fb_run<100> fb; + return 0; } diff --git a/Task/FizzBuzz/C++/fizzbuzz-6.cpp b/Task/FizzBuzz/C++/fizzbuzz-6.cpp new file mode 100644 index 0000000000..d00cefbbe2 --- /dev/null +++ b/Task/FizzBuzz/C++/fizzbuzz-6.cpp @@ -0,0 +1,164 @@ +#include +#include +#include +#include +#include +#include + +using namespace std; +using namespace boost; + +/////////////////////////////////////////////////////////////////////////////// +// exponentiation calculations +template struct POWER_CORE : POWER_CORE{}; + +template +struct POWER_CORE +{ + enum : int { val = accum }; +}; + +template struct POWER : POWER_CORE<1, base, exp>{}; + +/////////////////////////////////////////////////////////////////////////////// +// # of digit calculations +template struct NUM_DIGITS_CORE : NUM_DIGITS_CORE{}; + +template +struct NUM_DIGITS_CORE +{ + enum : int { val = depth}; +}; + +template struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{}; + +template <> +struct NUM_DIGITS<0> +{ + enum : int { val = 1 }; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Convert digit to character (1 -> '1') +template +struct DIGIT_TO_CHAR +{ + enum : char{ val = i + 48 }; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Find the digit at a given offset into a number of the form 0000000017 +template // place -> [0 .. 10] +struct DIGIT_AT +{ + enum : char{ val = (i / POWER<10, place>::val) % 10 }; +}; + +struct NULL_CHAR +{ + enum : char{ val = '\0' }; +}; + +/////////////////////////////////////////////////////////////////////////////// +// Convert the digit at a given offset into a number of the form '0000000017' to a character +template // place -> [0 .. 9] + struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT::val >{}; + +/////////////////////////////////////////////////////////////////////////////// +// Convert the digit at a given offset into a number of the form '17' to a character + +// Template description, with specialization to generate null characters for out of range offsets +template + struct OFFSET_CHAR_CORE_CHECKED{}; +template + struct OFFSET_CHAR_CORE_CHECKED : NULL_CHAR{}; +template + struct OFFSET_CHAR_CORE_CHECKED : ALT_CHAR{}; + +// Perform the range check and pass it on +template + struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED{}; + +// Calc the number of digits and pass it on +template + struct OFFSET_CHAR : OFFSET_CHAR_CORE::val>{}; + +/////////////////////////////////////////////////////////////////////////////// +// Integer to char* template. Works on unsigned ints. +template +struct IntToStr +{ + const static char str[]; + typedef typename mpl::string< + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + /*OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val,*/ + NULL_CHAR::val>::type type; +}; + +template +const char IntToStr::str[] = +{ + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + OFFSET_CHAR::val, + NULL_CHAR::val +}; + +template +struct IF +{ + typedef Then RET; +}; + +template +struct IF +{ + typedef Else RET; +}; + + +template < typename Str1, typename Str2 > +struct concat : mpl::insert_range::type, Str2> {}; +template +struct concat3 : mpl::insert_range::type, typename concat::type > {}; + +typedef typename mpl::string<'f','i','z','z'>::type fizz; +typedef typename mpl::string<'b','u','z','z'>::type buzz; +typedef typename mpl::string<'\r', '\n'>::type mpendl; +typedef typename concat::type fizzbuzz; + +// discovered boost mpl limitation on some length + +template +struct FizzBuzz +{ + typedef typename concat3::type, typename IF::type >::RET >::RET >::RET, typename mpendl::type>::type type; +}; + +template <> +struct FizzBuzz<1> +{ + typedef mpl::string<'1','\r','\n'>::type type; +}; + +int main(int argc, char** argv) +{ + const int n = 7; + std::cout << mpl::c_str::type>::value << std::endl; + return 0; +} diff --git a/Task/FizzBuzz/C/fizzbuzz-1.c b/Task/FizzBuzz/C/fizzbuzz-1.c index b6e087e7ae..d022ac5eb2 100644 --- a/Task/FizzBuzz/C/fizzbuzz-1.c +++ b/Task/FizzBuzz/C/fizzbuzz-1.c @@ -1,20 +1,5 @@ -#include +#include -int main (void) -{ - int i; - for (i = 1; i <= 100; i++) - { - if (!(i % 15)) - printf ("FizzBuzz"); - else if (!(i % 3)) - printf ("Fizz"); - else if (!(i % 5)) - printf ("Buzz"); - else - printf ("%d", i); - - printf("\n"); - } - return 0; +int main() { + for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n"); } diff --git a/Task/FizzBuzz/C/fizzbuzz-2.c b/Task/FizzBuzz/C/fizzbuzz-2.c index 10d5072f99..b6e087e7ae 100644 --- a/Task/FizzBuzz/C/fizzbuzz-2.c +++ b/Task/FizzBuzz/C/fizzbuzz-2.c @@ -1,16 +1,20 @@ -#include +#include -main() { - int i = 1; - while(i <= 100) { - if(i % 15 == 0) - puts("FizzBuzz"); - else if(i % 3 == 0) - puts("Fizz"); - else if(i % 5 == 0) - puts("Buzz"); - else - printf("%d\n", i); - i++; - } +int main (void) +{ + int i; + for (i = 1; i <= 100; i++) + { + if (!(i % 15)) + printf ("FizzBuzz"); + else if (!(i % 3)) + printf ("Fizz"); + else if (!(i % 5)) + printf ("Buzz"); + else + printf ("%d", i); + + printf("\n"); + } + return 0; } diff --git a/Task/FizzBuzz/C/fizzbuzz-3.c b/Task/FizzBuzz/C/fizzbuzz-3.c index daa85416cc..10d5072f99 100644 --- a/Task/FizzBuzz/C/fizzbuzz-3.c +++ b/Task/FizzBuzz/C/fizzbuzz-3.c @@ -1,3 +1,16 @@ #include -#define F(x,y) printf("%s",i%x?"":#y"zz") -int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;} + +main() { + int i = 1; + while(i <= 100) { + if(i % 15 == 0) + puts("FizzBuzz"); + else if(i % 3 == 0) + puts("Fizz"); + else if(i % 5 == 0) + puts("Buzz"); + else + printf("%d\n", i); + i++; + } +} diff --git a/Task/FizzBuzz/C/fizzbuzz-4.c b/Task/FizzBuzz/C/fizzbuzz-4.c index de8671632b..daa85416cc 100644 --- a/Task/FizzBuzz/C/fizzbuzz-4.c +++ b/Task/FizzBuzz/C/fizzbuzz-4.c @@ -1,11 +1,3 @@ -#include - -int main () -{ - int i; - const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; - for (i = 1; i <= 100; i++) - printf(s[!(i % 3) + 2 * !(i % 5)], i); - - return 0; -} +#include +#define F(x,y) printf("%s",i%x?"":#y"zz") +int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;} diff --git a/Task/FizzBuzz/C/fizzbuzz-5.c b/Task/FizzBuzz/C/fizzbuzz-5.c new file mode 100644 index 0000000000..de8671632b --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-5.c @@ -0,0 +1,11 @@ +#include + +int main () +{ + int i; + const char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; + for (i = 1; i <= 100; i++) + printf(s[!(i % 3) + 2 * !(i % 5)], i); + + return 0; +} diff --git a/Task/FizzBuzz/C/fizzbuzz-6.c b/Task/FizzBuzz/C/fizzbuzz-6.c new file mode 100644 index 0000000000..a3b8a4d01f --- /dev/null +++ b/Task/FizzBuzz/C/fizzbuzz-6.c @@ -0,0 +1,11 @@ +#include + +int main(void) +{ + for (int i = 1; i <= 100; ++i) { + if (i % 3 == 0) printf("fizz"); + if (i % 5 == 0) printf("buzz"); + if (i * i * i * i % 15 == 1) printf("%d", i); + puts(""); + } +} diff --git a/Task/FizzBuzz/Clipper/fizzbuzz.clipper b/Task/FizzBuzz/Clipper/fizzbuzz.clipper index 6e2334b5f6..22b5cee129 100644 --- a/Task/FizzBuzz/Clipper/fizzbuzz.clipper +++ b/Task/FizzBuzz/Clipper/fizzbuzz.clipper @@ -1,9 +1,12 @@ -Procedure Main() - Local n - Local cFB - For n := 1 to 100 +PROCEDURE Main() + + LOCAL n + LOCAL cFB + + FOR n := 1 TO 100 cFB := "" - AEval( {{3,"Fizz"},{5,"Buzz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")}) - ?? Iif(cFB == "", LTrim(Str(n)), cFB) + Iif(n == 100, ".", ", ") - Next -Return + AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } ) + ?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " ) + NEXT + + RETURN diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj index 086b301e3c..09465645d5 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-1.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-1.clj @@ -1,5 +1,9 @@ -(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz" - (zero? (mod x 5)) "Buzz" - (zero? (mod x 3)) "Fizz" - :else x)) - (range 1 101)) +(defn fizzbuzz [start finish] (map (fn [n] + (cond + (zero? (mod n 3)) "Fizz" + (zero? (mod n 5)) "Buzz" + (zero? (mod n 15)) "FizzBuzz" + :else n)) + (range start finish)) +) +(fizzbuzz 1 100) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-2.clj b/Task/FizzBuzz/Clojure/fizzbuzz-2.clj index 5e8e028b11..086b301e3c 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-2.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-2.clj @@ -1 +1,5 @@ -(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101)) +(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz" + (zero? (mod x 5)) "Buzz" + (zero? (mod x 3)) "Fizz" + :else x)) + (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj index 4021e6960c..5e8e028b11 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-3.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-3.clj @@ -1,6 +1 @@ -(def fizzbuzz (map - #(cond (zero? (mod % 15)) "FizzBuzz" - (zero? (mod % 5)) "Buzz" - (zero? (mod % 3)) "Fizz" - :else %) - (iterate inc 1))) +(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-4.clj b/Task/FizzBuzz/Clojure/fizzbuzz-4.clj index d104442437..4021e6960c 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-4.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-4.clj @@ -1,13 +1,6 @@ -(defn fizz-buzz - ([] (fizz-buzz (range 1 101))) - ([lst] - (letfn [(fizz? [n] (zero? (mod n 3))) - (buzz? [n] (zero? (mod n 5)))] - (let [f "Fizz" - b "Buzz" - items (map (fn [n] - (cond (and (fizz? n) (buzz? n)) (str f b) - (fizz? n) f - (buzz? n) b - :else n)) - lst)] items)))) +(def fizzbuzz (map + #(cond (zero? (mod % 15)) "FizzBuzz" + (zero? (mod % 5)) "Buzz" + (zero? (mod % 3)) "Fizz" + :else %) + (iterate inc 1))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-5.clj b/Task/FizzBuzz/Clojure/fizzbuzz-5.clj index 95073f3e20..d104442437 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-5.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-5.clj @@ -1,6 +1,13 @@ -(map (fn [n] - (if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") - (when (zero? (mod n 5)) "Buzz")))] - (apply str fb) - n)) - (range 1 101)) +(defn fizz-buzz + ([] (fizz-buzz (range 1 101))) + ([lst] + (letfn [(fizz? [n] (zero? (mod n 3))) + (buzz? [n] (zero? (mod n 5)))] + (let [f "Fizz" + b "Buzz" + items (map (fn [n] + (cond (and (fizz? n) (buzz? n)) (str f b) + (fizz? n) f + (buzz? n) b + :else n)) + lst)] items)))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-6.clj b/Task/FizzBuzz/Clojure/fizzbuzz-6.clj index b637918e95..95073f3e20 100644 --- a/Task/FizzBuzz/Clojure/fizzbuzz-6.clj +++ b/Task/FizzBuzz/Clojure/fizzbuzz-6.clj @@ -1,4 +1,6 @@ -(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) ) - (range) - (cycle [ "" "" "Fizz" ]) - (cycle [ "" "" "" "" "Buzz" ]))) +(map (fn [n] + (if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz") + (when (zero? (mod n 5)) "Buzz")))] + (apply str fb) + n)) + (range 1 101)) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-7.clj b/Task/FizzBuzz/Clojure/fizzbuzz-7.clj new file mode 100644 index 0000000000..b637918e95 --- /dev/null +++ b/Task/FizzBuzz/Clojure/fizzbuzz-7.clj @@ -0,0 +1,4 @@ +(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) ) + (range) + (cycle [ "" "" "Fizz" ]) + (cycle [ "" "" "" "" "Buzz" ]))) diff --git a/Task/FizzBuzz/Clojure/fizzbuzz-8.clj b/Task/FizzBuzz/Clojure/fizzbuzz-8.clj new file mode 100644 index 0000000000..0726c310ec --- /dev/null +++ b/Task/FizzBuzz/Clojure/fizzbuzz-8.clj @@ -0,0 +1 @@ +(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % % "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101)) diff --git a/Task/FizzBuzz/ColdFusion/fizzbuzz.cfm b/Task/FizzBuzz/ColdFusion/fizzbuzz.cfm new file mode 100644 index 0000000000..d6158ae1b8 --- /dev/null +++ b/Task/FizzBuzz/ColdFusion/fizzbuzz.cfm @@ -0,0 +1,7 @@ + + FizzBuzz + Fizz + Buzz + #i# + + diff --git a/Task/FizzBuzz/D/fizzbuzz.d b/Task/FizzBuzz/D/fizzbuzz.d index e330fd8473..9ecac80843 100644 --- a/Task/FizzBuzz/D/fizzbuzz.d +++ b/Task/FizzBuzz/D/fizzbuzz.d @@ -1,35 +1,53 @@ -import std.stdio: writeln; +import std.stdio, std.algorithm, std.conv; -// with if-else -void fizzBuzz(int n) { - foreach (i; 1 .. n+1) +/// With if-else. +void fizzBuzz(in uint n) { + foreach (immutable i; 1 .. n + 1) if (!(i % 15)) - writeln("FizzBuzz"); + "FizzBuzz".writeln; else if (!(i % 3)) - writeln("Fizz"); + "Fizz".writeln; else if (!(i % 5)) - writeln("Buzz"); + "Buzz".writeln; else - writeln(i); + i.writeln; } -// with switch case -void fizzBuzzSwitch(int n) { - foreach (i; 1 .. n+1) - switch(i % 15) { +/// With switch case. +void fizzBuzzSwitch(in uint n) { + foreach (immutable i; 1 .. n + 1) + switch (i % 15) { case 0: - writeln("FizzBuzz"); break; + "FizzBuzz".writeln; + break; case 3, 6, 9, 12: - writeln("Fizz"); break; + "Fizz".writeln; + break; case 5, 10: - writeln("Buzz"); break; + "Buzz".writeln; + break; default: - writeln(i); + i.writeln; } } -void main() { - fizzBuzz(100); - writeln(); - fizzBuzzSwitch(100); +void fizzBuzzSwitch2(in uint n) { + foreach (immutable i; 1 .. n + 1) + (i % 15).predSwitch( + 0, "FizzBuzz", + 3, "Fizz", + 5, "Buzz", + 6, "Fizz", + 9, "Fizz", + 10, "Buzz", + 12, "Fizz", + /*else*/ i.text).writeln; +} + +void main() { + 100.fizzBuzz; + writeln; + 100.fizzBuzzSwitch; + writeln; + 100.fizzBuzzSwitch2; } diff --git a/Task/FizzBuzz/Eiffel/fizzbuzz.e b/Task/FizzBuzz/Eiffel/fizzbuzz.e new file mode 100644 index 0000000000..1f43230922 --- /dev/null +++ b/Task/FizzBuzz/Eiffel/fizzbuzz.e @@ -0,0 +1,35 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + + make + do + fizzbuzz + end + + fizzbuzz + local + i: INTEGER + do + from + i:= 1 + until + i>100 + loop + if i\\15= 0 then + io.put_string ("FIZZBUZZ%N") + elseif i\\3=0 then + io.put_string ("FIZZ%N") + elseif i\\5=0 then + io.put_string ("BUZZ%N") + else + io.put_string (i.out + "%N") + end + i:= i+1 + end + end +end diff --git a/Task/FizzBuzz/Elixir/fizzbuzz.elixir b/Task/FizzBuzz/Elixir/fizzbuzz-1.elixir similarity index 100% rename from Task/FizzBuzz/Elixir/fizzbuzz.elixir rename to Task/FizzBuzz/Elixir/fizzbuzz-1.elixir diff --git a/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir b/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir new file mode 100644 index 0000000000..8ab6ffcdd6 --- /dev/null +++ b/Task/FizzBuzz/Elixir/fizzbuzz-2.elixir @@ -0,0 +1,13 @@ +#!/usr/bin/env elixir +1..100 |> Enum.map(fn i -> + cond do + rem(i,3*5) == 0 -> + "fizzbuzz" + rem(i,3) == 0 -> + "fizz" + rem(i,5) == 0 -> + "buzz" + true -> + i + end +end) |> Enum.map(fn i -> IO.puts i end) diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js index d7a25fd9ad..23309d3cf0 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-1.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-1.js @@ -1,21 +1,7 @@ -for (var i = 1; i <= 100; i++) { - if (i % 15 == 0) { - console.log("FizzBuzz"); - } else if (i % 3 == 0) { - console.log("Fizz"); - } else if (i % 5 == 0) { - console.log("Buzz"); - } else { - console.log(i); - } +var i, output; +for (i = 1; i < 101; i++) { + output = ''; + if (!(i % 3)) output += 'Fizz'; + if (!(i % 5)) output += 'Buzz'; + console.log(output || i); } - -Array.apply(null, { length: 100 }).map(function(n, i) { - ++i; - return !(i % 15) ? - "FizzBuzz" : - !(i % 3) ? - "Fizz" : - !(i % 5) ? - "Buzz" : i; -}).join("\r\n"); diff --git a/Task/FizzBuzz/JavaScript/fizzbuzz-2.js b/Task/FizzBuzz/JavaScript/fizzbuzz-2.js index 821c624692..6d37d23951 100644 --- a/Task/FizzBuzz/JavaScript/fizzbuzz-2.js +++ b/Task/FizzBuzz/JavaScript/fizzbuzz-2.js @@ -1 +1,25 @@ -for (var i=1; i<=100; i++) console.log( (i % 3 === 0 ? 'Fizz' : '') + (i % 5 === 0 ? 'Buzz' : '') || i ); +var divs = [15, 3, 5]; +var says = ['FizzBuzz', 'Fizz', 'Buzz']; + +function fizzBuzz(first, last) { + for (var n = first; n <= last; n++) { + print(getFizzBuzz(n)); + } +} + +function getFizzBuzz(n) { + var sayWhat = n; + for (var d = 0; d < divs.length; d++) { + if (isMultOf(n, divs[d])) { + sayWhat = says[d]; + break; + } + } + return sayWhat; +} + +function isMultOf(n, d) { + return n % d == 0; +} + +fizzBuzz(1, 100); diff --git a/Task/FizzBuzz/Julia/fizzbuzz-3.julia b/Task/FizzBuzz/Julia/fizzbuzz-3.julia index 4f2dd5f65c..e6c6d7751f 100644 --- a/Task/FizzBuzz/Julia/fizzbuzz-3.julia +++ b/Task/FizzBuzz/Julia/fizzbuzz-3.julia @@ -1,4 +1,4 @@ fb(i::Int) = "Fizz" ^ (i%3==0) * "Buzz" ^ (i%5==0) * string(i) ^ (i%3!=0 && i%5!=0) -[println(fb(i)) for i = 1:100]; +for i=1:100 println(fb(i)) end diff --git a/Task/FizzBuzz/Julia/fizzbuzz-4.julia b/Task/FizzBuzz/Julia/fizzbuzz-4.julia new file mode 100644 index 0000000000..01fe37eeb5 --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-4.julia @@ -0,0 +1 @@ +map((x) -> x % 15 == 0 ? "FizzBuzz" : (x % 5 == 0 ? "Buzz" : (x % 3 == 0 ? "Fizz" : x)), 1:100) diff --git a/Task/FizzBuzz/Julia/fizzbuzz-5.julia b/Task/FizzBuzz/Julia/fizzbuzz-5.julia new file mode 100644 index 0000000000..a714f5c4af --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-5.julia @@ -0,0 +1,7 @@ +fib(i) = let result = "" + (i%3 == 0 && (result *="Fizz" ; true)) | + (i%5 == 0 && (result *="Buzz" ; true)) || + (result = string(i)) + result + end +println([fib(i) for i = 1:100]) diff --git a/Task/FizzBuzz/Julia/fizzbuzz-6.julia b/Task/FizzBuzz/Julia/fizzbuzz-6.julia new file mode 100644 index 0000000000..20466c4c51 --- /dev/null +++ b/Task/FizzBuzz/Julia/fizzbuzz-6.julia @@ -0,0 +1,4 @@ +for i = 1:100 + msg = "Fizz" ^ (i%3==0) * "Buzz" ^ (i%5==0) + println(msg=="" ? i : msg) +end diff --git a/Task/FizzBuzz/Lua/fizzbuzz-2.lua b/Task/FizzBuzz/Lua/fizzbuzz-2.lua index 0709733a31..e3d3f8a089 100644 --- a/Task/FizzBuzz/Lua/fizzbuzz-2.lua +++ b/Task/FizzBuzz/Lua/fizzbuzz-2.lua @@ -7,7 +7,7 @@ for i = 1, 100 do output = output.."Buzz" end if(output == "") then - output = output..i + output = i end print(output) end diff --git a/Task/FizzBuzz/Maple/fizzbuzz-1.maple b/Task/FizzBuzz/Maple/fizzbuzz-1.maple new file mode 100644 index 0000000000..1cf58a8725 --- /dev/null +++ b/Task/FizzBuzz/Maple/fizzbuzz-1.maple @@ -0,0 +1 @@ +seq(print(`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n))),n=1..100): diff --git a/Task/FizzBuzz/Maple/fizzbuzz-2.maple b/Task/FizzBuzz/Maple/fizzbuzz-2.maple new file mode 100644 index 0000000000..bfd9dcdb39 --- /dev/null +++ b/Task/FizzBuzz/Maple/fizzbuzz-2.maple @@ -0,0 +1,2 @@ +fizzbuzz1 := n->`if`(modp(n,3)=0,`if`(modp(n,15)=0,"FizzBuzz","Fizz"),`if`(modp(n,5)=0,"Buzz",n)): +for i to 100 do fizzbuzz1(i); od; diff --git a/Task/FizzBuzz/Maple/fizzbuzz-3.maple b/Task/FizzBuzz/Maple/fizzbuzz-3.maple new file mode 100644 index 0000000000..ad8862b12d --- /dev/null +++ b/Task/FizzBuzz/Maple/fizzbuzz-3.maple @@ -0,0 +1,2 @@ +fizzbuzz2 := n->piecewise(modp(n,15)=0,"FizzBuzz",modp(n,3)=0,"Fizz",modp(n,5)=0,"Buzz",n): +for i to 100 do fizzbuzz2(i); od; diff --git a/Task/FizzBuzz/Maple/fizzbuzz-4.maple b/Task/FizzBuzz/Maple/fizzbuzz-4.maple new file mode 100644 index 0000000000..97a4f6c27e --- /dev/null +++ b/Task/FizzBuzz/Maple/fizzbuzz-4.maple @@ -0,0 +1,8 @@ +fizzbuzz3 := proc(n) local r; + r:=map2(modp,n,[3,5]); + if r=[0,0] then "FizzBuzz" + elif r[1]=0 then "Fizz" + elif r[2]=0 then "Buzz" + else n fi; +end proc: +for i to 100 do fizzbuzz3(i); od; diff --git a/Task/FizzBuzz/Mercury/fizzbuzz.mercury b/Task/FizzBuzz/Mercury/fizzbuzz.mercury index 589f583b0d..b0dd06bd82 100644 --- a/Task/FizzBuzz/Mercury/fizzbuzz.mercury +++ b/Task/FizzBuzz/Mercury/fizzbuzz.mercury @@ -1,26 +1,32 @@ :- module fizzbuzz. + :- interface. + :- import_module io. + :- pred main(io::di, io::uo) is det. + :- implementation. + :- import_module int, string, bool. :- func fizz(int) = bool. -:- func buzz(int) = bool. fizz(N) = ( if N mod 3 = 0 then yes else no ). + +:- func buzz(int) = bool. buzz(N) = ( if N mod 5 = 0 then yes else no ). -:- pred fizzbuzz(int::in, bool::in, bool::in, string::out) is det. -% 3? 5? -fizzbuzz(_, yes, yes, "FizzBuzz"). -fizzbuzz(_, yes, no, "Fizz"). -fizzbuzz(_, no, yes, "Buzz"). -fizzbuzz(N, no, no, S) :- S = from_int(N). +% N 3? 5? +:- func fizzbuzz(int, bool, bool) = string. +fizzbuzz(_, yes, yes) = "FizzBuzz". +fizzbuzz(_, yes, no) = "Fizz". +fizzbuzz(_, no, yes) = "Buzz". +fizzbuzz(N, no, no) = from_int(N). main(!IO) :- main(1, 100, !IO). :- pred main(int::in, int::in, io::di, io::uo) is det. main(N, To, !IO) :- - io.write_string(S, !IO), io.nl(!IO), - fizzbuzz(N, fizz(N), buzz(N), S), - ( if N < To then main(N + 1, To, !IO) else !:IO = !.IO ). + io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO), io.nl(!IO), + ( N < To -> main(N + 1, To, !IO) + ; !:IO = !.IO ). diff --git a/Task/FizzBuzz/Mirah/fizzbuzz-1.mirah b/Task/FizzBuzz/Mirah/fizzbuzz-1.mirah new file mode 100644 index 0000000000..936719bd97 --- /dev/null +++ b/Task/FizzBuzz/Mirah/fizzbuzz-1.mirah @@ -0,0 +1,6 @@ +1.upto(100) do |n| + print "Fizz" if a = ((n % 3) == 0) + print "Buzz" if b = ((n % 5) == 0) + print n unless (a || b) + print "\n" +end diff --git a/Task/FizzBuzz/Mirah/fizzbuzz.mirah b/Task/FizzBuzz/Mirah/fizzbuzz-2.mirah similarity index 51% rename from Task/FizzBuzz/Mirah/fizzbuzz.mirah rename to Task/FizzBuzz/Mirah/fizzbuzz-2.mirah index 57da4b44ae..8f5d27371a 100644 --- a/Task/FizzBuzz/Mirah/fizzbuzz.mirah +++ b/Task/FizzBuzz/Mirah/fizzbuzz-2.mirah @@ -1,11 +1,3 @@ -1.upto(100) do |n| - print "Fizz" if a = ((n % 3) == 0) - print "Buzz" if b = ((n % 5) == 0) - print n unless (a || b) - print "\n" -end - -# a little more straight forward 1.upto(100) do |n| if (n % 15) == 0 puts "FizzBuzz" diff --git a/Task/FizzBuzz/NewLISP/fizzbuzz.newlisp b/Task/FizzBuzz/NewLISP/fizzbuzz.newlisp new file mode 100644 index 0000000000..e83fe3955f --- /dev/null +++ b/Task/FizzBuzz/NewLISP/fizzbuzz.newlisp @@ -0,0 +1,7 @@ +(dotimes (i 100) + (println + (cond + ((= 0 (% i 15)) "FizzBuzz") + ((= 0 (% i 3)) "Fizz") + ((= 0 (% i 5)) "Buzz") + ('t i)))) diff --git a/Task/FizzBuzz/OCaml/fizzbuzz-1.ocaml b/Task/FizzBuzz/OCaml/fizzbuzz-1.ocaml new file mode 100644 index 0000000000..95a3c691b0 --- /dev/null +++ b/Task/FizzBuzz/OCaml/fizzbuzz-1.ocaml @@ -0,0 +1,9 @@ +let fizzbuzz i = + match i mod 3, i mod 5 with + 0, 0 -> "FizzBuzz" + | 0, _ -> "Fizz" + | _, 0 -> "Buzz" + | _ -> string_of_int i + +let _ = + for i = 1 to 100 do print_endline (fizzbuzz i) done diff --git a/Task/FizzBuzz/OCaml/fizzbuzz-2.ocaml b/Task/FizzBuzz/OCaml/fizzbuzz-2.ocaml new file mode 100644 index 0000000000..89451492cc --- /dev/null +++ b/Task/FizzBuzz/OCaml/fizzbuzz-2.ocaml @@ -0,0 +1,9 @@ +(* Useful rule declaration: "cond => f", 'cond'itionally applies 'f' to 'a'ccumulated value *) +let (=>) cond f a = if cond then f a else a +let append s a = a^s + +let fizzbuzz i = + "" |> (i mod 3 = 0 => append "Fizz") + |> (i mod 5 = 0 => append "Buzz") + |> (function "" -> string_of_int i + | s -> s) diff --git a/Task/FizzBuzz/OCaml/fizzbuzz.ocaml b/Task/FizzBuzz/OCaml/fizzbuzz.ocaml deleted file mode 100644 index 3612f22604..0000000000 --- a/Task/FizzBuzz/OCaml/fizzbuzz.ocaml +++ /dev/null @@ -1,9 +0,0 @@ -let output x = - match x mod 3 = 0, x mod 5 = 0 with - true, true -> "FizzBuzz" - | true, false -> "Fizz" - | false, true -> "Buzz" - | false, false -> string_of_int x - -let _ = - for i = 1 to 100 do print_endline (output i) done diff --git a/Task/FizzBuzz/PL-SQL/fizzbuzz.sql b/Task/FizzBuzz/PL-SQL/fizzbuzz.sql index a9dee2f443..f94a7e3b69 100644 --- a/Task/FizzBuzz/PL-SQL/fizzbuzz.sql +++ b/Task/FizzBuzz/PL-SQL/fizzbuzz.sql @@ -1,17 +1,15 @@ -CREATE OR REPLACE PROCEDURE FIZZBUZZ AS - i NUMBER; -BEGIN - - FOR i in 1 .. 100 LOOP - IF MOD(i, 15) = 0 THEN - DBMS_OUTPUT.PUT_LINE('FizzBuzz'); - ELSIF MOD(i, 5) = 0 THEN - DBMS_OUTPUT.PUT_LINE('Buzz'); - ELSIF MOD(i, 3) = 0 THEN - DBMS_OUTPUT.PUT_LINE('Fizz'); - ELSE - DBMS_OUTPUT.PUT_LINE(i); - END IF; - END LOOP; - -END FIZZBUZZ; +begin + for i in 1 .. 100 + loop + case + when mod(i, 15) = 0 then + dbms_output.put_line('FizzBuzz'); + when mod(i, 5) = 0 then + dbms_output.put_line('Buzz'); + when mod(i, 3) = 0 then + dbms_output.put_line('Fizz'); + else + dbms_output.put_line(i); + end case; + end loop; +end; diff --git a/Task/FizzBuzz/Perl-6/fizzbuzz-4.pl6 b/Task/FizzBuzz/Perl-6/fizzbuzz-4.pl6 index 860c42dac8..40879a121b 100644 --- a/Task/FizzBuzz/Perl-6/fizzbuzz-4.pl6 +++ b/Task/FizzBuzz/Perl-6/fizzbuzz-4.pl6 @@ -1,4 +1 @@ -.say for - (('' xx 2, 'Fizz') xx * Z~ - ('' xx 4, 'Buzz') xx *) Z|| - 1 .. 100; +say "Fizz"x$_%%3~"Buzz"x$_%%5||$_ for 1..100 diff --git a/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 b/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 new file mode 100644 index 0000000000..860c42dac8 --- /dev/null +++ b/Task/FizzBuzz/Perl-6/fizzbuzz-5.pl6 @@ -0,0 +1,4 @@ +.say for + (('' xx 2, 'Fizz') xx * Z~ + ('' xx 4, 'Buzz') xx *) Z|| + 1 .. 100; diff --git a/Task/FizzBuzz/Python/fizzbuzz-2.py b/Task/FizzBuzz/Python/fizzbuzz-2.py index 88c70464bb..45b2d7051a 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-2.py +++ b/Task/FizzBuzz/Python/fizzbuzz-2.py @@ -1,7 +1 @@ -for n in range(1,101): - msg = "" - if not (n%3): - msg += "Fizz" - if not (n%5): - msg += "Buzz" - print msg or str(n) +for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i) diff --git a/Task/FizzBuzz/Python/fizzbuzz-3.py b/Task/FizzBuzz/Python/fizzbuzz-3.py index 9e12c84b82..b29ebd9a54 100644 --- a/Task/FizzBuzz/Python/fizzbuzz-3.py +++ b/Task/FizzBuzz/Python/fizzbuzz-3.py @@ -1,3 +1,13 @@ -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 +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/R/fizzbuzz-1.r b/Task/FizzBuzz/R/fizzbuzz-1.r index ae7832a4ac..fdaa8b8634 100644 --- a/Task/FizzBuzz/R/fizzbuzz-1.r +++ b/Task/FizzBuzz/R/fizzbuzz-1.r @@ -1,6 +1,5 @@ -x <- 1:100 -xx <- as.character(x) -xx[x%%3==0] <- "Fizz" -xx[x%%5==0] <- "Buzz" -xx[x%%15==0] <- "FizzBuzz" +xx <- x <- 1:100 +xx[x %% 3 == 0] <- "Fizz" +xx[x %% 5 == 0] <- "Buzz" +xx[x %% 15 == 0] <- "FizzBuzz" xx diff --git a/Task/FizzBuzz/REXX/fizzbuzz-1.rexx b/Task/FizzBuzz/REXX/fizzbuzz-1.rexx index 719cf5d17e..aa990fe594 100644 --- a/Task/FizzBuzz/REXX/fizzbuzz-1.rexx +++ b/Task/FizzBuzz/REXX/fizzbuzz-1.rexx @@ -1,9 +1,8 @@ /*REXX program displays numbers 1 ──► 100 for the FizzBuzz problem. */ - do j=1 to 100; z=j - if j//3 ==0 then z='Fizz' - if j//5 ==0 then z='Buzz' - if j//(3*5)==0 then z='FizzBuzz' + do j=1 to 100; z=j /*╔═════════════════════════════╗*/ + if j//3 ==0 then z='Fizz' /*║ The IFs must be in ║*/ + if j//5 ==0 then z='Buzz' /*║ ascending order.║*/ + if j//(3*5)==0 then z='FizzBuzz' /*╚═════════════════════════════╝*/ say right(z,8) - end /*j*/ - /*stick a fork in it, we're done.*/ + end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/FizzBuzz/REXX/fizzbuzz-2.rexx b/Task/FizzBuzz/REXX/fizzbuzz-2.rexx index 82d1b40db8..0214638173 100644 --- a/Task/FizzBuzz/REXX/fizzbuzz-2.rexx +++ b/Task/FizzBuzz/REXX/fizzbuzz-2.rexx @@ -1,11 +1,10 @@ /*REXX program displays numbers 1 ──► 100 for the FizzBuzz problem. */ - do n=1 for 100 - select - when n//15==0 then say 'FizzBuzz' - when n//5 ==0 then say ' Buzz' - when n//3 ==0 then say ' Fizz' - otherwise say right(n,8) - end /*select*/ - end /*n*/ - /*stick a fork in it, we're done.*/ + do n=1 for 100 + select /*╔═════════════════════════════╗*/ + when n//15==0 then say 'FizzBuzz' /*║ The WHENs must be in ║*/ + when n//5 ==0 then say ' Buzz' /*║ descending order║*/ + when n//3 ==0 then say ' Fizz' /*╚═════════════════════════════╝*/ + otherwise say right(n,8) + end /*select*/ + end /*n*/ /*stick a fork in it, we're done.*/ diff --git a/Task/FizzBuzz/REXX/fizzbuzz-3.rexx b/Task/FizzBuzz/REXX/fizzbuzz-3.rexx index 6d2d478f39..b176cb3342 100644 --- a/Task/FizzBuzz/REXX/fizzbuzz-3.rexx +++ b/Task/FizzBuzz/REXX/fizzbuzz-3.rexx @@ -1,8 +1,8 @@ /*REXX program displays numbers 1 ──► 100 for the FizzBuzz problem. */ - do n=1 for 100; _= - if n//3 ==0 then _= 'Fizz' - if n//5 ==0 then _=_'Buzz' - say right(word(_ n,1),8) - end /*n*/ - /*stick a fork in it, we're done.*/ + do n=1 for 100; _= + if n//3 ==0 then _=_'Fizz' + if n//5 ==0 then _=_'Buzz' +/* if n//7 ==0 then _=_'Jazz' */ /*◄───note that this is a comment*/ + say right(word(_ n,1),8) + end /*n*/ /*stick a fork in it, we're done.*/ diff --git a/Task/FizzBuzz/REXX/fizzbuzz-4.rexx b/Task/FizzBuzz/REXX/fizzbuzz-4.rexx new file mode 100644 index 0000000000..41694674d1 --- /dev/null +++ b/Task/FizzBuzz/REXX/fizzbuzz-4.rexx @@ -0,0 +1,6 @@ +/*REXX program displays numbers 1 ──► 100 for the FizzBuzz problem. */ + /* [↓] concise & somewhat obtuse*/ + do n=1 for 100 + say right(word(word('Fizz',1+(n//3\==0))word('Buzz',1+(n//5\==0)) n,1),8) + end /*n*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-1.rb b/Task/FizzBuzz/Ruby/fizzbuzz-1.rb index 86a1e61158..307604ed07 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-1.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-1.rb @@ -2,5 +2,5 @@ print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) - print "\n" + puts end diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-10.rb b/Task/FizzBuzz/Ruby/fizzbuzz-10.rb new file mode 100644 index 0000000000..18ccc56ae3 --- /dev/null +++ b/Task/FizzBuzz/Ruby/fizzbuzz-10.rb @@ -0,0 +1,8 @@ +class Integer + def fizzbuzz + v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" + v.empty? ? self : v + end +end + +puts *(1..100).map(&:fizzbuzz) diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-11.rb b/Task/FizzBuzz/Ruby/fizzbuzz-11.rb new file mode 100644 index 0000000000..3a6a18d553 --- /dev/null +++ b/Task/FizzBuzz/Ruby/fizzbuzz-11.rb @@ -0,0 +1,8 @@ +fizzbuzz = ->(i) do + (i%15).zero? and next "FizzBuzz" + (i%3).zero? and next "Fizz" + (i%5).zero? and next "Buzz" + i +end + +puts (1..100).map(&fizzbuzz).join("\n") diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-7.rb b/Task/FizzBuzz/Ruby/fizzbuzz-7.rb index d0d167d009..58847e92a8 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-7.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-7.rb @@ -1 +1 @@ -1.upto(100) { |i| p "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/m] || i } +1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i } diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb index 18ccc56ae3..7d491782ed 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-8.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-8.rb @@ -1,8 +1,5 @@ -class Integer - def fizzbuzz - v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}" - v.empty? ? self : v - end +f = [nil, nil, :Fizz].cycle +b = [nil, nil, nil, nil, :Buzz].cycle +(1..100).each do |i| + puts "#{f.next}#{b.next}"[/.+/] || i end - -puts *(1..100).map(&:fizzbuzz) diff --git a/Task/FizzBuzz/Ruby/fizzbuzz-9.rb b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb index 3a6a18d553..1e8df2732d 100644 --- a/Task/FizzBuzz/Ruby/fizzbuzz-9.rb +++ b/Task/FizzBuzz/Ruby/fizzbuzz-9.rb @@ -1,8 +1,3 @@ -fizzbuzz = ->(i) do - (i%15).zero? and next "FizzBuzz" - (i%3).zero? and next "Fizz" - (i%5).zero? and next "Buzz" - i -end - -puts (1..100).map(&fizzbuzz).join("\n") +seq = *0..100 +{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}} +puts seq.drop(1) diff --git a/Task/FizzBuzz/Rust/fizzbuzz-1.rust b/Task/FizzBuzz/Rust/fizzbuzz-1.rust index f6c50bb0f1..867479dc0b 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-1.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-1.rust @@ -1,20 +1,12 @@ -// rust 0.8 - +// rust 0.13 fn main() { - 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; + for i in range(1i, 101){ + let value = i.to_string(); + println!("{}", match (i % 3, i % 5) { + (0,0) => "FizzBuzz", + (0,_) => "Fizz", + (_,0) => "Buzz", + _ => value.as_slice() + }); } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-2.rust b/Task/FizzBuzz/Rust/fizzbuzz-2.rust index 1f48319e30..adce026b3f 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-2.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-2.rust @@ -1,11 +1,11 @@ -// 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 ) } +// rust 0.11 +fn main() { + for num in std::iter::range_inclusive(1i, 100) { + match (num % 3, num % 5) { + (0, 0) => println!("FizzBuzz"), + (0, _) => println!("Fizz"), + (_, 0) => println!("Buzz"), + (_, _) => println!("{}", num), + } + } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-3.rust b/Task/FizzBuzz/Rust/fizzbuzz-3.rust index 7a71249c2b..f8ffe1699c 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-3.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-3.rust @@ -1,14 +1,16 @@ -// rust 0.8 +// rust 0.11 fn main() { - for num in std::iter::range_inclusive(1, 100) { - println( - match (num % 3, num % 5) { - (0, 0) => ~"FizzBuzz", - (0, _) => ~"Fizz", - (_, 0) => ~"Buzz", - (_, _) => num.to_str() - } - ); + for num in std::iter::range_inclusive(1i, 100) { + println!("{}", fizzbuzz(num)) + } +} + +fn fizzbuzz(num: int) -> String { + match (num % 3, num % 5) { + (0, 0) => format!("FizzBuzz"), + (0, _) => format!("Fizz"), + (_, 0) => format!("Buzz"), + (_, _) => format!("{}", num), } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-4.rust b/Task/FizzBuzz/Rust/fizzbuzz-4.rust index 7fe1c0669b..f6c50bb0f1 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-4.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-4.rust @@ -1,14 +1,20 @@ // rust 0.8 fn main() { - for num in std::iter::range_inclusive(1, 100) { - println( - match (num % 3 == 0, num % 5 == 0) { - (false, false) => num.to_str(), - (true, false) => ~"Fizz", - (false, true) => ~"Buzz", - (true, true) => ~"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; } } diff --git a/Task/FizzBuzz/Rust/fizzbuzz-5.rust b/Task/FizzBuzz/Rust/fizzbuzz-5.rust index 876ca5f309..1f48319e30 100644 --- a/Task/FizzBuzz/Rust/fizzbuzz-5.rust +++ b/Task/FizzBuzz/Rust/fizzbuzz-5.rust @@ -1,20 +1,11 @@ // 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); - } +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-6.rust b/Task/FizzBuzz/Rust/fizzbuzz-6.rust new file mode 100644 index 0000000000..7a71249c2b --- /dev/null +++ b/Task/FizzBuzz/Rust/fizzbuzz-6.rust @@ -0,0 +1,14 @@ +// rust 0.8 + +fn main() { + for num in std::iter::range_inclusive(1, 100) { + println( + match (num % 3, num % 5) { + (0, 0) => ~"FizzBuzz", + (0, _) => ~"Fizz", + (_, 0) => ~"Buzz", + (_, _) => num.to_str() + } + ); + } +} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-7.rust b/Task/FizzBuzz/Rust/fizzbuzz-7.rust new file mode 100644 index 0000000000..7fe1c0669b --- /dev/null +++ b/Task/FizzBuzz/Rust/fizzbuzz-7.rust @@ -0,0 +1,14 @@ +// rust 0.8 + +fn main() { + for num in std::iter::range_inclusive(1, 100) { + println( + match (num % 3 == 0, num % 5 == 0) { + (false, false) => num.to_str(), + (true, false) => ~"Fizz", + (false, true) => ~"Buzz", + (true, true) => ~"FizzBuzz" + } + ); + } +} diff --git a/Task/FizzBuzz/Rust/fizzbuzz-8.rust b/Task/FizzBuzz/Rust/fizzbuzz-8.rust new file mode 100644 index 0000000000..876ca5f309 --- /dev/null +++ b/Task/FizzBuzz/Rust/fizzbuzz-8.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 b063f91ba2..f1ab5ec2da 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-1.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-1.sql @@ -1,10 +1,8 @@ -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) +SELECT CASE + WHEN MOD(level,15)=0 THEN 'FizzBuzz' + WHEN MOD(level,3)=0 THEN 'Fizz' + WHEN MOD(level,5)=0 THEN 'Buzz' + ELSE TO_CHAR(level) + END FizzBuzz + FROM dual + CONNECT BY LEVEL <= 100; diff --git a/Task/FizzBuzz/SQL/fizzbuzz-2.sql b/Task/FizzBuzz/SQL/fizzbuzz-2.sql index 49ea56e974..575ff10ee8 100644 --- a/Task/FizzBuzz/SQL/fizzbuzz-2.sql +++ b/Task/FizzBuzz/SQL/fizzbuzz-2.sql @@ -1,2 +1,3 @@ -select nvl(decode(mod(n,3),0,'Fizz')||decode(mod(n,5),0,'Buzz'),n) -from (select level n from dual connect by level<=100) +SELECT nvl(decode(MOD(level,3),0,'Fizz')||decode(MOD(level,5),0,'Buzz'),level) +FROM dual +CONNECT BY level<=100; diff --git a/Task/FizzBuzz/Scala/fizzbuzz-1.scala b/Task/FizzBuzz/Scala/fizzbuzz-1.scala index e03bfb3d64..7a66b32e60 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-1.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-1.scala @@ -1,7 +1,10 @@ - for (x <- 1 to 100) println( - (x % 3, x % 5) match { +object FizzBuzz extends App { + 1 to 100 foreach { n => + println((n % 3, n % 5) match { case (0, 0) => "FizzBuzz" case (0, _) => "Fizz" case (_, 0) => "Buzz" - case _ => x + case _ => n }) + } +} diff --git a/Task/FizzBuzz/Scala/fizzbuzz-2.scala b/Task/FizzBuzz/Scala/fizzbuzz-2.scala index 4d90d86888..12d1d7412b 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-2.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-2.scala @@ -1,8 +1,7 @@ - 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 replaceMultiples(x: Int, rs: (Int, String)*): Either[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) +def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity) - 1 to 100 map fizzbuzz foreach println +1 to 100 map fizzbuzz foreach println diff --git a/Task/FizzBuzz/Scala/fizzbuzz-3.scala b/Task/FizzBuzz/Scala/fizzbuzz-3.scala index 8a35250f4f..713b519f41 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-3.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-3.scala @@ -1,2 +1,2 @@ - 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)))) +def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMet +for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString)))) diff --git a/Task/FizzBuzz/Scala/fizzbuzz-4.scala b/Task/FizzBuzz/Scala/fizzbuzz-4.scala index fd15578a3e..9f6125c0f9 100644 --- a/Task/FizzBuzz/Scala/fizzbuzz-4.scala +++ b/Task/FizzBuzz/Scala/fizzbuzz-4.scala @@ -1,2 +1 @@ -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)))) +for (n <- 1 to 100) println(List((15, "FizzBuzz"), (3, "Fizz"), (5, "Buzz")).find(t => n % t._1 == 0).getOrElse((0, n.toString))._2) diff --git a/Task/FizzBuzz/Scheme/fizzbuzz.ss b/Task/FizzBuzz/Scheme/fizzbuzz-1.ss similarity index 100% rename from Task/FizzBuzz/Scheme/fizzbuzz.ss rename to Task/FizzBuzz/Scheme/fizzbuzz-1.ss diff --git a/Task/FizzBuzz/Scheme/fizzbuzz-2.ss b/Task/FizzBuzz/Scheme/fizzbuzz-2.ss new file mode 100644 index 0000000000..ff83a93334 --- /dev/null +++ b/Task/FizzBuzz/Scheme/fizzbuzz-2.ss @@ -0,0 +1,10 @@ +(define (fizzbuzz x y) + (println + (cond (( = (modulo x 15) 0 ) "FizzBuzz") + (( = (modulo x 3) 0 ) "Fizz") + (( = (modulo x 5) 0 ) "Buzz") + (else x))) + + (if (< x y) (fizzbuzz (+ x 1) y))) + +(fizzbuzz 1 100) diff --git a/Task/FizzBuzz/Vim-Script/fizzbuzz.vim b/Task/FizzBuzz/Vim-Script/fizzbuzz.vim new file mode 100644 index 0000000000..60501a394f --- /dev/null +++ b/Task/FizzBuzz/Vim-Script/fizzbuzz.vim @@ -0,0 +1,11 @@ +for i in range(1, 100) + if i % 15 == 0 + echo "FizzBuzz" + elseif i % 5 == 0 + echo "Buzz" + elseif i % 3 == 0 + echo "Fizz" + else + echo i + endif +endfor diff --git a/Task/FizzBuzz/XSLT/fizzbuzz-1.xslt b/Task/FizzBuzz/XSLT/fizzbuzz-1.xslt new file mode 100644 index 0000000000..01f77c093c --- /dev/null +++ b/Task/FizzBuzz/XSLT/fizzbuzz-1.xslt @@ -0,0 +1,53 @@ + + + + + + + + + + + Fizz + Buzz + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Task/FizzBuzz/XSLT/fizzbuzz-2.xslt b/Task/FizzBuzz/XSLT/fizzbuzz-2.xslt new file mode 100644 index 0000000000..282be80d91 --- /dev/null +++ b/Task/FizzBuzz/XSLT/fizzbuzz-2.xslt @@ -0,0 +1,33 @@ + + + + + + + <_> + + + + + + + + + +Fizz + + +Buzz + + +FizzBuzz + + + + + + + diff --git a/Task/FizzBuzz/XSLT/fizzbuzz-3.xslt b/Task/FizzBuzz/XSLT/fizzbuzz-3.xslt new file mode 100644 index 0000000000..6cb338dede --- /dev/null +++ b/Task/FizzBuzz/XSLT/fizzbuzz-3.xslt @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/Task/Flatten-a-list/Elixir/flatten-a-list.elixir b/Task/Flatten-a-list/Elixir/flatten-a-list.elixir new file mode 100644 index 0000000000..3a67238dbe --- /dev/null +++ b/Task/Flatten-a-list/Elixir/flatten-a-list.elixir @@ -0,0 +1,12 @@ +defmodule RC do + def flatten([]), do: [] + def flatten([h|t]), do: flatten(h) ++ flatten(t) + def flatten(h), do: [h] +end + +list = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] + +# Our own implementation +IO.inspect RC.flatten(list) +# Library function +IO.inspect List.flatten(list) diff --git a/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js b/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js index 7a7c9a3bd3..5fdb352af1 100644 --- a/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js +++ b/Task/Flatten-a-list/JavaScript/flatten-a-list-2.js @@ -1,5 +1,3 @@ -let flatten = list => { - return list.reduce( +let flatten = list => list.reduce( (a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), [] - ); -} +); diff --git a/Task/Flatten-a-list/Mercury/flatten-a-list.mercury b/Task/Flatten-a-list/Mercury/flatten-a-list.mercury new file mode 100644 index 0000000000..a460b05442 --- /dev/null +++ b/Task/Flatten-a-list/Mercury/flatten-a-list.mercury @@ -0,0 +1,34 @@ +:- module flatten_a_list. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list. + +:- type tree(T) + ---> leaf(T) + ; node(list(tree(T))). + +:- func flatten(tree(T)) = list(T). + +flatten(leaf(X)) = [X]. +flatten(node(Xs)) = condense(map(flatten, Xs)). + +main(!IO) :- + List = node([ + node([leaf(1)]), + leaf(2), + node([node([leaf(3), leaf(4)]), leaf(5)]), + node([node([node([])])]), + node([node([node([leaf(6)])])]), + leaf(7), + leaf(8), + node([]) + ]), + io.print_line(flatten(List), !IO). + +:- end_module flatten_a_list. diff --git a/Task/Flatten-a-list/Python/flatten-a-list-1.py b/Task/Flatten-a-list/Python/flatten-a-list-1.py index 775c064adc..2510fa9e16 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-1.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-1.py @@ -1,7 +1,11 @@ ->>> def flatten(lst): - return sum( ([x] if not isinstance(x, list) else flatten(x) - for x in lst), [] ) +>>> def flatten(lst, results=[]): # 'results' defaults to an empty list [] + for e in lst: # for each element 'e' in lst + if type(e) is list: # if that element is a list, then + flatten(e, results) # flatten that sublist, appending results to "results" + else: # if element is not a list, then + results.append(e) # insert a copy of it at the end of "results" + return results ->>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] ->>> flatten(lst) +>>> l = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] +>>> flatten(l) [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flatten-a-list/Python/flatten-a-list-3.py b/Task/Flatten-a-list/Python/flatten-a-list-3.py index b1e465991b..4033430e75 100644 --- a/Task/Flatten-a-list/Python/flatten-a-list-3.py +++ b/Task/Flatten-a-list/Python/flatten-a-list-3.py @@ -7,6 +7,6 @@ yield x ->>>lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] ->>>print list(flatten(lst)) +>>> lst = [[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8, []] +>>> print list(flatten(lst)) [1, 2, 3, 4, 5, 6, 7, 8] diff --git a/Task/Flatten-a-list/Racket/flatten-a-list-2.rkt b/Task/Flatten-a-list/Racket/flatten-a-list-2.rkt index 2cc794db1d..23d561f717 100644 --- a/Task/Flatten-a-list/Racket/flatten-a-list-2.rkt +++ b/Task/Flatten-a-list/Racket/flatten-a-list-2.rkt @@ -1 +1,6 @@ -'(1 2 3 4 5 6 7 8 9) +#lang racket +(define (flatten l) + (cond [(empty? l) null] + [(not (list? l)) (list l)] + [else (append (flatten (first l)) (flatten (rest l)))])) +(flatten '(1 (2 (3 4 5) (6 7)) 8 9)) diff --git a/Task/Flatten-a-list/Run-BASIC/flatten-a-list.run b/Task/Flatten-a-list/Run-BASIC/flatten-a-list.run index 86abec4830..e609f36c47 100644 --- a/Task/Flatten-a-list/Run-BASIC/flatten-a-list.run +++ b/Task/Flatten-a-list/Run-BASIC/flatten-a-list.run @@ -1,15 +1,8 @@ -latten$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]" - -i = instr(flatten$,"[") -while i > 0 - flatten$ = left$(flatten$,i-1) + mid$(flatten$,i+1) - i = instr(flatten$,"]") - flatten$ = left$(flatten$,i-1) + mid$(flatten$,i+1) - i = instr(flatten$," ") - flatten$ = left$(flatten$,i-1) + mid$(flatten$,i+1) - i = instr(flatten$,",,") - flatten$ = left$(flatten$,i-1) + mid$(flatten$,i+1) - i = instr(flatten$,"[") -wend - -print flatten$ +n$ = "[[1], 2, [[3,4], 5], [[[]]], [[[6]]], 7, 8 []]" +for i = 1 to len(n$) + if instr("[] ,",mid$(n$,i,1)) = 0 then + flatten$ = flatten$ + c$ + mid$(n$,i,1) + c$ = "," + end if +next i +print "[";flatten$;"]" diff --git a/Task/Flatten-a-list/VBScript/flatten-a-list-3.vb b/Task/Flatten-a-list/VBScript/flatten-a-list-3.vb index 72cbbe5924..527938aa5f 100644 --- a/Task/Flatten-a-list/VBScript/flatten-a-list-3.vb +++ b/Task/Flatten-a-list/VBScript/flatten-a-list-3.vb @@ -1 +1,15 @@ -1!2!3!4!5!6!7!8 +' Flatten the example array... +a = FlattenArray(Array(Array(1), 2, Array(Array(3,4), 5), Array(Array(Array())), Array(Array(Array(6))), 7, 8, Array())) + +' Print the list, comma-separated... +WScript.Echo Join(a, ",") + +Function FlattenArray(a) + If IsArray(a) Then DoFlatten a, FlattenArray: FlattenArray = Split(Trim(FlattenArray)) +End Function + +Sub DoFlatten(a, s) + For i = 0 To UBound(a) + If IsArray(a(i)) Then DoFlatten a(i), s Else s = s & a(i) & " " + Next +End Sub diff --git a/Task/Flow-control-structures/00DESCRIPTION b/Task/Flow-control-structures/00DESCRIPTION index fe63203d02..cc3385f61c 100644 --- a/Task/Flow-control-structures/00DESCRIPTION +++ b/Task/Flow-control-structures/00DESCRIPTION @@ -1,2 +1,5 @@ {{Control Structures}} -In this task, we document common flow-control structures. One common example of a flow-control structure is the goto construct. Note that [[Conditional Structures]] and [[Iteration|Loop Structures]] have their own articles/categories. +In this task, we document common flow-control structures. +One common example of a flow-control structure is the goto construct. +Note that [[Conditional Structures]] and [[Iteration|Loop Structures]] +have their own articles/categories. diff --git a/Task/Flow-control-structures/Scala/flow-control-structures.scala b/Task/Flow-control-structures/Scala/flow-control-structures.scala new file mode 100644 index 0000000000..86d42d067f --- /dev/null +++ b/Task/Flow-control-structures/Scala/flow-control-structures.scala @@ -0,0 +1,26 @@ +import Goto._ +import scala.util.continuations._ + +object Goto { + + case class Label(k: Label => Unit) + + private case class GotoThunk(label: Label) extends Throwable + + def label: Label @suspendable = + shift((k: Label => Unit) => executeFrom(Label(k))) + + def goto(l: Label): Nothing = + throw new GotoThunk(l) + + private def executeFrom(label: Label): Unit = { + val nextLabel = try { + label.k(label) + None + } catch { + case g: GotoThunk => Some(g.label) + } + if (nextLabel.isDefined) executeFrom(nextLabel.get) + } + +} diff --git a/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg b/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg new file mode 100644 index 0000000000..3e06ecbe63 --- /dev/null +++ b/Task/Floyds-triangle/ALGOL-68/floyds-triangle.alg @@ -0,0 +1,33 @@ +# procedure to print a Floyd's Triangle with n lines # +PROC floyds triangle = ( INT n )VOID: +BEGIN + + # calculate the number of the highest number that will be printed # + # ( the sum of the integers 1, 2, ... n ) # + INT max number = ( n * ( n + 1 ) ) OVER 2; + + # determine the widths required to print the numbers of the final row # + [ n ]INT widths; + INT number := max number + 1; + FOR col FROM n BY -1 TO 1 DO + widths[ col ] := - ( UPB whole( number -:= 1, 0 ) + 1 ) + OD; + + # print the triangle # + INT element := 0; + FOR row TO n DO + FOR col TO row DO + print( ( whole( element +:= 1, widths[ col ] ) ) ) + OD; + print( ( newline ) ) + OD + +END; # floyds triangle # + +main: ( + + floyds triangle( 5 ); + print( ( newline ) ); + floyds triangle( 14 ) + +) diff --git a/Task/Floyds-triangle/C-sharp/floyds-triangle.cs b/Task/Floyds-triangle/C-sharp/floyds-triangle.cs new file mode 100644 index 0000000000..52d6a19b22 --- /dev/null +++ b/Task/Floyds-triangle/C-sharp/floyds-triangle.cs @@ -0,0 +1,46 @@ +using System; +using System.Text; + +public class FloydsTriangle +{ + internal static void Main(string[] args) + { + int count; + if (args.Length >= 1 && int.TryParse(args[0], out count) && count > 0) + { + Console.WriteLine(MakeTriangle(count)); + } + else + { + Console.WriteLine(MakeTriangle(5)); + Console.WriteLine(); + Console.WriteLine(MakeTriangle(14)); + } + } + + public static string MakeTriangle(int rows) + { + int maxValue = (rows * (rows + 1)) / 2; + int digit = 0; + StringBuilder output = new StringBuilder(); + + for (int row = 1; row <= rows; row++) + { + for (int column = 0; column < row; column++) + { + int colMaxDigit = (maxValue - rows) + column + 1; + if (column > 0) + { + output.Append(' '); + } + + digit++; + output.Append(digit.ToString().PadLeft(colMaxDigit.ToString().Length)); + } + + output.AppendLine(); + } + + return output.ToString(); + } +} diff --git a/Task/Floyds-triangle/Python/floyds-triangle-2.py b/Task/Floyds-triangle/Python/floyds-triangle-2.py index 54452c6cb2..54b77b6437 100644 --- a/Task/Floyds-triangle/Python/floyds-triangle-2.py +++ b/Task/Floyds-triangle/Python/floyds-triangle-2.py @@ -1,3 +1,3 @@ def floyd(rowcount=5): - return [list(range(i*(i-1)//2+1, i*(i+1)//2+1)) - for i in range(1, rowcount+1)] + return [list(range(i*(i-1)//2+1, i*(i+1)//2+1)) + for i in range(1, rowcount+1)] diff --git a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx index c7cdff08bb..02d123761a 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-2.rexx @@ -1,11 +1,11 @@ /*REXX pgm constructs & displays Floyd's triangle for any number of rows*/ -parse arg rows .; if rows=='' then rows=5 /*use 5 rows if not given. */ -mV = rows * (rows+1) % 2 /*calculate the max value. */ -say 'displaying a' rows "row Floyd's triangle:"; say -#=1; do r=1 for rows; i=0; _='' - do #=# for r; i=i+1 - _ = _ right(#, length(mV-rows+i)) - end /*#*/ - say substr(_,2) /*suppress a leading blank.*/ - end /*r*/ +parse arg rows .; if rows=='' then rows=5 /*Not specified? Use default*/ +maxV = rows * (rows+1) % 2 /*calculate the max value. */ +say 'displaying a' rows "row Floyd's triangle:"; say /*show header*/ +#=1; do r=1 for rows; i=0; _= /*row by row.*/ + do #=# for r; i=i+1 /*start a row*/ + _ = _ right(#, length(maxV-rows+i)) /*build a row*/ + end /*#*/ /*row is done*/ + say substr(_,2) /*suppress the 1st leading blank,*/ + end /*r*/ /* [↑] introduced by 1st abutt.*/ /*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 e34a93fc78..d24ef2c0aa 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-3.rexx @@ -1,11 +1,11 @@ /*REXX pgm displays Floyd's triangle for any number of rows in base 16.*/ -parse arg rows .; if rows=='' then rows=6 /*use 6 rows if not given. */ -mV = rows * (rows+1) % 2 /*calculate the max value. */ -say 'displaying a' rows "row Floyd's triangle in base 16:"; say -#=1; do r=1 for rows; i=0; _='' - do #=# for r; i=i+1 - _ = _ right(d2x(#), length(d2x(mV-rows+i))) - end /*#*/ - say substr(_,2) /*suppress a leading blank.*/ - end /*r*/ +parse arg rows .; if rows=='' then rows=6 /*Not specified? Use default*/ +maxV = rows * (rows+1) % 2 /*calculate the max value. */ +say 'displaying a' rows "row Floyd's triangle in base 16:"; say /*hdr*/ +#=1; do r=1 for rows; i=0; _= /*row by row.*/ + do #=# for r; i=i+1 /*start a row*/ + _ = _ right(d2x(#), length(d2x(maxV - rows + i))) + end /*#*/ /* [↑] the triangle row is done.*/ + say substr(_,2) /*suppress the 1st leading blank,*/ + end /*r*/ /* [↑] introduced by 1st abutt.*/ /*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 d5f2e8f3d4..63ded583c2 100644 --- a/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx +++ b/Task/Floyds-triangle/REXX/floyds-triangle-4.rexx @@ -1,23 +1,23 @@ /*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. */ -say 'displaying a' rows "row Floyd's triangle in base" b':'; say -#=1; do r=1 for rows; i=0; _='' - do #=# for r; i=i+1 - _ = _ right(base(#, b), length(base(mV-rows+i, b))) - end /*#*/ - say substr(_,2) /*suppress a leading blank.*/ - end /*r*/ +parse arg rows b .; if rows=='' then rows=5 /*Not given? Use default.*/ +if b=='' then b=10 /*use base 10 if not given.*/ +maxV = rows * (rows+1) % 2 /*calculate the max value. */ +say 'displaying a' rows "row Floyd's triangle in base" b':'; say +#=1; do r=1 for rows; i=0; _= /*row by row.*/ + do #=# for r; i=i+1 /*start a row*/ + _ = _ right(base(#, b), length(base(maxV-rows+i, b))) + end /*#*/ /*row is done*/ + say substr(_,2) /*suppress the 1st leading blank,*/ + end /*r*/ /* [↑] introduced by 1st abutt.*/ 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*/ +base: procedure; parse arg x 1 ox,toB,inB /*get 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.*/ @@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ - /*handles up to base 90 special chars must be viewable.*/ -numeric digits 1000 /*what the hey, support gihugics.*/ + /*handles up to base 90, special chars must be viewable.*/ +numeric digits 1000 /*what the hey, support gihugeics*/ 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,16 +27,16 @@ 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. */ + _=substr(x, j, 1) /*pick off a numeral 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*/ - -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 /*j*/ +y= + do while #>=toB /*convert #, base 10 ──► base toB*/ + y=substr(@@@, (#//toB)+1, 1)y /*construct the number for output*/ + #=#%toB /*··· and whittle # down also. */ + end /*while #≥toB*/ y=sigX || substr(@@@, #+1, 1)y /*prepend the sign if it existed.*/ return y /*rturn the number in base toB. */ diff --git a/Task/Floyds-triangle/Run-BASIC/floyds-triangle.run b/Task/Floyds-triangle/Run-BASIC/floyds-triangle.run index c2614b62b4..0d8d4ab488 100644 --- a/Task/Floyds-triangle/Run-BASIC/floyds-triangle.run +++ b/Task/Floyds-triangle/Run-BASIC/floyds-triangle.run @@ -1,8 +1,9 @@ input " Number of rows:"; rows +html "" for r = 1 to rows ' r = rows + html "" for c = 1 to r ' c = columns j = j + 1 - print using("#####",j);" "; - next c - print + html "" + next c next r diff --git a/Task/Forest-fire/D/forest-fire-1.d b/Task/Forest-fire/D/forest-fire-1.d index 6afba53282..64fa9b2212 100644 --- a/Task/Forest-fire/D/forest-fire-1.d +++ b/Task/Forest-fire/D/forest-fire-1.d @@ -1,54 +1,54 @@ import std.stdio, std.random, std.string, std.algorithm; -enum TREE_PROB = 0.55; // original tree probability -enum F_PROB = 0.01; // auto combustion probability -enum P_PROB = 0.01; // tree creation probability +enum treeProb = 0.55; // Original tree probability. +enum fProb = 0.01; // Auto combustion probability. +enum cProb = 0.01; // Tree creation probability. enum Cell : char { empty=' ', tree='T', fire='#' } -alias Cell[][] World; +alias World = Cell[][]; bool hasBurningNeighbours(in World world, in int r, in int c) -pure nothrow { - foreach (rowShift; -1 .. 2) - foreach (colShift; -1 .. 2) - if ((r + rowShift) >= 0 && (r + rowShift) < world.length && - (c + colShift) >= 0 && (c + colShift) < world[0].length && - world[r + rowShift][c + colShift] == Cell.fire) - return true; - return false; +pure nothrow @safe @nogc { + foreach (immutable rowShift; -1 .. 2) + foreach (immutable colShift; -1 .. 2) + if ((r + rowShift) >= 0 && (r + rowShift) < world.length && + (c + colShift) >= 0 && (c + colShift) < world[0].length && + world[r + rowShift][c + colShift] == Cell.fire) + return true; + return false; } -void nextState(in World world, World nextWorld) { - foreach (r, row; world) - foreach (c, elem; row) - final switch (elem) { - case Cell.empty: - nextWorld[r][c]= uniform(0.,1.) #self then goto continue1 end + for l = j - 1, j + 1 do + if l < 1 or + l > #self[i] or + math.abs((k - i) + (l - j)) ~= 1 + then + goto continue2 + end + if self[k][l] == 2 then return true end + ::continue2:: + end + ::continue1:: + end + return false +end + +local it = 1 +curses.initscr() +curses.start_color() +curses.echo(false) +curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) +curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) +win = curses.newwin(forest_y + 2, forest_x, 0, 0) +win:clear() +win:mvaddstr(forest_y + 1, 0, "p_spawn = " .. p_spawn .. ", p_ignite = " .. p_ignite) +repeat + forest:draw() + win:move(forest_y, 0) + win:clrtoeol() + win:addstr("Iteration: " .. it .. ", nap = " .. naptime*1000 .. "ms") + win:refresh() + forest:step() + it = it + 1 + socket.sleep(naptime) +until false diff --git a/Task/Forest-fire/Perl-6/forest-fire.pl6 b/Task/Forest-fire/Perl-6/forest-fire.pl6 index b40b574046..ed3a2d05c3 100644 --- a/Task/Forest-fire/Perl-6/forest-fire.pl6 +++ b/Task/Forest-fire/Perl-6/forest-fire.pl6 @@ -1,16 +1,19 @@ -constant RED = "\e[1;31m"; -constant CLEAR = "\e[0m"; +my $RED = "\e[1;31m"; +my $YELLOW = "\e[1;33m"; +my $GREEN = "\e[1;32m"; +my $CLEAR = "\e[0m"; -enum Cell-State ; -my @show = (' ', '木', RED ~ '木' ~ CLEAR); +enum Cell-State ; +my @show = (' ', $GREEN ~ '木', $YELLOW ~ '木', $RED ~ '木'); class Forest { - has Cell-State @!grid; + has @!grid; has @!neighbors; has Int $.height; has Int $.width; has $.p; has $.f; + has @!cells = ^$!height X ^$!width; method new(Int $height, Int $width, $p=0.01, $f=0.001) { my $c = self.bless(:$height, :$width, :$p, :$f); @@ -24,36 +27,35 @@ class Forest { } method !init-neighbors { - for ^$!height X ^$!width -> $i, $j { - @!neighbors[$i][$j] = gather for + for @!cells -> $i, $j { + @!neighbors[$i][$j] = eager gather for [-1,-1],[+0,-1],[+1,-1], [-1,+0],( ),[+1,+0], [-1,+1],[+0,+1],[+1,+1] { take-rw @!grid[$i + .[0]][$j + .[1]] // next; } - } + } } method step { - my @new; - for ^$!height X ^$!width -> $i, $j { + my @heat; + for @!cells -> $i, $j { given @!grid[$i][$j] { - when Empty { @new[$i][$j] = rand < $!p ?? Tree !! Empty } - when Tree { @new[$i][$j] = - (@!neighbors[$i][$j].any === Burning or rand < $!f) ?? Burning !! Tree; - } - when Burning { @new[$i][$j] = Empty } + when Empty { @!grid[$i][$j] = rand < $!p ?? Tree !! Empty } + when Tree { @!grid[$i][$j] = rand < $!f ?? Heating !! Tree } + when Heating { @!grid[$i][$j] = Burning; push @heat, $i, $j; } + when Burning { @!grid[$i][$j] = Empty } } } - for ^$!height X ^$!width -> $i, $j { - @!grid[$i][$j] = @new[$i][$j]; - } + for @heat -> $i,$j { + $_ = Heating for @!neighbors[$i][$j].grep(Tree); + } } - method Str { - join '', gather for ^$!height -> $i { - take @show[@!grid[$i].list], "\n"; + method show { + for ^$!height -> $i { + say @show[@!grid[$i].list].join; } } } @@ -64,7 +66,7 @@ print "\e[2J"; # ANSI clear screen my $i = 0; loop { print "\e[H"; # ANSI home - say $i++; - say $f.Str; + say $CLEAR, $i++; + $f.show; $f.step; } diff --git a/Task/Forest-fire/REXX/forest-fire.rexx b/Task/Forest-fire/REXX/forest-fire.rexx index 206106347b..2605f56ec7 100644 --- a/Task/Forest-fire/REXX/forest-fire.rexx +++ b/Task/Forest-fire/REXX/forest-fire.rexx @@ -3,64 +3,60 @@ ├─── full version has many more options and enhanced displays. ────┤ └──────────────────────────────────────────────────────────────────┘ */ signal on syntax; signal on novalue /*handle REXX program errors. */ -signal on halt /*handle cell growth interruptus.*/ -parse arg peeps '(' generations rows cols bare! life! clearscreen every -@abc='abcdefghijklmnopqrstuvwxyz'; @abcU=@abc; upper @abcU +signal on halt /*handle growth interruptus. */ +_= /*(below) nullify some options. */ +parse var _ generations rows cols birth lightning bare! fire! tree!, + randseed clearscreen every +if randseed\=='' then call random ,,randseed + percent = 100 /*handy-dandy constant for using%*/ + field = percent**2 /*size of the probability field. */ blank = 'BLANK' generations = p(generations 100) - rows = p(rows 3) - cols = p(cols 3) + rows = p(rows word(scrsize(),1)-2) + cols = p(cols max(79,linesize())-1) bare! = pickchar(bare! blank) -clearscreen = p(clearscreen 0) + fire! = pickchar(fire! '▒') + tree! = pickchar(tree! '18'x) +clearscreen = p(clearscreen 1) every = p(every 999999999) - life! = pickchar(life! '☼') -fents=max(79,cols) /*fence width shown after display*/ -$.=bare! /*the universe is new, and barren*/ + birth = p(strip(birth,,'%') 50 )*percent + lightning = p(strip(lightning,,'%') 1/8)*percent +$.=bare! /*the forest is a treeless field.*/ +@.=bare! /*also, the alternate universe. */ gens=abs(generations) /*use this for convenience. */ -x=space(peeps) /*remove superfluous spaces. */ -if x=='' then x='2,1 2,2 2,3' - - do while x \=='' - parse var x p x; parse var p r ',' c .; $.r=overlay(life!,$.r,c+1) - end -life=0; !.=0; call showCells /*show initial state of the cells*/ -/*─────────────────────────────────────watch cell colony grow/live/die. */ - do life=1 for gens - do r=1 for rows; rank=bare! - do c=2 for cols; ?=substr($.r,c,1); ??=?; n=neighbors() - select /*select da quickest choice first*/ - when ?==bare! then if n==3 then ??=life! - otherwise if n<2 | n>3 then ??=bare! - end /*select*/ +/*═════════════════════════════════════watch the forest grow and/or burn*/ + do life=1 for gens /*process a forest life cycle. */ + do r=1 for rows; rank=bare! + do c=2 for cols; ?=substr($.r,c,1); ??=? + select /*select da quickest choice first*/ + when ?==tree! then if ignite?() then ??=fire! + when ?==bare! then if random(1,field)<=birth then ??=tree! + otherwise /*fire*/ ??=bare! + end /*select*/ rank=rank || ?? - end /*c*/ + end /*c*/ /*ignore column 1, start with 2.*/ @.r=rank - end /*c*/ + end /*r*/ - do r=1 for rows; $.r=@.r; end /*assign alternate cells ──► real*/ - if life//every==0 | generations>0 | life==gens then call showCells - end /*life*/ -/*─────────────────────────────────────stop watching the universe (life)*/ + do r=1 for rows; $.r=@.r; end /*assign alternate cells ──► real*/ + if life//every==0 | generations>0 | life==gens then call showForest + end /*life*/ +/*═════════════════════════════════════stop watching the forest grow. */ halt: cycles=life-1; if cycles\==gens then say 'REXX program interrupted.' exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────SHOWCELLS subroutine─-─────────────────*/ -showCells: if clearscreen then 'CLS' /* ◄─── change this for your OS.*/ -_=; do r=rows by -1 for rows /*show the forest in proper order*/ - z=strip(substr($.r,2),'T') /*pick off the meat of the row. */ - say z; _=_ || z /*be neat about trailing blanks. */ +/*───────────────────────────────SHOWFOREST subroutine──────────────────*/ +showForest: if clearscreen then 'CLS' /* ◄─── change this for your OS.*/ + do r=rows by -1 for rows /*show the forest in proper order*/ + say strip(substr($.r,2),'T') /*be neat about trailing blanks. */ end /*r*/ -say right(copies('═',fents)life,fents) /*show&tell for a stand of trees.*/ -if _=='' then exit /*if no life, then stop the run. */ -if !._ then do; say 'repeating ...'; exit; end -!._=1 /*assign a state & compare later.*/ +say right(copies('═',cols)life, cols) /*show&tell for a stand of trees.*/ return -/*───────────────────────────────NEIGHBORS subroutine───────────────────*/ -neighbors: rp=r+1; cp=c+1; rm=r-1; cm=c-1 /*count 8 neighbors of a cell*/ -return (substr($.rm,cm,1)==life!) + (substr($.rm,c ,1)==life!) + , - (substr($.rm,cp,1)==life!) + (substr($.r ,cm,1)==life!) + , - (substr($.r ,cp,1)==life!) + (substr($.rp,cm,1)==life!) + , - (substr($.rp,c ,1)==life!) + (substr($.rp,cp,1)==life!) -/*───────────────────────────────1-liner subroutines────────────────────*/ +/*──────────────────────────────────IGNITE? subroutine──────────────────*/ +ignite?: if substr($.r,c+1,1)==fire! then return 1 /*east on fire ?*/ + if substr($.r,c-1,1)==fire! then return 1; rp=r+1; rm=r-1 +cm=c-1; if pos(fire!,substr($.rm,cm,3)substr($.rp,cm,3))\==0 then return 1 +return random(1,field) <= lightning +/*───────────────────────────────1─liner subroutines─────────────────────────────────────────────────────────────────────────────────*/ 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) pickchar: _=p(arg(1));if translate(_)==blank then _=' ';if length(_) ==3 then _=d2c(_);if length(_) ==2 then _=x2c(_);return _ diff --git a/Task/Forest-fire/Ruby/forest-fire.rb b/Task/Forest-fire/Ruby/forest-fire.rb index bbb8134de3..32f4479744 100644 --- a/Task/Forest-fire/Ruby/forest-fire.rb +++ b/Task/Forest-fire/Ruby/forest-fire.rb @@ -1,60 +1,44 @@ -require 'enumerator' +class Forest_Fire + Neighborhood = [-1,0,1].product([-1,0,1]) - [0,0] + States = {empty:" ", tree:"T", fire:"#"} -def transition arr, tree_prob, fire_prob - arr.enum_with_index.map do |cell, i| - if i == 0 or i == arr.length - 1 - # boundary conditions: cells are always empty here - :empty - else - case cell - when :fire - # burning cells become empty - :empty - when :empty - # empty cells grow a tree with probability tree_prob - rand < tree_prob ? :tree : :empty - when :tree - # check my neighbouring cells, are they on fire? - if arr[i - 1] == :fire or arr[i + 1] == :fire - :fire + def initialize(xsize, ysize=xsize, p=0.5, f=0.01) + @xsize, @ysize, @p, @f = xsize, ysize, p, f + @field = Array.new(xsize+1) {|i| Array.new(ysize+1, :empty)} + @generation = 0 + end + + def evolve + @generation += 1 + work = @field.map{|row| row.map{|cell| cell}} + for i in 0...@xsize + for j in 0...@ysize + case cell=@field[i][j] + when :empty + cell = :tree if rand < @p + when :tree + cell = :fire if fire?(i,j) else - # neighbours not on fire, but catch fire at random - rand < fire_prob ? :fire : :tree + cell = :empty end + work[i][j] = cell end end + @field = work + end + + def fire?(i,j) + rand < @f or Neighborhood.any? {|di,dj| @field[i+di][j+dj] == :fire} + end + + def display + puts "Generation : #@generation" + puts @xsize.times.map{|i| @ysize.times.map{|j| States[@field[i][j]]}.join} end end -def pretty_print arr - # colour the trees green, the fires red, and the empty spaces black - print(arr.map { |cell| - "\e[3" + - case cell - when :tree - "2mT" - when :fire - "1mF" - when :empty - "0m " - end + "\e[0m" - }.join) +forest = Forest_Fire.new(10,30) +10.times do |i| + forest.evolve + forest.display end - -N = 20 # 20 trees -P = 0.5 # probability of growing a tree -F = 0.1 # probability of catching on fire - -srand Time.now.to_i - -# each cell has a 50/50 chance of being a tree -array = (1..N).map { rand < 0.5 ? :tree : :empty } -array[0] = array[-1] = :empty # boundary conditions -pretty_print array -puts - -begin - array = transition(array, P, F) - - pretty_print array -end while gets.chomp.downcase != "q" diff --git a/Task/Fork/J/fork.j b/Task/Fork/J/fork.j new file mode 100644 index 0000000000..09b0b34d77 --- /dev/null +++ b/Task/Fork/J/fork.j @@ -0,0 +1,2 @@ +load'dll' +Fork =: (('Error'"_)`('Parent'"_)`)(@.([: >: [: * '/lib/x86_64-linux-gnu/libc-2.19.so __fork > x' cd [: i. 0&[)) diff --git a/Task/Fork/NewLISP/fork.newlisp b/Task/Fork/NewLISP/fork.newlisp new file mode 100644 index 0000000000..d99a154450 --- /dev/null +++ b/Task/Fork/NewLISP/fork.newlisp @@ -0,0 +1,4 @@ +(let (pid (fork (println "Hello from child"))) + (cond + ((nil? pid) (throw-error "Unable to fork")) + ('t (wait-pid pid)))) diff --git a/Task/Fork/Scala/fork-1.scala b/Task/Fork/Scala/fork-1.scala new file mode 100644 index 0000000000..25c9337231 --- /dev/null +++ b/Task/Fork/Scala/fork-1.scala @@ -0,0 +1,16 @@ +import java.io.IOException + +object Fork extends App { + val builder: ProcessBuilder = new ProcessBuilder() + val currentUser: String = builder.environment.get("USER") + val command: java.util.List[String] = java.util.Arrays.asList("ps", "-f", "-U", currentUser) + builder.command(command) + try { + val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines() + println(s"Output of running $command is:") + while (lines.hasNext) println(lines.next()) + } + catch { + case iox: IOException => iox.printStackTrace() + } +} diff --git a/Task/Fork/Scala/fork-2.scala b/Task/Fork/Scala/fork-2.scala new file mode 100644 index 0000000000..2424735f81 --- /dev/null +++ b/Task/Fork/Scala/fork-2.scala @@ -0,0 +1,14 @@ +import java.io.IOException + +object Fork extends App { + val command: java.util.List[String] = java.util.Arrays.asList("cmd.exe", "/C", "ECHO.| TIME") + val builder: ProcessBuilder = new ProcessBuilder(command) + try { + val lines = scala.io.Source.fromInputStream(builder.start.getInputStream).getLines() + println(s"Output of running $command is:") + while (lines.hasNext) println(lines.next()) + } + catch { + case iox: IOException => iox.printStackTrace() + } +} diff --git a/Task/Formatted-numeric-output/00META.yaml b/Task/Formatted-numeric-output/00META.yaml index b94a3d25d9..127f3871fc 100644 --- a/Task/Formatted-numeric-output/00META.yaml +++ b/Task/Formatted-numeric-output/00META.yaml @@ -1,4 +1,5 @@ --- category: - Text processing +- Simple note: Basic language learning diff --git a/Task/Formatted-numeric-output/Mathematica/formatted-numeric-output.math b/Task/Formatted-numeric-output/Mathematica/formatted-numeric-output.math index c1128a131e..d6780e7650 100644 --- a/Task/Formatted-numeric-output/Mathematica/formatted-numeric-output.math +++ b/Task/Formatted-numeric-output/Mathematica/formatted-numeric-output.math @@ -1,2 +1,2 @@ -StringJoin[ToString /@ PadLeft[Characters[ToString[ 7.125]], 9]] -->"00007.125" +StringTake["000000" <> ToString[7.125], -9] +00007.125 diff --git a/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol b/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol index e6ea7e60fd..f4897a87eb 100644 --- a/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol +++ b/Task/Formatted-numeric-output/REBOL/formatted-numeric-output.rebol @@ -5,8 +5,8 @@ REBOL [ URL: http://rosettacode.org/wiki/Formatted_Numeric_Output ] -; REBOL has no built-in facilities for printing pictured -; output. However, it's not too hard to cook something up using the +; REBOL has no built-in facilities for printing pictured output. +; However, it's not too hard to cook something up using the ; string manipulation facilities. zeropad: func [ diff --git a/Task/Formatted-numeric-output/Scheme/formatted-numeric-output.ss b/Task/Formatted-numeric-output/Scheme/formatted-numeric-output.ss new file mode 100644 index 0000000000..4efe1f7053 --- /dev/null +++ b/Task/Formatted-numeric-output/Scheme/formatted-numeric-output.ss @@ -0,0 +1,7 @@ +(load "srfi-54.scm") +(load "srfi-54.scm") ;; Don't ask. + +(define x 295643087.65432) + +(dotimes (i 4) + (print (cat x 25 3.0 #\0 (list #\, (- 4 i))))) diff --git a/Task/Forward-difference/00DESCRIPTION b/Task/Forward-difference/00DESCRIPTION index cd1a663440..f10fa20388 100644 --- a/Task/Forward-difference/00DESCRIPTION +++ b/Task/Forward-difference/00DESCRIPTION @@ -1,4 +1,8 @@ -Provide code that produces a list of numbers which is the n-th order forward difference, given a non-negative integer (specifying the order) and a list of numbers. The first-order forward difference of a list of numbers (A) is a new list (B) where Bn = An+1 - An. List B should have one fewer element as a result. The second-order forward difference of A will be the same as the first-order forward difference of B. That new list will have two fewer elements than A and one less than B. The goal of this task is to repeat this process up to the desired order. +Provide code that produces a list of numbers which is the n-th order forward difference, given a non-negative integer (specifying the order) and a list of numbers. +The first-order forward difference of a list of numbers (A) is a new list (B) where Bn = An+1 - An. List B should have one fewer element as a result. +The second-order forward difference of A will be the same as the first-order forward difference of B. +That new list will have two fewer elements than A and one less than B. +The goal of this task is to repeat this process up to the desired order. For a more formal description, see the related [http://mathworld.wolfram.com/ForwardDifference.html Mathworld article]. diff --git a/Task/Forward-difference/C++/forward-difference-1.cpp b/Task/Forward-difference/C++/forward-difference-1.cpp index a1c64c929c..3c43fc2fb0 100644 --- a/Task/Forward-difference/C++/forward-difference-1.cpp +++ b/Task/Forward-difference/C++/forward-difference-1.cpp @@ -82,7 +82,7 @@ int main() std::vector dest; nth_forward_difference(1, array, array+10, std::back_inserter(dest)); - // outut dest + // output dest std::copy(dest.begin(), dest.end(), std::ostream_iterator(std::cout, " ")); std::cout << std::endl; diff --git a/Task/Forward-difference/D/forward-difference-1.d b/Task/Forward-difference/D/forward-difference-1.d index a5e6e4031b..839df3cd56 100644 --- a/Task/Forward-difference/D/forward-difference-1.d +++ b/Task/Forward-difference/D/forward-difference-1.d @@ -1,20 +1,19 @@ -import std.stdio; - T[] forwardDifference(T)(in T[] data, in int level) pure nothrow - in { - assert(level >= 0 && level < data.length); - } body { - //auto result = data.dup; // not nothrow - auto result = data ~ []; // slower - foreach (i; 0 .. level) - foreach (j, ref el; result[0 .. $ - i - 1]) - el = result[j + 1] - el; - result.length -= level; - return result; - } +in { + assert(level >= 0 && level < data.length); +} body { + auto result = data.dup; + foreach (immutable i; 0 .. level) + foreach (immutable j, ref el; result[0 .. $ - i - 1]) + el = result[j + 1] - el; + result.length -= level; + return result; +} void main() { - auto data = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; - foreach (level; 0 .. data.length) - writeln(forwardDifference(data, level)); + import std.stdio; + + const data = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; + foreach (immutable level; 0 .. data.length) + forwardDifference(data, level).writeln; } diff --git a/Task/Forward-difference/D/forward-difference-2.d b/Task/Forward-difference/D/forward-difference-2.d index 4896c315d2..a25fbdba8a 100644 --- a/Task/Forward-difference/D/forward-difference-2.d +++ b/Task/Forward-difference/D/forward-difference-2.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range, std.array; -auto forwardDifference(Range)(Range d, in int level) { +auto forwardDifference(Range)(Range d, in int level) pure { foreach (immutable _; 0 .. level) d = d.zip(d.dropOne).map!(a => a[0] - a[1]).array; return d; diff --git a/Task/Forward-difference/D/forward-difference-3.d b/Task/Forward-difference/D/forward-difference-3.d index c30c2b0fff..a43cf7c5cb 100644 --- a/Task/Forward-difference/D/forward-difference-3.d +++ b/Task/Forward-difference/D/forward-difference-3.d @@ -1,12 +1,12 @@ import std.stdio; -T[] forwardDifference(T)(T[] s, in int n) pure { - foreach (_; 0 .. n) - s[] -= s[1 .. $]; +T[] forwardDifference(T)(T[] s, in int n) pure nothrow @nogc { + foreach (immutable i; 0 .. n) + s[0 .. $ - i - 1] = s[1 .. $ - i] - s[0 .. $ - i - 1]; return s[0 .. $ - n]; } void main() { immutable A = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; - foreach (level; 0 .. A.length) - writeln(forwardDifference(A.dup, level)); + foreach (immutable level; 0 .. A.length) + forwardDifference(A.dup, level).writeln; } diff --git a/Task/Forward-difference/D/forward-difference-4.d b/Task/Forward-difference/D/forward-difference-4.d index 767393125b..e8029b5e75 100644 --- a/Task/Forward-difference/D/forward-difference-4.d +++ b/Task/Forward-difference/D/forward-difference-4.d @@ -1,8 +1,10 @@ -import std.stdio, std.range; - void main() { + import std.stdio, std.range; + auto D = [90.5, 47, 58, 29, 22, 32, 55, 5, 55, 73.5]; - auto R = recurrence!q{(a[n-1].dup[] -= a[n-1][1..$])[0..$-1]}(D); - foreach (di; take(R, D.length)) - writeln(di); + writefln("%(%s\n%)", + recurrence!q{ (a[n - 1][0 .. $ - 1] = + a[n - 1][1 .. $] - + a[n - 1][0 .. $ - 1])[0 .. $] }(D) + .take(D.length)); } diff --git a/Task/Forward-difference/HicEst/forward-difference.hicest b/Task/Forward-difference/HicEst/forward-difference.hicest new file mode 100644 index 0000000000..83e9a5903e --- /dev/null +++ b/Task/Forward-difference/HicEst/forward-difference.hicest @@ -0,0 +1,12 @@ +REAL :: n=10, list(n) + +list = ( 90, 47, 58, 29, 22, 32, 55, 5, 55, 73 ) +WRITE(Format='i1, (i6)') 0, list + +DO i = 1, n-1 + ALIAS(list,1, diff,n-i) ! rename list(1 ... n-i) with diff + diff = list($+1) - diff ! $ is the running left hand array index + WRITE(Format='i1, (i6)') i, diff +ENDDO + +END diff --git a/Task/Forward-difference/Julia/forward-difference.julia b/Task/Forward-difference/Julia/forward-difference.julia new file mode 100644 index 0000000000..18d19000f9 --- /dev/null +++ b/Task/Forward-difference/Julia/forward-difference.julia @@ -0,0 +1 @@ +ndiff(A, n::Integer) = n < 1 ? A : diff(ndiff(A, n-1)) diff --git a/Task/Forward-difference/MATLAB/forward-difference.m b/Task/Forward-difference/MATLAB/forward-difference.m new file mode 100644 index 0000000000..e0126dd9c9 --- /dev/null +++ b/Task/Forward-difference/MATLAB/forward-difference.m @@ -0,0 +1 @@ +Y = diff(X,n); diff --git a/Task/Forward-difference/REXX/forward-difference-1.rexx b/Task/Forward-difference/REXX/forward-difference-1.rexx index b421308627..e9af4e5aaf 100644 --- a/Task/Forward-difference/REXX/forward-difference-1.rexx +++ b/Task/Forward-difference/REXX/forward-difference-1.rexx @@ -1,44 +1,41 @@ -/*REXX program to compute the forward difference of a list of numbers.*/ -/* ┌───────────────────────────────────────────────────────────────────┐ - │ /\ n n n-k │ - │ {delta} / \ n [ƒ] (x) ≡ Σ Ç ∙ (-1) ∙ ƒ(x+k) │ - │ /____\ k=0 k │ - │ │ - │ {n=order} {Ç=comb or binomial coeff.} │ - └───────────────────────────────────────────────────────────────────┘*/ -numeric digits 100 /*ensure enough accuracy. */ -arg numbers ',' ord /*input: x1 x2 x3 x4 ... ,ORD */ -if numbers=='' then numbers='90 47 58 29 22 32 55 5 55 73' /*default?*/ -w=words(numbers) /*set W to # of numbers in list.*/ - - do i=1 for w /*validate input (valid numbers?)*/ - @.i=word(numbers,i) /*assign the next # in the list. */ - if \datatype(@.i,'N') then call ser @.i "isn't a valid number" - @.i=@.i/1 /*normalize the #, prettify the #*/ - end /*i*/ -/*═════════════════════════════════════════process the (optional) input.*/ -if w==0 then call ser 'no numbers were specified' -if ord\=='' & ord<0 then call ser ord "(ner) can't be negative" -if ord\=='' & ord>w then call ser ord "(ner) can't be greater than" w -say right(w 'numbers: ' numbers,64) /*sloppy way to do a header, ... */ -say right(copies('─',length(numbers)),64) /* and the header fence.*/ -if ord=='' then do; bot=0; top=w; end /*define default ners.*/ - else do; bot=n; top=n; end /*just a specific ner?*/ + butchers/mangles some of the characters in the documentation box. --> +/*REXX program computes the forward difference of a list of numbers. + ╔════════════════════════════════════════════════════════════════════╗ + ║ /\ n n n-k ║ + ║ / \ n [ƒ] (x) ≡ Σ C ∙ (-1) ∙ ƒ(x+k) ║ + ║ /____\ k=0 k ║ + ║ ↑ ↑ ↑ ║ + ║ │ │ │ ║ + ║ {delta}─────┘ {n=order} {C=comb or binomial coeff.} ║ + ╚════════════════════════════════════════════════════════════════════╝*/ +numeric digits 100 /*ensure enough accuracy (digits)*/ +parse arg xxx ',' N /*input: ε1 ε2 ε3 ε4 ··· , order*/ +if xxx=='' then xxx='90 47 58 29 22 32 55 5 55 73' /*default numbers.*/ +w=words(xxx) /*set W to # of numbers in list.*/ + /* [↓] validate the input numbers*/ + do i=1 for w; _=word(xxx,i) /*process each number 1 at a time*/ + if \datatype(_,'N') then call ser _ "isn't a valid number" + @.i=_/1 /*normalize the #, prettify the #*/ + end /*i*/ /* [↑] removes superfluous stuff*/ + /* [↓] process (optional) order.*/ +if w==0 then call ser 'no numbers were specified.' +if N\=='' & N<0 then call ser N "(order) can't be negative." +if N\=='' & N>w then call ser N "(order) can't be greater than" w +say right(w 'numbers:', 44) xxx /*display the header ··· */ +say left('', 44)copies('─', length(xxx)+2) /* and the header fence.*/ +if N=='' then do; bot=0; top=w; end /*define default orders. */ + else do; bot=N; top=N; end /*just a specific order? */ /*═════════════════════════════════════════where da rubber meets da road*/ - do order=bot to top; do r=1 for w; !.r=@.r; end; $= - do j=1 for order; d=!.j; do k=j+1 to w /*order diff.*/ - parse value !.k !.k-d with d !.k - end /*k*/ + do #=bot to top; do r=1 for w; !.r=@.r; end; $= + do j=1 for #; d=!.j; do k=j+1 to w + parse value !.k !.k-d with d !.k + end /*k*/ end /*j*/ - do i=order+1 to w /*build list.*/ - $=$ !.i/1 /*append it. */ - end /*i*/ - if $=='' then $='[null]' /*pretty null*/ - what=right(order,length(w))th(order)'-order' /*nice format*/ - say what 'forward difference vector = ' strip($) /*display it.*/ + do i=#+1 to w; $=$ !.i/1; end + if $=='' then $='[null]' + say right(#, 7)th(#)'-order forward difference vector = ' strip($) end /*o*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SER subroutine──────────────────────*/ -ser: say; say '*** error! ***'; say arg(1); say; exit 13 -/*──────────────────────────────────TH subroutine───────────────────────*/ -th: parse arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) +/*──────────────────────────────────one─liner subroutines───────────────*/ +ser: say; say '***error!***'; say arg(1); say; exit 13 +th: arg ?; return word('th st nd rd',1+?//10*(?//100%10\==1)*(?//10<4)) diff --git a/Task/Four-bit-adder/00DESCRIPTION b/Task/Four-bit-adder/00DESCRIPTION index 004f380d65..94352a9a7d 100644 --- a/Task/Four-bit-adder/00DESCRIPTION +++ b/Task/Four-bit-adder/00DESCRIPTION @@ -1,6 +1,10 @@ -The aim of this task is to "''simulate''" a four-bit adder "chip". This "chip" can be realized using four [[wp:Adder_(electronics)#Full_adder|1-bit full adder]]s. Each of these 1-bit full adders can be with two [[wp:Adder_(electronics)#Half_adder|half adder]]s and an ''or'' [[wp:Logic gate|gate]]. Finally a half adder can be made using a ''xor'' gate and an ''and'' gate. The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. +The aim of this task is to "''simulate''" a four-bit adder "chip". +This "chip" can be realized using four [[wp:Adder_(electronics)#Full_adder|1-bit full adder]]s. +Each of these 1-bit full adders can be built with two [[wp:Adder_(electronics)#Half_adder|half adder]]s and an ''or'' [[wp:Logic gate|gate]]. Finally a half adder can be made using a ''xor'' gate and an ''and'' gate. +The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. -'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the [[Bitwise operations|bitwise operators]] of your language. If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant 1 on one input. +'''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the [[Bitwise operations|bitwise operators]] of your language. +If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant 1 on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones. @@ -17,7 +21,8 @@ Instead of optimizing and reducing the number of gates used for the final 4-bit |[[File:4bitsadder.png|frameless|A 4-bit adder]] |} -Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. +Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". +It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
diff --git a/Task/Four-bit-adder/D/four-bit-adder-1.d b/Task/Four-bit-adder/D/four-bit-adder-1.d index 069324c136..927ecb6110 100644 --- a/Task/Four-bit-adder/D/four-bit-adder-1.d +++ b/Task/Four-bit-adder/D/four-bit-adder-1.d @@ -4,22 +4,22 @@ 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 { + out T overflow) pure nothrow @nogc { // A XOR using only NOT, AND and OR, as task requires. - static T xor(in T x, in T y) pure nothrow { + static T xor(in T x, in T y) pure nothrow @nogc { return (~x & y) | (x & ~y); } static void halfAdder(in T a, in T b, - out T s, out T c) pure nothrow { + out T s, out T c) pure nothrow @nogc { 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 { + out T s, out T oc) pure nothrow @nogc { T ps, pc, tc; halfAdder(/*in*/a, b, /*out*/ps, pc); diff --git a/Task/Four-bit-adder/Go/four-bit-adder-2.go b/Task/Four-bit-adder/Go/four-bit-adder-2.go index e92a378b23..83bc11e8b8 100644 --- a/Task/Four-bit-adder/Go/four-bit-adder-2.go +++ b/Task/Four-bit-adder/Go/four-bit-adder-2.go @@ -6,124 +6,120 @@ import "fmt" // You can feed it a single value without blocking. // Reading a value blocks until a value is available. type Wire chan bool -func MakeWire() Wire { - return make(Wire,1) + +func MkWire() Wire { + return make(Wire, 1) } // A source for zero values. -func Zero() Wire { - r := MakeWire() - go func() { - for { - r <- false - } - }() - return r +func Zero() (r Wire) { + r = MkWire() + go func() { + for { + r <- false + } + }() + return } // And gate. -func And(a,b Wire) Wire { - r := MakeWire() - go func() { - for { - x := <-a - y := <-b - r <- (x && y) - } - }() - return r +func And(a, b Wire) (r Wire) { + r = MkWire() + go func() { + for { + r <- (<-a && <-b) + } + }() + return } // Or gate. -func Or(a,b Wire) Wire { - r := MakeWire() - go func() { - for { - x := <-a - y := <-b - r <- (x || y) - } - }() - return r +func Or(a, b Wire) (r Wire) { + r = MkWire() + go func() { + for { + r <- (<-a || <-b) + } + }() + return } // Not gate. -func Not(a Wire) Wire { - r := MakeWire() - go func() { - for { - x := <-a - r <- !x - } - }() - return r +func Not(a Wire) (r Wire) { + r = MkWire() + go func() { + for { + r <- !(<-a) + } + }() + return } // Split a wire in two. -func Split(a Wire) (Wire,Wire) { - r1 := MakeWire() - r2 := MakeWire() - go func() { - for { - x := <-a - r1 <- x - r2 <- x - } - }() - return r1, r2 +func Split(a Wire) (Wire, Wire) { + r1 := MkWire() + r2 := MkWire() + go func() { + for { + x := <-a + r1 <- x + r2 <- x + } + }() + return r1, r2 } // Xor gate, composed of Or, And and Not gates. -func Xor(a,b Wire) Wire { - a1,a2 := Split(a) - b1,b2 := Split(b) - return Or(And(Not(a1),b1),And(a2,Not(b2))) +func Xor(a, b Wire) Wire { + a1, a2 := Split(a) + b1, b2 := Split(b) + return Or(And(Not(a1), b1), And(a2, Not(b2))) } // A half adder, composed of two splits and an And and Xor gate. -func HalfAdder(a,b Wire) (sum,carry Wire) { - a1,a2 := Split(a) - b1,b2 := Split(b) - carry = And(a1,b1) - sum = Xor(a2,b2) - return +func HalfAdder(a, b Wire) (sum, carry Wire) { + a1, a2 := Split(a) + b1, b2 := Split(b) + carry = And(a1, b1) + sum = Xor(a2, b2) + return } // A full adder, composed of two half adders, and an Or gate. -func FullAdder(a,b,carryIn Wire) (result,carryOut Wire) { - s1,c1 := HalfAdder(carryIn,a) - result,c2 := HalfAdder(b,s1) - carryOut = Or(c1,c2) - return +func FullAdder(a, b, carryIn Wire) (result, carryOut Wire) { + s1, c1 := HalfAdder(carryIn, a) + result, c2 := HalfAdder(b, s1) + carryOut = Or(c1, c2) + return } // A four bit adder, composed of a zero source, and four full adders. -func FourBitAdder(a1,a2,a3,a4 Wire, b1,b2,b3,b4 Wire) (r1,r2,r3,r4 Wire, carry Wire) { - carry = Zero() - r1,carry = FullAdder(a1,b1,carry) - r2,carry = FullAdder(a2,b2,carry) - r3,carry = FullAdder(a3,b3,carry) - r4,carry = FullAdder(a4,b4,carry) - return +func FourBitAdder(a1, a2, a3, a4 Wire, b1, b2, b3, b4 Wire) (r1, r2, r3, r4 Wire, carry Wire) { + carry = Zero() + r1, carry = FullAdder(a1, b1, carry) + r2, carry = FullAdder(a2, b2, carry) + r3, carry = FullAdder(a3, b3, carry) + r4, carry = FullAdder(a4, b4, carry) + return } func main() { - // Create wires - a1 := MakeWire() - a2 := MakeWire() - a3 := MakeWire() - a4 := MakeWire() - b1 := MakeWire() - b2 := MakeWire() - b3 := MakeWire() - b4 := MakeWire() - // Construct circuit - r1,r2,r3,r4, carry := FourBitAdder(a1,a2,a3,a4, b1,b2,b3,b4) - // Feed it some values - a4 <- false; a3 <- false; a2 <- true; a1 <- false // 0010 - b4 <- true; b3 <- true; b2 <- true; b1 <- false // 1110 - B := map[bool]int { false: 0, true: 1 } - // Read the result - fmt.Printf("0010 + 1110 = %d%d%d%d (carry = %d)\n", - B[<-r4],B[<-r3],B[<-r2],B[<-r1], B[<-carry]) + // Create wires + a1, a2, a3, a4 := MakeWire(), MakeWire(), MakeWire(), MakeWire() + b1, b2, b3, b4 := MakeWire(), MakeWire(), MakeWire(), MakeWire() + // Construct circuit + r1, r2, r3, r4, carry := FourBitAdder(a1, a2, a3, a4, b1, b2, b3, b4) + // Feed it some values + a4 <- false + a3 <- false + a2 <- true + a1 <- false // 0010 + b4 <- true + b3 <- true + b2 <- true + b1 <- false // 1110 + B := map[bool]int{false: 0, true: 1} + // Read the result + fmt.Printf("0010 + 1110 = %d%d%d%d (carry = %d)\n", + B[<-r4], B[<-r3], B[<-r2], B[<-r1], B[<-carry]) } diff --git a/Task/Four-bit-adder/Perl/four-bit-adder.pl b/Task/Four-bit-adder/Perl/four-bit-adder.pl new file mode 100644 index 0000000000..4c2636f41e --- /dev/null +++ b/Task/Four-bit-adder/Perl/four-bit-adder.pl @@ -0,0 +1,43 @@ +sub dec2bin { sprintf "%04b", shift } +sub bin2dec { oct "0b".shift } +sub bin2bits { reverse split(//, substr(shift,0,shift)); } +sub bits2bin { join "", map { 0+$_ } reverse @_ } + +sub bxor { + my($a, $b) = @_; + (!$a & $b) | ($a & !$b); +} + +sub half_adder { + my($a, $b) = @_; + ( bxor($a,$b), $a & $b ); +} + +sub full_adder { + my($a, $b, $c) = @_; + my($s1, $c1) = half_adder($a, $c); + my($s2, $c2) = half_adder($s1, $b); + ($s2, $c1 | $c2); +} + +sub four_bit_adder { + my($a, $b) = @_; + my @abits = bin2bits($a,4); + my @bbits = bin2bits($b,4); + + my($s0,$c0) = full_adder($abits[0], $bbits[0], 0); + my($s1,$c1) = full_adder($abits[1], $bbits[1], $c0); + my($s2,$c2) = full_adder($abits[2], $bbits[2], $c1); + my($s3,$c3) = full_adder($abits[3], $bbits[3], $c2); + (bits2bin($s0, $s1, $s2, $s3), $c3); +} + +print " A B A B C S sum\n"; +for my $a (0 .. 15) { + for my $b (0 .. 15) { + my($abin, $bbin) = map { dec2bin($_) } $a,$b; + my($s,$c) = four_bit_adder( $abin, $bbin ); + printf "%2d + %2d = %s + %s = %s %s = %2d\n", + $a, $b, $abin, $bbin, $c, $s, bin2dec($c.$s); + } +} diff --git a/Task/Four-bit-adder/REXX/four-bit-adder.rexx b/Task/Four-bit-adder/REXX/four-bit-adder.rexx index 83af5d1ce0..290f2b5e77 100644 --- a/Task/Four-bit-adder/REXX/four-bit-adder.rexx +++ b/Task/Four-bit-adder/REXX/four-bit-adder.rexx @@ -1,35 +1,30 @@ -/*REXX program shows (all) the sums of a full 4-bit adder (with carry).*/ -call hdr1; call hdr2 - - do j=0 for 16 +/*REXX program shows (all) the sums of a full 4─bit adder (with carry).*/ +call hdr1; call hdr2 /*note order of headers (& below)*/ + /* [↓] traipse all possibilities*/ + do j=0 for 16 do m=0 for 4; a.m=bit(j,m); end do k=0 for 16 do m=0 for 4; b.m=bit(k,m); end - sc=4bitAdder(a.,b.) + sc=4bitAdder(a., b.) z=a.3 a.2 a.1 a.0 '_+_' b.3 b.2 b.1 b.0 '_=_' sc ',' s.3 s.2 s.1 s.0 - say translate(space(z,0),,'_') + say translate(space(z,0),,'_') /*remove all underbars (_) from Z*/ end /*k*/ end /*j*/ -call hdr2; call hdr1 +call hdr2; call hdr1 /*display 2 headers (note order).*/ exit /*stick a fork in it, we're done.*/ - -/*──────────────────────────────────subroutines/functions───────────────*/ -hdr1: say 'aaaa + bbbb = c, sum [c=carry]'; return -hdr2: say '════ ════ ══════' ; return +/*──────────────────────────────────one─line subroutines────────────────*/ bit: procedure; arg x,y; return substr(reverse(x2b(d2x(x))),y+1,1) - -/*──────────────────────────────────HALFADDER subroutine-───────────────*/ -halfAdder: procedure expose c; parse arg x,y; c=x & y; return x && y - -/*──────────────────────────────────FULLADDER subroutine-───────────────*/ +halfAdder: procedure expose c; parse arg x,y; c=x & y; return x && y +hdr1: say 'aaaa + bbbb = c, sum [c=carry]'; return +hdr2: say '════ ════ ══════' ; return +/*──────────────────────────────────FULLADDER subroutine────────────────*/ fullAdder: procedure expose c; parse arg x,y,fc -_1=halfAdder(fc,x); c1=c -_2=halfAdder(_1,y); c=c | c1; return _2 - -/*──────────────────────────────────3BITADDER subroutine-───────────────*/ + _1 = halfAdder(fc,x); c1=c + _2 = halfAdder(_1,y); c=c | c1; return _2 +/*──────────────────────────────────4BITADDER subroutine────────────────*/ 4bitAdder: procedure expose s. a. b.; carry.=0 - do j=0 for 4; n=j-1 - s.j=fullAdder(a.j, b.j, carry.n); carry.j=c - end /*j*/ + do j=0 for 4; n=j-1 + s.j=fullAdder(a.j, b.j, carry.n); carry.j=c + end /*j*/ return c diff --git a/Task/Four-bit-adder/Ruby/four-bit-adder.rb b/Task/Four-bit-adder/Ruby/four-bit-adder.rb index 78ac8483cc..4e79b4d46c 100644 --- a/Task/Four-bit-adder/Ruby/four-bit-adder.rb +++ b/Task/Four-bit-adder/Ruby/four-bit-adder.rb @@ -28,18 +28,20 @@ def xor(a, b) end # "and", "or" and "not" are Ruby keywords -def _and(a, b); a & b; end -def _or(a, b); a | b; end -def _not(a); ~a & 1; end +def _and(a, b) a & b end +def _or(a, b) a | b end +def _not(a) ~a & 1 end def int_to_binary_string(n, length) - ("0"*length + n.to_s(2))[-length .. -1] + "%0#{length}b" % n end + def binary_string_to_bits(s, length) - (s.reverse + "0"*length)[0..length-1].chars.map(&:to_i) + ("%#{length}s" % s).reverse.chars.map(&:to_i) end + def bits_to_binary_string(bits) - bits.map(&:to_s).reverse.join("") + bits.map(&:to_s).reverse.join end puts " A B A B C S sum" @@ -48,8 +50,7 @@ puts " A B A B C S sum" bin_a = int_to_binary_string(a, 4) bin_b = int_to_binary_string(b, 4) sum, carry = four_bit_adder(bin_a, bin_b) - puts "%2d + %2d = %s + %s = %s %s = %2d" % [ - a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2) - ] + puts "%2d + %2d = %s + %s = %s %s = %2d" % + [a, b, bin_a, bin_b, carry, sum, (carry + sum).to_i(2)] end end diff --git a/Task/Fractal-tree/BBC-BASIC/fractal-tree-1.bbc b/Task/Fractal-tree/BBC-BASIC/fractal-tree-1.bbc new file mode 100644 index 0000000000..1bac770a1b --- /dev/null +++ b/Task/Fractal-tree/BBC-BASIC/fractal-tree-1.bbc @@ -0,0 +1,5 @@ + Spread = 25 + Scale = 0.76 + SizeX% = 400 + SizeY% = 300 + Depth% = 10 diff --git a/Task/Fractal-tree/BBC-BASIC/fractal-tree.bbc b/Task/Fractal-tree/BBC-BASIC/fractal-tree-2.bbc similarity index 83% rename from Task/Fractal-tree/BBC-BASIC/fractal-tree.bbc rename to Task/Fractal-tree/BBC-BASIC/fractal-tree-2.bbc index d04238c276..18cd91ed62 100644 --- a/Task/Fractal-tree/BBC-BASIC/fractal-tree.bbc +++ b/Task/Fractal-tree/BBC-BASIC/fractal-tree-2.bbc @@ -1,9 +1,3 @@ - Spread = 25 - Scale = 0.76 - SizeX% = 400 - SizeY% = 300 - Depth% = 10 - VDU 23,22,SizeX%;SizeY%;8,16,16,128 PROCbranch(SizeX%, 0, SizeY%/2, 90, Depth%) diff --git a/Task/Function-composition/00DESCRIPTION b/Task/Function-composition/00DESCRIPTION index ad9306e434..395be0ecfe 100644 --- a/Task/Function-composition/00DESCRIPTION +++ b/Task/Function-composition/00DESCRIPTION @@ -1,4 +1,5 @@ -Create a function, compose, whose two arguments ''f'' and ''g'', are both functions with one argument. The result of compose is to be a function of one argument, (lets call the argument ''x''), which works like applying function ''f'' to the result of applying function ''g'' to ''x'', i.e, +Create a function, compose, whose two arguments ''f'' and ''g'', are both functions with one argument. +The result of compose is to be a function of one argument, (lets call the argument ''x''), which works like applying function ''f'' to the result of applying function ''g'' to ''x'', i.e, : compose(''f'', ''g'') (''x'') = ''f''(''g''(''x'')) Reference: [[wp:Function composition (computer science)|Function composition]] diff --git a/Task/Function-composition/AppleScript/function-composition.applescript b/Task/Function-composition/AppleScript/function-composition.applescript new file mode 100644 index 0000000000..f124afe5ac --- /dev/null +++ b/Task/Function-composition/AppleScript/function-composition.applescript @@ -0,0 +1,24 @@ +-- Compose two functions where each function is +-- a script object with a call(x) handler. +on compose(f, g) + script + on call(x) + f's call(g's call(x)) + end call + end script +end compose + +script sqrt + on call(x) + x ^ 0.5 + end call +end script + +script twice + on call(x) + 2 * x + end call +end script + +compose(sqrt, twice)'s call(32) +-- Result: 8.0 diff --git a/Task/Function-composition/C++/function-composition-3.cpp b/Task/Function-composition/C++/function-composition-3.cpp index 840f3b493b..feeee55a3c 100644 --- a/Task/Function-composition/C++/function-composition-3.cpp +++ b/Task/Function-composition/C++/function-composition-3.cpp @@ -1,9 +1,13 @@ #include -#include -#include +#include + +template +decltype(auto) compose(F&& f, G&& g) +{ + return [=](auto x) { return f(g(x)); }; +} int main() { - std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl; - + std::cout << compose(sin, asin)(0.5) << "\n"; return 0; } diff --git a/Task/Function-composition/C++/function-composition-4.cpp b/Task/Function-composition/C++/function-composition-4.cpp new file mode 100644 index 0000000000..840f3b493b --- /dev/null +++ b/Task/Function-composition/C++/function-composition-4.cpp @@ -0,0 +1,9 @@ +#include +#include +#include + +int main() { + std::cout << __gnu_cxx::compose1(std::ptr_fun(::sin), std::ptr_fun(::asin))(0.5) << std::endl; + + return 0; +} diff --git a/Task/Function-composition/CoffeeScript/function-composition.coffee b/Task/Function-composition/CoffeeScript/function-composition-1.coffee similarity index 78% rename from Task/Function-composition/CoffeeScript/function-composition.coffee rename to Task/Function-composition/CoffeeScript/function-composition-1.coffee index 55c53ab0d7..545e6823bd 100644 --- a/Task/Function-composition/CoffeeScript/function-composition.coffee +++ b/Task/Function-composition/CoffeeScript/function-composition-1.coffee @@ -6,8 +6,10 @@ mul2 = ( x ) -> x * 2 mulFirst = compose add2, mul2 addFirst = compose mul2, add2 +multiple = compose mul2, compose add2, mul2 console.log "add2 2 #=> #{ add2 2 }" console.log "mul2 2 #=> #{ mul2 2 }" console.log "mulFirst 2 #=> #{ mulFirst 2 }" console.log "addFirst 2 #=> #{ addFirst 2 }" +console.log "multiple 2 #=> #{ multiple 2 }" diff --git a/Task/Function-composition/CoffeeScript/function-composition-2.coffee b/Task/Function-composition/CoffeeScript/function-composition-2.coffee new file mode 100644 index 0000000000..6de9107503 --- /dev/null +++ b/Task/Function-composition/CoffeeScript/function-composition-2.coffee @@ -0,0 +1,15 @@ +Function::of = (f) -> (args...) => @ f args... + +# Example +add2 = (x) -> x + 2 +mul2 = (x) -> x * 2 + +mulFirst = add2.of mul2 +addFirst = mul2.of add2 +multiple = mul2.of add2.of mul2 + +console.log "add2 2 #=> #{ add2 2 }" +console.log "mul2 2 #=> #{ mul2 2 }" +console.log "mulFirst 2 #=> #{ mulFirst 2 }" +console.log "addFirst 2 #=> #{ addFirst 2 }" +console.log "multiple 2 #=> #{ multiple 2 }" diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-1.l b/Task/Function-composition/Emacs-Lisp/function-composition-1.l new file mode 100644 index 0000000000..e32cf16781 --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-1.l @@ -0,0 +1,7 @@ +(defun compose (f g) + `(lambda (x) (,f (,g x)))) + +(let ((func (compose '1+ '1+))) + (funcall func 5)) +=> +7 diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-2.l b/Task/Function-composition/Emacs-Lisp/function-composition-2.l new file mode 100644 index 0000000000..a900467c38 --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-2.l @@ -0,0 +1,7 @@ +(defmacro compose (f g) + `(lambda (x) (,f (,g x)))) + +(let ((func (compose 1+ 1+))) + (funcall func 5)) +=> +7 diff --git a/Task/Function-composition/Emacs-Lisp/function-composition-3.l b/Task/Function-composition/Emacs-Lisp/function-composition-3.l new file mode 100644 index 0000000000..cbaf4d79e8 --- /dev/null +++ b/Task/Function-composition/Emacs-Lisp/function-composition-3.l @@ -0,0 +1,11 @@ +(eval-when-compile (require 'cl)) ;; for `lexical-let' macro +(defun compose (f g) + (lexical-let ((f f) + (g g)) + (lambda (x) + (funcall f (funcall g x))))) + +(let ((func (compose '1+ '1+))) + (funcall func 5)) +=> +7 diff --git a/Task/Function-composition/REXX/function-composition.rexx b/Task/Function-composition/REXX/function-composition.rexx index b6d9ef1667..4f3fba4bdb 100644 --- a/Task/Function-composition/REXX/function-composition.rexx +++ b/Task/Function-composition/REXX/function-composition.rexx @@ -1,2 +1,3 @@ compose: procedure; parse arg f,g,x; interpret 'return' f"(" g'(' x "))" + exit /*control never gets here, but this was added just in case.*/ diff --git a/Task/Function-composition/UNIX-Shell/function-composition-2.sh b/Task/Function-composition/UNIX-Shell/function-composition-2.sh index 3c2856730e..b9d79a734c 100644 --- a/Task/Function-composition/UNIX-Shell/function-composition-2.sh +++ b/Task/Function-composition/UNIX-Shell/function-composition-2.sh @@ -1,9 +1,137 @@ -fn compose f g { - result @ {$g | $f} +#compose a new function consisting of the application of 2 unary functions + + compose () { f="$1"; g="$2"; x="$3"; "$f" "$("$g" "$x")";} + + +chartolowervowel() +# Usage: chartolowervowel "A" --> "a" + +#Based on a to_upper script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation +#(with minor tweaks to use local variables and return the value of the converted character +#http://cfajohnson.com/books/cfajohnson/pbp/ +#highly recommended I have a copy and have bought another for a friend +{ + + local LWR=""; + + case $1 in + A*) _LWR=a ;; +# B*) _LWR=b ;; +# C*) _LWR=c ;; +# D*) _LWR=d ;; + E*) _LWR=e ;; +# F*) _LWR=f ;; +# G*) _LWR=g ;; +# H*) _LWR=h ;; + I*) _LWR=i ;; +# J*) _LWR=j ;; +# K*) _LWR=k ;; +# L*) _LWR=L ;; +# M*) _LWR=m ;; +# N*) _LWR=n ;; + O*) _LWR=o ;; +# P*) _LWR=p ;; +# Q*) _LWR=q ;; +# R*) _LWR=r ;; +# S*) _LWR=s ;; +# T*) _LWR=t ;; + U*) _LWR=u ;; +# V*) _LWR=v ;; +# W*) _LWR=w ;; +# X*) _LWR=x ;; +# Y*) _LWR=y ;; +# Z*) _LWR=z ;; + *) _LWR=${1%${1#?}} ;; + esac; + echo "$_LWR"; + } + +strdownvowel() +# Usage: strdownvowel "STRING" --> "STRiNG" + +#Based on an upword script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation +#(with minor tweaks to use local variables and return the value of the converted string +#http://cfajohnson.com/books/cfajohnson/pbp/ +#highly recommended I have a copy and have bought another for a friend + +{ + local _DWNWORD="" + local word="$1" + while [ -n "$word" ] ## loop until nothing is left in $word + do + chartolowervowel "$word" >> /dev/null + _DWNWORD=$_DWNWORD$_LWR + word=${word#?} ## remove the first character from $word + + done + Echo "$_DWNWORD" } -fn downvowel {tr AEIOU aeiou} -fn upcase {tr a-z A-Z} -fn-c = <={compose $fn-downvowel $fn-upcase} -echo 'Cozy lummox gives smart squid who asks for job pen.' | c -# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN. + + + +chartoupper() +# Usage: chartoupper "s" --> "S" + +#From Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation +#(with minor tweaks to use local variables and return the value of the converted character +#http://cfajohnson.com/books/cfajohnson/pbp/ +#highly recommended I have a copy and have bought another for a friend + { + local UPR=""; + + case $1 in + a*) _UPR=A ;; + b*) _UPR=B ;; + c*) _UPR=C ;; + d*) _UPR=D ;; + e*) _UPR=E ;; + f*) _UPR=F ;; + g*) _UPR=G ;; + h*) _UPR=H ;; + i*) _UPR=I ;; + j*) _UPR=J ;; + k*) _UPR=K ;; + l*) _UPR=L ;; + m*) _UPR=M ;; + n*) _UPR=N ;; + o*) _UPR=O ;; + p*) _UPR=P ;; + q*) _UPR=Q ;; + r*) _UPR=R ;; + s*) _UPR=S ;; + t*) _UPR=T ;; + u*) _UPR=U ;; + v*) _UPR=V ;; + w*) _UPR=W ;; + x*) _UPR=X ;; + y*) _UPR=Y ;; + z*) _UPR=Z ;; + *) _UPR=${1%${1#?}} ;; + esac; + echo "$_UPR"; + } + +strupcase() +# Usage: strupcase "string" --> "STRING" + +#Based on an upword script in Chris F. A. Johnson's book Pro Bash Programming Ch7. String Manipulation +#(with minor tweaks to use local variables and return the value of the converted string +#http://cfajohnson.com/books/cfajohnson/pbp/ +#highly recommended I have a copy and have bought another for a friend + +{ + local _UPWORD="" + local word="$1" + while [ -n "$word" ] ## loop until nothing is left in $word + do + chartoupper "$word" >> /dev/null + _UPWORD=$_UPWORD$_UPR + word=${word#?} ## remove the first character from $word + + done + Echo "$_UPWORD" +} + +compose strdownvowel strupcase "Cozy lummox gives smart squid who asks for job pen." +# --> CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN. diff --git a/Task/Function-composition/UNIX-Shell/function-composition-3.sh b/Task/Function-composition/UNIX-Shell/function-composition-3.sh index 9fdd65d30c..3c2856730e 100644 --- a/Task/Function-composition/UNIX-Shell/function-composition-3.sh +++ b/Task/Function-composition/UNIX-Shell/function-composition-3.sh @@ -1,9 +1,9 @@ fn compose f g { - result @ x {result <={$f <={$g $x}}} + result @ {$g | $f} } -fn downvowel x {result `` '' {tr AEIOU aeiou <<< $x}} -fn upcase x {result `` '' {tr a-z A-Z <<< $x}} +fn downvowel {tr AEIOU aeiou} +fn upcase {tr a-z A-Z} fn-c = <={compose $fn-downvowel $fn-upcase} -echo <={c 'Cozy lummox gives smart squid who asks for job pen.'} +echo 'Cozy lummox gives smart squid who asks for job pen.' | c # => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN. diff --git a/Task/Function-composition/UNIX-Shell/function-composition-4.sh b/Task/Function-composition/UNIX-Shell/function-composition-4.sh new file mode 100644 index 0000000000..9fdd65d30c --- /dev/null +++ b/Task/Function-composition/UNIX-Shell/function-composition-4.sh @@ -0,0 +1,9 @@ +fn compose f g { + result @ x {result <={$f <={$g $x}}} +} + +fn downvowel x {result `` '' {tr AEIOU aeiou <<< $x}} +fn upcase x {result `` '' {tr a-z A-Z <<< $x}} +fn-c = <={compose $fn-downvowel $fn-upcase} +echo <={c 'Cozy lummox gives smart squid who asks for job pen.'} +# => CoZY LuMMoX GiVeS SMaRT SQuiD WHo aSKS FoR JoB PeN. diff --git a/Task/Function-definition/00DESCRIPTION b/Task/Function-definition/00DESCRIPTION index 4536c60b3f..39b6282dc3 100644 --- a/Task/Function-definition/00DESCRIPTION +++ b/Task/Function-definition/00DESCRIPTION @@ -1,4 +1,5 @@ -A function is a body of code that returns a value. The value returned may depend on arguments provided to the function. +A function is a body of code that returns a value. +The value returned may depend on arguments provided to the function. Write a definition of a function called "multiply" that takes two arguments and returns their product. (Argument types should be chosen so as not to distract from showing how functions are created and values returned). diff --git a/Task/Function-definition/00META.yaml b/Task/Function-definition/00META.yaml index e316a9ad81..76e179d490 100644 --- a/Task/Function-definition/00META.yaml +++ b/Task/Function-definition/00META.yaml @@ -1,4 +1,5 @@ --- category: - Functions and subroutines +- Simple note: Basic language learning diff --git a/Task/Function-definition/Eiffel/function-definition.e b/Task/Function-definition/Eiffel/function-definition.e new file mode 100644 index 0000000000..c5418d1a74 --- /dev/null +++ b/Task/Function-definition/Eiffel/function-definition.e @@ -0,0 +1,4 @@ +multiply(a, b: INTEGER): INTEGER + do + Result := a*b + end diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-1.l b/Task/Function-definition/Emacs-Lisp/function-definition-1.l new file mode 100644 index 0000000000..1e5a8148c1 --- /dev/null +++ b/Task/Function-definition/Emacs-Lisp/function-definition-1.l @@ -0,0 +1,2 @@ +(defun multiply (x y) + (* x y)) diff --git a/Task/Function-definition/Emacs-Lisp/function-definition-2.l b/Task/Function-definition/Emacs-Lisp/function-definition-2.l new file mode 100644 index 0000000000..0eaa89d659 --- /dev/null +++ b/Task/Function-definition/Emacs-Lisp/function-definition-2.l @@ -0,0 +1,3 @@ +(defun multiply (x y) + "Return the product of X and Y." + (* x y)) diff --git a/Task/Function-definition/Gnuplot/function-definition.gnuplot b/Task/Function-definition/Gnuplot/function-definition.gnuplot new file mode 100644 index 0000000000..39babdfdc8 --- /dev/null +++ b/Task/Function-definition/Gnuplot/function-definition.gnuplot @@ -0,0 +1,4 @@ +multiply(x,y) = x*y + +# then for example +print multiply(123,456) diff --git a/Task/Function-definition/OOC/function-definition.ooc b/Task/Function-definition/OOC/function-definition.ooc new file mode 100644 index 0000000000..74b52301dd --- /dev/null +++ b/Task/Function-definition/OOC/function-definition.ooc @@ -0,0 +1,3 @@ +multiply: func (a: Double, b: Double) -> Double { + a * b +} diff --git a/Task/Function-definition/Perl/function-definition-4.pl b/Task/Function-definition/Perl/function-definition-4.pl index 5d6a0e217f..6398c0de1a 100644 --- a/Task/Function-definition/Perl/function-definition-4.pl +++ b/Task/Function-definition/Perl/function-definition-4.pl @@ -1,4 +1,4 @@ -use signatures; +use experimental 'signatures'; sub multiply ($x, $y) { return $x * $y; } diff --git a/Task/Function-definition/REALbasic/function-definition.realbasic b/Task/Function-definition/REALbasic/function-definition.realbasic new file mode 100644 index 0000000000..ad505ef218 --- /dev/null +++ b/Task/Function-definition/REALbasic/function-definition.realbasic @@ -0,0 +1,3 @@ +Function Multiply(a As Integer, b As Integer) As Integer + Return a * b +End Function diff --git a/Task/Function-definition/TXR/function-definition-2.txr b/Task/Function-definition/TXR/function-definition-2.txr index 5653d1d6e7..9571d20a15 100644 --- a/Task/Function-definition/TXR/function-definition-2.txr +++ b/Task/Function-definition/TXR/function-definition-2.txr @@ -1,2 +1,2 @@ @(do (defun mult (a b) (* a b)) - (format t "3 * 4 = ~a\n" (* 3 4))) + (put-line `3 * 4 = @(mult 3 4)`)) diff --git a/Task/Function-definition/X86-Assembly/function-definition-1.x86 b/Task/Function-definition/X86-Assembly/function-definition-1.x86 index 923ccc1151..dde744cc44 100644 --- a/Task/Function-definition/X86-Assembly/function-definition-1.x86 +++ b/Task/Function-definition/X86-Assembly/function-definition-1.x86 @@ -1,24 +1,7 @@ -section .text -global _start - -_multiply_regs: - mul ebx - mov eax, ebx - ret - -_multiply_stack: - enter 2,0 - mov eax, [esp+4] - mov ebx, [esp+8] - mul ebx - mov eax, ebx - leave - ret - -_start: - mov ax, 6 ;The number to multiply by - mov ebx, 16 ;base number to multiply. - call _multiply_regs - push 6 - push 16 - call _multiply_stack + .text + .globl multiply + .type multiply,@function +multiply: + movl 4(%esp), %eax + mull 8(%esp) + ret diff --git a/Task/Function-definition/X86-Assembly/function-definition-2.x86 b/Task/Function-definition/X86-Assembly/function-definition-2.x86 index 3e329f32cb..923ccc1151 100644 --- a/Task/Function-definition/X86-Assembly/function-definition-2.x86 +++ b/Task/Function-definition/X86-Assembly/function-definition-2.x86 @@ -1,7 +1,24 @@ -multiply proc arg1:dword, arg2:dword - mov eax, arg1 - mov ebx, arg2 +section .text +global _start + +_multiply_regs: mul ebx mov eax, ebx ret -multiply endp + +_multiply_stack: + enter 2,0 + mov eax, [esp+4] + mov ebx, [esp+8] + mul ebx + mov eax, ebx + leave + ret + +_start: + mov ax, 6 ;The number to multiply by + mov ebx, 16 ;base number to multiply. + call _multiply_regs + push 6 + push 16 + call _multiply_stack diff --git a/Task/Function-definition/X86-Assembly/function-definition-3.x86 b/Task/Function-definition/X86-Assembly/function-definition-3.x86 index 6c2b51d9cc..3e329f32cb 100644 --- a/Task/Function-definition/X86-Assembly/function-definition-3.x86 +++ b/Task/Function-definition/X86-Assembly/function-definition-3.x86 @@ -1,5 +1,7 @@ -invoke multiply, 6, 16 -;or.. -push 16 -push 6 -call multiply +multiply proc arg1:dword, arg2:dword + mov eax, arg1 + mov ebx, arg2 + mul ebx + mov eax, ebx + ret +multiply endp diff --git a/Task/Function-definition/X86-Assembly/function-definition-4.x86 b/Task/Function-definition/X86-Assembly/function-definition-4.x86 new file mode 100644 index 0000000000..6c2b51d9cc --- /dev/null +++ b/Task/Function-definition/X86-Assembly/function-definition-4.x86 @@ -0,0 +1,5 @@ +invoke multiply, 6, 16 +;or.. +push 16 +push 6 +call multiply diff --git a/Task/Function-prototype/ALGOL-68/function-prototype.alg b/Task/Function-prototype/ALGOL-68/function-prototype.alg new file mode 100644 index 0000000000..1f3c639786 --- /dev/null +++ b/Task/Function-prototype/ALGOL-68/function-prototype.alg @@ -0,0 +1,37 @@ +#!/usr/bin/a68g --script # +# -*- coding: utf-8 -*- # + +# An explanation of any placement restrictions for prototype declarations # +PROC VOID no args; # Declare a function with no argument that returns an INTeger # +PROC (INT #a#,INT #b#)VOID two args; # Declare a function with two arguments that returns an INTeger # +MODE VARARGS = UNION(INT,REAL,COMPL); +PROC ([]VARARGS)VOID var args; # An empty parameter list can be used to declare a function that accepts varargs # +PROC (INT, []VARARGS)VOID at least one args; # One mandatory INTeger argument followed by varargs # + +MODE OPTINT = UNION(VOID,INT), OPTSTRING=UNION(VOID,STRING); # a function that utilizes optional arguments # +PROC (OPTINT, OPTSTRING)VOID optional arguments; + +# A prototype declaration for a function that utilizes named parameters # +MODE KWNAME = STRUCT(STRING name), + KWSPECIES = STRUCT(STRING species), + KWBREED = STRUCT(STRING breed), + OWNER=STRUCT(STRING first name, middle name, last name); + +# due to the "Yoneda ambiguity" simple arguments must have an unique operator defined # +OP NAME = (STRING name)KWNAME: (KWNAME opt; name OF opt := name; opt), + SPECIES = (STRING species)KWSPECIES: (KWSPECIES opt; species OF opt := species; opt), + BREED = (STRING breed)KWBREED: (KWBREED opt; breed OF opt := breed; opt); + +PROC ([]UNION(KWNAME,KWSPECIES,KWBREED,OWNER) #options#)VOID print pet; + +# subroutines, and fuctions are procedures, so have the same prototype declarations # + +# An explanation and example of any special forms of prototyping not covered by the above: # +COMMENT + If a function has no arguments, eg f, + then it is not requied to pass it a "vacuum()" to call it, eg "f()" not correct! + Rather is can be called without the () vacuum. eg "f" + A GOTO "label" is equivalent to "PROC VOID label". +END COMMENT + +SKIP diff --git a/Task/Function-prototype/C++/function-prototype.cpp b/Task/Function-prototype/C++/function-prototype.cpp new file mode 100644 index 0000000000..626ad1fc5a --- /dev/null +++ b/Task/Function-prototype/C++/function-prototype.cpp @@ -0,0 +1,7 @@ +int noargs(); // Declare a function with no arguments that returns an integer +int twoargs(int a,int b); // Declare a function with two arguments that returns an integer +int twoargs(int ,int); // Parameter names are optional in a prototype definition +int anyargs(...); // An ellipsis is used to declare a function that accepts varargs +int atleastoneargs(int, ...); // One mandatory integer argument followed by varargs +template T declval(T); //A function template +template tuple make_tuple(T...); //Function template using parameter pack (since c++11) diff --git a/Task/Function-prototype/C/function-prototype.c b/Task/Function-prototype/C/function-prototype.c index f789ceb56c..486deca7f4 100644 --- a/Task/Function-prototype/C/function-prototype.c +++ b/Task/Function-prototype/C/function-prototype.c @@ -1,5 +1,5 @@ -int noargs(); /* Declare a function with no arguments that returns an integer */ -int twoargs(int a,int b); /* Declare a function with no arguments that returns an integer */ +int noargs(void); /* Declare a function with no argument that returns an integer */ +int twoargs(int a,int b); /* Declare a function with two arguments that returns an integer */ int twoargs(int ,int); /* Parameter names are optional in a prototype definition */ -int anyargs(...); /* An ellipsis can be used to declare a function that accepts varargs */ +int anyargs(); /* An empty parameter list can be used to declare a function that accepts varargs */ int atleastoneargs(int, ...); /* One mandatory integer argument followed by varargs */ diff --git a/Task/Function-prototype/Clojure/function-prototype.clj b/Task/Function-prototype/Clojure/function-prototype.clj new file mode 100644 index 0000000000..3f1c50324a --- /dev/null +++ b/Task/Function-prototype/Clojure/function-prototype.clj @@ -0,0 +1 @@ +(declare foo) diff --git a/Task/Function-prototype/Perl/function-prototype.pl b/Task/Function-prototype/Perl/function-prototype.pl index 4034ccb497..0f75f43a95 100644 --- a/Task/Function-prototype/Perl/function-prototype.pl +++ b/Task/Function-prototype/Perl/function-prototype.pl @@ -1,2 +1,4 @@ sub noargs(); # Declare a function with no arguments sub twoargs($$); # Declare a function with two scalar arguments. The two sigils act as argument type placeholders +sub noargs :prototype(); # Using the :attribute syntax instead +sub twoargs :prototype($$); diff --git a/Task/GUI-Maximum-window-dimensions/Java/gui-maximum-window-dimensions.java b/Task/GUI-Maximum-window-dimensions/Java/gui-maximum-window-dimensions.java new file mode 100644 index 0000000000..9e62a81970 --- /dev/null +++ b/Task/GUI-Maximum-window-dimensions/Java/gui-maximum-window-dimensions.java @@ -0,0 +1,23 @@ +import java.awt.*; +import javax.swing.JFrame; + +public class Test extends JFrame { + + public static void main(String[] args) { + new Test(); + } + + Test() { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + + Dimension screenSize = toolkit.getScreenSize(); + System.out.println("Physical screen size: " + screenSize); + + Insets insets = toolkit.getScreenInsets(getGraphicsConfiguration()); + System.out.println("Insets: " + insets); + + screenSize.width -= (insets.left + insets.right); + screenSize.height -= (insets.top + insets.bottom); + System.out.println("Max available: " + screenSize); + } +} diff --git a/Task/GUI-component-interaction/00DESCRIPTION b/Task/GUI-component-interaction/00DESCRIPTION index 659ad47102..a3b2fabbe2 100644 --- a/Task/GUI-component-interaction/00DESCRIPTION +++ b/Task/GUI-component-interaction/00DESCRIPTION @@ -1,20 +1,40 @@ +{{omit from|ACL2}} +{{omit from|Applesoft BASIC|no concept of a GUI}} +{{omit from|AWK|no concept of a GUI}} +{{omit from|Batch File}} +{{omit from|Blast}} +{{omit from|Brainf***}} +{{omit from|GUISS|Only makes use of installed applications}} +{{omit from|Integer BASIC|no concept of a GUI}} +{{omit from|Lilypond}} +{{omit from|Logtalk}} +{{omit from|Lotus 123}} +{{omit from|Maxima}} +{{omit from|PARI/GP}} +{{omit from|PostScript}} +{{omit from|Retro}} + Almost every application needs to communicate with the user in some way. -Therefore, a substantial part of the code deals with the interaction of program -logic with GUI components. Typically, the following is needed: +Therefore, a substantial part of the code deals with the interaction +of program logic with GUI components. + +Typically, the following is needed: * put values into input fields under program control * read and check input from the user * pop up dialogs to query the user for further information -The task: For a minimal "application", write a program that presents a form with -three components to the user: A numeric input field ("Value") and two buttons -("increment" and "random"). +The task: For a minimal "application", write a program that presents +a form with three components to the user: +A numeric input field ("Value") and two buttons ("increment" and "random"). -The field is initialized to zero. The user may manually enter a new value into -the field, or increment its value with the "increment" button. Entering a -non-numeric value should be either impossible, or issue an error message. +The field is initialized to zero. +The user may manually enter a new value into the field, +or increment its value with the "increment" button. +Entering a non-numeric value should be either impossible, +or issue an error message. -Pressing the "random" button presents a confirmation dialog, and resets the -field's value to a random value if the answer is "Yes". +Pressing the "random" button presents a confirmation dialog, +and resets the field's value to a random value if the answer is "Yes". (This task may be regarded as an extension of the task [[Simple windowed application]]). diff --git a/Task/GUI-component-interaction/J/gui-component-interaction-1.j b/Task/GUI-component-interaction/J/gui-component-interaction-1.j index dcd2487d40..0d6f2d38e3 100644 --- a/Task/GUI-component-interaction/J/gui-component-interaction-1.j +++ b/Task/GUI-component-interaction/J/gui-component-interaction-1.j @@ -1,32 +1,31 @@ -INTERACT=: 0 : 0 -pc interact closeok; -xywh 6 6 48 12;cc Value edit; -xywh 6 18 48 12;cc increment button;cn "+"; -xywh 6 30 48 12;cc random button;cn "?"; +INTERACT=: noun define +pc interact; +cc Value edit center; +cc increment button;cn "Increment"; +cc random button;cn "Random"; pas 6 6;pcenter; -rem form end; ) -interact_run=: 3 : 0 +interact_run=: verb define wd INTERACT - wd 'set Value 0;' + wd 'set Value text 0;' wd 'pshow;' ) -interact_close=: 3 : 0 +interact_cancel=: interact_close=: verb define wd'pclose' ) -interact_Value_button=: 3 : 0 - wd 'set Value ' , ": {. 0 ". Value +interact_Value_button=: verb define + wd 'set Value text ' , ": {. 0 ". Value ) -interact_increment_button=: 3 : 0 - wd 'set Value ' , ": 1 + {. 0 ". Value +interact_increment_button=: verb define + wd 'set Value text ' , ": 1 + {. 0 ". Value ) -interact_random_button=: 3 : 0 - if. 0 = 2 wdquery 'Confirm';'Reset to random number?' do. - wd 'set Value ' , ": ?100 +interact_random_button=: verb define + if. 2 = 2 3 wdquery 'Confirm';'Reset to random number?' do. + wd 'set Value text ' , ": ?100 end. ) diff --git a/Task/GUI-component-interaction/J/gui-component-interaction-2.j b/Task/GUI-component-interaction/J/gui-component-interaction-2.j index 627b35345d..dcd2487d40 100644 --- a/Task/GUI-component-interaction/J/gui-component-interaction-2.j +++ b/Task/GUI-component-interaction/J/gui-component-interaction-2.j @@ -1 +1,32 @@ -interact_run'' +INTERACT=: 0 : 0 +pc interact closeok; +xywh 6 6 48 12;cc Value edit; +xywh 6 18 48 12;cc increment button;cn "+"; +xywh 6 30 48 12;cc random button;cn "?"; +pas 6 6;pcenter; +rem form end; +) + +interact_run=: 3 : 0 + wd INTERACT + wd 'set Value 0;' + wd 'pshow;' +) + +interact_close=: 3 : 0 + wd'pclose' +) + +interact_Value_button=: 3 : 0 + wd 'set Value ' , ": {. 0 ". Value +) + +interact_increment_button=: 3 : 0 + wd 'set Value ' , ": 1 + {. 0 ". Value +) + +interact_random_button=: 3 : 0 + if. 0 = 2 wdquery 'Confirm';'Reset to random number?' do. + wd 'set Value ' , ": ?100 + end. +) diff --git a/Task/GUI-component-interaction/J/gui-component-interaction-3.j b/Task/GUI-component-interaction/J/gui-component-interaction-3.j new file mode 100644 index 0000000000..627b35345d --- /dev/null +++ b/Task/GUI-component-interaction/J/gui-component-interaction-3.j @@ -0,0 +1 @@ +interact_run'' diff --git a/Task/GUI-component-interaction/Python/gui-component-interaction.py b/Task/GUI-component-interaction/Python/gui-component-interaction.py new file mode 100644 index 0000000000..eebacfbae5 --- /dev/null +++ b/Task/GUI-component-interaction/Python/gui-component-interaction.py @@ -0,0 +1,55 @@ +import random +from Tkinter import * +import tkMessageBox + + +class Application(Frame): + def __init__(self, master): + Frame.__init__(self, master) + self.counter = 0 + self.contents = StringVar() + self.contents.set(str(self.counter)) + self.pack(expand=True, fill='both', padx=10, pady=15) + self.create_widgets() + + def increment(self, *args): + self.counter += 1 + self.update_entry() + + def random(self): + if tkMessageBox.askyesno("Confirmation", "Reset to random value ?"): + self.counter = random.randint(0, 5000) + self.update_entry() + + def entry_updated(self, event, *args): + if not event.char: + return 'break' + if not event.char.isdigit(): + tkMessageBox.showerror('Error', 'Invalid input !') + return 'break' + self.counter = int('%s%s' % (self.contents.get(), event.char)) + + def update_entry(self): + self.contents.set(str(self.counter)) + self.entry['textvariable'] = self.contents + + def create_widgets(self): + options = {'expand': True, 'fill': 'x', 'side': 'left', 'padx': 5} + self.entry = Entry(self) + self.entry.bind('', self.entry_updated) + self.entry.pack(**options) + self.update_entry() + self.increment_button = Button(self, text='Increment', command=self.increment) + self.increment_button.pack(**options) + self.random_button = Button(self, text='Random', command=self.random) + self.random_button.pack(**options) + + +if __name__ == '__main__': + root = Tk() + try: + app = Application(master=root) + app.master.title("Rosetta code") + app.mainloop() + except KeyboardInterrupt: + root.destroy() diff --git a/Task/GUI-component-interaction/Ruby/gui-component-interaction.rb b/Task/GUI-component-interaction/Ruby/gui-component-interaction.rb index 6dd193ea9e..d6b912a009 100644 --- a/Task/GUI-component-interaction/Ruby/gui-component-interaction.rb +++ b/Task/GUI-component-interaction/Ruby/gui-component-interaction.rb @@ -1,18 +1,18 @@ -Shoes.app do +Shoes.app(title: "GUI component interaction") do stack do - @textbox = edit_line + textbox = edit_line - @textbox.change do - @textbox.text = @textbox.text.gsub(/[^\d]/, '') and alert "Input must be a number!" if @textbox.text !~ /^\d*$/ + textbox.change do + textbox.text = textbox.text.gsub(/[^\d]/, '') and alert "Input must be a number!" if textbox.text !~ /^\d*$/ end flow do button "Increment" do - @textbox.text = @textbox.text.to_i + 1 + textbox.text = textbox.text.to_i + 1 end button "Random" do - @textbox.text = rand 5000 if confirm "Do you want a random number?" + textbox.text = rand 5000 if confirm "Do you want a random number?" end end end diff --git a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION index 9458dae01e..835d29c226 100644 --- a/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION +++ b/Task/GUI-enabling-disabling-of-controls/00DESCRIPTION @@ -1,22 +1,39 @@ +{{omit from|ACL2}} +{{omit from|Applesoft BASIC|no concept of a GUI}} +{{omit from|AWK|no concept of a GUI}} +{{omit from|Batch File}} +{{omit from|Blast}} +{{omit from|Brainf***}} +{{omit from|GUISS|Can only do what the installed applications can do}} +{{omit from|Integer BASIC|no concept of a GUI}} +{{omit from|Lilypond}} +{{omit from|Logtalk}} +{{omit from|Lotus 123}} +{{omit from|Maxima}} +{{omit from|PARI/GP}} +{{omit from|PostScript}} +{{omit from|Retro}} + In addition to fundamental [[GUI component interaction]], an application should dynamically enable and disable GUI components, to give some guidance to the user, and prohibit (inter)actions which are inappropriate in the current state of the application. -The task: Similar to the task [[GUI component interaction]] write a program that -presents a form with three components to the user: A numeric input field -("Value") and two buttons ("increment" and "decrement"). +The task: Similar to the task [[GUI component interaction]] write a program +that presents a form with three components to the user: +A numeric input field ("Value") and two buttons ("increment" and "decrement"). -The field is initialized to zero. The user may manually enter a new value into -the field, increment its value with the "increment" button, or decrement the -value with the "decrement" button. +The field is initialized to zero. +The user may manually enter a new value into the field, +increment its value with the "increment" button, +or decrement the value with the "decrement" button. -The input field should be enabled only when its value is zero. The "increment" -button only as long as the field's value is less then 10: When the value 10 is -reached, the button should go into a disabled state. Analogously, the -"decrement" button should be enabled only as long as the value is greater than -zero. +The input field should be enabled only when its value is zero. +The "increment" button only as long as the field's value is less then 10: +When the value 10 is reached, the button should go into a disabled state. +Analogously, the "decrement" button should be enabled only as long as +the value is greater than zero. Effectively, the user can now either increment up to 10, or down to zero. -Manually entering values outside that range is still legal, but the buttons -should reflect that and enable/disable accordingly. +Manually entering values outside that range is still legal, +but the buttons should reflect that and enable/disable accordingly. diff --git a/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-1.j b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-1.j index 35f52428b0..340ba344a1 100644 --- a/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-1.j +++ b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-1.j @@ -1,24 +1,26 @@ task_run=: wd bind (noun define) pc task nosize; - xywh 6 30 48 12;cc decrement button;cn "-"; - xywh 6 18 48 12;cc increment button;cn "+"; - xywh 6 6 48 12;cc Value edit; set Value 0; + cc decrement button;cn "Decrement"; + cc increment button;cn "Increment"; + cc Value edit center;set Value text 0; + set decrement enable 0; pas 6 6;pcenter; pshow; ) -task_close=: wd bind 'pclose' +task_cancel=: task_close=: wd bind 'pclose' task_Value_button=: update=: verb define - wd 'set Value ',":n=.{.0".Value - wd 'setenable Value ',":n=0 - wd 'setenable increment ',":n<10 - wd 'setenable decrement ',":n>0 + wd 'set Value text ', ": n=. {. 0 ". Value + wd 'set Value enable ', ": n=0 + wd 'set increment enable ', ": n<10 + wd 'set decrement enable ', ": n>0 ) task_increment_button=:verb define - update Value=:":1+0".Value + update Value=: ": 1 + 0 ". Value ) + task_decrement_button=:verb define - update Value=:":_1+0".Value + update Value=: ": _1 + 0 ". Value ) diff --git a/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-2.j b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-2.j index 7f02804a3a..92de33e208 100644 --- a/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-2.j +++ b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-2.j @@ -1 +1,24 @@ - task_run'' +task_run=: wd bind (noun define) + pc task nosize; + xywh 6 30 48 12;cc decrement button;cn "-"; + xywh 6 18 48 12;cc increment button;cn "+"; + xywh 6 6 48 12;cc Value edit; set Value 0; + pas 6 6;pcenter; + pshow; +) + +task_close=: wd bind 'pclose' + +task_Value_button=: update=: verb define + wd 'set Value ', ": n=. {. 0 ". Value + wd 'setenable Value ', ": n=0 + wd 'setenable increment ', ": n<10 + wd 'setenable decrement ', ": n>0 +) + +task_increment_button=:verb define + update Value=: ": 1 + 0 ". Value +) +task_decrement_button=:verb define + update Value=: ": _1 + 0 ". Value +) diff --git a/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-3.j b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-3.j new file mode 100644 index 0000000000..7f02804a3a --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/J/gui-enabling-disabling-of-controls-3.j @@ -0,0 +1 @@ + task_run'' diff --git a/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls.java b/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-1.java similarity index 100% rename from Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls.java rename to Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-1.java diff --git a/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java b/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java new file mode 100644 index 0000000000..b2697d13df --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Java/gui-enabling-disabling-of-controls-2.java @@ -0,0 +1,78 @@ +import javafx.application.Application; +import javafx.beans.property.LongProperty; +import javafx.beans.property.SimpleLongProperty; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.TextField; +import javafx.scene.layout.HBox; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; +import javafx.util.converter.NumberStringConverter; + +public class InteractFX extends Application { + + public static void main(String[] args) { + launch(args); + } + + @Override + public void start(Stage stage) throws Exception { + + TextField input = new TextField("0"){ + // only accept numbers as input + @Override public void replaceText(int start, int end, String text) { + if (text.matches("[0-9]*")) { + super.replaceText(start, end, text); + } + } + + // only accept numbers on copy+paste + @Override public void replaceSelection(String text) { + if (text.matches("[0-9]*")) { + super.replaceSelection(text); + } + } + }; + + // when the textfield is empty, replace text with "0" + input.textProperty().addListener((observable, oldValue, newValue)->{ + if(newValue == null || newValue.trim().isEmpty()){ + input.setText("0"); + } + }); + + + // get a bi-directional bound long-property of the input value + LongProperty inputValue = new SimpleLongProperty(); + input.textProperty().bindBidirectional(inputValue, new NumberStringConverter()); + + // textfield is disabled when the current value is other than "0" + input.disableProperty().bind(inputValue.isNotEqualTo(0)); + + + Button increment = new Button("Increment"); + increment.setOnAction(event-> inputValue.set(inputValue.get() + 1)); + + // incr-button is disabled when input is >= 0 + increment.disableProperty().bind(inputValue.greaterThanOrEqualTo(10)); + + + Button decrement = new Button("Decrement"); + decrement.setOnAction(event-> inputValue.set(inputValue.get() - 1)); + + // decrement button is disabled when input is <=0 + decrement.disableProperty().bind(inputValue.lessThanOrEqualTo(0)); + + + // layout + VBox root = new VBox(); + root.getChildren().add(input); + HBox buttons = new HBox(); + buttons.getChildren().addAll(increment,decrement); + root.getChildren().add(buttons); + + stage.setScene(new Scene(root)); + stage.sizeToScene(); + stage.show(); + } +} diff --git a/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 new file mode 100644 index 0000000000..03aca62999 --- /dev/null +++ b/Task/GUI-enabling-disabling-of-controls/Perl-6/gui-enabling-disabling-of-controls.pl6 @@ -0,0 +1,26 @@ +use GTK::Simple; + +my GTK::Simple::App $app .= new( title => 'Controls Enable \ Disable' ); + +$app.border_width = 20; + +$app.set_content( + GTK::Simple::HBox.new( + my $inc = GTK::Simple::Button.new( label => ' + ' ), + my $value = GTK::Simple::Entry.new, + my $dec = GTK::Simple::Button.new( label => ' - ' ) + ) +); + +$value.changed.tap: { + $value.text.=subst(/\D/, ''); + $inc.sensitive = $value.text < 10; + $dec.sensitive = $value.text > 0; +} + +$value.text = 0; + +$inc.clicked.tap: { $value.text += 1 } +$dec.clicked.tap: { $value.text -= 1 } + +$app.run; 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 61ef3f4e33..f45ad49062 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 @@ -1,41 +1,34 @@ -import scala.swing._ -import scala.swing.Swing._ -import scala.swing.event._ +import swing.{ BoxPanel, Button, GridPanel, Orientation, Swing, TextField } +import swing.event.{ ButtonClicked, Key, KeyPressed, KeyTyped } -object Enabling extends SimpleSwingApplication { - def top = new MainFrame { +object Enabling extends swing.SimpleSwingApplication { + def top = new swing.MainFrame { title = "Rosetta Code >>> Task: GUI enabling/disabling of controls | Language: Scala" val numberField = new TextField { text = "0" // start at 0 - horizontalAlignment = Alignment.Right + horizontalAlignment = swing.Alignment.Right } - val incButton = new Button("Increment") - val decButton = new Button { text = "Decrement"; enabled = false } + val (incButton, decButton) = (new Button("Increment"), // Two variables initialized + new Button("Decrement") { enabled = false }) // arrange buttons in a grid with 1 row, 2 columns - val buttonPanel = new GridPanel(1, 2) { - contents ++= List(incButton, decButton) - } + 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 BoxPanel(Orientation.Vertical) { 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 val specialKeys = List(Key.BackSpace, Key.Delete) // listen for keys pressed in numberField and button clicks listenTo(numberField.keys, incButton, decButton) 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) - else { + if (kt.char.isDigit) // if the entered char is a digit ... Swing.onEDT(switching) // ensure GUI-updating - } - case KeyPressed(_, kp, _, _) if (!specialKeys.filter(_ == kp).isEmpty) => + else kt.consume // ... eat the event (i.e. stop it from being processed) + case KeyPressed(_, kp, _, _) if (!specialKeys.contains(kp)) => Swing.onEDT(switching) // ensure GUI-updating case ButtonClicked(`incButton`) => numberField.text = (numberField.text.toLong + 1).toString @@ -46,9 +39,9 @@ object Enabling extends SimpleSwingApplication { } def switching = { - val n = (if (numberField.text == "") "0" else numberField.text).toLong + val n = (if (numberField.text.isEmpty()) "0" else numberField.text).toLong numberField.text = n.toString - numberField.enabled = n <= 0 + numberField.enabled = n == 0 incButton.enabled = n < 10 decButton.enabled = n > 0 } diff --git a/Task/Galton-box-animation/00DESCRIPTION b/Task/Galton-box-animation/00DESCRIPTION index 404850e927..e4fbc1e64f 100644 --- a/Task/Galton-box-animation/00DESCRIPTION +++ b/Task/Galton-box-animation/00DESCRIPTION @@ -1,9 +1,16 @@ -Generate an animated simulation of [[wp:Bean_machine|Sir Francis Galton's device]]. An example can be found to the right. [[File:Galtonbox-Unicon.PNG|thumb|Example of a Galton Box at the end of animation.]] +{{omit from|GUISS}} -In a Galton box, there are a set of pins arranged in a triangular pattern. A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of subsequent pins before arriving at one of the collection points between and to the sides of the bottom row of pins. +Generate an animated simulation of [[wp:Bean_machine|Sir Francis Galton's device]]. +An example can be found to the right. [[File:Galtonbox-Unicon.PNG|thumb|Example of a Galton Box at the end of animation.]] -For the purpose of this task the box should have at least 5 pins on the bottom row. Your solution can use graphics or ASCII animation. Provide a sample of the output/display such as a screenshot. +In a Galton box, there are a set of pins arranged in a triangular pattern. +A number of balls are dropped so that they fall in line with the top pin, deflecting to the left or the right of the pin. The ball continues to fall to the left or right of subsequent pins before arriving at one of the collection points between and to the sides of the bottom row of pins. -Your solution can have either one or more balls in flight at the same time. If multiple balls are in flight, ensure they don't interfere with each other. +For the purpose of this task the box should have at least 5 pins on the bottom row. +Your solution can use graphics or ASCII animation. +Provide a sample of the output/display such as a screenshot. + +Your solution can have either one or more balls in flight at the same time. +If multiple balls are in flight, ensure they don't interfere with each other. Your solution should allow users to specify the number of balls or it should run until full or a preset limit. Optionally, display the number of balls. diff --git a/Task/Galton-box-animation/00META.yaml b/Task/Galton-box-animation/00META.yaml new file mode 100644 index 0000000000..182e87560a --- /dev/null +++ b/Task/Galton-box-animation/00META.yaml @@ -0,0 +1,5 @@ +--- +category: +- Animation +- Randomness +note: Galton box animation diff --git a/Task/Galton-box-animation/D/galton-box-animation.d b/Task/Galton-box-animation/D/galton-box-animation.d index 9f974a8a39..f2be9f1ed8 100644 --- a/Task/Galton-box-animation/D/galton-box-animation.d +++ b/Task/Galton-box-animation/D/galton-box-animation.d @@ -9,20 +9,19 @@ static assert((boxW - 4) >= (pinsBaseW * 2 - 1)); static assert((boxH - 3) >= pinsBaseW); enum centerH = pinsBaseW + (boxW - (pinsBaseW * 2 - 1)) / 2 - 1; -alias CellBaseType = char; -enum Cell : CellBaseType { empty = ' ', - ball = 'o', - wall = '|', - corner = '+', - floor = '-', - pin = '.' } +enum Cell : char { empty = ' ', + ball = 'o', + wall = '|', + corner = '+', + floor = '-', + pin = '.' } Cell[boxW][boxH] box; // Galton box. Will be printed upside-down. struct Ball { int x, y; // Position. - this(in int x_, in int y_) nothrow + this(in int x_, in int y_) nothrow @safe @nogc in { assert(box[y_][x_] == Cell.empty); } body { @@ -31,7 +30,7 @@ struct Ball { box[y][x] = Cell.ball; } - nothrow const invariant() { + nothrow const @safe @nogc invariant { assert(x >= 0 && x < boxW && y >= 0 && y < boxH); assert(box[y][x] == Cell.ball); } @@ -40,55 +39,51 @@ struct Ball { if (y <= 0) return; // Reached the bottom of the box. - with (Cell) { - final switch (box[y - 1][x]) { - case empty: - box[y][x] = Cell.empty; - y--; + final switch (box[y - 1][x]) with (Cell) { + case empty: + box[y][x] = Cell.empty; + y--; + box[y][x] = Cell.ball; + break; + case ball, wall, corner, floor: + // It's frozen. (It always piles on other balls). + break; + case pin: + box[y][x] = Cell.empty; + y--; + if (box[y][x - 1] == Cell.empty && box[y][x + 1] == Cell.empty) { + x += uniform(0, 2) * 2 - 1; box[y][x] = Cell.ball; - break; - case ball, wall, corner, floor: - // It's frozen. (It always piles on other balls). - break; - case pin: - box[y][x] = Cell.empty; - y--; - if (box[y][x - 1] == Cell.empty && - box[y][x + 1] == Cell.empty) { - x += uniform(0, 2) * 2 - 1; - box[y][x] = Cell.ball; - return; - } else if (box[y][x - 1] == Cell.empty) - x++; - else - x--; - box[y][x] = Cell.ball; - break; - } + return; + } else if (box[y][x - 1] == Cell.empty) { + x++; + } else { + x--; + } + box[y][x] = Cell.ball; + break; } } } void initializeBox() { // Set ceiling and floor: - box[0][] = (Cell.corner ~ [Cell.floor].replicate(boxW - 2) - ~ Cell.corner)[]; + box[0][] = Cell.corner ~ [Cell.floor].replicate(boxW - 2) ~ Cell.corner; box[$ - 1][] = box[0][]; // Set walls: - foreach (r; 1 .. boxH - 1) + foreach (immutable r; 1 .. boxH - 1) box[r][0] = box[r][$ - 1] = Cell.wall; // Set pins: foreach (immutable nPins; 1 .. pinsBaseW + 1) foreach (pin; 0 .. nPins) - box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] - = Cell.pin; + box[boxH - 2 - nPins][centerH + 1 - nPins + pin * 2] = Cell.pin; } void drawBox() { - foreach_reverse (ref row; box) - writeln(cast(CellBaseType[])row); + foreach_reverse (const ref row; box) + writefln("%(%c%)", row); } void main() { @@ -99,7 +94,7 @@ void main() { writefln("\nStep %d:", i); if (i < nMaxBalls) balls ~= Ball(centerH, boxH - 2); // Add ball. - drawBox(); + drawBox; // Next step for the simulation. // Frozen balls are kept in balls array for simplicity. diff --git a/Task/Gamma-function/360-Assembly/gamma-function.360 b/Task/Gamma-function/360-Assembly/gamma-function.360 new file mode 100644 index 0000000000..a91c847914 --- /dev/null +++ b/Task/Gamma-function/360-Assembly/gamma-function.360 @@ -0,0 +1,159 @@ +GAMMAT CSECT + USING GAMMAT,R13 +SAVEAR B STM-SAVEAR(R15) + DC 17F'0' + DC CL8'GAMMAT' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 +* ---- CODE + LE F4,=E'0' + LH R2,NI +LOOPI EQU * + AE F4,=E'1' xi=xi+1 + LER F0,F4 + DE F0,=E'10' x=xi/10 + STE F0,X + LE F6,X + SE F6,=E'1' xx=x-1.0 + LH R4,NT + BCTR R4,0 + SLA R4,2 + LE F0,T(R4) + STE F0,SUM sum=t(nt) + LH R3,NT + BCTR R3,0 + SH R4,=H'4' +LOOPJ CH R3,=H'1' for j=nt-1 downto 1 + BL ENDLOOPJ + LE F0,SUM + MER F0,F6 sum*xx + LE F2,T(R4) t(j) + AER F0,F2 + STE F0,SUM sum=sum*xx+t(j) + BCTR R3,0 + SH R4,=H'4' + B LOOPJ +ENDLOOPJ EQU * + LE F0,=E'1' + DE F0,SUM + STE F0,GAMMA gamma=1/sum + LE F0,X + BAL R14,CONVERT + MVC BUF(8),CONVERTM + LE F0,GAMMA + BAL R14,CONVERT + MVC BUF+9(13),CONVERTM + WTO MF=(E,WTOMSG) + BCT R2,LOOPI +* ---- END CODE + CNOP 0,4 + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +* ---- DATA +NI DC H'30' +NT DC AL2((TEND-T)/4) +T DC E'1.00000000000000000000' + DC E'0.57721566490153286061' + DC E'-0.65587807152025388108' + DC E'-0.04200263503409523553' + DC E'0.16653861138229148950' + DC E'-0.04219773455554433675' + DC E'-0.00962197152787697356' + DC E'0.00721894324666309954' + DC E'-0.00116516759185906511' + DC E'-0.00021524167411495097' + DC E'0.00012805028238811619' + DC E'-0.00002013485478078824' + DC E'-0.00000125049348214267' + DC E'0.00000113302723198170' + DC E'-0.00000020563384169776' + DC E'0.00000000611609510448' + DC E'0.00000000500200764447' + DC E'-0.00000000118127457049' + DC E'0.00000000010434267117' + DC E'0.00000000000778226344' + DC E'-0.00000000000369680562' + DC E'0.00000000000051003703' + DC E'-0.00000000000002058326' + DC E'-0.00000000000000534812' + DC E'0.00000000000000122678' + DC E'-0.00000000000000011813' + DC E'0.00000000000000000119' + DC E'0.00000000000000000141' + DC E'-0.00000000000000000023' + DC E'0.00000000000000000002' +TEND DS 0E +X DS E +SUM DS E +GAMMA DS E +WTOMSG DS 0F + DC AL2(L'BUF),XL2'0000' +BUF DC CL80' ' +* Subroutine Convertion Float->Display +CONVERT CNOP 0,4 + ME F0,CONVERTC + STE F0,CONVERTF + MVI CONVERTS,X'00' + L R9,CONVERTF + CH R9,=H'0' + BZ CONVERT7 + BNL CONVERT1 is negative? + MVI CONVERTS,X'80' + N R9,=X'7FFFFFFF' sign bit +CONVERT1 LR R8,R9 + N R8,=X'00FFFFFF' + BNZ CONVERT2 + SR R9,R9 + B CONVERT7 +CONVERT2 LR R8,R9 + N R8,=X'FF000000' characteristic + SRL R8,24 + CH R8,=H'64' + BH CONVERT3 + SR R9,R9 + B CONVERT7 +CONVERT3 CH R8,=H'72' 2**32 + BNH CONVERT4 + L R9,=X'7FFFFFFF' biggest + B CONVERT6 +CONVERT4 SR R8,R8 + SLDL R8,8 + CH R8,=H'72' + BL CONVERT5 + CH R9,=H'0' + BP CONVERT5 + L R9,=X'7FFFFFFF' + B CONVERT6 +CONVERT5 SH R8,=H'72' + LCR R8,R8 + SLL R8,2 + SRL R9,0(R8) +CONVERT6 SR R8,R8 + IC R8,CONVERTS + CH R8,=H'0' sign bit set? + BZ CONVERT7 + LCR R9,R9 +CONVERT7 ST R9,CONVERTB + CVD R9,CONVERTP + MVC CONVERTD,=X'402020202120202020202020' + ED CONVERTD,CONVERTP+2 + MVC CONVERTM(6),CONVERTD + MVI CONVERTM+6,C'.' + MVC CONVERTM+7(6),CONVERTD+6 + BR R14 +* +CONVERTC DC E'1E6' X'45F42400' +CONVERTF DS F +CONVERTB DS F +CONVERTS DS X +CONVERTM DS CL13 +CONVERTD DS CL12 +CONVERTP DS PL8 +* + EQUREGS + EQUREGS REGS=FPR + END GAMMAT diff --git a/Task/Gamma-function/C-sharp/gamma-function.cs b/Task/Gamma-function/C-sharp/gamma-function.cs new file mode 100644 index 0000000000..bb7b8e4516 --- /dev/null +++ b/Task/Gamma-function/C-sharp/gamma-function.cs @@ -0,0 +1,27 @@ +using System; +using System.Numerics; + +static int g = 7; +static double[] p = {0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7}; + +Complex Gamma(Complex z) +{ + // Reflection formula + if (z.Real < 0.5) + { + return Math.PI / (Complex.Sin( Math.PI * z) * Gamma(1 - z)); + } + else + { + z -= 1; + Complex x = p[0]; + for (var i = 1; i < g + 2; i++) + { + x += p[i]/(z+i); + } + Complex t = z + g + 0.5; + return Complex.Sqrt(2 * Math.PI) * (Complex.Pow(t, z + 0.5)) * Complex.Exp(-t) * x; + } +} diff --git a/Task/Gamma-function/D/gamma-function.d b/Task/Gamma-function/D/gamma-function.d index 6311cf822c..dc26f21e42 100644 --- a/Task/Gamma-function/D/gamma-function.d +++ b/Task/Gamma-function/D/gamma-function.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.mathspecial; -real taylorGamma(in real x) pure nothrow { +real taylorGamma(in real x) pure nothrow @safe @nogc { static immutable real[30] table = [ 0x1p+0, 0x1.2788cfc6fb618f4cp-1, -0x1.4fcf4026afa2dcecp-1, -0x1.5815e8fa27047c8cp-5, @@ -25,7 +25,7 @@ real taylorGamma(in real x) pure nothrow { return 1.0L / sm; } -real lanczosGamma(real z) pure nothrow { +real lanczosGamma(real z) pure nothrow @safe @nogc { // Coefficients used by the GNU Scientific Library. // http://en.wikipedia.org/wiki/Lanczos_approximation enum g = 7; diff --git a/Task/Gamma-function/F-Sharp/gamma-function.fs b/Task/Gamma-function/F-Sharp/gamma-function.fs new file mode 100644 index 0000000000..3c24e14a1f --- /dev/null +++ b/Task/Gamma-function/F-Sharp/gamma-function.fs @@ -0,0 +1,14 @@ +open System + +let gamma z = + let lanczosCoefficients = [76.18009172947146;-86.50532032941677;24.01409824083091;-1.231739572450155;0.1208650973866179e-2;-0.5395239384953e-5] + let rec sumCoefficients acc i coefficients = + match coefficients with + | [] -> acc + | h::t -> sumCoefficients (acc + (h/i)) (i+1.0) t + let gamma = 5.0 + let x = z - 1.0 + Math.Pow(x + gamma + 0.5, x + 0.5) * Math.Exp( -(x + gamma + 0.5) ) * Math.Sqrt( 2.0 * Math.PI ) * sumCoefficients 1.000000000190015 (x + 1.0) lanczosCoefficients + +seq { for i in 1 .. 20 do yield ((double)i/10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine("{0} : {1}", v, gamma v ) ) +seq { for i in 1 .. 10 do yield ((double)i*10.0) } |> Seq.iter ( fun v -> System.Console.WriteLine("{0} : {1}", v, gamma v ) ) diff --git a/Task/Gamma-function/Haskell/gamma-function.hs b/Task/Gamma-function/Haskell/gamma-function-1.hs similarity index 100% rename from Task/Gamma-function/Haskell/gamma-function.hs rename to Task/Gamma-function/Haskell/gamma-function-1.hs diff --git a/Task/Gamma-function/Haskell/gamma-function-2.hs b/Task/Gamma-function/Haskell/gamma-function-2.hs new file mode 100644 index 0000000000..0c92290926 --- /dev/null +++ b/Task/Gamma-function/Haskell/gamma-function-2.hs @@ -0,0 +1,7 @@ +procedure main() + every write(left(i := !10/10.0,5),gamma(.i)) +end + +procedure gamma(z) # Stirling's approximation + return (2*&pi/z)^0.5 * (z/&e)^z +end diff --git a/Task/Gamma-function/JavaScript/gamma-function.js b/Task/Gamma-function/JavaScript/gamma-function.js new file mode 100644 index 0000000000..fcb80dc1c7 --- /dev/null +++ b/Task/Gamma-function/JavaScript/gamma-function.js @@ -0,0 +1,19 @@ +function gamma(x){ + var p = [0.99999999999980993, 676.5203681218851, -1259.1392167224028, + 771.32342877765313, -176.61502916214059, 12.507343278686905, + -0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7]; + + var g = 7; + if(x < 0.5){ + return Math.PI / (Math.sin(Math.PI * x)*gamma(1-x)); + } + + x -= 1; + var a = p[0]; + var t = x+g+0.5; + for(var i = 1; i < p.length; i++){ + a += p[i]/(x+i); + } + + return Math.sqrt(2*Math.PI)*Math.pow(t, x+0.5)*Math.exp(-t)*a; +} diff --git a/Task/Gamma-function/Perl-6/gamma-function.pl6 b/Task/Gamma-function/Perl-6/gamma-function.pl6 index aa0f5ac7dc..b800be9b82 100644 --- a/Task/Gamma-function/Perl-6/gamma-function.pl6 +++ b/Task/Gamma-function/Perl-6/gamma-function.pl6 @@ -1,51 +1,22 @@ -sub Γ(\z, :$method = 'lanczos') { - given $method { - when 'lanczos' { - constant g = 9; - z < .5 ?? pi/ sin(pi * z) / Γ(1 - z, :$method) !! - sqrt(2*pi) * - (z + g - 1/2)**(z - 1/2) * - exp(-(z + g - 1/2)) * - [+] < - 1.000000000000000174663 - 5716.400188274341379136 - -14815.30426768413909044 - 14291.49277657478554025 - -6348.160217641458813289 - 1301.608286058321874105 - -108.1767053514369634679 - 2.605696505611755827729 - -0.7423452510201416151527e-2 - 0.5384136432509564062961e-7 - -0.4023533141268236372067e-8 - > Z* 1, map 1/(z + *), 0..* - } - when 'stirling' { - z < 10 ?? Γ(z + 1, :$method) / z !! - sqrt(2*pi*z)*(z/e + 1/(12*z*e))**z / z - } - when 'taylor' { - z > 3/2 ?? (z - 1)*Γ(z - 1, :$method) !! - z < 1/2 ?? Γ(z + 1, :$method)/z !! - 1 / < - 0.00000_00000_00000_00002 -0.00000_00000_00000_00023 0.00000_00000_00000_00141 - 0.00000_00000_00000_00119 -0.00000_00000_00000_11813 0.00000_00000_00001_22678 - -0.00000_00000_00005_34812 -0.00000_00000_00020_58326 0.00000_00000_00510_03703 - -0.00000_00000_03696_80562 0.00000_00000_07782_26344 0.00000_00001_04342_67117 - -0.00000_00011_81274_57049 0.00000_00050_02007_64447 0.00000_00061_16095_10448 - -0.00000_02056_33841_69776 0.00000_11330_27231_98170 -0.00000_12504_93482_14267 - -0.00002_01348_54780_78824 0.00012_80502_82388_11619 -0.00021_52416_74114_95097 - -0.00116_51675_91859_06511 0.00721_89432_46663_09954 -0.00962_19715_27876_97356 - -0.04219_77345_55544_33675 0.16653_86113_82291_48950 -0.04200_26350_34095_23553 - -0.65587_80715_20253_88108 0.57721_56649_01532_86061 1.00000_00000_00000_00000 - >.reduce: * *(z-1) + * - } - default { die "unknow method '$method'" } - } +sub Γ(\z) { + constant g = 9; + z < .5 ?? pi/ sin(pi * z) / Γ(1 - z) !! + sqrt(2*pi) * + (z + g - 1/2)**(z - 1/2) * + exp(-(z + g - 1/2)) * + [+] < + 1.000000000000000174663 + 5716.400188274341379136 + -14815.30426768413909044 + 14291.49277657478554025 + -6348.160217641458813289 + 1301.608286058321874105 + -108.1767053514369634679 + 2.605696505611755827729 + -0.7423452510201416151527e-2 + 0.5384136432509564062961e-7 + -0.4023533141268236372067e-8 + > Z* 1, map 1/(z + *), 0..* } -for -> $method { - # a bug in fmt forces us to round numbers before displaying them - say "{$method.fmt("%10s")}: ", - map { Γ($_, :$method).round(1e-12).fmt("%.12f") }, (1/3, 2/3 ... 10/3); -} +say Γ($_) for 1/3, 2/3 ... 10/3; diff --git a/Task/Gamma-function/Perl/gamma-function.pl b/Task/Gamma-function/Perl/gamma-function.pl index 4c57070b88..40a73f5aec 100644 --- a/Task/Gamma-function/Perl/gamma-function.pl +++ b/Task/Gamma-function/Perl/gamma-function.pl @@ -3,6 +3,10 @@ use warnings; use constant pi => 4*atan2(1, 1); use constant e => exp(1); +# Normally would be: use Math::MPFR +# but this will use it if it's installed and ignore otherwise +my $have_MPFR = eval { require Math::MPFR; Math::MPFR->import(); 1; }; + sub Gamma { my $z = shift; my $method = shift // 'lanczos'; @@ -51,10 +55,15 @@ sub Gamma { no warnings qw(recursion); $z < 100 ? Gamma($z + 1, $method)/$z : sqrt(2*pi*$z)*($z/e + 1/(12*e*$z))**$z / $z; + } elsif ($method eq 'MPFR') { + my $result = Math::MPFR->new(); + Math::MPFR::Rmpfr_gamma($result, Math::MPFR->new($z), 0); + $result; } else { die "unknown method '$method'" } } -for my $method (qw(lanczos taylor stirling)) { +for my $method (qw(MPFR lanczos taylor stirling)) { + next if $method eq 'MPFR' && !$have_MPFR; printf "%10s: ", $method; print join(' ', map { sprintf "%.12f", Gamma($_/3, $method) } 1 .. 10); print "\n"; diff --git a/Task/Gamma-function/Ruby/gamma-function.rb b/Task/Gamma-function/Ruby/gamma-function-1.rb similarity index 100% rename from Task/Gamma-function/Ruby/gamma-function.rb rename to Task/Gamma-function/Ruby/gamma-function-1.rb diff --git a/Task/Gamma-function/Ruby/gamma-function-2.rb b/Task/Gamma-function/Ruby/gamma-function-2.rb new file mode 100644 index 0000000000..5a4713645f --- /dev/null +++ b/Task/Gamma-function/Ruby/gamma-function-2.rb @@ -0,0 +1 @@ +(1..10).each{|i| puts Math.gamma(i/3.0)} diff --git a/Task/Gamma-function/Scilab/gamma-function.scilab b/Task/Gamma-function/Scilab/gamma-function.scilab new file mode 100644 index 0000000000..0a6a362603 --- /dev/null +++ b/Task/Gamma-function/Scilab/gamma-function.scilab @@ -0,0 +1,22 @@ +function x=gammal(z) // Lanczos' + lz=[ 1.000000000190015 .. + 76.18009172947146 -86.50532032941677 24.01409824083091 .. + -1.231739572450155 1.208650973866179e-3 -5.395239384953129e-6 ] + if z < 0.5 then + x=%pi/sin(%pi*z)-gammal(1-z) + else + z=z-1.0 + b=z+5.5 + a=lz(1) + for i=1:6 + a=a+(lz(i+1)/(z+i)) + end + x=exp((log(sqrt(2*%pi))+log(a)-b)+log(b)*(z+0.5)) + end +endfunction + +printf("%4s %-9s %-9s\n","x","gamma(x)","gammal(x)") +for i=1:30 + x=i/10 + printf("%4.1f %9f %9f\n",x,gamma(x),gammal(x)) +end diff --git a/Task/Gamma-function/TI-83-BASIC/gamma-function-1.ti-83 b/Task/Gamma-function/TI-83-BASIC/gamma-function-1.ti-83 new file mode 100644 index 0000000000..8f25664d67 --- /dev/null +++ b/Task/Gamma-function/TI-83-BASIC/gamma-function-1.ti-83 @@ -0,0 +1,6 @@ +for(I,1,10) +I/2→X +X^(X-1/2)e^(-X)√(2π)→Y +Disp X,(X-1)!,Y +Pause +End diff --git a/Task/Gamma-function/TI-83-BASIC/gamma-function-2.ti-83 b/Task/Gamma-function/TI-83-BASIC/gamma-function-2.ti-83 new file mode 100644 index 0000000000..f7fd2a2afe --- /dev/null +++ b/Task/Gamma-function/TI-83-BASIC/gamma-function-2.ti-83 @@ -0,0 +1,14 @@ +for(I,1,10) +I/2→X +e^(ln((1.0 ++76.18009173/(X+1) +-86.50532033/(X+2) ++24.01409824/(X+3) +-1.231739572/(X+4) ++1.208650974E-3/(X+5) +-5.395239385E-6/(X+6) +)√(2π)/X) ++(X+.5)ln(X+5.5)-X-5.5)->Y +Disp X,(X-1)!,Y +Pause +End diff --git a/Task/Generator-Exponential/00DESCRIPTION b/Task/Generator-Exponential/00DESCRIPTION index 452b80ac47..73f09b0d92 100644 --- a/Task/Generator-Exponential/00DESCRIPTION +++ b/Task/Generator-Exponential/00DESCRIPTION @@ -1,4 +1,9 @@ -A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. +{{omit from|Lilypond}} +[[Category:Non parametric generators]] +[[Category:Stateful transactions]] +A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. +Generators are often built on top of coroutines or objects so that the internal state of the object is handled “naturally”. +Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. '''Task description''' diff --git a/Task/Generator-Exponential/D/generator-exponential-5.d b/Task/Generator-Exponential/D/generator-exponential-5.d new file mode 100644 index 0000000000..fc569f49ee --- /dev/null +++ b/Task/Generator-Exponential/D/generator-exponential-5.d @@ -0,0 +1,28 @@ +import std.stdio, std.range, std.algorithm, std.concurrency, std.bigint; + +auto powers(in uint m) pure nothrow @safe { + return 0.sequence!"n".map!(i => i.BigInt ^^ m); +} + +auto filtered(R1, R2)(R1 r1, R2 r2) /*@safe*/ +if (isForwardRange!R1 && isForwardRange!R2 && + is(ElementType!R1 == ElementType!R2)) { + return new Generator!(ElementType!R1)({ + auto v = r1.front; r1.popFront; + auto f = r2.front; r2.popFront; + + while (true) { + if (v > f) { + f = r2.front; r2.popFront; + continue; + } else if (v < f) + yield(v); + v = r1.front; r1.popFront; + } + }); +} + +void main() { + auto squares = 2.powers, cubes = 3.powers; + filtered(squares, cubes).drop(20).take(10).writeln; +} diff --git a/Task/Generator-Exponential/Julia/generator-exponential.julia b/Task/Generator-Exponential/Julia/generator-exponential.julia new file mode 100644 index 0000000000..d713569aa5 --- /dev/null +++ b/Task/Generator-Exponential/Julia/generator-exponential.julia @@ -0,0 +1,16 @@ +drop(n, gen) = (for i=1:n gen() end ; gen) + +take(n, gen) = [gen() for i=1:n] + +pgen(n) = let x=0; () -> (x+=1)^n; end + +function genfilter(gen1, gen2) + let r1 = -Inf, r2 = gen2() + () -> begin + r1 = gen1() + while r2 < r1 r2 = gen2() end + while r1 == r2 r1 = gen1() end + r1 + end + end +end diff --git a/Task/Generator-Exponential/Ruby/generator-exponential-1.rb b/Task/Generator-Exponential/Ruby/generator-exponential-1.rb index a3782e8176..e6648d6203 100644 --- a/Task/Generator-Exponential/Ruby/generator-exponential-1.rb +++ b/Task/Generator-Exponential/Ruby/generator-exponential-1.rb @@ -1,21 +1,22 @@ # This solution cheats and uses only one generator! def powers(m) - return enum_for(:powers, m) unless block_given? + return enum_for(__method__, m) unless block_given? n = 0 loop { yield n ** m; n += 1 } end def squares_without_cubes - return enum_for(:squares_without_cubes) unless block_given? + return enum_for(__method__) unless block_given? cubes = powers(3) c = cubes.next powers(2) do |s| - (c = cubes.next) until c >= s + c = cubes.next while c < s yield s unless c == s end end p squares_without_cubes.take(30).drop(20) +# p squares_without_cubes.lazy.drop(20).first(10) # Ruby 2.0+ diff --git a/Task/Generator-Exponential/Ruby/generator-exponential-2.rb b/Task/Generator-Exponential/Ruby/generator-exponential-2.rb index 0e6c6d01a9..83340be244 100644 --- a/Task/Generator-Exponential/Ruby/generator-exponential-2.rb +++ b/Task/Generator-Exponential/Ruby/generator-exponential-2.rb @@ -1,25 +1,25 @@ # This solution uses three generators. def powers(m) - return enum_for(:powers, m) unless block_given? + return enum_for(__method__, m) unless block_given? n = 0 loop { yield n ** m; n += 1 } end def squares_without_cubes - return enum_for(:squares_without_cubes) unless block_given? + return enum_for(__method__) unless block_given? cubes = powers(3) c = cubes.next squares = powers(2) loop do s = squares.next - (c = cubes.next) until c >= s + c = cubes.next while c < s yield s unless c == s end end answer = squares_without_cubes 20.times { answer.next } -p (1..10).map { answer.next } +p 10.times.map { answer.next } diff --git a/Task/Generator-Exponential/Ruby/generator-exponential-3.rb b/Task/Generator-Exponential/Ruby/generator-exponential-3.rb new file mode 100644 index 0000000000..ef60d0df92 --- /dev/null +++ b/Task/Generator-Exponential/Ruby/generator-exponential-3.rb @@ -0,0 +1,14 @@ +def filtered(s1, s2) + return enum_for(__method__, s1, s2) unless block_given? + v, f = s1.next, s2.next + loop do + v > f and f = s2.next and next + v < f and yield v + v = s1.next + end +end + +squares, cubes = powers(2), powers(3) +f = filtered(squares, cubes) +p f.take(30).last(10) +# p f.lazy.drop(20).first(10) # Ruby 2.0+ diff --git a/Task/Generator-Exponential/Scheme/generator-exponential.ss b/Task/Generator-Exponential/Scheme/generator-exponential.ss new file mode 100644 index 0000000000..8e72b6dd0f --- /dev/null +++ b/Task/Generator-Exponential/Scheme/generator-exponential.ss @@ -0,0 +1,27 @@ +(define (power-seq n) + (let ((i 0)) + (lambda () + (set! i (+ 1 i)) + (expt i n)))) + +(define (filter-seq m n) + (let* ((s1 (power-seq m)) (s2 (power-seq n)) + (a 0) (b 0)) + (lambda () + (set! a (s1)) + (let loop () + (if (>= a b) (begin + (cond ((> a b) (set! b (s2))) + ((= a b) (set! a (s1)))) + (loop)))) + a))) + +(let loop ((seq (filter-seq 2 3)) (i 0)) + (if (< i 30) + (begin + (if (> i 20) + (begin + (display (seq)) + (newline)) + (seq)) + (loop seq (+ 1 i))))) diff --git a/Task/Generic-swap/Aime/generic-swap.aime b/Task/Generic-swap/Aime/generic-swap.aime new file mode 100644 index 0000000000..0730ec1bb1 --- /dev/null +++ b/Task/Generic-swap/Aime/generic-swap.aime @@ -0,0 +1,12 @@ +void +__swap(&, &,,) +{ + set(0, $3); + set(1, $2); +} + +void +swap(&, &) +{ + xcall(xcall, __swap); +} diff --git a/Task/Generic-swap/Emacs-Lisp/generic-swap-1.l b/Task/Generic-swap/Emacs-Lisp/generic-swap-1.l new file mode 100644 index 0000000000..a260d050ce --- /dev/null +++ b/Task/Generic-swap/Emacs-Lisp/generic-swap-1.l @@ -0,0 +1,6 @@ +(defun swap (a-sym b-sym) + "Swap values of the variables given by A-SYM and B-SYM." + (let ((a-val (symbol-value a-sym))) + (set a-sym (symbol-value b-sym)) + (set b-sym a-val))) +(swap 'a 'b) diff --git a/Task/Generic-swap/Emacs-Lisp/generic-swap-2.l b/Task/Generic-swap/Emacs-Lisp/generic-swap-2.l new file mode 100644 index 0000000000..c40c143819 --- /dev/null +++ b/Task/Generic-swap/Emacs-Lisp/generic-swap-2.l @@ -0,0 +1,2 @@ +(defmacro swap (a b) + `(setq ,b (prog1 ,a (setq ,a ,b)))) diff --git a/Task/Generic-swap/Emacs-Lisp/generic-swap-3.l b/Task/Generic-swap/Emacs-Lisp/generic-swap-3.l new file mode 100644 index 0000000000..ff552bf099 --- /dev/null +++ b/Task/Generic-swap/Emacs-Lisp/generic-swap-3.l @@ -0,0 +1,8 @@ +(require 'cl) +(defmacro swap (a b) + `(psetf ,a ,b + ,b ,a)) + +(setq lst (list 123 456)) +(swap (car lst) (cadr lst)) +;; now lst is '(456 123) diff --git a/Task/Generic-swap/NewLISP/generic-swap.newlisp b/Task/Generic-swap/NewLISP/generic-swap.newlisp new file mode 100644 index 0000000000..0521357f74 --- /dev/null +++ b/Task/Generic-swap/NewLISP/generic-swap.newlisp @@ -0,0 +1 @@ +(swap a b) diff --git a/Task/Generic-swap/UNIX-Shell/generic-swap-1.sh b/Task/Generic-swap/UNIX-Shell/generic-swap-1.sh new file mode 100644 index 0000000000..dfdd43a27d --- /dev/null +++ b/Task/Generic-swap/UNIX-Shell/generic-swap-1.sh @@ -0,0 +1,10 @@ +$ swap() { typeset -n var1=$1 var2=$2; set -- "$var1" "$var2"; var1=$2; var2=$1; } +$ a=1 b=2 +$ echo $a $b +1 2 +$ swap a b +$ echo $a $b +2 1 +$ swap a b +$ echo $a $b +1 2 diff --git a/Task/Generic-swap/UNIX-Shell/generic-swap-2.sh b/Task/Generic-swap/UNIX-Shell/generic-swap-2.sh new file mode 100644 index 0000000000..7d49b86694 --- /dev/null +++ b/Task/Generic-swap/UNIX-Shell/generic-swap-2.sh @@ -0,0 +1,10 @@ +$ swap() { local var1=$1 var2=$2; set -- "${!var1}" "${!var2}"; declare -g "$var1"="$2" "$var2"="$1"; } +$ a=1 b=2 +$ echo $a $b +1 2 +$ swap a b +$ echo $a $b +2 1 +$ swap a b +$ echo $a $b +1 2 diff --git a/Task/Globally-replace-text-in-several-files/Clojure/globally-replace-text-in-several-files.clj b/Task/Globally-replace-text-in-several-files/Clojure/globally-replace-text-in-several-files.clj new file mode 100644 index 0000000000..cda3f8331f --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Clojure/globally-replace-text-in-several-files.clj @@ -0,0 +1,3 @@ +(defn hello-goodbye [& more] + (doseq [file more] + (spit file (.replace (slurp file) "Goodbye London!" "Hello New York!")))) diff --git a/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java b/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java index f67ef2c2ae..f8ff0c0ba2 100644 --- a/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java +++ b/Task/Globally-replace-text-in-several-files/Java/globally-replace-text-in-several-files.java @@ -1,53 +1,16 @@ -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.FileWriter; +import java.io.*; +import java.nio.file.*; -public class GlobalReplace -{ - public static void main(String[] args) - { - //Enter names of the files here - String[] filename={"foobar0.txt","foobar1.txt","foobar2.txt","foobar3.txt","foobar4.txt"}; - //Enter text to replace here - String from="Goodbye London!"; - //Enter replacing text here - String to="Hello New York!"; - - GlobalReplace now=new GlobalReplace(); - for(int i=0;i "Hello New York!"]; + Export[filename, filetext, "Text"] + , {i, 1, Length[listOfFiles]}] diff --git a/Task/Globally-replace-text-in-several-files/Sed/globally-replace-text-in-several-files.sed b/Task/Globally-replace-text-in-several-files/Sed/globally-replace-text-in-several-files.sed new file mode 100644 index 0000000000..5dc1050baa --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/Sed/globally-replace-text-in-several-files.sed @@ -0,0 +1 @@ +sed -i 's/Goodbye London!/Hello New York!/g' a.txt b.txt c.txt diff --git a/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files.txr b/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-1.txr similarity index 77% rename from Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files.txr rename to Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-1.txr index c598061212..000389b8f0 100644 --- a/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files.txr +++ b/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-1.txr @@ -1,5 +1,5 @@ @(next :args) -@(collect) +@(repeat) @file @(next `@file`) @(freeform) @@ -7,7 +7,5 @@ @(output `@file.tmp`) @(rep)@{notmatch}Hello, New York!@(end)@tail @(end) -@(next `!mv @file.tmp @file`) -@(output) -@(end) +@(do @(rename-path `@file.tmp` file)) @(end) diff --git a/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-2.txr b/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-2.txr new file mode 100644 index 0000000000..9561d549cc --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/TXR/globally-replace-text-in-several-files-2.txr @@ -0,0 +1,8 @@ +@(do + (each ((fname *args*)) + (let* ((infile (open-file fname)) + (outfile (open-file `@fname.tmp` "w")) + (content (get-string infile)) + (edited (regsub #/Goodbye, London/ "Hello, New York" content))) + (put-string edited outfile) + (rename-path `@fname.tmp` fname)))) diff --git a/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-1.sh b/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-1.sh new file mode 100644 index 0000000000..8f5509e05f --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-1.sh @@ -0,0 +1,13 @@ +replace() { + local search=$1 replace=$2 + local file lines line + shift 2 + for file in "$@"; do + lines=() + while IFS= read -r line; do + lines+=( "${line//$search/$replace}" ) + done < "$file" + printf "%s\n" "${lines[@]}" > "$file" + done +} +replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt diff --git a/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-2.sh b/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-2.sh new file mode 100644 index 0000000000..041441ea9f --- /dev/null +++ b/Task/Globally-replace-text-in-several-files/UNIX-Shell/globally-replace-text-in-several-files-2.sh @@ -0,0 +1,13 @@ +function replace { + typeset search=$1 replace=$2 + typeset file lines line + shift 2 + for file in "$@"; do + lines=() + while IFS= read -r line; do + lines+=( "${line//$search/$replace}" ) + done < "$file" + printf "%s\n" "${lines[@]}" > "$file" + done +} +replace "Goodbye London!" "Hello New York!" a.txt b.txt c.txt diff --git a/Task/Gray-code/00DESCRIPTION b/Task/Gray-code/00DESCRIPTION index e526d86fbe..9c9f633f11 100644 --- a/Task/Gray-code/00DESCRIPTION +++ b/Task/Gray-code/00DESCRIPTION @@ -1,8 +1,17 @@ -[[wp:Gray code|Gray code]] is a form of binary encoding where transitions between consecutive numbers differ by only one bit. This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs. It is also useful for generating inputs for [[wp:Karnaugh map|Karnaugh maps]] in order from left to right or top to bottom. +[[wp:Gray code|Gray code]] is a form of binary encoding +where transitions between consecutive numbers differ by only one bit. +This is a useful encoding for reducing hardware data hazards +with values that change rapidly and/or connect to slower hardware as inputs. +It is also useful for generating inputs for [[wp:Karnaugh map|Karnaugh maps]] +in order from left to right or top to bottom. -Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). +Create functions to encode a number to and decode a number from Gray code. +Display the normal binary representations, Gray code representations, +and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, +leading 0's not necessary). -There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." +There are many possible Gray codes. +The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code):
if b[i-1] = 1
diff --git a/Task/Gray-code/D/gray-code-1.d b/Task/Gray-code/D/gray-code-1.d
index 930c6da424..af9b15e222 100644
--- a/Task/Gray-code/D/gray-code-1.d
+++ b/Task/Gray-code/D/gray-code-1.d
@@ -1,8 +1,8 @@
-uint grayEncode(in uint n) pure nothrow {
+uint grayEncode(in uint n) pure nothrow @nogc {
     return n ^ (n >> 1);
 }
 
-uint grayDecode(uint n) pure nothrow {
+uint grayDecode(uint n) pure nothrow @nogc {
     auto p = n;
     while (n >>= 1)
         p ^= n;
diff --git a/Task/Gray-code/D/gray-code-2.d b/Task/Gray-code/D/gray-code-2.d
index 8d1cd3ba43..af792710c9 100644
--- a/Task/Gray-code/D/gray-code-2.d
+++ b/Task/Gray-code/D/gray-code-2.d
@@ -1,35 +1,36 @@
-import std.stdio, std.conv, std.algorithm;
+import std.stdio, std.algorithm;
 
-T[] gray(int N : 1, T)() { return [to!T(0), 1]; }
+T[] gray(int N : 1, T)() pure nothrow {
+    return [T(0), 1];
+}
 
-/// recursively generate gray encoding mapping table
-T[] gray(int N, T)() pure nothrow {
-    assert(N <= T.sizeof * 8, "N exceed number of bit of T");
-    enum T M = to!T(2) ^^ (N - 1);
+/// Recursively generate gray encoding mapping table.
+T[] gray(int N, T)() pure nothrow if (N <= T.sizeof * 8) {
+    enum T M = T(2) ^^ (N - 1);
     T[] g = gray!(N - 1, T)();
-    foreach (i; 0 .. M)
+    foreach (immutable i; 0 .. M)
         g ~= M + g[M - i - 1];
     return g;
 }
 
-T[][] grayDict(int N, T)() {
+T[][] grayDict(int N, T)() pure nothrow {
     T[][] dict = [gray!(N, T)(), [0]];
-    // append inversed gray encoding mapping
-    foreach (i; 1 .. dict[0].length)
+    // Append inversed gray encoding mapping.
+    foreach (immutable i; 1 .. dict[0].length)
         dict[1] ~= countUntil(dict[0], i);
     return dict;
 }
 
-enum M { Encode = 0, Decode = 1 };
+enum M { Encode = 0, Decode = 1 }
 
-T gray(int N, T)(in T n, in int mode=M.Encode) {
-    // generated at compile time
+T gray(int N, T)(in T n, in int mode=M.Encode) pure nothrow {
+    // Generated at compile time.
     enum dict = grayDict!(N, T)();
     return dict[mode][n];
 }
 
 void main() {
-    foreach (i; 0 .. 32) {
+    foreach (immutable i; 0 .. 32) {
         immutable encoded = gray!(5)(i, M.Encode);
         immutable decoded = gray!(5)(encoded, M.Decode);
         writefln("%2d: %5b => %5b : %2d", i, i, encoded, decoded);
diff --git a/Task/Gray-code/Haskell/gray-code.hs b/Task/Gray-code/Haskell/gray-code.hs
index f28983ffcb..ac401eb676 100644
--- a/Task/Gray-code/Haskell/gray-code.hs
+++ b/Task/Gray-code/Haskell/gray-code.hs
@@ -1,9 +1,9 @@
 import Data.Bits
 import Data.Char
 import Numeric
+import Control.Monad
 import Text.Printf
 
--- Conversion to and from traditional binary and Gray code
 grayToBin :: (Integral t, Bits t) => t -> t
 grayToBin 0 = 0
 grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)
@@ -11,8 +11,13 @@ grayToBin g = g `xor` (grayToBin $ g `shiftR` 1)
 binToGray :: (Integral t, Bits t) => t -> t
 binToGray b = b `xor` (b `shiftR` 1)
 
--- Print the first 32 Gray codes alongside their decimal and binary equivalences.
-main = flip mapM_ (take 32 [0,1..] :: [Int]) (\num -> do
-	let bin  = showIntAtBase 2 intToDigit num ""
-	    gray = showIntAtBase 2 intToDigit (binToGray num) ""
-	printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray)
+showBinary :: (Integral t, Show t) => t -> String
+showBinary n = showIntAtBase 2 intToDigit n ""
+
+showGrayCode :: (Integral t, Bits t, PrintfArg t, Show t) => t -> IO ()
+showGrayCode num = do
+    let bin  = showBinary num
+    let gray = showBinary (binToGray num)
+    printf "int: %2d -> bin: %5s -> gray: %5s\n" num bin gray
+
+main = forM_ [0..31::Int] showGrayCode
diff --git a/Task/Gray-code/MATLAB/gray-code.m b/Task/Gray-code/MATLAB/gray-code.m
new file mode 100644
index 0000000000..8beda54fe7
--- /dev/null
+++ b/Task/Gray-code/MATLAB/gray-code.m
@@ -0,0 +1,43 @@
+%% Gray Code Generator
+% this script generates gray codes of n bits
+% total 2^n -1 continuous gray codes will be generated.
+% this code follows a recursive approach. therefore,
+% it can be slow for large n
+
+
+
+clear all;
+clc;
+
+bits = input('Enter the number of bits: ');
+if (bits<1)
+    disp('Sorry, number of bits should be positive');
+elseif (mod(bits,1)~=0)
+    disp('Sorry, number of bits can only be positive integers');
+else
+    initial_container = [0;1];
+    if bits == 1
+        result = initial_container;
+    else
+        previous_container = initial_container;
+        for i=2:bits
+            new_gray_container = zeros(2^i,i);
+            new_gray_container(1:(2^i)/2,1) = 0;
+            new_gray_container(((2^i)/2)+1:end,1) = 1;
+
+            for j = 1:(2^i)/2
+                new_gray_container(j,2:end) = previous_container(j,:);
+            end
+
+            for j = ((2^i)/2)+1:2^i
+                new_gray_container(j,2:end) = previous_container((2^i)+1-j,:);
+            end
+
+            previous_container = new_gray_container;
+        end
+        result = previous_container;
+    end
+    fprintf('Gray code of %d bits',bits);
+    disp(' ');
+    disp(result);
+end
diff --git a/Task/Gray-code/R/gray-code.r b/Task/Gray-code/R/gray-code.r
new file mode 100644
index 0000000000..09785f729d
--- /dev/null
+++ b/Task/Gray-code/R/gray-code.r
@@ -0,0 +1,25 @@
+GrayEncode <- function(binary) {
+	gray <- substr(binary,1,1)
+	repeat {
+	if  (substr(binary,1,1) != substr(binary,2,2)) gray <- paste(gray,"1",sep="")
+	else gray <- paste(gray,"0",sep="")
+	binary <- substr(binary,2,nchar(binary))
+	if (nchar(binary) <=1) {
+		break
+		}
+	}
+return (gray)
+}
+GrayDecode <- function(gray) {
+	binary <- substr(gray,1,1)
+	repeat {
+	if  (substr(binary,nchar(binary),nchar(binary)) != substr(gray,2,2)) binary <- paste(binary ,"1",sep="")
+	else binary <- paste(binary ,"0",sep="")
+	gray <- substr(gray,2,nchar(gray))
+
+	if (nchar(gray) <=1) {
+		break
+		}
+	}
+return (binary)
+}
diff --git a/Task/Gray-code/Ruby/gray-code.rb b/Task/Gray-code/Ruby/gray-code.rb
index e3af40f625..28bebb5bcf 100644
--- a/Task/Gray-code/Ruby/gray-code.rb
+++ b/Task/Gray-code/Ruby/gray-code.rb
@@ -17,10 +17,9 @@ class Integer
   end
 end
 
-
 (0..31).each do |number|
   encoded = number.to_gray
   decoded = encoded.from_gray
-  printf("%2d: %5b => %5b => %5b: %2d\n",
-         number, number, encoded, decoded, decoded)
+  printf "%2d : %5b => %5b => %5b : %2d\n",
+         number, number, encoded, decoded, decoded
 end
diff --git a/Task/Gray-code/SQL/gray-code.sql b/Task/Gray-code/SQL/gray-code.sql
new file mode 100644
index 0000000000..7780a7be4b
--- /dev/null
+++ b/Task/Gray-code/SQL/gray-code.sql
@@ -0,0 +1,32 @@
+DECLARE @binary AS NVARCHAR(MAX) = '001010111'
+DECLARE @gray AS NVARCHAR(MAX) = ''
+
+--Encoder
+SET @gray = LEFT(@binary, 1)
+
+WHILE LEN(@binary) > 1
+  BEGIN
+      IF LEFT(@binary, 1) != SUBSTRING(@binary, 2, 1)
+        SET @gray = @gray + '1'
+      ELSE
+        SET @gray = @gray + '0'
+
+      SET @binary = RIGHT(@binary, LEN(@binary) - 1)
+  END
+
+SELECT @gray
+
+--Decoder
+SET @binary = LEFT(@gray, 1)
+
+WHILE LEN(@gray) > 1
+  BEGIN
+      IF RIGHT(@binary, 1) != SUBSTRING(@gray, 2, 1)
+        SET @binary = @binary + '1'
+      ELSE
+        SET @binary = @binary + '0'
+
+      SET @gray = RIGHT(@gray, LEN(@gray) - 1)
+  END
+
+SELECT @binary
diff --git a/Task/Gray-code/Seed7/gray-code.seed7 b/Task/Gray-code/Seed7/gray-code.seed7
new file mode 100644
index 0000000000..9bf43a56d4
--- /dev/null
+++ b/Task/Gray-code/Seed7/gray-code.seed7
@@ -0,0 +1,25 @@
+$ include "seed7_05.s7i";
+  include "bin32.s7i";
+
+const func integer: grayEncode (in integer: n) is
+  return ord(bin32(n) >< bin32(n >> 1));
+
+const func integer: grayDecode (in var integer: n) is func
+  result
+    var integer: decoded is 0;
+  begin
+    decoded := n;
+    while n > 1 do
+      n >>:= 1;
+      decoded := ord(bin32(decoded) >< bin32(n));
+    end while;
+  end func;
+
+const proc: main is func
+  local
+    var integer: i is 0;
+  begin
+    for i range 0 to 32 do
+      writeln(i <& " => " <& grayEncode(i) radix 2 lpad0 6 <& " => " <& grayDecode(grayEncode(i)));
+    end for;
+  end func;
diff --git a/Task/Grayscale-image/D/grayscale-image.d b/Task/Grayscale-image/D/grayscale-image.d
index 18b4408ed6..359f73621b 100644
--- a/Task/Grayscale-image/D/grayscale-image.d
+++ b/Task/Grayscale-image/D/grayscale-image.d
@@ -12,7 +12,7 @@ struct Gray {
 
 
 Image!Color loadPGM(Color)(Image!Color img, in string fileName) {
-    static int readNum(FILE* f) nothrow {
+    static int readNum(FILE* f) nothrow @nogc {
         int n;
         while (!fscanf(f, "%d ", &n)) {
             if ((n = fgetc(f)) == '#') {
@@ -25,11 +25,11 @@ Image!Color loadPGM(Color)(Image!Color img, in string fileName) {
         return n;
     }
 
-    scope(exit) if (fin) fclose(fin);
     if (img is null)
         img = new Image!Color();
 
     auto fin = fopen(fileName.toStringz(), "rb");
+    scope(exit) if (fin) fclose(fin);
     if (!fin)
         throw new Exception("Can't open input file.");
 
@@ -78,28 +78,28 @@ in {
 }
 
 
-Gray lumCIE(in RGB c) pure nothrow {
+Gray lumCIE(in RGB c) pure nothrow @nogc {
     return Gray(cast(ubyte)(0.2126 * c.r +
                             0.7152 * c.g +
                             0.0722 * c.b + 0.5));
 }
 
-Gray lumAVG(in RGB c) pure nothrow {
+Gray lumAVG(in RGB c) pure nothrow @nogc {
     return Gray(cast(ubyte)(0.3333 * c.r +
                             0.3333 * c.g +
                             0.3333 * c.b + 0.5));
 }
 
-Image!Gray rgb2grayImage(alias Conv=lumCIE)(in Image!RGB im) {
+Image!Gray rgb2grayImage(alias Conv=lumCIE)(in Image!RGB im) nothrow {
     auto result = new typeof(return)(im.nx, im.ny);
-    foreach (i, immutable rgb; im.image)
+    foreach (immutable i, immutable rgb; im.image)
         result.image[i] = Conv(rgb);
     return result;
 }
 
-Image!RGB gray2rgbImage(in Image!Gray im) {
+Image!RGB gray2rgbImage(in Image!Gray im) nothrow {
     auto result = new typeof(return)(im.nx, im.ny);
-    foreach (i, immutable gr; im.image)
+    foreach (immutable i, immutable gr; im.image)
         result.image[i] = RGB(gr, gr, gr);
     return result;
 }
diff --git a/Task/Greatest-common-divisor/C++/greatest-common-divisor.cpp b/Task/Greatest-common-divisor/C++/greatest-common-divisor.cpp
new file mode 100644
index 0000000000..4d8e2fc71f
--- /dev/null
+++ b/Task/Greatest-common-divisor/C++/greatest-common-divisor.cpp
@@ -0,0 +1,9 @@
+#include 
+#include 
+
+int main( ) {
+   std::cout << "The least common multiple of 12 and 18 is " <<
+      boost::math::lcm( 12 , 18 ) << " ,\n"
+      << "and the greatest common divisor " << boost::math::gcd( 12 , 18 ) << " !" << std::endl ;
+   return 0 ;
+}
diff --git a/Task/Greatest-common-divisor/D/greatest-common-divisor.d b/Task/Greatest-common-divisor/D/greatest-common-divisor.d
index 49d2f710e2..7f937f7c73 100644
--- a/Task/Greatest-common-divisor/D/greatest-common-divisor.d
+++ b/Task/Greatest-common-divisor/D/greatest-common-divisor.d
@@ -1,12 +1,12 @@
 import std.stdio, std.numeric;
 
-long myGCD(in long x, in long y) pure nothrow {
+long myGCD(in long x, in long y) pure nothrow @nogc {
     if (y == 0)
         return x;
     return myGCD(y, x % y);
 }
 
 void main() {
-    writeln(gcd(15, 10)); // from Phobos
-    writeln(myGCD(15, 10));
+    gcd(15, 10).writeln; // From Phobos.
+    myGCD(15, 10).writeln;
 }
diff --git a/Task/Greatest-common-divisor/Frink/greatest-common-divisor.frink b/Task/Greatest-common-divisor/Frink/greatest-common-divisor.frink
new file mode 100644
index 0000000000..5f3dcda643
--- /dev/null
+++ b/Task/Greatest-common-divisor/Frink/greatest-common-divisor.frink
@@ -0,0 +1 @@
+println[gcd[12345,98765]]
diff --git a/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-1.mercury b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-1.mercury
new file mode 100644
index 0000000000..ec534151c5
--- /dev/null
+++ b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-1.mercury
@@ -0,0 +1,11 @@
+:- module gcd.
+
+:- interface.
+:- import_module integer.
+
+:- func gcd(integer, integer) = integer.
+
+:- implementation.
+
+:- pragma memo(gcd/2).
+gcd(A, B) = (if B = integer(0) then A else gcd(B, A mod B)).
diff --git a/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-2.mercury b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-2.mercury
new file mode 100644
index 0000000000..1b95e8d0a1
--- /dev/null
+++ b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-2.mercury
@@ -0,0 +1,28 @@
+:- module test_gcd.
+
+:- interface.
+
+:- import_module io.
+
+:- pred main(io::di, io::uo) is det.
+
+:- implementation.
+
+:- import_module char.
+:- import_module gcd.
+:- import_module integer.
+:- import_module list.
+:- import_module string.
+
+main(!IO) :-
+    command_line_arguments(Args, !IO),
+    filter(is_all_digits, Args, CleanArgs),
+
+    Arg1 = list.det_index0(CleanArgs, 0),
+    Arg2 = list.det_index0(CleanArgs, 1),
+    A = integer.det_from_string(Arg1),
+    B = integer.det_from_string(Arg2),
+
+    Fmt = integer.to_string,
+    GCD = gcd(A, B),
+    io.format("gcd(%s, %s) = %s\n", [s(Fmt(A)), s(Fmt(B)), s(Fmt(GCD))], !IO).
diff --git a/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-3.mercury b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-3.mercury
new file mode 100644
index 0000000000..7b015e6287
--- /dev/null
+++ b/Task/Greatest-common-divisor/Mercury/greatest-common-divisor-3.mercury
@@ -0,0 +1 @@
+gcd(70000000000000000000000, 60000000000000000000000000) = 10000000000000000000000
diff --git a/Task/Greatest-common-divisor/Oberon-2/greatest-common-divisor.oberon-2 b/Task/Greatest-common-divisor/Oberon-2/greatest-common-divisor.oberon-2
new file mode 100644
index 0000000000..e81af17de6
--- /dev/null
+++ b/Task/Greatest-common-divisor/Oberon-2/greatest-common-divisor.oberon-2
@@ -0,0 +1,22 @@
+MODULE GCD;
+(* Greatest Common Divisor *)
+IMPORT
+  Out;
+
+  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;
+BEGIN
+  Out.String("GCD of    12 and     8 : ");Out.LongInt(Gcd(12,8),4);Out.Ln;
+  Out.String("GCD of   100 and     5 : ");Out.LongInt(Gcd(100,5),4);Out.Ln;
+  Out.String("GCD of     7 and    23 : ");Out.LongInt(Gcd(7,23),4);Out.Ln;
+  Out.String("GCD of    24 and  -112 : ");Out.LongInt(Gcd(12,8),4);Out.Ln;
+  Out.String("GCD of 40902 and 24140 : ");Out.LongInt(Gcd(40902,24140),4);Out.Ln
+END GCD.
diff --git a/Task/Greatest-common-divisor/Perl/greatest-common-divisor-4.pl b/Task/Greatest-common-divisor/Perl/greatest-common-divisor-4.pl
index 44b9d860ed..519bd59845 100644
--- a/Task/Greatest-common-divisor/Perl/greatest-common-divisor-4.pl
+++ b/Task/Greatest-common-divisor/Perl/greatest-common-divisor-4.pl
@@ -1,9 +1,11 @@
-use Benchmark qw(cmpthese);
+# Fastest, takes multiple inputs
+use Math::Prime::Util "gcd";
+$gcd = gcd(49865, 69811);
 
-my $u = 40902;
-my $v = 24140;
-cmpthese(-5, {
-  'gcd' => sub { gcd($u, $v); },
-  'gcd_iter' => sub { gcd_iter($u, $v); },
-  'gcd_bin' => sub { gcd_bin($u, $v); },
-});
+# In CORE.  Slowest, takes multiple inputs, result is a Math::BigInt unless converted
+use Math::BigInt;
+$gcd = Math::BigInt::bgcd(49865, 69811)->numify;
+
+# Result is a Math::Pari object unless converted
+use Math::Pari "gcd";
+$gcd = gcd(49865, 69811)->pari2iv
diff --git a/Task/Greatest-common-divisor/Perl/greatest-common-divisor-5.pl b/Task/Greatest-common-divisor/Perl/greatest-common-divisor-5.pl
index 2da40af913..d6eb444ee2 100644
--- a/Task/Greatest-common-divisor/Perl/greatest-common-divisor-5.pl
+++ b/Task/Greatest-common-divisor/Perl/greatest-common-divisor-5.pl
@@ -1,5 +1,15 @@
+use Benchmark qw(cmpthese);
 use Math::BigInt;
+use Math::Pari;
+use Math::Prime::Util;
 
-sub gcd($$) {
-  Math::BigInt::bgcd(@_)->numify();
-}
+my $u = 40902;
+my $v = 24140;
+cmpthese(-5, {
+  'gcd_rec' => sub { gcd($u, $v); },
+  'gcd_iter' => sub { gcd_iter($u, $v); },
+  'gcd_bin' => sub { gcd_bin($u, $v); },
+  'gcd_bigint' => sub { Math::BigInt::bgcd($u,$v)->numify(); },
+  'gcd_pari' => sub { Math::Pari::gcd($u,$v)->pari2iv(); },
+  'gcd_mpu' => sub { Math::Prime::Util::gcd($u,$v); },
+});
diff --git a/Task/Greatest-common-divisor/R/greatest-common-divisor-2.r b/Task/Greatest-common-divisor/R/greatest-common-divisor-2.r
index d44c0f05df..eedfd66434 100644
--- a/Task/Greatest-common-divisor/R/greatest-common-divisor-2.r
+++ b/Task/Greatest-common-divisor/R/greatest-common-divisor-2.r
@@ -3,4 +3,5 @@
     v <- t
     t <- c
   }
+  t
 }
diff --git a/Task/Greatest-common-divisor/REXX/greatest-common-divisor-2.rexx b/Task/Greatest-common-divisor/REXX/greatest-common-divisor-2.rexx
index c5bcad2b1d..c3631641a7 100644
--- a/Task/Greatest-common-divisor/REXX/greatest-common-divisor-2.rexx
+++ b/Task/Greatest-common-divisor/REXX/greatest-common-divisor-2.rexx
@@ -22,7 +22,7 @@ test:
 n=arg()                             /* Number of arguments           */
 gcde=arg(n)                         /* Expected result               */
 gcdx=gcd(arg(1),arg(2))             /* gcd of the first 2 numbers    */
-Do i=2 To n-2                       /* proceed with all te others    */
+Do i=2 To n-2                       /* proceed with all the others   */
   If arg(i+1)<>0 Then
     gcdx=gcd(gcdx,arg(i+1))
   End
@@ -30,7 +30,7 @@ If gcdx=arg(arg()) Then             /* result is as expected         */
   tag='as expected'
 Else                                /* result is not correct         */
   Tag='*** wrong. expected:' gcde
-numbers=arg(1)                      /* build sting to show the input */
+numbers=arg(1)                      /* build string to show the input*/
 Do i=2 To n-1
   numbers=numbers 'and' arg(i)
   End
diff --git a/Task/Greatest-common-divisor/REXX/greatest-common-divisor-3.rexx b/Task/Greatest-common-divisor/REXX/greatest-common-divisor-3.rexx
new file mode 100644
index 0000000000..b2a2a14fb2
--- /dev/null
+++ b/Task/Greatest-common-divisor/REXX/greatest-common-divisor-3.rexx
@@ -0,0 +1,13 @@
+gcd: procedure
+x=abs(arg(1))
+do j=2 to arg()
+  y=abs(arg(j))
+  If y<>0 Then Do
+    do until z==0
+      z=x//y
+      x=y
+      y=z
+      end
+    end
+  end
+return x
diff --git a/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb b/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb
index e9fb6662f9..47ad20a77b 100644
--- a/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb
+++ b/Task/Greatest-common-divisor/Ruby/greatest-common-divisor-1.rb
@@ -1,4 +1,2 @@
-irb(main):001:0> require 'rational'#Not necessary in Ruby 1.9+
-=> true
-irb(main):002:0> 40902.gcd(24140)
+irb(main):001:0> 40902.gcd(24140)
 => 34
diff --git a/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr b/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr
index 2c229a1b74..20242a646f 100644
--- a/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr
+++ b/Task/Greatest-common-divisor/TXR/greatest-common-divisor.txr
@@ -1 +1,2 @@
-@(bind g @(gcd (expt 2 123) (expt 6 49)))
+$ txr -c @(bind g @(gcd (expt 2 123) (expt 6 49)))
+g="562949953421312"
diff --git a/Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb b/Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb
new file mode 100644
index 0000000000..6580721f0d
--- /dev/null
+++ b/Task/Greatest-common-divisor/VBScript/greatest-common-divisor.vb
@@ -0,0 +1,17 @@
+Function GCD(a,b)
+	Do
+		If a Mod b > 0 Then
+			c = a Mod b
+			a = b
+			b = c
+		Else
+			GCD = b
+			Exit Do
+		End If
+	Loop
+End Function
+
+WScript.Echo "The GCD of 48 and 18 is " & GCD(48,18) & "."
+WScript.Echo "The GCD of 1280 and 240 is " & GCD(1280,240) & "."
+WScript.Echo "The GCD of 1280 and 240 is " & GCD(3475689,23566319) & "."
+WScript.Echo "The GCD of 1280 and 240 is " & GCD(123456789,234736437) & "."
diff --git a/Task/Greatest-element-of-a-list/00DESCRIPTION b/Task/Greatest-element-of-a-list/00DESCRIPTION
index 050070239f..9db404e063 100644
--- a/Task/Greatest-element-of-a-list/00DESCRIPTION
+++ b/Task/Greatest-element-of-a-list/00DESCRIPTION
@@ -1 +1,2 @@
-Create a function that returns the maximum value in a provided set of values, where the number of values may not be known until runtime.
+Create a function that returns the maximum value in a provided set of values,
+where the number of values may not be known until runtime.
diff --git a/Task/Greatest-element-of-a-list/00META.yaml b/Task/Greatest-element-of-a-list/00META.yaml
index 8644b2ad9b..5065df2172 100644
--- a/Task/Greatest-element-of-a-list/00META.yaml
+++ b/Task/Greatest-element-of-a-list/00META.yaml
@@ -1,2 +1,4 @@
 ---
+category:
+- Simple
 note: Arithmetic operations
diff --git a/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list.apl b/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list.apl
new file mode 100644
index 0000000000..ab345d8fe1
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/APL/greatest-element-of-a-list.apl
@@ -0,0 +1,2 @@
+LIST←2 4 6 3 8
+⌈/LIST
diff --git a/Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list.awk b/Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-1.awk
similarity index 100%
rename from Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list.awk
rename to Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-1.awk
diff --git a/Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-2.awk b/Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-2.awk
new file mode 100644
index 0000000000..2d4b562455
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/AWK/greatest-element-of-a-list-2.awk
@@ -0,0 +1,12 @@
+# Usage: awk -f greatest_list_element.awk
+#
+function max(a) {
+    for(i in a) if(a[i]>r) r=a[i];
+    return r
+}
+#
+BEGIN { a[0]=42;
+        a[1]=33;
+        a[2]=21;
+        print max(a)
+      }
diff --git a/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada b/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada
index cc9ef7f578..5a7f51a052 100644
--- a/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada
+++ b/Task/Greatest-element-of-a-list/Ada/greatest-element-of-a-list-1.ada
@@ -1,6 +1,6 @@
 with Ada.Text_Io;
 
-procedure Max_Test is
+procedure Max_Test isco
    -- substitute any array type with a scalar element
    type Flt_Array is array (Natural range <>) of Float;
 
diff --git a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime
index a6a987cdc8..29d9a7af9f 100644
--- a/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime
+++ b/Task/Greatest-element-of-a-list/Aime/greatest-element-of-a-list.aime
@@ -1,14 +1,15 @@
 integer
 lmax(list l)
 {
-    integer i, max;
+    integer i, max, x;
 
-    max = l_q_integer(l, 0);
+    max = l[0];
 
     i = 1;
     while (i < l_length(l)) {
-	if (max < l_q_integer(l, i)) {
-	    max = l_q_integer(l, i);
+	x = l[i];
+	if (max < x) {
+	    max = x;
 	}
 
 	i += 1;
diff --git a/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-1.cfm b/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-1.cfm
new file mode 100644
index 0000000000..244d6dac9b
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-1.cfm
@@ -0,0 +1,6 @@
+
+
+
+  
+
+#maxNum#
diff --git a/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-2.cfm b/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-2.cfm
new file mode 100644
index 0000000000..004c55fe93
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/ColdFusion/greatest-element-of-a-list-2.cfm
@@ -0,0 +1,3 @@
+
+
+#maxNum#
diff --git a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-2.math b/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-2.math
index e0f0636b8c..a396d4eb25 100644
--- a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-2.math
+++ b/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-2.math
@@ -1,4 +1,4 @@
- 7
- 17 Cos[6]/5
- Infinity
--Infinity
+Max[Max[],Max[a,b,c]]
+Max[Max[a],Max[b,c]]
+Max[Max[a,b],Max[c]]
+Max[Max[a,b,c],Max[]]
diff --git a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-3.math b/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-3.math
index a396d4eb25..4825b3c27f 100644
--- a/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-3.math
+++ b/Task/Greatest-element-of-a-list/Mathematica/greatest-element-of-a-list-3.math
@@ -1,4 +1 @@
-Max[Max[],Max[a,b,c]]
-Max[Max[a],Max[b,c]]
-Max[Max[a,b],Max[c]]
-Max[Max[a,b,c],Max[]]
+Max[Max[], Max[-4, -3]]
diff --git a/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-1.oberon-2 b/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-1.oberon-2
new file mode 100644
index 0000000000..c1bc8546fd
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-1.oberon-2
@@ -0,0 +1,38 @@
+MODULE GreatestElement1;
+IMPORT
+  ADT:ArrayList,
+  Object:Boxed,
+  Out;
+
+VAR
+  a: ArrayList.ArrayList(Boxed.LongInt);
+  max: Boxed.LongInt;
+
+
+  PROCEDURE Max(al: ArrayList.ArrayList(Boxed.LongInt)): Boxed.LongInt;
+  VAR
+    i: LONGINT;
+    item, max: Boxed.LongInt;
+  BEGIN
+    max := NEW(Boxed.LongInt,MIN(LONGINT));
+
+    i := 0;
+    WHILE (i < al.size) DO
+      item := al.Get(i);
+      IF item.value > max.value THEN max := item END;
+      INC(i)
+    END;
+    RETURN max
+  END Max;
+
+BEGIN
+  a := NEW(ArrayList.ArrayList(Boxed.LongInt),5);
+  a.Append(NEW(Boxed.LongInt,10));
+  a.Append(NEW(Boxed.LongInt,32));
+  a.Append(NEW(Boxed.LongInt,4));
+  a.Append(NEW(Boxed.LongInt,43));
+  a.Append(NEW(Boxed.LongInt,9));
+
+  max := Max(a);
+  Out.String("Max: ");Out.LongInt(max.value,4);Out.Ln
+END GreatestElement1.
diff --git a/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-2.oberon-2 b/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-2.oberon-2
new file mode 100644
index 0000000000..fa02ad568d
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Oberon-2/greatest-element-of-a-list-2.oberon-2
@@ -0,0 +1,26 @@
+MODULE GreatestElement2;
+IMPORT
+  Out;
+VAR
+  a: ARRAY 10 OF LONGINT;
+
+  PROCEDURE Max(a: ARRAY OF LONGINT): LONGINT;
+  VAR
+    i, max: LONGINT;
+  BEGIN
+    max := MIN(LONGINT);
+    FOR i := 0 TO LEN(a) - 1 DO
+      IF a[i] > max THEN max := a[i] END;
+    END;
+
+    RETURN max
+  END Max;
+BEGIN
+  a[0] := 10;
+  a[1] := 32;
+  a[2] := 4;
+  a[3] := 43;
+  a[4] := 9;
+
+  Out.String("Max: ");Out.LongInt(Max(a),4);Out.Ln
+END GreatestElement2.
diff --git a/Task/Greatest-element-of-a-list/RapidQ/greatest-element-of-a-list.rapidq b/Task/Greatest-element-of-a-list/RapidQ/greatest-element-of-a-list.rapidq
new file mode 100644
index 0000000000..6211e5ead2
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/RapidQ/greatest-element-of-a-list.rapidq
@@ -0,0 +1,9 @@
+functioni FindMax(...) as double
+    dim x as integer
+
+    for x = 1 to ParamValCount
+        IF ParamVal(x) > Result THEN Result = ParamVal(x)
+    next
+End functioni
+
+Print FindMax(50, 20, 65, 20, 105)
diff --git a/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-1.vim b/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-1.vim
new file mode 100644
index 0000000000..73a1329be0
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-1.vim
@@ -0,0 +1 @@
+max([1, 3, 2])
diff --git a/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-2.vim b/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-2.vim
new file mode 100644
index 0000000000..39505c3329
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Vim-Script/greatest-element-of-a-list-2.vim
@@ -0,0 +1,19 @@
+function! Max(list, ...)
+    " {list}	list of strings
+    " {a:1}	'i': ignore case, 'I': match case, otherwise use 'ignorecase' option
+    if empty(a:list)
+	return 0
+    endif
+    let gt_op = a:0>=1 ? get({'i': '>?', 'I': '>#'}, a:1, '>') : '>'
+    let cmp_expr = printf('a:list[idx] %s maxval', gt_op)
+    let maxval = a:list[0]
+    let len = len(a:list)
+    let idx = 1
+    while idx < len
+	if eval(cmp_expr)
+	    let maxval = a:list[idx]
+	endif
+	let idx += 1
+    endwhile
+    return maxval
+endfunction
diff --git a/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-1.xslt b/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-1.xslt
new file mode 100644
index 0000000000..ca1e6e381e
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-1.xslt
@@ -0,0 +1,13 @@
+
+	
+
+	
+		
+			
+			
+			
+				
+			
+		
+	
+
diff --git a/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-2.xslt b/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-2.xslt
new file mode 100644
index 0000000000..3c95deea8d
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/XSLT/greatest-element-of-a-list-2.xslt
@@ -0,0 +1,6 @@
+
+	3
+	1
+	12
+	7
+
diff --git a/Task/Greatest-element-of-a-list/Yacas/greatest-element-of-a-list.yacas b/Task/Greatest-element-of-a-list/Yacas/greatest-element-of-a-list.yacas
new file mode 100644
index 0000000000..5a56de9d7c
--- /dev/null
+++ b/Task/Greatest-element-of-a-list/Yacas/greatest-element-of-a-list.yacas
@@ -0,0 +1,4 @@
+Max({1, 3, 3, 7})
+Max({Pi,Exp(1)+2/5,17*Cos(6)/5,Sqrt(91/10)})
+Max({1,6,Infinity})
+Max({})
diff --git a/Task/Greatest-subsequential-sum/00DESCRIPTION b/Task/Greatest-subsequential-sum/00DESCRIPTION
index 28a0e35add..3ce28f6374 100644
--- a/Task/Greatest-subsequential-sum/00DESCRIPTION
+++ b/Task/Greatest-subsequential-sum/00DESCRIPTION
@@ -1 +1,2 @@
-Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum 0; thus if all elements are negative, the result must be the empty sequence.
+Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. 
+An empty subsequence is considered to have the sum 0; thus if all elements are negative, the result must be the empty sequence. diff --git a/Task/Greatest-subsequential-sum/ATS/greatest-subsequential-sum.ats b/Task/Greatest-subsequential-sum/ATS/greatest-subsequential-sum.ats new file mode 100644 index 0000000000..2e7bc21c17 --- /dev/null +++ b/Task/Greatest-subsequential-sum/ATS/greatest-subsequential-sum.ats @@ -0,0 +1,71 @@ +(* +** This one is +** translated into ATS from the Ocaml entry +*) + +(* ****** ****** *) +// +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o maxsubseq maxsubseq.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +typedef ints = List0(int) + +(* ****** ****** *) + +fun +maxsubseq + (xs: ints): (int, ints) = let +// +fun +loop +( + sum: int, seq: ints +, maxsum: int, maxseq: ints, xs: ints +) : (int, ints) = +( +case+ xs of +| nil () => + ( + maxsum + , list_vt2t(list_reverse(maxseq)) + ) (* end of [nil] *) +| cons (x, xs) => let + val sum = sum + x + and seq = cons (x, seq) + in + if sum < 0 + then loop (0, nil, maxsum, maxseq, xs) + else ( + if sum > maxsum + then loop (sum, seq, sum, seq, xs) + else loop (sum, seq, maxsum, maxseq, xs) + ) (* end of [else] *) + end // end of [cons] +) +// +in + loop (0, nil, 0, nil, xs) +end // end of [maxsubseq] + +implement +main0 () = () where +{ +val +(maxsum +,maxseq) = +maxsubseq +( + $list{int}(~1,~2,3,5,6,~2,~1,4,~4,2,~1) +) +// +val () = println! ("maxsum = ", maxsum) +val () = println! ("maxseq = ", maxseq) +// +} (* end of [main0] *) diff --git a/Task/Greatest-subsequential-sum/Component-Pascal/greatest-subsequential-sum.component b/Task/Greatest-subsequential-sum/Component-Pascal/greatest-subsequential-sum.component new file mode 100644 index 0000000000..690353c5e1 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Component-Pascal/greatest-subsequential-sum.component @@ -0,0 +1,45 @@ +MODULE OvctGreatestSubsequentialSum; +IMPORT StdLog, Strings, Args; + +PROCEDURE Gss(iseq: ARRAY OF INTEGER;OUT start, end, maxsum: INTEGER); +VAR + i,j,sum: INTEGER; +BEGIN + i := 0; maxsum := 0; start := 0; end := -1; + WHILE i < LEN(iseq) - 1 DO + sum := 0; j := i; + WHILE j < LEN(iseq) -1 DO + INC(sum ,iseq[j]); + IF sum > maxsum THEN + maxsum := sum; + start := i; + end := j + END; + INC(j); + END; + INC(i) + END +END Gss; + +PROCEDURE Do*; +VAR + p: Args.Params; + iseq: POINTER TO ARRAY OF INTEGER; + i, res, start, end, sum: INTEGER; +BEGIN + Args.Get(p); (* Get Params *) + NEW(iseq,p.argc); + (* Transform params to INTEGERs *) + FOR i := 0 TO p.argc - 1 DO + Strings.StringToInt(p.args[i],iseq[i],res) + END; + Gss(iseq,start,end,sum); + StdLog.String("["); + FOR i := start TO end DO + StdLog.Int(iseq[i]); + IF i < end THEN StdLog.String(",") END + END; + StdLog.String("]=");StdLog.Int(sum);StdLog.Ln; +END Do; + +END OvctGreatestSubsequentialSum. diff --git a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-1.d b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-1.d index 898ef780ef..5c35d2d9a0 100644 --- a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-1.d +++ b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-1.d @@ -1,9 +1,9 @@ import std.stdio; -inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow { +inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow @nogc { int maxSum, thisSum, i, start, end = -1; - foreach (j, x; sequence) { + foreach (immutable j, immutable x; sequence) { thisSum += x; if (thisSum < 0) { i = j + 1; @@ -23,8 +23,8 @@ inout(T[]) maxSubseq(T)(inout T[] sequence) pure nothrow { void main() { const a1 = [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]; - writeln("Maximal subsequence: ", maxSubseq(a1)); + writeln("Maximal subsequence: ", a1.maxSubseq); const a2 = [-1, -2, -3, -5, -6, -2, -1, -4, -4, -2, -1]; - writeln("Maximal subsequence: ", maxSubseq(a2)); + writeln("Maximal subsequence: ", a2.maxSubseq); } 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 e99daa0a79..8fef930a73 100644 --- a/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d +++ b/Task/Greatest-subsequential-sum/D/greatest-subsequential-sum-2.d @@ -3,35 +3,29 @@ import std.stdio, std.algorithm, std.range, std.typecons; mixin template InitsTails(T) { T[] data; size_t pos; - @property bool empty() pure nothrow { + @property bool empty() pure nothrow @nogc { return pos > data.length; } - void popFront() pure nothrow { pos++; } + void popFront() pure nothrow @nogc { pos++; } } struct Inits(T) { mixin InitsTails!T; - @property T[] front() pure nothrow { return data[0 .. pos]; } + @property T[] front() pure nothrow @nogc { return data[0 .. pos]; } } -auto inits(T)(T[] seq) { return seq.Inits!T; } +auto inits(T)(T[] seq) pure nothrow @nogc { return seq.Inits!T; } struct Tails(T) { mixin InitsTails!T; - @property T[] front() pure nothrow { return data[pos .. $]; } + @property T[] front() pure nothrow @nogc { return data[pos .. $]; } } -auto tails(T)(T[] seq) pure nothrow { return seq.Tails!T; } +auto tails(T)(T[] seq) pure nothrow @nogc { return seq.Tails!T; } -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(a.sum, a) } - )[1]; +T[] maxSubseq(T)(T[] seq) pure nothrow /*@nogc*/ { + //return seq.tails.map!inits.joiner.reduce!(max!sum); + return seq.tails.map!inits.join.minPos!q{ a.sum > b.sum }[0]; } void main() { diff --git a/Task/Greatest-subsequential-sum/Oberon-2/greatest-subsequential-sum.oberon-2 b/Task/Greatest-subsequential-sum/Oberon-2/greatest-subsequential-sum.oberon-2 new file mode 100644 index 0000000000..3159af516a --- /dev/null +++ b/Task/Greatest-subsequential-sum/Oberon-2/greatest-subsequential-sum.oberon-2 @@ -0,0 +1,85 @@ +MODULE GreatestSubsequentialSum; +IMPORT + Out, + Err, + IntStr, + ProgramArgs, + TextRider; +TYPE + IntSeq= POINTER TO ARRAY OF LONGINT; + +PROCEDURE ShowUsage(); +BEGIN + Out.String("Usage: GreatestSubsequentialSum {int}+");Out.Ln +END ShowUsage; + +PROCEDURE Gss(iseq: IntSeq; VAR start, end, maxsum: LONGINT); +VAR + i, j, sum: LONGINT; +BEGIN + i := 0; maxsum := 0; start := 0; end := -1; + WHILE (i < LEN(iseq^)) DO + sum := 0; j := i; + WHILE (j < LEN(iseq^) - 1) DO + INC(sum,iseq[j]); + IF sum > maxsum THEN + maxsum := sum; + start := i; + end := j + END; + INC(j) + END; + INC(i) + END +END Gss; + + +PROCEDURE GetParams():IntSeq; +VAR + reader: TextRider.Reader; + iseq: IntSeq; + param: ARRAY 32 OF CHAR; + argc,i: LONGINT; + res: SHORTINT; +BEGIN + iseq := NIL; + reader := TextRider.ConnectReader(ProgramArgs.args); + IF reader # NIL THEN + argc := ProgramArgs.args.ArgNumber(); + IF argc < 1 THEN + Err.String("There is no enough arguments.");Err.Ln; + ShowUsage; + HALT(0) + END; + + reader.ReadLn; (* Skips program name *) + + NEW(iseq,argc); + FOR i := 0 TO argc - 1 DO + reader.ReadLine(param); + IntStr.StrToInt(param,iseq[i],res); + END + END; + RETURN iseq +END GetParams; + +PROCEDURE Do; +VAR + iseq: IntSeq; + start, end, sum, i: LONGINT; +BEGIN + iseq := GetParams(); + Gss(iseq, start, end, sum); + i := start; + Out.String("["); + WHILE (i <= end) DO + Out.LongInt(iseq[i],0); + IF (i < end) THEN Out.Char(',') END; + INC(i) + END; + Out.String("]: ");Out.LongInt(sum,0);Out.Ln +END Do; + +BEGIN + Do +END GreatestSubsequentialSum. diff --git a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx index 32ca88cc3d..bde0344a92 100644 --- a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx +++ b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-1.rexx @@ -1,20 +1,14 @@ -/*REXX program finds the shortest greatest continous subsequence sum.*/ -arg @ /*get the arugment LIST (if any).*/ -say 'words='words(@) ' list='@ /*show WORDS and LIST to console.*/ -sum=word(@,1) /*a "starter" sum (of a sequence)*/ -w=words(@) /*number of words in the list. */ -at=1 /*where the sequence starts at. */ -L=0 /*the length of the sequence. */ - /*process the list. */ - do j=1 for w; f=word(@,j) - do k=j to w; s=f - do m=j+1 to k - s=s+word(@,m) - end /*m*/ - if s>sum then do; sum=s; at=j; L=k-j+1; end - end /*k*/ - end /*j*/ +/*REXX program finds the shortest greatest continuous subsequence sum.*/ +parse arg @; w=words(@) /*get arg list; # words in list.*/ +say 'words='w " list="@ /*show #words & LIST to console.*/ +sum=0; L=0; at=w+1 /*default sum, length, starts at.*/ + /* [↓] process the list of nums.*/ + do j=1 for w; f=word(@,j) /*select one number at a time. */ + do k=j to w /* [↓] process a sub─list of #s.*/ + s=f; do m=j+1 to k; s=s+word(@,m); end /*m*/ + if s>sum then do; sum=s; at=j; L=k-j+1; end + end /*k*/ /* [↑] chose greatest sum of #s.*/ + end /*j*/ -seq=subword(@,at,L); if seq=='' then seq="[NULL]" -say; say 'sum='word(sum 0,1)/1 " sequence="seq - /*stick a fork in it, we're done.*/ +$=subword(@,at,L); if $=='' then $="[NULL]" /*Englishize it.*/ +say; say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're done.*/ diff --git a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx index becc81213a..eae256b02b 100644 --- a/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx +++ b/Task/Greatest-subsequential-sum/REXX/greatest-subsequential-sum-2.rexx @@ -1,21 +1,14 @@ -/*REXX program finds the longest greatest continous subsequence sum. */ -arg @ /*get the arugment LIST (if any).*/ -say 'words='words(@) ' list='@ /*show WORDS and LIST to console.*/ -sum=word(@,1) /*a "starter" sum (of a sequence)*/ -w=words(@) /*number of words in the list. */ -at=1 /*where the sequence starts at. */ -L=0 /*the length of the sequence. */ - /*process the list. */ - do j=1 for w; f=word(@,j) - do k=j to w; s=f - do m=j+1 to k - s=s+word(@,m) - end /*m*/ - _=k-j+1 - if (s==sum & _>L) | s>sum then do; sum=s; at=j; L=_; end - end /*k*/ - end /*j*/ +/*REXX program finds the longest greatest continuous subsequence sum.*/ +parse arg @; w=words(@) /*get arg list; # words in list.*/ +say 'words='w " list="@ /*show #words & LIST to console.*/ +sum=0; L=0; at=w+1 /*default sum, length, starts at.*/ + /* [↓] process the list of nums.*/ + do j=1 for w; f=word(@,j) /*select one number at a time. */ + do k=j to w; _=k-j+1 /* [↓] process a sub─list of #s.*/ + s=f; do m=j+1 to k; s=s+word(@,m); end /*m*/ + if (s==sum & _>L) | s>sum then do; sum=s; at=j; L=_; end + end /*k*/ /* [↑] chose longest greatest sum*/ + end /*j*/ -seq=subword(@,at,L); if seq=='' then seq="[NULL]" -say; say 'sum='word(sum 0,1)/1 " sequence="seq - /*stick a fork in it, we're done.*/ +$=subword(@,at,L); if $=='' then $="[NULL]" /*Englishize it.*/ +say; say 'sum='sum/1 " sequence="$ /*stick a fork in it, we're done.*/ diff --git a/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-1.rb b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-1.rb index 631c3ca373..39f8861929 100644 --- a/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-1.rb +++ b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-1.rb @@ -1,13 +1,9 @@ -Infinity = 1.0/0 def subarray_sum(arr) - max, slice = -Infinity, [] - arr.each_with_index do |n, i| + max, slice = 0, [] + arr.each_index do |i| (i...arr.length).each do |j| - sum = arr[i..j].inject(0) { |x, sum| sum += x } - if sum > max - max = sum - slice = arr[i..j] - end + sum = arr[i..j].inject(0, :+) + max, slice = sum, arr[i..j] if sum > max end end [max, slice] diff --git a/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-2.rb b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-2.rb index 5643779875..7f3ea10cb7 100644 --- a/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-2.rb +++ b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-2.rb @@ -1,30 +1,8 @@ -# the trick is that at any point -# in the iteration if starting a new chain is -# better than your current score with this element -# added to it, then do so. -# the interesting part is proving the math behind it -Infinity = 1.0/0 -def subarray_sum(arr) - curr,max = -Infinity,-Infinity - first,last= 0,0 - arr.each_with_index do |e,i| - curr = e + curr - if(e>curr) - curr = e - first=i - end - if(curr > max) - max = curr - last=i - end - end - return max,arr[first...last+1] +[ [1, 2, 3, 4, 5, -8, -9, -20, 40, 25, -5], + [-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1], + [-1, -2, -3, -4, -5], + [] +].each do |input| + puts "\nInput seq: #{input}" + puts " Max sum: %d\n Subseq: %s" % subarray_sum(input) end - -input=[1,2,3,4,5,-8,-9,-20,40,25,-5] -p subarray_sum(input) -=>[65, [40, 25]] - -input=[-3, -1] -p subarray_sum(input) -=>[-1, [-1]] diff --git a/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-3.rb b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-3.rb new file mode 100644 index 0000000000..0dd019a195 --- /dev/null +++ b/Task/Greatest-subsequential-sum/Ruby/greatest-subsequential-sum-3.rb @@ -0,0 +1,22 @@ +# the trick is that at any point +# in the iteration if starting a new chain is +# better than your current score with this element +# added to it, then do so. +# the interesting part is proving the math behind it +def subarray_sum(arr) + curr = max = 0 + first, last, curr_first = arr.size, 0, 0 + arr.each_with_index do |e,i| + curr += e + if e > curr + curr = e + curr_first = i + end + if curr > max + max = curr + first = curr_first + last = i + end + end + return max, arr[first..last] +end diff --git a/Task/Greyscale-bars-Display/Frink/greyscale-bars-display.frink b/Task/Greyscale-bars-Display/Frink/greyscale-bars-display.frink new file mode 100644 index 0000000000..098a4e7d27 --- /dev/null +++ b/Task/Greyscale-bars-Display/Frink/greyscale-bars-display.frink @@ -0,0 +1,20 @@ +fakewidth =!= dummy + +g = new graphics +drawBars[g, 0, 1, 0, 1/4, 8] +drawBars[g, 1, 0, 1/4, 1/2, 16] +drawBars[g, 0, 1, 1/2, 3/4, 32] +drawBars[g, 1, 0, 3/4, 1, 64] +g.show[640,480,1] // No portable fullscreen mode; user must maximize window. + +drawBars[g is graphics, leftColor, rightColor, top, bottom, steps] := +{ + colorStep = (rightColor - leftColor) / steps + color = leftColor + for i=0 to steps-1 + { + g.color[color, color, color] + g.fillRectSides[i/dummy/steps, top, (i+1)/dummy/steps, bottom] + color = color + colorStep + } +} diff --git a/Task/Greyscale-bars-Display/MAXScript/greyscale-bars-display.max b/Task/Greyscale-bars-Display/MAXScript/greyscale-bars-display.max new file mode 100644 index 0000000000..4ccf34334a --- /dev/null +++ b/Task/Greyscale-bars-Display/MAXScript/greyscale-bars-display.max @@ -0,0 +1,69 @@ +fn drawBarRow _bmp _row _width _number _inverse= +( + local dir = if _inverse then 1 else -1 + if not _inverse then + ( + setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (black)) + for i = (_width/_number) to _width by (_width/_number) do + ( + local loopPosition = i/(_width-(_width/_number)) as float + local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition) + setpixels _bmp [i,_row] colorsArr + ) + return _bmp + ) + else + ( + setpixels _bmp [0,_row] (for i in 1 to (_width/_number) collect (white)) + for i = _width to (_width/_number) by ((_width/_number)*-1) do + ( + local loopPosition = 1.0-(i/(_width-(_width/_number))) as float + local colorsArr = for c in 1 to (_width/_number) collect (white*loopPosition) + setpixels _bmp [i,_row] colorsArr + ) + return _bmp + ) + +) + +fn bitmap_verticalBars = +( + local width = (sysinfo.desktopsize).x + local height = (sysinfo.desktopsize).y + local theBitmap = bitmap width height color:white + + local row = 0 + while row <= (height-1) do + ( + local barNumber = 0 + case of + ( + (row < (height/4)): (barNumber = 1) + (row >= (height/4) and row < (height/2)): (barNumber = 2) + (row >= (height/2) and row < (height-(height/4))): (barNumber = 3) + (row >= (height-(height/4))): (barNumber = 4) + default: return theBitmap + ) + case barNumber of + ( + 1: ( + theBitmap = drawBarRow theBitmap row width 8 false + ) + 2: ( + theBitmap = drawBarRow theBitmap row width 16 true + ) + 3: ( + theBitmap = drawBarRow theBitmap row width 32 false + ) + 4: ( + theBitmap = drawBarRow theBitmap row width 64 true + ) + ) + row += 1 + -- + ) + return theBitmap +) + +b = bitmap_verticalBars() +display b diff --git a/Task/Greyscale-bars-Display/RapidQ/greyscale-bars-display.rapidq b/Task/Greyscale-bars-Display/RapidQ/greyscale-bars-display.rapidq new file mode 100644 index 0000000000..d2a89fd027 --- /dev/null +++ b/Task/Greyscale-bars-Display/RapidQ/greyscale-bars-display.rapidq @@ -0,0 +1,28 @@ +Declare Sub PaintCanvas + +Create Form as Qform + Caption = "Rosetta Greyscale" + Center + create Canv as QCanvas + align = 5 + onPaint = PaintCanvas + end create +end create + +Sub PaintCanvas + NumRows = 4 'Change for number of rows + for curbar = 0 to NumRows-1 + Bars = 2^(curbar+3) + for x = 0 to (Bars -1) + x1=Canv.Width/Bars*x + y1=Canv.Height/NumRows*CurBar + x2=Canv.Width/Bars*(x+1) + y2=Canv.Height/NumRows*(CurBar+1) + c=(255/(Bars-1))*x + c=iif(curbar mod 2, 255-c, c) + Canv.FillRect(x1, y1, x2, y2, rgb(c, c, c)) + next x + next curbar +end sub + +Form.showmodal diff --git a/Task/Guess-the-number-With-feedback--player-/C-sharp/guess-the-number-with-feedback--player-.cs b/Task/Guess-the-number-With-feedback--player-/C-sharp/guess-the-number-with-feedback--player-.cs new file mode 100644 index 0000000000..8fee19cb34 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/C-sharp/guess-the-number-with-feedback--player-.cs @@ -0,0 +1,132 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; //Remember to add this if you want the game to pause in RealisticGuess.Start() + +namespace ConsoleApplication1 +{ + class RealisticGuess //Simulates a guessing game between two people. Guessing efficiency is not a goal. + { + private int max; + private int min; + private int guess; + + public void Start() + { + Console.Clear(); + string input; + + try + { + Console.WriteLine("Please enter the lower boundary"); + input = Console.ReadLine(); + min = Convert.ToInt32(input); + Console.WriteLine("Please enter the upper boundary"); + input = Console.ReadLine(); + max = Convert.ToInt32(input); + } + catch (FormatException) + { + Console.WriteLine("The entry you have made is invalid. Please make sure your entry is an integer and try again."); + Console.ReadKey(true); + Start(); + } + Console.WriteLine("Think of a number between {0} and {1}.", min, max); + Thread.Sleep(2500); + Console.WriteLine("Ready?"); + Console.WriteLine("Press any key to begin."); + Console.ReadKey(true); + Guess(min, max); + } + public void Guess(int min, int max) + { + int counter = 1; + string userAnswer; + bool correct = false; + Random rand = new Random(); + + while (correct == false) + { + guess = rand.Next(min, max); + Console.Clear(); + Console.WriteLine("{0}", guess); + Console.WriteLine("Is this number correct? {Y/N}"); + userAnswer = Console.ReadLine(); + if (userAnswer != "y" && userAnswer != "Y" && userAnswer != "n" && userAnswer != "N") + { + Console.WriteLine("Your entry is invalid. Please enter either 'Y' or 'N'"); + Console.WriteLine("Is the number correct? {Y/N}"); + userAnswer = Console.ReadLine(); + } + if (userAnswer == "y" || userAnswer == "Y") + { + correct = true; + } + if (userAnswer == "n" || userAnswer == "N") + { + counter++; + if (max == min) + { + Console.WriteLine("Error: Range Intersect. Press enter to restart the game."); //This message should never pop up if the user enters good data. + Console.ReadKey(true); //It handles the game-breaking exception that occurs + Guess(1, 101); //when the max guess number is the same as the min number. + } + Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); + userAnswer = Console.ReadLine(); + if (userAnswer != "l" && userAnswer != "L" && userAnswer != "h" && userAnswer != "H") + { + Console.WriteLine("Your entry is invalid. Please enter either 'L' or 'H'"); + Console.WriteLine("Is the number you're thinking of lower or higher? {L/H}"); + userAnswer = Console.ReadLine(); + } + if (userAnswer == "l" || userAnswer == "L") + { + max = guess; + } + if (userAnswer == "h" || userAnswer == "H") + { + min = guess; + } + } + } + if (correct == true) + { + EndAndLoop(counter); + } + } + + public void EndAndLoop(int iterations) + { + string userChoice; + bool loop = false; + Console.WriteLine("Game over. It took {0} guesses to find the number.", iterations); + while (loop == false) + { + Console.WriteLine("Would you like to play again? {Y/N}"); + userChoice = Console.ReadLine(); + if (userChoice != "Y" && userChoice != "y" && userChoice != "N" && userChoice != "n") + { + Console.WriteLine("Sorry, your input is invalid. Please answer 'Y' to play again, or 'N' to quit."); + } + if (userChoice == "Y" || userChoice == "y") + { + Start(); + } + if (userChoice == "N" || userChoice == "n") + { + Environment.Exit(1); + } + } + } + } + class Program + { + static void Main(string[] args) + { + Console.Title = "Random Number"; + RealisticGuess game = new RealisticGuess(); + game.Start(); + } + } +} diff --git a/Task/Guess-the-number-With-feedback--player-/MATLAB/guess-the-number-with-feedback--player-.m b/Task/Guess-the-number-With-feedback--player-/MATLAB/guess-the-number-with-feedback--player-.m new file mode 100644 index 0000000000..ad2a608955 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/MATLAB/guess-the-number-with-feedback--player-.m @@ -0,0 +1,30 @@ +function GuessNumberFeedbackPlayer + + lowVal = input('Lower limit: '); + highVal = input('Upper limit: '); + fprintf('Think of your number. Press Enter when ready.\n') + pause + nGuesses = 1; + done = false; + while ~done + guess = floor(0.5*(lowVal+highVal)); + score = input(sprintf( ... + 'Is %d too high (H), too low (L), or equal (E)? ', guess), 's'); + if any(strcmpi(score, {'h' 'hi' 'high' 'too high' '+'})) + highVal = guess-1; + nGuesses = nGuesses+1; + elseif any(strcmpi(score, {'l' 'lo' 'low' 'too low' '-'})) + lowVal = guess+1; + nGuesses = nGuesses+1; + elseif any(strcmpi(score, {'e' 'eq' 'equal' 'right' 'correct' '='})) + fprintf('Yay! I win in %d guesses.\n', nGuesses) + done = true; + else + fprintf('Unclear response. Try again.\n') + end + if highVal < lowVal + fprintf('Incorrect scoring. No further guesses.\n') + done = true; + end + end +end diff --git a/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--1.max b/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--1.max new file mode 100644 index 0000000000..ff1de3624b --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--1.max @@ -0,0 +1,26 @@ +inclusiveRange = [1,100] +lowRange = inclusiveRange.x +maxRange = inclusiveRange.y +guesses = 1 +inf = "Think of a number between % and % and I will try to guess it.\n" +\ + "Type -1 if the guess is less than your number,\n"+\ + "0 if the guess is correct, " +\ + "or 1 if it's too high.\nPress esc to exit.\n" +clearListener() +format inf (int lowRange) (int maxRange) +while not keyboard.escpressed do +( + local chosen = ((lowRange + maxRange) / 2) as integer + if lowRange == maxRange do format "\nHaving fun?" + format "\nI choose %.\n" chosen + local theAnswer = getKBValue prompt:"Answer? " + case theAnswer of + ( + (-1): (lowRange = chosen; guesses += 1) + (0): (format "\nYay. I guessed your number after % %.\n" \ + guesses (if guesses == 1 then "try" else "tries") + exit with OK) + (1): (maxRange = chosen; guesses += 1) + default: (format "\nI don't understand your input.") + ) +) diff --git a/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--2.max b/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--2.max new file mode 100644 index 0000000000..a2bdfabeb1 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/MAXScript/guess-the-number-with-feedback--player--2.max @@ -0,0 +1,21 @@ +OK +Think of a number between 1 and 100 and I will try to guess it. +Type -1 if the guess is less than your number, +0 if the guess is correct, or 1 if it's too high. +Press esc to exit. +OK + +I choose 50. +Answer? -1 +I choose 75. +Answer? -1 +I choose 87. +Answer? 1 +I choose 81. +Answer? -1 +I choose 84. +Answer? -1 +I choose 85. +Answer? 0 +Yay. I guessed your number after 6 tries. +OK diff --git a/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--1.pro b/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--1.pro new file mode 100644 index 0000000000..3281415895 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--1.pro @@ -0,0 +1,22 @@ +min(1). max(10). + +pick_number(Min, Max) :- + min(Min), max(Max), + format('Pick a number between ~d and ~d, and I will guess it...~nReady? (Enter anything when ready):', [Min, Max]), + read(_). + +guess_number(Min, Max) :- + Guess is (Min + Max) // 2, + format('I guess ~d...~nAm I correct (c), too low (l), or too high (h)? ', [Guess]), + repeat, + read(Score), + ( Score = l -> NewMin is Guess + 1, guess_number(NewMin, Max) + ; Score = h -> NewMax is Guess - 1, guess_number(Min, NewMax) + ; Score = c -> writeln('I am correct!') + ; writeln('Invalid input'), + false + ). + +play :- + pick_number(Min, Max), + guess_number(Min, Max). diff --git a/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--2.pro b/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--2.pro new file mode 100644 index 0000000000..2ca99eefd8 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/Prolog/guess-the-number-with-feedback--player--2.pro @@ -0,0 +1,11 @@ +?- play. +Pick a number between 1 and 10, and I will guess it... +Ready? (Enter anything when ready):y. +I guess 5... +Am I correct (c), too low (l), or too high (h)? h. +I guess 2... +Am I correct (c), too low (l), or too high (h)? l. +I guess 3... +Am I correct (c), too low (l), or too high (h)? c. +I'm correct! +true diff --git a/Task/Guess-the-number-With-feedback--player-/REXX/guess-the-number-with-feedback--player--1.rexx b/Task/Guess-the-number-With-feedback--player-/REXX/guess-the-number-with-feedback--player--1.rexx index 09772a5dca..4dd8da5188 100644 --- a/Task/Guess-the-number-With-feedback--player-/REXX/guess-the-number-with-feedback--player--1.rexx +++ b/Task/Guess-the-number-With-feedback--player-/REXX/guess-the-number-with-feedback--player--1.rexx @@ -1,28 +1,24 @@ -/*REXX pgm to play guess-the-number (with itself) with positive integers*/ -parse arg low high . -if low=='' then low=1 -if high=='' then high=1000 -?=random(low,high) -say -try="Try to guess my integer (it's between" low 'and' high" inclusive)." +/*REXX pgm plays guess-the-number (with itself) with positive integers*/ +numeric digits 9 /*this is the normal REXX default*/ +parse arg low high .,guess /*get optional args from the C.L.*/ +if low=='' then low=1 /*Not given? Then use the default*/ +if high=='' then high=1000 /* " " " " " " */ +?=random(low,high) /*get a random (non-negative) int*/ +$="Try to guess my integer (it's between" low 'and' high" inclusive)." - do j=1 - say try; say - call guesser - select - when guess>? then info=right("It's too high.",40) - when guess? then info=right("It's too high.",40) + when guess? then info=right("It's too high.",40) when guess { - println!("Jolly good! I got it in only {} tries!", number_of_guesses); - break; - } - "l" | "L" => take_a_guess(current_guess, high), - "h" | "H" => take_a_guess(low, current_guess), - _ => println("sorry, I didn't quite get that") + let mut stdin = stdin(); + loop { + let mut min = MIN; + let mut max = MAX; + let mut num_guesses = 1is; + println!("Please think of a number between {} and {}", min, max); + loop { + let guess = (min + max) / 2; + println!("Is it {}?", guess); + println!("(type h if my guess is too high, l if too low, e if equal and q to quit)"); + match stdin.read_line().ok().and_then(|line| Some(line.as_slice().char_at(0).to_uppercase())) { + Some('H') => { + max = guess - 1; + num_guesses += 1; + }, + Some('L')=> { + min = guess + 1; + num_guesses += 1; + }, + Some('E') => { + if num_guesses == 1 { + println!("\n*** That was easy! Got it in one guess! ***\n"); + } else { + println!("\n*** I knew it! Got it in only {} guesses! ***\n", num_guesses); + } + break; + }, + Some('Q') => return, + _ => println!("Sorry, I didn't quite get that. Please try again.") + } + } } - if low == high { - println!("Your number must be {}. Or maybe you forgot it? It happens!", low); - break; - } - if low > high { - println("Uh, I think something went wrong. Entirely my fault, I'm sure!"); - break; - } - } -} - -fn calculate_guess(low: int, high: int) -> int { - (low + high) / 2 } diff --git a/Task/Guess-the-number-With-feedback--player-/UNIX-Shell/guess-the-number-with-feedback--player-.sh b/Task/Guess-the-number-With-feedback--player-/UNIX-Shell/guess-the-number-with-feedback--player-.sh new file mode 100644 index 0000000000..4dbd5bcc23 --- /dev/null +++ b/Task/Guess-the-number-With-feedback--player-/UNIX-Shell/guess-the-number-with-feedback--player-.sh @@ -0,0 +1,18 @@ +read -p "Lower bound: " lower +read -p "Upper bound: " upper +moves=0 +PS3="> " +while :; do + ((moves++)) + guess=$(( lower + (upper-lower)/2 )) + echo "Is it $guess?" + select ans in "too small" "too big" "got it!"; do + case $ans in + "got it!") break 2 ;; + "too big") upper=$(( upper==guess ? upper-1 : guess )); break ;; + "too small") lower=$(( lower==guess ? lower+1 : guess )); break ;; + esac + done + ((lower>upper)) && echo "you must be cheating!" +done +echo "I guessed it in $moves guesses" diff --git a/Task/Guess-the-number-With-feedback/ALGOL-68/guess-the-number-with-feedback.alg b/Task/Guess-the-number-With-feedback/ALGOL-68/guess-the-number-with-feedback.alg new file mode 100644 index 0000000000..2e7fc07971 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/ALGOL-68/guess-the-number-with-feedback.alg @@ -0,0 +1,47 @@ +# simple guess-the-number game # + +main:( + + BOOL valid input := TRUE; + + # register an error handler so we can detect and recover from # + # invalid input # + on value error( stand in + , ( REF FILE f )BOOL: + BEGIN + valid input := FALSE; + TRUE + END + ); + + # construct a random integer between 1 and 100 # + INT number = 1 + ROUND ( random * 99 ); + + print( ( "I'm thinking of a number between 1 and 100", newline ) ); + + # read the user's guesses until they guess correctly # + # we give feedback so they can find the number using interval # + # halving # + WHILE + print( ( "What do you think it is? " ) ); + INT guess; + WHILE + valid input := TRUE; + read( ( guess, newline ) ); + NOT valid input + DO + print( ( "Please guess a number between 1 and 100", newline ) ) + OD; + number /= guess + DO + IF number > guess + THEN + # the user's guess was too small # + print( ( newline, "My number is higher than that", newline ) ) + ELSE + # the user's guess was too large # + print( ( newline, "My number is lower than that", newline ) ) + FI + OD; + print( ( "That's correct!", newline ) ) +) diff --git a/Task/Guess-the-number-With-feedback/Batch-File/guess-the-number-with-feedback.bat b/Task/Guess-the-number-With-feedback/Batch-File/guess-the-number-with-feedback.bat new file mode 100644 index 0000000000..d9c868938b --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Batch-File/guess-the-number-with-feedback.bat @@ -0,0 +1,17 @@ +@echo off + +:A +set /a number=%random% %% 10 + 1 +:B +set /p guess=Choose a number between 1 and 10: +if %guess equ %number% goto win +if %guess% gtr 10 msg * "Number must be between 1 and 10." +if %guess% leq 0 msg * "Number must be between 1 and 10." +if %guess% gtr %number% echo Higher! +if %guess% lss %number% echo Lower! +goto B +:win +cls +echo You won! The number was %number% +pause>nul +goto A diff --git a/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir b/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir new file mode 100644 index 0000000000..362ba62bea --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Elixir/guess-the-number-with-feedback.elixir @@ -0,0 +1,28 @@ +defmodule GuessingGame do + def init() do + :random.seed(:erlang.now()) + end + def play(lower, upper) do + play(lower, upper, :random.uniform(upper + 1 - lower) + lower - 1) + end + defp play(lower, upper, number) do + guess = Integer.parse(IO.gets "Guess a number (#{lower}-#{upper}): ") + case guess do + {n, _} when n == number -> + IO.puts "Well guessed!" + {n, _} when lower <= n and n <= upper -> + if n > number do + IO.puts "Too high." + else + IO.puts "Too low." + end + play(lower, upper, number) + _ -> + IO.puts "Guess not in valid range." + play(lower, upper, number) + end + end +end + +GuessingGame.init() +GuessingGame.play(1, 100) 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 index 41cf1b13af..b9a379c954 100644 --- 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 @@ -1,24 +1,26 @@ -function [S,GS]=guess_a_number(low,high) +function guess_a_number(low, high) -if nargin<1, - low=1; -end; -if nargin<2, - high=10; +if nargin < 1 || ~isnumeric(low) || length(low) > 1 || isnan(low) + low = 1; end; +if nargin < 2 || ~isnumeric(high) || length(high) > 1 || isnan(high) + high = low+9; +elseif low > high + [low, high] = deal(high, low); +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 +gs = input(sprintf('Guess an integer between %i and %i (inclusive): ', low, high), 's'); +while gs % No guess quits the game + g = str2double(gs); + if length(g) > 1 || isnan(g) || g < low || g > high + gs = input('Invalid input, guess again: ', 's'); + elseif g < n + gs = input('Too low, guess again: ', 's'); + elseif g > n + gs = input('Too high, guess again: ', 's'); + else + disp('Good job, you win!') + gs = ''; + end end -disp('Well guessed!') diff --git a/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-1.max b/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-1.max new file mode 100644 index 0000000000..c29de01df6 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-1.max @@ -0,0 +1,15 @@ +Range = [1,100] +randomNumber = (random Range.x Range.y) as integer +clearListener() +while true do +( + userVal = getKBValue prompt:("Enter a number between "+(range[1] as integer) as string+" and "+(range[2] as integer) as string+": ") + if userVal == randomNumber do (format "\nWell guessed!\n"; exit with OK) + case of + ( + (classOf userVal != classof randomNumber): (format "\nBad number!\n") + (userVal > Range[2] or userVal < Range[1]): (format "\nNumber out of range\n") + (userVal > randomNumber): (format "\nToo high!\n") + (userVal < randomNumber): (format "\nToo low!\n") + ) +) diff --git a/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-2.max b/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-2.max new file mode 100644 index 0000000000..2fa06ee0b9 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/MAXScript/guess-the-number-with-feedback-2.max @@ -0,0 +1,13 @@ +Enter a number between 1 and 100: 5 +Too low! +Enter a number between 1 and 100: 9.0 +Bad number! +Enter a number between 1 and 100: 145 +Number out of range +Enter a number between 1 and 100: 95 +Too low! +Enter a number between 1 and 100: 99 +Too high! +Enter a number between 1 and 100: 97 +Well guessed! +OK diff --git a/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-1.pro b/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-1.pro new file mode 100644 index 0000000000..4da8105089 --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-1.pro @@ -0,0 +1,37 @@ +main :- + play_guess_number. + + +/* Parameteres */ + +low(1). +high(10). + + +/* Basic Game Logic */ + +play_guess_number :- + low(Low), + high(High), + random(Low, High, N), + tell_range(Low, High), + repeat, % roughly, "repeat ... (until) Guess == N " + ask_for_guess(Guess), + give_feedback(N, Guess), + Guess == N. + +/* IO Stuff */ + +tell_range(Low, High) :- + format('Guess an integer between ~d and ~d.~n', [Low,High]). + +ask_for_guess(Guess) :- + format('Guess the number: '), + read(Guess). + +give_feedback(N, Guess) :- + ( \+integer(Guess) -> writeln('Invalid input.') + ; Guess < N -> writeln('Your guess is too low.') + ; Guess > N -> writeln('Your guess is too high.') + ; Guess =:= N -> writeln("Correct!") + ). diff --git a/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-2.pro b/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-2.pro new file mode 100644 index 0000000000..40ac4a9aba --- /dev/null +++ b/Task/Guess-the-number-With-feedback/Prolog/guess-the-number-with-feedback-2.pro @@ -0,0 +1,6 @@ +?- main. +Guess an integer between 1 and 10. +Guess the number: a. +Invalid input. +Guess the number: 3. +Your guess is too low. diff --git a/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust index c63b9939ab..89fd9bcce8 100644 --- a/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust +++ b/Task/Guess-the-number-With-feedback/Rust/guess-the-number-with-feedback.rust @@ -1,42 +1,39 @@ +use std::io::IoResult; use std::io::stdio::stdin; -use std::str; -use std::rand::{task_rng, Rng}; +use std::rand::{Rng, thread_rng}; +use std::str::FromStr; -static LOWEST: int = 0; -static HIGHEST: int = 100; +const LOWEST: isize = 1; +const HIGHEST: isize = 100; fn main() { - let mut rng = task_rng(); - let mut stdin = stdin(); - let mut num_guesses = 0; + let mut rng = thread_rng(); + let mut stdin = stdin(); - loop { + loop { - let number = rng.gen_range(LOWEST, HIGHEST); + let number: isize = rng.gen_range(LOWEST, HIGHEST + 1); + let mut num_guesses = 0is; - println!("I have chosen my number between {:d} and {:d}. You know what to do", LOWEST, HIGHEST); + println!("I have chosen my number between {} and {}. You know what to do", LOWEST, HIGHEST); - loop { + loop { - let buf: &mut [u8] = [0u8, ..64]; - let num_bytes = stdin.read(buf).unwrap(); - let guess_str = str::from_utf8(buf).slice_to(num_bytes).trim(); + num_guesses += 1; - match from_str::(guess_str) { - None => println("not a number! please try again"), - Some(guess) => { - num_guesses += 1; - if guess == number { - println!("you got it in {:d} tries!", num_guesses); - num_guesses = 0; - break; - } else if guess < number { - println("too low!"); - } else { - println("too high!"); - } - } - } - } - } + let line: IoResult = stdin.read_line(); + let input: Option = line.ok().map_or(None, |line| line.as_slice().trim().parse()); + + match input { + None => println!("numbers only, please"), + Some(n) if n == number => { + println!("you got it in {} tries!", num_guesses); + break; + } + Some(n) if n < number => println!("too low!"), + Some(n) if n > number => println!("too high!"), + Some(_) => println!("something went wrong") + } + } + } } diff --git a/Task/Guess-the-number-With-feedback/Seed7/guess-the-number-with-feedback.seed7 b/Task/Guess-the-number-With-feedback/Seed7/guess-the-number-with-feedback.seed7 index e23d51e896..b627a07410 100644 --- a/Task/Guess-the-number-With-feedback/Seed7/guess-the-number-with-feedback.seed7 +++ b/Task/Guess-the-number-With-feedback/Seed7/guess-the-number-with-feedback.seed7 @@ -10,8 +10,7 @@ const proc: main is func begin number := rand(lower_limit, upper_limit); write("Guess the number between " <& lower_limit <& " and " <& upper_limit <& ": "); - readln(guess); - while IN.io_ok and number <> guess do + while succeeds(readln(guess)) and number <> guess do write("Your guess was too "); if number < guess then writeln("high."); @@ -19,7 +18,6 @@ const proc: main is func writeln("low."); end if; write("Try again: "); - readln(guess); end while; if number = guess then writeln("You guessed correctly!"); diff --git a/Task/Guess-the-number/Eiffel/guess-the-number.e b/Task/Guess-the-number/Eiffel/guess-the-number.e new file mode 100644 index 0000000000..72de7a0341 --- /dev/null +++ b/Task/Guess-the-number/Eiffel/guess-the-number.e @@ -0,0 +1,33 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + number : INTEGER_32 -- Number to guess + random : RANDOM + do + create random.make + number := (random.double_item*10.0).truncated_to_integer + 1 + print ("I'm thinking of a number between 1 and 10.%N") + print ("Please guess the number!%N") + + from io.read_integer + until io.last_integer = number + loop + print ("Sorry. Please guess again!%N") + io.read_integer + end + + print ("Correct!%N") + end + +end diff --git a/Task/Guess-the-number/Elixir/guess-the-number.elixir b/Task/Guess-the-number/Elixir/guess-the-number.elixir new file mode 100644 index 0000000000..fddfc6bfbb --- /dev/null +++ b/Task/Guess-the-number/Elixir/guess-the-number.elixir @@ -0,0 +1,24 @@ +defmodule GuessingGame do + def init() do + :random.seed(:erlang.now()) + end + def play() do + play(:random.uniform(10)) + end + defp play(number) do + guess = Integer.parse(IO.gets "Guess a number (1-10): ") + case guess do + {n, _} when n == number -> + IO.puts "Well guessed!" + {n, _} when 1 <= n and n <= 10 -> + IO.puts "That's not it." + play(number) + _ -> + IO.puts "Guess not in valid range." + play(number) + end + end +end + +GuessingGame.init() +GuessingGame.play() diff --git a/Task/Guess-the-number/MAXScript/guess-the-number.max b/Task/Guess-the-number/MAXScript/guess-the-number.max new file mode 100644 index 0000000000..b8b273ab33 --- /dev/null +++ b/Task/Guess-the-number/MAXScript/guess-the-number.max @@ -0,0 +1,8 @@ +rand = random 1 10 +clearListener() +while true do +( + userval = getKBValue prompt:"Enter an integer between 1 and 10: " + if userval == rand do (format "\nWell guessed!\n"; exit) + format "\nChoose another value\n" +) diff --git a/Task/Guess-the-number/Oberon-2/guess-the-number.oberon-2 b/Task/Guess-the-number/Oberon-2/guess-the-number.oberon-2 new file mode 100644 index 0000000000..f191ab2e27 --- /dev/null +++ b/Task/Guess-the-number/Oberon-2/guess-the-number.oberon-2 @@ -0,0 +1,24 @@ +MODULE GuessTheNumber; +IMPORT + RandomNumbers, + In, + Out; + + PROCEDURE Do; + VAR + n,guess: LONGINT; + BEGIN + n := RandomNumbers.RND(10); + Out.String("Guess a number between 1 and 10: ");Out.Flush(); + LOOP + In.LongInt(guess); + IF guess = n THEN + Out.String("You guessed!!"); Out.Ln; EXIT + END; + Out.String(" Sorry, try again: ");Out.Flush() + END + END Do; + +BEGIN + Do; +END GuessTheNumber. diff --git a/Task/Guess-the-number/Objective-C/guess-the-number.m b/Task/Guess-the-number/Objective-C/guess-the-number.m index 62b65ac46c..86f3f37233 100644 --- a/Task/Guess-the-number/Objective-C/guess-the-number.m +++ b/Task/Guess-the-number/Objective-C/guess-the-number.m @@ -7,7 +7,7 @@ int main(int argc, const char * argv[]) NSLog(@"I'm thinking of a number between 1 - 10. Can you guess what it is?\n"); - int rndNumber = (arc4random() % 10) + 1; + int rndNumber = arc4random_uniform(10) + 1; // Debug (Show rndNumber in console) //NSLog(@"Random number is %i", rndNumber); diff --git a/Task/Guess-the-number/Prolog/guess-the-number-1.pro b/Task/Guess-the-number/Prolog/guess-the-number-1.pro new file mode 100644 index 0000000000..5982de0d25 --- /dev/null +++ b/Task/Guess-the-number/Prolog/guess-the-number-1.pro @@ -0,0 +1,7 @@ +main :- + random_between(1, 10, N), + repeat, + prompt1('Guess the number: '), + read(N), + writeln('Well guessed!'), + !. diff --git a/Task/Guess-the-number/Prolog/guess-the-number-2.pro b/Task/Guess-the-number/Prolog/guess-the-number-2.pro new file mode 100644 index 0000000000..7dbbadd6f6 --- /dev/null +++ b/Task/Guess-the-number/Prolog/guess-the-number-2.pro @@ -0,0 +1,6 @@ +?- main. +Guess the number: 1. +Guess the number: 2. +Guess the number: 3. +Well guessed! +true. diff --git a/Task/Guess-the-number/R/guess-the-number.r b/Task/Guess-the-number/R/guess-the-number.r index 92d1196613..293867eb2c 100644 --- a/Task/Guess-the-number/R/guess-the-number.r +++ b/Task/Guess-the-number/R/guess-the-number.r @@ -1,6 +1,6 @@ f <- function() { print("Guess a number between 1 and 10 until you get it right.") - n <- 1 + floor(10*runif(1)) + n <- sample(10, 1) while (as.numeric(readline()) != n) { print("Try again.") } diff --git a/Task/Guess-the-number/REXX/guess-the-number-2.rexx b/Task/Guess-the-number/REXX/guess-the-number-2.rexx index 187e305791..8a013f7c5c 100644 --- a/Task/Guess-the-number/REXX/guess-the-number-2.rexx +++ b/Task/Guess-the-number/REXX/guess-the-number-2.rexx @@ -1,10 +1,9 @@ -/*REXX program to (interactively) play "guess my number". */ -?=random(1,10) -say 'Try to guess my number between 1 ──► 10 (inclusive).' +/*REXX program interactively plays "guess my number" with a human. */ +?=random(1,10) /*generate a low random integer. */ +say 'Try to guess my number between 1 ──► 10 (inclusive).' /*directive*/ - do j=1 while g\=? - if j\==1 then say 'Try again.' - pull g - end /*j*/ -say 'Well guessed!' - /*stick a fork in it, we're done.*/ + do j=1 until g=? /*keep at it ···*/ + if j\==1 then say 'Try again.' /*2nd-ary prompt*/ + pull g /*obtain a guess*/ + end /*j*/ +say 'Well guessed!' /*stick a fork in it, we're done.*/ diff --git a/Task/Guess-the-number/RapidQ/guess-the-number.rapidq b/Task/Guess-the-number/RapidQ/guess-the-number.rapidq new file mode 100644 index 0000000000..3b08045cdd --- /dev/null +++ b/Task/Guess-the-number/RapidQ/guess-the-number.rapidq @@ -0,0 +1,10 @@ +RANDOMIZE +number = rnd(10) + 1 +Print "I selected a number between 1 and 10, try to find it:" + chr$(10) + +while Guess <> Number + input "Your guess: "; Guess +wend + +print "You guessed right, well done !" +input "Press enter to quit";a$ diff --git a/Task/Guess-the-number/Rust/guess-the-number.rust b/Task/Guess-the-number/Rust/guess-the-number.rust new file mode 100644 index 0000000000..6c238d7c88 --- /dev/null +++ b/Task/Guess-the-number/Rust/guess-the-number.rust @@ -0,0 +1,26 @@ +use std::num; +use std::rand::random; +use std::io::stdio::stdin; + +fn main() { + println!("Type in an integer between 1 and 10 and press enter."); + + let n = num::abs(random::()) % 10 + 1; + loop { + let line = stdin().read_line().unwrap(); + let option: Option = from_str(line.as_slice().trim()); + match option { + Some(guess) => { + if guess < 1 || guess > 10 { + println!("Guess is out of bounds; try again."); + } else if guess == n { + println!("Well guessed!"); + break; + } else { + println!("Wrong! Try again."); + } + }, + None => println!("Invalid input; try again.") + } + } +} diff --git a/Task/HTTP/Dart/http.dart b/Task/HTTP/Dart/http.dart index 8ccb380057..630faeacae 100644 --- a/Task/HTTP/Dart/http.dart +++ b/Task/HTTP/Dart/http.dart @@ -1,7 +1,7 @@ import 'dart:io'; void main(){ - String url = 'http://rosettacode.org'; - HttpClient client = new HttpClient(); + var url = 'http://rosettacode.org'; + var client = new HttpClient(); client.getUrl(Uri.parse(url)) .then((HttpClientRequest request) => request.close()) .then((HttpClientResponse response) => response.pipe(stdout)); diff --git a/Task/HTTP/JavaScript/http-1.js b/Task/HTTP/JavaScript/http-1.js new file mode 100644 index 0000000000..336fe95110 --- /dev/null +++ b/Task/HTTP/JavaScript/http-1.js @@ -0,0 +1,7 @@ +var req = new XMLHTTPRequest(); +req.onload = function() { + console.log(this.responseText); +}; + +req.open('get', 'http://rosettacode.org', true); +req.send() diff --git a/Task/HTTP/JavaScript/http-2.js b/Task/HTTP/JavaScript/http-2.js new file mode 100644 index 0000000000..1dc4829fb1 --- /dev/null +++ b/Task/HTTP/JavaScript/http-2.js @@ -0,0 +1,3 @@ +$.get('http://rosettacode.org', function(data) { + console.log(data); +}; diff --git a/Task/HTTP/JavaScript/http.js b/Task/HTTP/JavaScript/http.js deleted file mode 100644 index 2cb3670d8d..0000000000 --- a/Task/HTTP/JavaScript/http.js +++ /dev/null @@ -1,35 +0,0 @@ -((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/Lua/http.lua b/Task/HTTP/Lua/http.lua index 6aece5b097..fe9c6bf8c5 100644 --- a/Task/HTTP/Lua/http.lua +++ b/Task/HTTP/Lua/http.lua @@ -1,20 +1,4 @@ local http = require("socket.http") -function url_encode(str) - if (str) then - str = string.gsub (str, "\n", "\r\n") - str = string.gsub (str, "([^%w ])", - function (c) return string.format ("%%%02X", string.byte(c)) end) - str = string.gsub (str, " ", "+") - end - return str -end -function url_decode(str) - str = string.gsub (str, "+", " ") - str = string.gsub (str, "%%(%x%x)", - function(h) return string.char(tonumber(h,16)) end) - str = string.gsub (str, "\r\n", "\n") - return str -end - -local page = http.request( 'http://www.google.com/m/search?q=' .. url_encode("lua") ) -print( page ) +local url = require("socket.url") +local page = http.request('http://www.google.com/m/search?q=' .. url.escape("lua")) +print(page) diff --git a/Task/HTTP/Maple/http-1.maple b/Task/HTTP/Maple/http-1.maple new file mode 100644 index 0000000000..de0c5f2d17 --- /dev/null +++ b/Task/HTTP/Maple/http-1.maple @@ -0,0 +1 @@ +content := URL:-Get( "http://www.google.com/" ); diff --git a/Task/HTTP/Maple/http-2.maple b/Task/HTTP/Maple/http-2.maple new file mode 100644 index 0000000000..6592a17931 --- /dev/null +++ b/Task/HTTP/Maple/http-2.maple @@ -0,0 +1 @@ +content := HTTP:-Get( "http://www.google.com/" ); diff --git a/Task/HTTP/Maple/http.maple b/Task/HTTP/Maple/http.maple deleted file mode 100644 index 81e46268ad..0000000000 --- a/Task/HTTP/Maple/http.maple +++ /dev/null @@ -1 +0,0 @@ -HTTP:-Get( "http://www.google.com" ); diff --git a/Task/HTTPS/Delphi/https.delphi b/Task/HTTPS/Delphi/https.delphi index bfb69d86fd..58098cda56 100644 --- a/Task/HTTPS/Delphi/https.delphi +++ b/Task/HTTPS/Delphi/https.delphi @@ -7,17 +7,14 @@ uses IdHttp, IdSSLOpenSSL; var s: string; lHTTP: TIdHTTP; - lIOHandler: TIdSSLIOHandlerSocketOpenSSL; begin lHTTP := TIdHTTP.Create(nil); - lIOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(nil); try - lHTTP.IOHandler := lIOHandler; + lHTTP.IOHandler := TIdSSLIOHandlerSocketOpenSSL.Create(lHTTP); lHTTP.HandleRedirects := True; s := lHTTP.Get('https://sourceforge.net/'); Writeln(s); finally lHTTP.Free; - lIOHandler.Free; end; end. diff --git a/Task/HTTPS/Maple/https.maple b/Task/HTTPS/Maple/https.maple new file mode 100644 index 0000000000..b085206ada --- /dev/null +++ b/Task/HTTPS/Maple/https.maple @@ -0,0 +1 @@ +content := URL:-Get( "https://www.google.ca/" ); diff --git a/Task/Hailstone-sequence/Aime/hailstone-sequence.aime b/Task/Hailstone-sequence/Aime/hailstone-sequence.aime new file mode 100644 index 0000000000..5819a7a6ec --- /dev/null +++ b/Task/Hailstone-sequence/Aime/hailstone-sequence.aime @@ -0,0 +1,58 @@ +void +print_hailstone(integer h) +{ + list l; + + while (h ^ 1) { + lb_p_integer(l, h); + h = __hold(h & 1, 3 * h + 1, h / 2); + } + + o_form("hailstone sequence for ~ is ~1 ~ ~ ~ .. ~ ~ ~ ~, it is ~ long\n", + l[0], l[1], l[2], l[3], l[-3], l[-2], l[-1], 1, l_length(l) + 1); +} + +void +max_hailstone(integer x) +{ + integer e, i, m; + record r; + + m = 0; + i = 1; + while (i < x) { + integer h, k, l; + + h = i; + l = 1; + while (h ^ 1) { + if (r_j_integer(k, r, itoa(h))) { + l += k; + break; + } else { + l += 1; + h = __hold(h & 1, 3 * h + 1, h / 2); + } + } + + r_f_integer(r, itoa(i), l - 1); + + if (m < l) { + m = l; + e = i; + } + + i += 1; + } + + o_form("hailstone sequence length for ~ is ~ long\n", e, m); +} + +integer +main(void) +{ + print_hailstone(27); + max_hailstone(100000); + + return 0; +} diff --git a/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf b/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf index cd49289286..adca2bdc33 100644 --- a/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf +++ b/Task/Hailstone-sequence/Befunge/hailstone-sequence.bf @@ -1,4 +1,18 @@ -&>:.:1-| - >3*^ @ - |%2: < - v>2/>+ +93*:. v +> :2%v > +v+1*3_2/ +>" ",:.v v< +^>::v +>" "03pv :* p +v67:" "< 0: 1 +>p78p25 *^*p0 + v!-1: <<*^< +9$_:0\ ^-^< v +v01g00:< 1 4 +>g"@"*+`v^ <+ +v01/"@":_ $ ^, +>p"@"%00p\$:^. +vg01g00 ,+49< +>"@"*+.@ diff --git a/Task/Hailstone-sequence/D/hailstone-sequence-1.d b/Task/Hailstone-sequence/D/hailstone-sequence-1.d index c4220398f8..4fa37c1a31 100644 --- a/Task/Hailstone-sequence/D/hailstone-sequence-1.d +++ b/Task/Hailstone-sequence/D/hailstone-sequence-1.d @@ -3,7 +3,7 @@ import std.stdio, std.algorithm, std.range, std.typecons; auto hailstone(uint n) pure nothrow { auto result = [n]; while (n != 1) { - n = n & 1 ? n*3 + 1 : n/2; + n = (n & 1) ? (n * 3 + 1) : (n / 2); result ~= n; } return result; diff --git a/Task/Hailstone-sequence/D/hailstone-sequence-2.d b/Task/Hailstone-sequence/D/hailstone-sequence-2.d index d34ec12083..7f9881569f 100644 --- a/Task/Hailstone-sequence/D/hailstone-sequence-2.d +++ b/Task/Hailstone-sequence/D/hailstone-sequence-2.d @@ -1,23 +1,20 @@ -import std.stdio, std.algorithm, std.range, std.typecons; +import std.stdio, std.algorithm, std.typecons, std.range; -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); - } +auto hailstone(uint m) pure nothrow @nogc { + return m + .recurrence!q{ a[n - 1] & 1 ? a[n - 1] * 3 + 1 : a[n - 1]/2} + .until!q{ a == 1 }(OpenRight.no); } void main() { enum M = 27; - immutable h = M.Hailstone.array; + immutable 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)) + .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 index 8b3353eb43..fda480d9e5 100644 --- a/Task/Hailstone-sequence/D/hailstone-sequence-3.d +++ b/Task/Hailstone-sequence/D/hailstone-sequence-3.d @@ -1,33 +1,23 @@ -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; - } +struct Hailstone { + uint n; + bool empty() const pure nothrow @nogc { return n == 0; } + uint front() const pure nothrow @nogc { return n; } + void popFront() pure nothrow @nogc { + n = n == 1 ? 0 : (n & 1 ? (n * 3 + 1) : n / 2); } } void main() { + import std.stdio, std.algorithm, std.range, std.typecons; + enum M = 27; - const h = M.Hailstone!().array; + immutable 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)) + .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-4.d b/Task/Hailstone-sequence/D/hailstone-sequence-4.d new file mode 100644 index 0000000000..0be32658a1 --- /dev/null +++ b/Task/Hailstone-sequence/D/hailstone-sequence-4.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 @nogc { return n == 0; } + size_t front() const pure nothrow @nogc { 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/D/hailstone-sequence-5.d b/Task/Hailstone-sequence/D/hailstone-sequence-5.d new file mode 100644 index 0000000000..b6aa3fe257 --- /dev/null +++ b/Task/Hailstone-sequence/D/hailstone-sequence-5.d @@ -0,0 +1,24 @@ +import std.stdio, std.algorithm, std.range, std.typecons, std.concurrency; + +auto hailstone(size_t n) { + return new Generator!size_t({ + yield(n); + while (n > 1) { + n = (n & 1) ? (3 * n + 1) : (n / 2); + yield(n); + } + }); +} + +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/Frege/hailstone-sequence.frege b/Task/Hailstone-sequence/Frege/hailstone-sequence.frege index 842065eda6..6459a1283a 100644 --- a/Task/Hailstone-sequence/Frege/hailstone-sequence.frege +++ b/Task/Hailstone-sequence/Frege/hailstone-sequence.frege @@ -10,10 +10,11 @@ hailstone n | even n = n : hailstone (n `div` 2) withResult :: (t -> t1) -> t -> (t1, t) withResult f x = (f x, x) -main _ = do +main :: IO () +main = do let h27 = hailstone 27 - printStrLn $ show $ length h27 + putStrLn $ show $ length h27 let h4 = show $ take 4 h27 let t4 = show $ drop (length h27 - 4) h27 - printStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4) - printStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) (1..100000) + putStrLn ("hailstone 27: " ++ h4 ++ " ... " ++ t4) + putStrLn $ show $ maximumBy (comparing fst) $ map (withResult (length . hailstone)) [1..100000] diff --git a/Task/Hailstone-sequence/Pascal/hailstone-sequence.pascal b/Task/Hailstone-sequence/Pascal/hailstone-sequence.pascal new file mode 100644 index 0000000000..f060a674bd --- /dev/null +++ b/Task/Hailstone-sequence/Pascal/hailstone-sequence.pascal @@ -0,0 +1,94 @@ +program ShowHailstoneSequence; +{$IFDEF FPC} + {$MODE delphi} //or objfpc +{$Else} + {$Apptype Console} // for delphi +{$ENDIF} + +uses + SysUtils;// format +type + tIntArr = record + iaAktPos : integer; + iaMaxPos : integer; + iaArr : array of integer; + end; + +procedure GetHailstoneSequence(aStartingNumber: Integer;var aHailstoneList: tIntArr); +var + n: UInt64; +begin + with aHailstoneList do + begin + iaAktPos := 0; + iaArr[iaAktPos] := aStartingNumber; + n := aStartingNumber; + while n <> 1 do + begin + if Odd(n) then + n := (3 * n) + 1 + else + n := n div 2; + inc(iaAktPos); + IF iaAktPos>iaMaxPos then + Begin + iaMaxPos := round(iaMaxPos*1.62)+2; + setlength(iaArr,iaMaxPos+1); + end; + iaArr[iaAktPos] := n; + end; + end; +end; + +var + i,Limit: Integer; + lList: tIntArr; + lMaxSequence: Integer; + lMaxLength: Integer; +begin + try + with lList do + begin + setlength(iaArr,0+1); + iaMaxPos := 0; + iaAktPos := 0; + end; + + GetHailstoneSequence(27, lList); + with lList do + begin + i := iaAktPos+1; + Writeln(Format('27: %d elements', [i])); + Writeln(Format('[%d,%d,%d,%d ... %d,%d,%d,%d]', + [iaArr[0], iaArr[1], iaArr[2], iaArr[3], + iaArr[i - 4], iaArr[i - 3], iaArr[i - 2], iaArr[i - 1]])); + Writeln; + + lMaxSequence := 0; + lMaxLength := 0; + limit := 10; + for i := 1 to 10000000 do + begin + GetHailstoneSequence(i, lList); + if iaAktPos >= lMaxLength then + begin + IF i> limit then + begin + Writeln(Format('Longest sequence under %8d : %7d with %3d elements', + [limit,lMaxSequence, lMaxLength])); + limit := limit*10; + end; + lMaxSequence := i; + lMaxLength := iaAktPos+1; + end; + end; + Writeln(Format('Longest sequence under %8d : %7d with %3d elements', + [limit,lMaxSequence, lMaxLength])); + + end; + finally + setlength(lList.iaArr,0); + end; + writeln('game over, wait for >ENTER< '); + Readln; +end. diff --git a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh index 52183708a3..2cb529eb3f 100644 --- a/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh +++ b/Task/Hailstone-sequence/PowerShell/hailstone-sequence.psh @@ -1,26 +1,27 @@ # Author M. McNabb + +function Get-HailStone { + param($n) + + switch($n) { + 1 {$n;return} + {$n % 2 -eq 0} {$n; return Get-Hailstone ($n = $n / 2)} + {$n % 2 -ne 0} {$n; return Get-Hailstone ($n = ($n * 3) +1)} + } +} + function Get-HailStoneBelowLimit { -param($UpperLimit) - begin { - function Get-HailStone { - param($n) - switch($n) { - 1 {$n;return} - {$n % 2 -eq 0} {$n; return Get-Hailstone ($n = $n / 2)} - {$n % 2 -ne 0} {$n; return Get-Hailstone ($n = ($n * 3) +1)} - } + param($UpperLimit) + + $Counts = @() + + for ($i = 1; $i -lt $UpperLimit; $i++) { + $Object = [pscustomobject]@{ + 'Number' = $i + 'Count' = (Get-HailStone $i).count } - $Counts = @() + $Counts += $Object } - process { - for ($i = 1; $i -lt $UpperLimit; $i++) { - $Object = [pscustomobject]@{ - 'Number' = $i - 'Count' = (Get-HailStone $i).count - } - $Counts += $Object - } - } - end {$Counts} + $Counts } diff --git a/Task/Hailstone-sequence/R/hailstone-sequence.r b/Task/Hailstone-sequence/R/hailstone-sequence.r new file mode 100644 index 0000000000..7fce19013e --- /dev/null +++ b/Task/Hailstone-sequence/R/hailstone-sequence.r @@ -0,0 +1,34 @@ +### PART 1: +makeHailstone <- function(n){ + hseq <- n + while (hseq[length(hseq)] > 1){ + current.value <- hseq[length(hseq)] + if (current.value %% 2 == 0){ + next.value <- current.value / 2 + } else { + next.value <- (3 * current.value) + 1 + } + hseq <- append(hseq, next.value) + } + return(list(hseq=hseq, seq.length=length(hseq))) +} + +### PART 2: +twenty.seven <- makeHailstone(27) +twenty.seven$hseq +twenty.seven$seq.length + +### PART 3: +max.length <- 0; lower.bound <- 1; upper.bound <- 100000 + +for (index in lower.bound:upper.bound){ + current.hseq <- makeHailstone(index) + if (current.hseq$seq.length > max.length){ + max.length <- current.hseq$seq.length + max.index <- index + } +} + +cat("Between ", lower.bound, " and ", upper.bound, ", the input of ", + max.index, " gives the longest hailstone sequence, which has length ", + max.length, ". \n", sep="") diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx index 18085dde23..b2675b302a 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-1.rexx @@ -8,7 +8,7 @@ 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═════════════════════════*/ +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.*/ diff --git a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx index 1c821a28e6..685ec6aad1 100644 --- a/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx +++ b/Task/Hailstone-sequence/REXX/hailstone-sequence-2.rexx @@ -8,7 +8,7 @@ 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═════════════════════════*/ +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*/ @@ -20,11 +20,11 @@ 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?*/ + do while @.n==0 /*loop while residual is unknown.*/ 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*/ + end /*while*/ +s=s @.n /*append to a sequence list. */ @.o=subword(s,2) /*memoization for this hailstone.*/ return s diff --git a/Task/Hailstone-sequence/Ruby/hailstone-sequence-1.rb b/Task/Hailstone-sequence/Ruby/hailstone-sequence-1.rb index 20d8531d63..54d6cb3486 100644 --- a/Task/Hailstone-sequence/Ruby/hailstone-sequence-1.rb +++ b/Task/Hailstone-sequence/Ruby/hailstone-sequence-1.rb @@ -7,12 +7,11 @@ def hailstone n seq end -# for n = 27, show sequence length and first and last 4 elements +puts "for n = 27, show sequence length and first and last 4 elements" hs27 = hailstone 27 p [hs27.length, hs27[0..3], hs27[-4..-1]] # find the longest sequence among n less than 100,000 -n, len = (1 ... 100_000) .collect {|n| - [n, hailstone(n).length]} .max_by {|n, len| len} -puts "#{n} has a hailstone sequence length of #{len}" +n = (1 ... 100_000).max_by{|n| hailstone(n).length} +puts "#{n} has a hailstone sequence length of #{hailstone(n).length}" puts "the largest number in that sequence is #{hailstone(n).max}" diff --git a/Task/Hailstone-sequence/Ruby/hailstone-sequence-2.rb b/Task/Hailstone-sequence/Ruby/hailstone-sequence-2.rb index 9963dd51f8..171fc1d22d 100644 --- a/Task/Hailstone-sequence/Ruby/hailstone-sequence-2.rb +++ b/Task/Hailstone-sequence/Ruby/hailstone-sequence-2.rb @@ -1,47 +1,38 @@ module Hailstone - class ListNode - include Enumerable - attr_reader :value, :size, :succ - - def initialize(value, size, succ=nil) - @value, @size, @succ = value, size, succ - end - + ListNode = Struct.new(:value, :size, :succ) do def each node = self while node - yield node.value - node = node.succ + yield node.value + node = node.succ end end end - @@sequence = {1 => ListNode.new(1, 1)} + @@sequence = {1 => ListNode[1,1]} module_function def sequence(n) unless @@sequence[n] - ary = [] - m = n + m, ary = n, [] until succ = @@sequence[m] ary << m - m = (m.even?) ? (m / 2) : (3 * m + 1) + m = m.even? ? (m / 2) : (3 * m + 1) end ary.reverse_each do |m| - @@sequence[m] = succ = ListNode.new(m, succ.size + 1, succ) + @@sequence[m] = succ = ListNode[m, succ.size + 1, succ] end end @@sequence[n] end end -# for n = 27, show sequence length and first and last 4 elements -hs27 = Hailstone.sequence(27).to_a -p [hs27.length, hs27[0..3], hs27[-4..-1]] +puts "for n = 27, show sequence length and first and last 4 elements" +hs27 = Hailstone.sequence(27).entries +p [hs27.size, hs27[0..3], hs27[-4..-1]] # find the longest sequence among n less than 100,000 -hs_big = (1 ... 100_000) .collect {|n| - Hailstone.sequence n}.max_by {|hs| hs.size} -puts "#{hs_big.first} has a hailstone sequence length of #{hs_big.size}" -puts "the largest number in that sequence is #{hs_big.max}" +n = (1 ... 100_000).max_by{|n| Hailstone.sequence(n).size} +puts "#{n} has a hailstone sequence length of #{Hailstone.sequence(n).size}" +puts "the largest number in that sequence is #{Hailstone.sequence(n).max}" diff --git a/Task/Hailstone-sequence/Rust/hailstone-sequence.rust b/Task/Hailstone-sequence/Rust/hailstone-sequence.rust new file mode 100644 index 0000000000..1b9f31967f --- /dev/null +++ b/Task/Hailstone-sequence/Rust/hailstone-sequence.rust @@ -0,0 +1,27 @@ +use std::vec::Vec; + +fn hailstone(mut n : int) -> Vec{ + let mut v = vec!(n); + while n > 1{ + n = if n % 2 == 0 { n / 2 } + else { 3 * n + 1 }; + v.push(n); + } + return v; +} + +fn main() { + let mut max_sequence = 0i; + let mut number_max_sequence = 0i; + let hs27 = hailstone(27); + println!("hailstone(27) has {} elements, starting from {} and ending to {}.", hs27.len(), hs27[0..4], hs27[hs27.len()-4..hs27.len()]); + + for i in range(1i, 100000) { + let hs_i = hailstone(i); + if hs_i.len() as int > max_sequence { + max_sequence = hs_i.len() as int; + number_max_sequence = i; + } + } + println!("Maximum : {} elements with number {}.", max_sequence, number_max_sequence); +} diff --git a/Task/Hailstone-sequence/SAS/hailstone-sequence.sas b/Task/Hailstone-sequence/SAS/hailstone-sequence.sas new file mode 100644 index 0000000000..5fcea1e887 --- /dev/null +++ b/Task/Hailstone-sequence/SAS/hailstone-sequence.sas @@ -0,0 +1,54 @@ +* Create a routine to generate the hailstone sequence for one number; +%macro gen_seq(n); + data hailstone; + array hs_seq(100000); + n=&n; + do until (n=1); + seq_size + 1; + hs_seq(seq_size) = n; + if mod(n,2)=0 then n=n/2; + else n=(3*n)+1; + end; + seq_size + 1; + hs_seq(seq_size)=n; + call symputx('seq_length',seq_size); + run; + + proc sql; + title "First and last elements of Hailstone Sequence for number &n"; + select seq_size as sequence_length, hs_seq1, hs_seq2, hs_seq3, hs_seq4 + %do i=&seq_length-3 %to &seq_length; + , hs_seq&i + %end; + from hailstone; + quit; +%mend; + +* Use the routine to output the first and last four numbers in the sequence for 27; +%gen_seq(27); + +* Show the number less than 100,000 which has the longest hailstone sequence, and what that length is ; +%macro longest_hailstone(start_num, end_num); + data hailstone_analysis; + do start=&start_num to &end_num; + n=start; + length_of_sequence=1; + do while (n>1); + length_of_sequence+1; + if mod(n,2)=0 then n=n/2; + else n=(3*n) + 1; + end; + output; + end; + run; + + proc sort data=hailstone_analysis; + by descending length_of_sequence; + run; + + proc print data=hailstone_analysis (obs=1) noobs; + title "Number from &start_num to &end_num with longest Hailstone sequence"; + var start length_of_sequence; + run; +%mend; +%longest_hailstone(1,99999); diff --git a/Task/Hailstone-sequence/Scilab/hailstone-sequence.scilab b/Task/Hailstone-sequence/Scilab/hailstone-sequence.scilab new file mode 100644 index 0000000000..e7045c4461 --- /dev/null +++ b/Task/Hailstone-sequence/Scilab/hailstone-sequence.scilab @@ -0,0 +1,33 @@ +function x=hailstone(n) + // iterative definition + // usage: global verbose; verbose=%T; hailstone(27) + global verbose + x=0; loop=%T + while(loop) + x=x+1 + if verbose then + printf('%i ',n) + end + if n==1 then + loop=%F + elseif modulo(n,2)==1 then + n=3*n+1 + else + n=n/2 + end + end +endfunction + +global verbose; +verbose=1; +N=hailstone(27); +printf('\n\n%i\n',N); + +global verbose; +verbose=0; +N=100000; +M=zeros(N,1); +for k=1:N + M(k)=hailstone(k); +end; +[maxLength,n]=max(M) diff --git a/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-1.ti-83 b/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-1.ti-83 new file mode 100644 index 0000000000..507c80f303 --- /dev/null +++ b/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-1.ti-83 @@ -0,0 +1,15 @@ +prompt N +N→M: 0→X: 1→L +While L=1 +X+1→X +Disp M +If M=1 +Then: 0→L +Else +If remainder(M,2)=1 +Then: 3*M+1→M +Else: M/2→M +End +End +End +{N,X} diff --git a/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-2.ti-83 b/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-2.ti-83 new file mode 100644 index 0000000000..120c99ecf3 --- /dev/null +++ b/Task/Hailstone-sequence/TI-83-BASIC/hailstone-sequence-2.ti-83 @@ -0,0 +1,21 @@ +prompt N +0→A:0→B +for(I,1,N) +I→M: 0→X: 1→L +While L=1 +X+1→X +If M=1 +Then: 0→L +Else +If remainder(M,2)=1 +Then: 3*M+1→M +Else: M/2→M +End +End +End +If X>B: Then +I→A:X→B +End +Disp {I,X} +End +{A,B} diff --git a/Task/Hailstone-sequence/Visual-Basic/hailstone-sequence.vb b/Task/Hailstone-sequence/Visual-Basic/hailstone-sequence.vb new file mode 100644 index 0000000000..e0bcf8b914 --- /dev/null +++ b/Task/Hailstone-sequence/Visual-Basic/hailstone-sequence.vb @@ -0,0 +1,57 @@ +Option Explicit +Dim flag As Boolean ' true to print values +Sub main() + Dim longest As Long, n As Long + Dim i As Long, value As Long + ' Task 1: + flag = True + i = 27 + Debug.Print "The hailstone sequence has length of "; i; " is "; hailstones(i) + ' Task 2: + flag = False + longest = 0 + For i = 1 To 99999 + If longest < hailstones(i) Then + longest = hailstones(i) + value = i + End If + Next i + Debug.Print value; " has the longest sequence of "; longest +End Sub 'main +Function hailstones(n As Long) As Long + Dim m As Long, p As Long + Dim m1 As Long, m2 As Long, m3 As Long, m4 As Long + If flag Then Debug.Print "The sequence for"; n; "is: "; + p = 1 + m = n + If flag Then Debug.Print m; + While m > 1 + p = p + 1 + If (m Mod 2) = 0 Then + m = m / 2 + Else + m = 3 * m + 1 + End If + If p <= 4 Then If flag Then Debug.Print m; + m4 = m3 + m3 = m2 + m2 = m1 + m1 = m + Wend + If flag Then + If p <= 4 Then + Debug.Print + ElseIf p = 5 Then + Debug.Print m1 + ElseIf p = 6 Then + Debug.Print m2; m1 + ElseIf p = 7 Then + Debug.Print m3; m2; m1 + ElseIf p = 8 Then + Debug.Print m4; m3; m2; m1 + Else + Debug.Print "..."; m4; m3; m2; m1 + End If + End If + hailstones = p +End Function 'hailstones diff --git a/Task/Hamming-numbers/ATS/hamming-numbers.ats b/Task/Hamming-numbers/ATS/hamming-numbers.ats new file mode 100644 index 0000000000..c9b21435d1 --- /dev/null +++ b/Task/Hamming-numbers/ATS/hamming-numbers.ats @@ -0,0 +1,89 @@ +// +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o hamming hamming.dats +// +#include +"share/atspre_staload.hats" + +fun +min3 +( + A: arrayref(int, 3) +) : natLt(3) = i where +{ + var x: int = A[0] + var i: natLt(3) = 0 + val () = if A[1] < x then (x := A[1]; i := 1) + val () = if A[2] < x then (x := A[2]; i := 2) +} (* end of [min3] *) + +fun +hamming +{n:pos} +( + n: int(n) +) : int = let +// +var A = @[int](2, 3, 5) +val A = $UNSAFE.cast{arrayref(int, 3)}(addr@A) +var I = @[int](1, 1, 1) +val I = $UNSAFE.cast{arrayref(int, 3)}(addr@I) +val H = arrayref_make_elt (i2sz(succ(n)), 0) +val () = H[0] := 1 +// +fun +loop{k:pos} + (k: int(k)) : void = +( +// +if +k < n +then let + val i = min3(A) + val k = + ( + if A[i] > H[k-1] then (H[k] := A[i]; k+1) else k + ) : intBtwe(k, k+1) + val ii = I[i] + val () = I[i] := ii+1 + val ii = $UNSAFE.cast{natLte(n)}(ii) + val () = if i = 0 then A[i] := 2*H[ii] + val () = if i = 1 then A[i] := 3*H[ii] + val () = if i = 2 then A[i] := 5*H[ii] +in + loop(k) +end // end of [then] +else () // end of [else] +// +) (* end of [loop] *) +// +in + loop (1); H[n-1] +end (* end of [hamming] *) + +implement +main0 () = +{ +val () = +loop(1) where +{ +fun +loop +{n:pos} +( + n: int(n) +) : void = +if +n <= 20 +then let + val () = + println! ("hamming(",n,") = ", hamming(n)) +in + loop(n+1) +end // end of [then] +// end of [if] +} (* end of [val] *) +val n = 1691 +val () = println! ("hamming(",n,") = ", hamming(n)) +// +} (* end of [main0] *) diff --git a/Task/Hamming-numbers/Clojure/hamming-numbers.clj b/Task/Hamming-numbers/Clojure/hamming-numbers.clj index fad60b0c5d..56be4ad75d 100644 --- a/Task/Hamming-numbers/Clojure/hamming-numbers.clj +++ b/Task/Hamming-numbers/Clojure/hamming-numbers.clj @@ -9,11 +9,9 @@ :else [x (rest xs) (rest ys)])] (cons z (smerge xs* ys*))))) -(defn smerge3 [xs ys zs] - (smerge xs (smerge ys zs))) - -(defn map*n [n ks] (map #(*' n %) ks)) - (def hamming (lazy-seq - (cons 1 (smerge3 (map*n 2 hamming) (map*n 3 hamming) (map*n 5 hamming))))) + (->> (map #(*' 5 %) hamming) + (smerge (map #(*' 3 %) hamming)) + (smerge (map #(*' 2 %) hamming)) + (cons 1)))) diff --git a/Task/Hamming-numbers/D/hamming-numbers-1.d b/Task/Hamming-numbers/D/hamming-numbers-1.d index 537521e65a..ef5465061b 100644 --- a/Task/Hamming-numbers/D/hamming-numbers-1.d +++ b/Task/Hamming-numbers/D/hamming-numbers-1.d @@ -1,13 +1,13 @@ import std.stdio, std.bigint, std.algorithm, std.range, core.memory; -auto hamming(in int n) { - BigInt two = 2, three = 3, five = 5; +auto hamming(in uint n) pure nothrow /*@safe*/ { + immutable BigInt two = 2, three = 3, five = 5; auto h = new BigInt[n]; h[0] = 1; BigInt x2 = 2, x3 = 3, x5 = 5; - int i, j, k; + size_t i, j, k; - foreach (ref el; h[1 .. $]) { + foreach (ref el; h.dropOne) { el = min(x2, x3, x5); if (el == x2) x2 = two * h[++i]; if (el == x3) x3 = three * h[++j]; diff --git a/Task/Hamming-numbers/D/hamming-numbers-3.d b/Task/Hamming-numbers/D/hamming-numbers-3.d index ef572b1f84..acccecb623 100644 --- a/Task/Hamming-numbers/D/hamming-numbers-3.d +++ b/Task/Hamming-numbers/D/hamming-numbers-3.d @@ -3,6 +3,7 @@ import std.bigint: BigInt; import std.conv: text; import std.numeric: gcd; import std.algorithm: copy, map; +import std.array: array; import core.stdc.stdlib: calloc; import std.math: log; // ^^ @@ -20,18 +21,10 @@ struct Hamming { double v; // Log of the number, for convenience. ushort[NK] e; // Exponents of each factor. - // 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; + public static __gshared immutable double[factors.length] inc = + factors[].map!log.array; - nothrow pure static this() { - //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 { + bool opEquals(in ref Hamming y) const pure nothrow @nogc { //return this.e == y.e; // Too much slow. foreach (immutable i; 0 .. this.e.length) if (this.e[i] != y.e[i]) @@ -39,7 +32,7 @@ struct Hamming { return true; } - void update() pure nothrow { + void update() pure nothrow @nogc { //this.v = dotProduct(inc, this.e); // Too much slow. this.v = 0.0; foreach (immutable i; 0 .. this.e.length) @@ -58,13 +51,14 @@ struct Hamming { __gshared Hamming[] hams; __gshared Hamming[NK] values; -nothrow static this() { +nothrow @nogc static this() { // Slower than calloc if you don't use all the MAX_HAM items. //hams = new Hamming[MAX_HAM]; auto ptr = cast(Hamming*)calloc(MAX_HAM, Hamming.sizeof); + static const err = new Error("Not enough memory."); if (!ptr) - throw new Error("Not enough memory."); + throw err; hams = ptr[0 .. MAX_HAM]; foreach (immutable i, ref v; values) { @@ -74,7 +68,7 @@ nothrow static this() { } -ref Hamming getHam(in size_t n) nothrow +ref Hamming getHam(in size_t n) nothrow @nogc in { assert(n <= MAX_HAM); } body { diff --git a/Task/Hamming-numbers/D/hamming-numbers-4.d b/Task/Hamming-numbers/D/hamming-numbers-4.d new file mode 100644 index 0000000000..05a41e07b7 --- /dev/null +++ b/Task/Hamming-numbers/D/hamming-numbers-4.d @@ -0,0 +1,154 @@ +import std.stdio: writefln; +import std.bigint: BigInt; +import std.conv: text; +import std.algorithm: map; +import std.array: array; +import core.stdc.stdlib: malloc, calloc, free; +import std.math: log; // ^^ + +// Number of factors. +enum NK = 3; + +__gshared immutable int[NK] primes = [2, 3, 5]; +__gshared immutable double[NK] lnPrimes = primes[].map!log.array; + +/// K-smooth numbers (stored as their exponents of each factor). + +struct Hamming { + double ln; // Log of the number. + ushort[NK] e; // Exponents of each factor. + Hamming* next; + size_t n; + + // Recompute the logarithm from the exponents. + void recalculate() pure nothrow @safe @nogc { + this.ln = 0.0; + foreach (immutable i, immutable ei; this.e) + this.ln += lnPrimes[i] * ei; + } + + string toString() const { + BigInt result = 1; + foreach (immutable i, immutable f; primes) + result *= f.BigInt ^^ this.e[i]; + return result.text; + } +} + +Hamming getHam(in size_t n) nothrow @nogc +in { + assert(n && n != size_t.max); +} body { + static struct Candidate { + typeof(Hamming.ln) ln; + typeof(Hamming.e) e; + + void increment(in size_t n) pure nothrow @safe @nogc { + e[n] += 1; + ln += lnPrimes[n]; + } + + bool opEquals(T)(in ref T y) const pure nothrow @safe @nogc { + // return this.e == y.e; // Slow. + return !((this.e[0] ^ y.e[0]) | + (this.e[1] ^ y.e[1]) | + (this.e[2] ^ y.e[2])); + } + + int opCmp(T)(in ref T y) const pure nothrow @safe @nogc { + return (ln > y.ln) ? 1 : (ln < y.ln ? -1 : 0); + } + } + + static struct HammingIterator { // Not a Range. + Candidate cand; + Hamming* base; + size_t primeIdx; + + this(in size_t i, Hamming* b) pure nothrow @safe @nogc { + primeIdx = i; + base = b; + cand.e = base.e; + cand.ln = base.ln; + cand.increment(primeIdx); + } + + void next() pure nothrow @safe @nogc { + base = base.next; + cand.e = base.e; + cand.ln = base.ln; + cand.increment(primeIdx); + } + } + + HammingIterator[NK] its; + Hamming* head = cast(Hamming*)calloc(Hamming.sizeof, 1); + Hamming* freeList, cur = head; + Candidate next; + + foreach (immutable i, ref it; its) + it = HammingIterator(i, cur); + + for (size_t i = cur.n = 1; i < n; ) { + auto leastReferenced = size_t.max; + next.ln = double.max; + foreach (ref it; its) { + if (it.cand == *cur) + it.next; + if (it.base.n < leastReferenced) + leastReferenced = it.base.n; + if (it.cand < next) + next = it.cand; + } + + // Collect unferenced numbers. + while (head.n < leastReferenced) { + auto tmp = head; + head = head.next; + tmp.next = freeList; + freeList = tmp; + } + + if (!freeList) { + cur.next = cast(Hamming*)malloc(Hamming.sizeof); + } else { + cur.next = freeList; + freeList = freeList.next; + } + + cur = cur.next; + version (fastmath) { + cur.ln = next.ln; + cur.e = next.e; + } else { + cur.e = next.e; + cur.recalculate; // Prevent FP error accumulation. + } + + cur.n = i++; + cur.next = null; + } + + auto result = *cur; + version (leak) {} + else { + while (head) { + auto tmp = head; + head = head.next; + tmp.free; + } + + while (freeList) { + auto tmp = freeList; + freeList = freeList.next; + tmp.free; + } + } + + return result; +} + +void main() { + foreach (immutable n; [1691, 10 ^^ 6, 10_000_000]) + writefln("%8d: %s", n, n.getHam); +} diff --git a/Task/Hamming-numbers/Go/hamming-numbers-2.go b/Task/Hamming-numbers/Go/hamming-numbers-2.go index f3fb932931..c9fe36a463 100644 --- a/Task/Hamming-numbers/Go/hamming-numbers-2.go +++ b/Task/Hamming-numbers/Go/hamming-numbers-2.go @@ -1,99 +1,93 @@ package main import ( - "flag" - "fmt" - "math" - "math/big" - "os" + "flag" + "fmt" + "log" + "math" + "math/big" + "os" ) -var ordinal int // ordinal of last sequence element to compute -var sequenceMode bool // print the whole sequence or just one element? +var ( + // print the whole sequence or just one element? -var lg3, lg5 float64 // precomputed base-2 logarithms for 3 and 5 + seqMode = flag.Bool("s", false, "sequence mode") + // precomputed base-2 logarithms for 3 and 5 + lg3, lg5 float64 = math.Log2(3), math.Log2(5) -var table [][3]int16 // table for dynamic-programming stored results -var front [3]cursor // state of the three multiplied sequences + // state of the three multiplied sequences + front = [3]cursor{ + {0, 0, 1}, // 2 + {1, 0, lg3}, // 3 + {2, 0, lg5}, // 5 + } + + // table for dynamic-programming stored results + table [][3]int16 +) type cursor struct { - f int // index (0, 1, 2) corresponding to factor (2, 3, 5) - i int // index into table for the entry being multiplied - lg float64 // base-2 logarithm of the multiple (for ordering) + f int // index (0, 1, 2) corresponding to factor (2, 3, 5) + i int // index into table for the entry being multiplied + lg float64 // base-2 logarithm of the multiple (for ordering) } -func (c *cursor) value() [3]int16 { - x := table[c.i] - x[c.f]++ // multiply by incrementing the exponent - return x +func (c *cursor) val() [3]int16 { + x := table[c.i] + x[c.f]++ // multiply by incrementing the exponent + return x } func (c *cursor) advance() { - c.i++ - // skip entries that would produce duplicates - for (c.f < 2 && table[c.i][2] > 0) || (c.f < 1 && table[c.i][1] > 0) { - c.i++ - } - x := c.value() - c.lg = float64(x[0]) + lg3*float64(x[1]) + lg5*float64(x[2]) + c.i++ + // skip entries that would produce duplicates + for (c.f < 2 && table[c.i][2] > 0) || (c.f < 1 && table[c.i][1] > 0) { + c.i++ + } + x := c.val() + c.lg = float64(x[0]) + lg3*float64(x[1]) + lg5*float64(x[2]) } func step() { - table = append(table, front[0].value()) - front[0].advance() - // re-establish sorted order - if front[0].lg > front[1].lg { - front[0], front[1] = front[1], front[0] - if front[1].lg > front[2].lg { - front[1], front[2] = front[2], front[1] - } - } + table = append(table, front[0].val()) + front[0].advance() + // re-establish sorted order + if front[0].lg > front[1].lg { + front[0], front[1] = front[1], front[0] + if front[1].lg > front[2].lg { + front[1], front[2] = front[2], front[1] + } + } } func show(elem [3]int16) { - z := big.NewInt(1) - for i, base := range []int64{2, 3, 5} { - b := big.NewInt(base) - x := big.NewInt(int64(elem[i])) - z.Mul(z, b.Exp(b, x, nil)) - } - fmt.Println(z) -} - -func fail(msg string) { - fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], msg) - os.Exit(1) -} - -func parse() { - flag.Parse() - if flag.NArg() != 1 { - fail("need one argument") - } - _, err := fmt.Sscan(flag.Arg(0), &ordinal) - if err != nil || ordinal <= 0 { - fail("argument must be a positive integer") - } -} - -func init() { - flag.BoolVar(&sequenceMode, "s", false, "sequence mode") - lg3 = math.Log2(3) - lg5 = math.Log2(5) - front = [3]cursor{ - {0, 0, 1}, // 2 - {1, 0, lg3}, // 3 - {2, 0, lg5}, // 5 - } + z := big.NewInt(1) + for i, base := range []int64{2, 3, 5} { + b := big.NewInt(base) + x := big.NewInt(int64(elem[i])) + z.Mul(z, b.Exp(b, x, nil)) + } + fmt.Println(z) } func main() { - parse() - table = make([][3]int16, 1, ordinal) - for i, n := 1, ordinal; i < n; i++ { - if sequenceMode { - show(table[i-1]) - } - step() - } - show(table[ordinal-1]) + log.SetPrefix(os.Args[0] + ": ") + log.SetOutput(os.Stderr) + flag.Parse() + if flag.NArg() != 1 { + log.Fatalln("need one positive integer argument") + } + var ordinal int // ordinal of last sequence element to compute + _, err := fmt.Sscan(flag.Arg(0), &ordinal) + if err != nil || ordinal <= 0 { + log.Fatalln("argument must be a positive integer") + } + table = make([][3]int16, 1, ordinal) + for i, n := 1, ordinal; i < n; i++ { + if *seqMode { + show(table[i-1]) + } + step() + } + show(table[ordinal-1]) } diff --git a/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs b/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs index 9e4a65b423..32ea1828e9 100644 --- a/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs +++ b/Task/Hamming-numbers/Haskell/hamming-numbers-5.hs @@ -21,10 +21,10 @@ rngval n 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) - | m >= nb = error $ "Generated band is too narrow: " ++ show (m,nb) - | True = res + | w >= 1 = error $ "Breach of contract: (w < 1): " ++ show w + | m < 0 = error $ "Not enough triples generated: " ++ show (c,n) + | m >= nb = error $ "Generated band is too narrow: " ++ show (m,nb) + | otherwise = res where (d,w) = rngval n -- correction dist, width hi = estval n - d -- hi > logval > hi-w diff --git a/Task/Hamming-numbers/J/hamming-numbers-1.j b/Task/Hamming-numbers/J/hamming-numbers-1.j index d44ef07880..635cfa21ff 100644 --- a/Task/Hamming-numbers/J/hamming-numbers-1.j +++ b/Task/Hamming-numbers/J/hamming-numbers-1.j @@ -1 +1 @@ -hamming=: {. (/:~@~.@], 2 3 5 * {)/ @ (1x,~i.@-) +hamming=: {. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-) diff --git a/Task/Hamming-numbers/J/hamming-numbers-6.j b/Task/Hamming-numbers/J/hamming-numbers-6.j index 0be33e15a2..f20a11d84f 100644 --- a/Task/Hamming-numbers/J/hamming-numbers-6.j +++ b/Task/Hamming-numbers/J/hamming-numbers-6.j @@ -1 +1 @@ - (1x,~i.@-) + (1x ,~ i.@-) diff --git a/Task/Hamming-numbers/J/hamming-numbers-7.j b/Task/Hamming-numbers/J/hamming-numbers-7.j index ba5d495bdc..f76f769c44 100644 --- a/Task/Hamming-numbers/J/hamming-numbers-7.j +++ b/Task/Hamming-numbers/J/hamming-numbers-7.j @@ -1,2 +1,2 @@ - ({. (/:~@~.@], 2 3 5 * {)/ @ (1x,~i.@-)) 7 + ({. (/:~@~.@] , 2 3 5 * {)/@(1x ,~ i.@-)) 7 1 2 3 4 5 6 8 diff --git a/Task/Hamming-numbers/J/hamming-numbers-8.j b/Task/Hamming-numbers/J/hamming-numbers-8.j index 7544032d27..e5c2392b11 100644 --- a/Task/Hamming-numbers/J/hamming-numbers-8.j +++ b/Task/Hamming-numbers/J/hamming-numbers-8.j @@ -1,2 +1,2 @@ - (1x,~i.@-) 7 + (1x ,~ i.@-) 7 6 5 4 3 2 1 0 1 diff --git a/Task/Hamming-numbers/J/hamming-numbers-9.j b/Task/Hamming-numbers/J/hamming-numbers-9.j index b973d50b05..7f22b4c0b3 100644 --- a/Task/Hamming-numbers/J/hamming-numbers-9.j +++ b/Task/Hamming-numbers/J/hamming-numbers-9.j @@ -1,2 +1,2 @@ - 6(/:~@~.@], 2 3 5 * {) 5(/:~@~.@], 2 3 5 * {) 4(/:~@~.@], 2 3 5 * {) 3(/:~@~.@], 2 3 5 * {) 2(/:~@~.@], 2 3 5 * {) 1(/:~@~.@], 2 3 5 * {) 0(/:~@~.@], 2 3 5 * {) 1 + 6(/:~@~.@] , 2 3 5 * {) 5(/:~@~.@] , 2 3 5 * {) 4(/:~@~.@] , 2 3 5 * {) 3(/:~@~.@] , 2 3 5 * {) 2(/:~@~.@] , 2 3 5 * {) 1(/:~@~.@] , 2 3 5 * {) 0(/:~@~.@] , 2 3 5 * {) 1 1 2 3 4 5 6 8 9 10 12 15 18 20 25 30 16 24 40 diff --git a/Task/Hamming-numbers/Java/hamming-numbers-3.java b/Task/Hamming-numbers/Java/hamming-numbers-3.java new file mode 100644 index 0000000000..3754927462 --- /dev/null +++ b/Task/Hamming-numbers/Java/hamming-numbers-3.java @@ -0,0 +1,110 @@ +import java.math.BigInteger; + +public class Hamming +{ + public static void main(String args[]) + { + Stream hamming = makeHamming(); + System.out.print("H[1..20] "); + for (int i=0; i<20; i++) { + System.out.print(hamming.value()); + System.out.print(" "); + hamming = hamming.advance(); + } + System.out.println(); + + System.out.print("H[1691] "); + hamming = makeHamming(); + for (int i=1; i<1691; i++) { + hamming = hamming.advance(); + } + System.out.println(hamming.value()); + + hamming = makeHamming(); + System.out.print("H[10^6] "); + for (int i=1; i<1000000; i++) { + hamming = hamming.advance(); + } + System.out.println(hamming.value()); + } + + public interface Stream + { + BigInteger value(); + Stream advance(); + } + + public static class MultStream implements Stream + { + MultStream(int mult) + { m_mult = BigInteger.valueOf(mult); } + MultStream setBase(Stream s) + { m_base = s; return this; } + public BigInteger value() + { return m_mult.multiply(m_base.value()); } + public Stream advance() + { return setBase(m_base.advance()); } + + private final BigInteger m_mult; + private Stream m_base; + } + + private final static class RegularStream implements Stream + { + RegularStream(Stream[] streams, BigInteger val) + { + m_streams = streams; + m_val = val; + } + public BigInteger value() + { return m_val; } + + public Stream advance() + { + // memoized value for the next stream instance. + if (m_advance != null) { return m_advance; } + + int minidx = 0 ; + BigInteger next = nextStreamValue(0); + for (int i=1; i 0] + +println(powers_235[1:20]) +println(powers_235[1691]) diff --git a/Task/Hamming-numbers/MATLAB/hamming-numbers.m b/Task/Hamming-numbers/MATLAB/hamming-numbers.m new file mode 100644 index 0000000000..13638189d4 --- /dev/null +++ b/Task/Hamming-numbers/MATLAB/hamming-numbers.m @@ -0,0 +1,20 @@ +n = 40; + +powers_2 = 2.^[0:n-1]; +powers_3 = 3.^[0:n-1]; +powers_5 = 5.^[0:n-1]; + +matrix = powers_2' * powers_3; +powers_23 = sort(reshape(matrix,n*n,1)); + + +matrix = powers_23 * powers_5; +powers_235 = sort(reshape(matrix,n*n*n,1)); + +% +% Remove the integer overflow values. +% +powers_235 = powers_235(powers_235 > 0); + +disp(powers_235(1:20)) +disp(powers_235(1691)) diff --git a/Task/Hamming-numbers/Oz/hamming-numbers.oz b/Task/Hamming-numbers/Oz/hamming-numbers-1.oz similarity index 100% rename from Task/Hamming-numbers/Oz/hamming-numbers.oz rename to Task/Hamming-numbers/Oz/hamming-numbers-1.oz diff --git a/Task/Hamming-numbers/Oz/hamming-numbers-2.oz b/Task/Hamming-numbers/Oz/hamming-numbers-2.oz new file mode 100644 index 0000000000..07bd3746db --- /dev/null +++ b/Task/Hamming-numbers/Oz/hamming-numbers-2.oz @@ -0,0 +1,163 @@ +functor +import + Application + System +define + +class Multiplier + attr lst + factor + current + + meth init(Factor Lst) + lst := Lst + factor := Factor + {self next} + end + meth next + local + A + AS + in + A|AS = @lst + current := A*@factor + lst := AS + end + end + meth peek(?X) + X = @current + end + + meth dump + {System.showInfo "DUMP"} + {System.showInfo "Factor: "#@factor} + {System.showInfo "current: "#@current} + end +end + +% a priority queue of multipliers. The one which currently holds the smallest value is put on front +class PriorityQueue + attr mults + current % for duplicate detection + + meth init(Mults) + mults := Mults + current := 0 + end + + meth insert(Mult) + local + fun {Insert M Lst} + local + Av + Mv + in + case Lst of + nil then M|Lst + [] A|AS then {A peek(Av)} + {M peek(Mv)} + if Av < Mv then + A|{Insert M AS} + else M|A|AS + end + end + end + end + in + mults := {Insert Mult @mults} + end + end + + meth next(Tail NextTail) + local + M + Ms + X + Curr + in + M|Ms = @mults + {M peek(X)} % gets value of lowest iterator + Curr = @current + if Curr == X then + skip + else + Tail = X|NextTail % if we found a new value: append + end + {M next} + mults := Ms + {self insert(M)} + if Curr == X then + {self next(Tail NextTail)} + else + current := X + end + end + end + +end + + +local + + % Sieve of erasthothenes, adapted from http://rosettacode.org/wiki/Sieve_of_Eratosthenes#Oz + fun {Sieve N} + S = {Array.new 2 N true} + M = {Float.toInt {Sqrt {Int.toFloat N}}} + in + for I in 2..M do + if S.I then + for J in I*I..N;I do + S.J := false + end + end + end + S + end + + fun {Primes N} + S = {Sieve N} + in + for I in 2..N collect:C do + if S.I then {C I} end + end + end + + + % help method to extract args + proc {GetNK ArgList N K} + case ArgList of + A|B|_ then + N={StringToInt A} + K={StringToInt B} + end + end + + + proc {Generate N PriorQ Tail} + local + NewTail + in + if N == 0 then + Tail = nil + else + {PriorQ next(Tail NewTail)} + {Generate (N-1) PriorQ NewTail} + end + end + end + + K = 3 + PrimeFactors + Lst + Tail +in + ArgList = {Application.getArgs plain} + Lst = 1|Tail + PrimeFactors = {List.take {Primes K*K} K} + Mults = {List.map PrimeFactors fun {$ A} {New Multiplier init(A Lst) } end} + PriorQ = {New PriorityQueue init(Mults)} + {Generate 20 PriorQ Tail} + {ForAll Lst System.showInfo} + {Application.exit 0} +end +end diff --git a/Task/Hamming-numbers/Pascal/hamming-numbers-1.pascal b/Task/Hamming-numbers/Pascal/hamming-numbers-1.pascal new file mode 100644 index 0000000000..c6110cf110 --- /dev/null +++ b/Task/Hamming-numbers/Pascal/hamming-numbers-1.pascal @@ -0,0 +1,75 @@ +program HammNumb; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +{ +type + NativeUInt = longWord; +} +var + pot : array[0..2] of NativeUInt; + +function NextHammNumb(n:NativeUInt):NativeUInt; +var + q,p,nr : NativeUInt; +begin + repeat + nr := n+1; + n := nr; + + p := 0; + while NOT(ODD(nr)) do + begin + inc(p); + nr := nr div 2; + end; + Pot[0]:= p; + + p := 0; + q := nr div 3; + while q*3=nr do + Begin + inc(P); + nr := q; + q := nr div 3; + end; + Pot[1] := p; + + p := 0; + q := nr div 5; + while q*5=nr do + Begin + inc(P); + nr := q; + q := nr div 5; + end; + Pot[2] := p; + + until nr = 1; + result:= n; +end; + +procedure Check; +var + i,n: NativeUint; +begin + n := 1; + for i := 1 to 20 do + begin + n := NextHammNumb(n); + write(n,' '); + end; + writeln; + writeln; + n := 1; + for i := 1 to 1690 do + n := NextHammNumb(n); + writeln('No ',i:4,' | ',n,' = 2^',Pot[0],' 3^',Pot[1],' 5^',Pot[2]); +end; + +Begin + Check; +End. diff --git a/Task/Hamming-numbers/Pascal/hamming-numbers-2.pascal b/Task/Hamming-numbers/Pascal/hamming-numbers-2.pascal new file mode 100644 index 0000000000..52d330eb71 --- /dev/null +++ b/Task/Hamming-numbers/Pascal/hamming-numbers-2.pascal @@ -0,0 +1,329 @@ +program hammNumb; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,ASMCSE,CSE,PEEPHOLE} + {$ALIGN 16} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + sysutils; +const + maxPrimFakCnt = 3;//3 or 3+8 if tNumber= double, else -1 for extended to keep data aligned + minElemCnt = 10; +type + tPrimList = array of NativeUint; + tnumber = double; + tpNumber= ^tnumber; + tElem = record + n : tnumber;//ln(prime[0]^Pots[0]*... + Pots: array[0..maxPrimFakCnt] of word; + end; + tpElem = ^tElem; + tElems = array of tElem; + tElemArr = array [0..0] of tElem; + tpElemArr = ^tElemArr; + + tpFaktorRec = ^tFaktorRec; + tFaktorRec = record + frElems : tElems; + frInsElems: tElems; + frAktIdx : NativeUint; + frMaxIdx : NativeUint; + frPotNo : NativeUint; + frActPot : NativeUint; + frNextFr : tpFaktorRec; + frActNumb: tElem; + frLnPrime: tnumber; + end; + tArrFR = array of tFaktorRec; + +var + Pl : tPrimList; + ActIndex : NativeUint; + ArrInsert : tElems; + +procedure PlInit(n: integer); +const + cPl : array[0..11] of byte=(2,3,5,7,11,13,17,19,23,29,31,37); +var + i : integer; +Begin + IF n>High(cPl)+1 then + n := High(cPl) + else + IF n < 0 then + n := 1; + setlength(Pl,n); + dec(n); + For i := 0 to n do + Pl[i] := cPl[i]; +end; + +procedure AusgabeElem(pElem: tElem); +var + i : integer; +Begin + with pElem do + Begin + IF n < 23 then + write(round(exp(n)):16) + else + write('ln ',n:13:7); + For i := 0 to maxPrimFakCnt do + write(' ',PL[i]:2,'^',Pots[i]); + end; + writeln +end; + +//LoE == List of Elements +function LoEGetNextNumber(pFR :tpFaktorRec):tElem;forward; + +procedure LoECreate(const Pl: tPrimList;var FA:tArrFR); +var + i : integer; +Begin + setlength(ArrInsert,100); + setlength(FA,Length(PL)); + For i := 0 to High(PL) do + with FA[i] do + Begin + //automatic zeroing + IF i < High(PL) then + Begin + setlength(frElems,minElemCnt); + setlength(frInsElems,minElemCnt); + frNextFr := @FA[i+1] + end + else + Begin + setlength(frElems,2); + setlength(frInsElems,0); + frNextFr := NIL; + end; + frPotNo := i; + frLnPrime:= ln(PL[i]); + frMaxIdx := 0; + frAktIdx := 0; + frActPot := 1; + With frElems[0] do + Begin + n := frLnPrime; + Pots[i]:= 1; + end; + frActNumb := frElems[0]; + end; +end; + + +procedure LoEFree(var FA:tArrFR); +var + i : integer; +Begin + For i := High(FA) downto Low(FA) do + setlength(FA[i].frElems,0); + setLength(FA,0); +end; + +function LoEGetActElem(pFr:tpFaktorRec):tElem; +Begin + with pFr^ do + result := frElems[frAktIdx]; +end; + +function LoEGetActLstNumber(pFr:tpFaktorRec):tpNumber; +Begin + with pFr^ do + result := @frElems[frAktIdx].n; +end; + +procedure LoEIncInsArr(var a:tElems); +Begin + setlength(a,Length(a)*8 div 5); +end; + +procedure LoEIncreaseElems(pFr:tpFaktorRec;minCnt:NativeUint); +var + newLen: NativeUint; +Begin + with pFR^ do + begin + newLen := Length(frElems); + minCnt := minCnt+frMaxIdx; + repeat + newLen := newLen*8 div 5 +1; + until newLen > minCnt; + setlength(frElems,newLen); + end; +end; + +procedure LoEInsertNext(pFr:tpFaktorRec;Limit:tnumber); +var + pNum : tpNumber; + pElems : tpElemArr; + cnt,i,u : NativeInt; +begin + with pFr^ do + Begin + //collect numbers of heigher primes + cnt := 0; + pNum := LoEGetActLstNumber(frNextFr); + while Limit > pNum^ do + Begin + frInsElems[cnt] := LoEGetNextNumber(frNextFr); +// writeln( 'Ins ',frInsElems[cnt].n:10:8,' < ',pNum^:10:8); + + inc(cnt); + IF cnt > High(frInsElems) then + LoEIncInsArr(frInsElems); + pNum := LoEGetActLstNumber(frNextFr); + end; + + if cnt = 0 then + EXIT; + + i := frMaxIdx; + u := frMaxIdx+cnt+1; + + IF u > High(frElems) then + LoEIncreaseElems(pFr,cnt); + + IF frPotNo = 0 then + inc(ActIndex,u); + //Merge + pElems := @frElems[0]; + dec(cnt); + dec(u); + frMaxIdx:= u; + repeat +// writeln(i:10,cnt:10,u:10); writeln( pElems^[i].n:10:8,' < ',frInsElems[cnt].n:10:8); + IF pElems^[i].n < frInsElems[cnt].n then + Begin + pElems^[u] := frInsElems[cnt]; + dec(cnt); + end + else + Begin + pElems^[u] := pElems^[i]; + dec(i); + end; + dec(u); + until (i<0) or (cnt<0); + IF i < 0 then + For u := cnt downto 0 do + pElems^[u] := frInsElems[u]; + + end; +end; + +procedure LoEAppendNext(pFr:tpFaktorRec;Limit:tnumber); +var + pNum : tpNumber; + pElems : tpElemArr; + i : NativeInt; +begin + with pFr^ do + Begin + i := frMaxIdx+1; + pElems := @frElems[0]; + pNum := LoEGetActLstNumber(frNextFr); + while Limit > pNum^ do + Begin + IF i > High(frElems) then + Begin + LoEIncreaseElems(pFr,10); + pElems := @frElems[0]; + end; + pElems^[i] := LoEGetNextNumber(frNextFr); + inc(i); + pNum := LoEGetActLstNumber(frNextFr); + end; + inc(ActIndex,i); + frMaxIdx:= i-1; + end; +end; + +procedure LoENextList(pFr:tpFaktorRec); +var + pElems : tpElemArr; + j : NativeUint; +begin + with pFR^ do + Begin + //increase Elements by factor + pElems := @frElems[0]; + for j := frMaxIdx Downto 0 do + with pElems^[j] do + Begin + n := n+frLnPrime; + inc(Pots[frPotNo]); + end; + //x^j -> x^(j+1) + j := frActPot+1; + with frActNumb do + begin + n:= j*frLnPrime; + Pots[frPotNo]:= j; + end; + frActPot := j; + //if something follows + IF frNextFr <> NIL then + LoEInsertNext(pFR,frActNumb.n); + frAktIdx := 0; + end; +end; + +function LoEGetNextNumber(pFR :tpFaktorRec):tElem; +Begin + with pFr^ do + Begin + result := frElems[frAktIdx]; + inc(frAktIdx); + IF frMaxIdx < frAktIdx then + LoENextList(pFr); + end; +end; + +procedure LoEGetNumber(pFR :tpFaktorRec;no:NativeUint); +Begin + dec(no); + while ActIndex < no do + LoENextList(pFR); + with pFr^ do + frAktIdx := (no-(ActIndex-frMaxIdx)-1); + +end; + +var + T1,T0: tDateTime; + FA: tArrFR; + i : integer; +Begin + PlInit(3);// 3 -> 2,3,5 + LoECreate(Pl,FA); + i := 1; + i := 1; + T0 := time; + + For i := 1 to 20 do + AusgabeElem(LoEGetNextNumber(@FA[0])); + + LoEGetNumber(@FA[0],1691); + AusgabeElem(LoEGetNextNumber(@FA[0])); + + + LoEGetNumber(@FA[0],1000*1000); + AusgabeElem(LoEGetNextNumber(@FA[0])); + LoEGetNumber(@FA[0],100*1000*1000); + T1 := time; + AusgabeElem(LoEGetNextNumber(@FA[0])); + Writeln('Timed 100*1000*1000 in ',FormatDateTime('HH:NN:SS.ZZZ',T1-T0)); + + + Writeln('Actual Index ',ActIndex ); + AusgabeElem(LoEGetNextNumber(@FA[0])); + For i := 0 to High(FA) do + writeln(pL[i]:2, + ' elemcount ',FA[i].frMaxIdx+1:7,' out of',length(FA[i].frElems):7); + LoEFree(FA); +End. diff --git a/Task/Hamming-numbers/Perl/hamming-numbers.pl b/Task/Hamming-numbers/Perl/hamming-numbers.pl index 1748da77a7..0c31c18459 100644 --- a/Task/Hamming-numbers/Perl/hamming-numbers.pl +++ b/Task/Hamming-numbers/Perl/hamming-numbers.pl @@ -1,11 +1,15 @@ use List::Util 'min'; +# If you want the large output, uncomment either the one line +# marked (1) or the two lines marked (2) +#use Math::GMP qw/:constant/; # (1) uncomment this to use Math::GMP +#use Math::GMPz; # (2) uncomment this plus later line for Math::GMPz sub ham_gen { my @s = ([1], [1], [1]); my @m = (2, 3, 5); + #@m = map { Math::GMPz->new($_) } @m; # (2) uncomment for Math::GMPz return sub { - # use bigint; my $n = min($s[0][0], $s[1][0], $s[2][0]); for (0 .. 2) { shift @{$s[$_]} if $s[$_][0] == $n; @@ -23,3 +27,7 @@ print "...\n"; ++$i, $h->() until $i == 1690; print ++$i, "-th: ", $h->(), "\n"; + +# You will need to pick one of the bigint choices +#++$i, $h->() until $i == 999999; +#print ++$i, "-th: ", $h->(), "\n"; diff --git a/Task/Hamming-numbers/R/hamming-numbers.r b/Task/Hamming-numbers/R/hamming-numbers.r index ae5d0b7785..45e976c574 100644 --- a/Task/Hamming-numbers/R/hamming-numbers.r +++ b/Task/Hamming-numbers/R/hamming-numbers.r @@ -9,4 +9,6 @@ hamming=function(hamms,limit) { } hamms } -sort(hamming(1,limit=2^31)[-1]) +h <- sort(hamming(1,limit=2^31-1)) +print(h[1:20]) +print(h[length(h)]) diff --git a/Task/Hamming-numbers/Ruby/hamming-numbers-1.rb b/Task/Hamming-numbers/Ruby/hamming-numbers-1.rb index 4331e55049..8b43ccc002 100644 --- a/Task/Hamming-numbers/Ruby/hamming-numbers-1.rb +++ b/Task/Hamming-numbers/Ruby/hamming-numbers-1.rb @@ -1,14 +1,12 @@ -require 'generator' - -# the Hamming number generator -hamming = Generator.new do |generator| +hamming = Enumerator.new do |yielder| next_ham = 1 - queues = { 2 => [], 3 => [], 5 => [] } - loop do - generator.yield next_ham + queues = [[ 2, []], [3, []], [5, []] ] - [2,3,5].each {|m| queues[m] << (next_ham * m)} - next_ham = [2,3,5].collect {|m| queues[m][0]}.min - [2,3,5].each {|m| queues[m].shift if queues[m][0] == next_ham} + loop do + yielder << next_ham # or: yielder.yield(next_ham) + + queues.each {|m,queue| queue << next_ham * m} + next_ham = queues.collect{|m,queue| queue.first}.min + queues.each {|m,queue| queue.shift if queue.first==next_ham} end end diff --git a/Task/Hamming-numbers/Ruby/hamming-numbers-2.rb b/Task/Hamming-numbers/Ruby/hamming-numbers-2.rb index 70751dd8ff..cb368c5b4a 100644 --- a/Task/Hamming-numbers/Ruby/hamming-numbers-2.rb +++ b/Task/Hamming-numbers/Ruby/hamming-numbers-2.rb @@ -1,12 +1,13 @@ -hamming = Enumerator.new do |yielder| - next_ham = 1 - queues = { 2 => [], 3 => [], 5 => [] } +start = Time.now - loop do - yielder << next_ham # or: yielder.yield(next_ham) - - [2,3,5].each {|m| queues[m]<< (next_ham * m)} - next_ham = [2,3,5].collect {|m| queues[m][0]}.min - [2,3,5].each {|m| queues[m].shift if queues[m][0]== next_ham} +hamming.each.with_index(1) do |ham, idx| + case idx + when (1..20), 1691 + puts "#{idx} => #{ham}" + when 1_000_000 + puts "#{idx} => #{ham}" + break end end + +puts "elapsed: #{Time.now - start} seconds" diff --git a/Task/Hamming-numbers/UNIX-Shell/hamming-numbers.sh b/Task/Hamming-numbers/UNIX-Shell/hamming-numbers.sh new file mode 100644 index 0000000000..4a0370960e --- /dev/null +++ b/Task/Hamming-numbers/UNIX-Shell/hamming-numbers.sh @@ -0,0 +1,36 @@ +typeset -a hamming=(1) +function nextHamming { + typeset -Sa q2 q3 q5 + integer h=${hamming[${#hamming[@]}-1]} + q2+=( $(( h*2 )) ) + q3+=( $(( h*3 )) ) + q5+=( $(( h*5 )) ) + h=$( min3 ${q2[0]} ${q3[0]} ${q5[0]} ) + (( ${q2[0]} == h )) && ashift q2 >/dev/null + (( ${q3[0]} == h )) && ashift q3 >/dev/null + (( ${q5[0]} == h )) && ashift q5 >/dev/null + hamming+=($h) +} + +function ashift { + nameref ary=$1 + print -- "${ary[0]}" + ary=( "${ary[@]:1}" ) +} + +function min3 { + if (( $1 < $2 )); then + (( $1 < $3 )) && print -- $1 || print -- $3 + else + (( $2 < $3 )) && print -- $2 || print -- $3 + fi +} + +for ((i=1; i<=20; i++)); do + nextHamming + printf "%d\t%d\n" $i ${hamming[i-1]} +done +for ((; i<=1690; i++)); do nextHamming; done +nextHamming +printf "%d\t%d\n" $i ${hamming[i-1]} +print "elapsed: $SECONDS" diff --git a/Task/Handle-a-signal/00DESCRIPTION b/Task/Handle-a-signal/00DESCRIPTION index 1d9bdf8911..25f1b1f5c1 100644 --- a/Task/Handle-a-signal/00DESCRIPTION +++ b/Task/Handle-a-signal/00DESCRIPTION @@ -1,3 +1,19 @@ -Most general purpose operating systems provide interrupt facilities, sometimes called signals. Unhandled signals generally terminate a program in a disorderly manner. Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal. +{{omit from|Erlang|Does not handle signals.}} +{{omit from|GUISS}} +{{omit from|M4}} +{{omit from|ML/I}} +{{omit from|Mathematica}} +{{omit from|PARI/GP}} +{{omit from|Retro}} +{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} +{{omit from|Unlambda|Does not handle signals.}} +{{omit from|XSLT}} -For this task you will provide a program that displays a single integer on each line of output at the rate of one integer in each half second. Upon receipt of the SigInt signal (often created by the user typing ctrl-C) the program will cease printing integers to its output, print the number of seconds the program has run, and then the program will terminate. +Most general purpose operating systems provide interrupt facilities, sometimes called signals. +Unhandled signals generally terminate a program in a disorderly manner. +Signal handlers are created so that the program behaves in a well-defined manner upon receipt of a signal. + +For this task you will provide a program that displays a single integer +on each line of output at the rate of one integer in each half second. +Upon receipt of the SigInt signal (often created by the user typing ctrl-C) the program will cease printing integers to its output, print the number of seconds +the program has run, and then the program will terminate. diff --git a/Task/Handle-a-signal/JavaScript/handle-a-signal.js b/Task/Handle-a-signal/JavaScript/handle-a-signal.js new file mode 100644 index 0000000000..f81f7f16cc --- /dev/null +++ b/Task/Handle-a-signal/JavaScript/handle-a-signal.js @@ -0,0 +1,16 @@ +(function(){ + var count=0 + secs=0 + + var i= setInterval( function (){ + count++ + secs+=0.5 + console.log(count) + }, 500); + + process.on('SIGINT', function() { + clearInterval(i) + console.log(secs+' seconds elapsed'); + process.exit() + }); +})(); diff --git a/Task/Handle-a-signal/MATLAB/handle-a-signal-1.m b/Task/Handle-a-signal/MATLAB/handle-a-signal-1.m new file mode 100644 index 0000000000..33c9eab90a --- /dev/null +++ b/Task/Handle-a-signal/MATLAB/handle-a-signal-1.m @@ -0,0 +1,10 @@ +function sigintHandle + k = 1; + tic + catchObj = onCleanup(@toc); + while true + pause(0.5) + fprintf('%d\n', k) + k = k+1; + end +end diff --git a/Task/Handle-a-signal/MATLAB/handle-a-signal-2.m b/Task/Handle-a-signal/MATLAB/handle-a-signal-2.m new file mode 100644 index 0000000000..7624744eae --- /dev/null +++ b/Task/Handle-a-signal/MATLAB/handle-a-signal-2.m @@ -0,0 +1,14 @@ +function sigintHandle + k = 1; + tic + try + while true + pause(0.5) + fprintf('%d\n', k) + k = k+1; + end + catch me + toc + rethrow me + end +end diff --git a/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp b/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp new file mode 100644 index 0000000000..2f3b398933 --- /dev/null +++ b/Task/Handle-a-signal/NewLISP/handle-a-signal.newlisp @@ -0,0 +1,11 @@ +(setq start-time (now)) + +(signal 2 (lambda() + (println + (format "Program has run for %d seconds" + (- (apply date-value (now)) + (apply date-value start-time)))) + (exit 0))) + +(while (println (++ i)) + (sleep 500)) diff --git a/Task/Handle-a-signal/Perl-6/handle-a-signal.pl6 b/Task/Handle-a-signal/Perl-6/handle-a-signal.pl6 new file mode 100644 index 0000000000..94bc669861 --- /dev/null +++ b/Task/Handle-a-signal/Perl-6/handle-a-signal.pl6 @@ -0,0 +1,9 @@ +signal(Signal::SIGINT).tap: { + note "Took { now - INIT now } seconds."; + exit; +} + +for 0, 1, *+* ... * { + sleep 0.5; + .say; +} diff --git a/Task/Handle-a-signal/Python/handle-a-signal-1.py b/Task/Handle-a-signal/Python/handle-a-signal-1.py index d893249411..0641f91503 100644 --- a/Task/Handle-a-signal/Python/handle-a-signal-1.py +++ b/Task/Handle-a-signal/Python/handle-a-signal-1.py @@ -1,18 +1,15 @@ import time -def intrptWIN(): - procDone = False - n = 0 +def counter(): + n = 0 + t1 = time.time() + while True: + try: + time.sleep(0.5) + n += 1 + print n + except KeyboardInterrupt, e: + print 'Program has run for %5.3f seconds.' % (time.time() - t1) + break - while not procDone: - try: - time.sleep(0.5) - n += 1 - print n - except KeyboardInterrupt, e: - procDone = True - -t1 = time.time() -intrptWIN() -tdelt = time.time() - t1 -print 'Program has run for %5.3f seconds.' % tdelt +counter() diff --git a/Task/Handle-a-signal/Python/handle-a-signal-2.py b/Task/Handle-a-signal/Python/handle-a-signal-2.py index 171ae28a5f..d893249411 100644 --- a/Task/Handle-a-signal/Python/handle-a-signal-2.py +++ b/Task/Handle-a-signal/Python/handle-a-signal-2.py @@ -1,29 +1,18 @@ -import signal, time, threading -done = False -n = 0 +import time -def counter(): - global n, timer - n += 1 - print n - timer = threading.Timer(0.5, counter) - timer.start() +def intrptWIN(): + procDone = False + n = 0 -def sigIntHandler(signum, frame): - global done - timer.cancel() - done = True - -def intrptUNIX(): - global timer - signal.signal(signal.SIGINT, sigIntHandler) - - timer = threading.Timer(0.5, counter) - timer.start() - while not done: - signal.pause() + while not procDone: + try: + time.sleep(0.5) + n += 1 + print n + except KeyboardInterrupt, e: + procDone = True t1 = time.time() -intrptUNIX() +intrptWIN() tdelt = time.time() - t1 print 'Program has run for %5.3f seconds.' % tdelt diff --git a/Task/Handle-a-signal/Python/handle-a-signal-3.py b/Task/Handle-a-signal/Python/handle-a-signal-3.py index 708305e655..171ae28a5f 100644 --- a/Task/Handle-a-signal/Python/handle-a-signal-3.py +++ b/Task/Handle-a-signal/Python/handle-a-signal-3.py @@ -1,23 +1,29 @@ -import time, signal +import signal, time, threading +done = False +n = 0 -class WeAreDoneException(Exception): - pass +def counter(): + global n, timer + n += 1 + print n + timer = threading.Timer(0.5, counter) + timer.start() def sigIntHandler(signum, frame): - signal.signal(signal.SIGINT, signal.SIG_DFL) # resets to default handler - raise WeAreDoneException + global done + timer.cancel() + done = True + +def intrptUNIX(): + global timer + signal.signal(signal.SIGINT, sigIntHandler) + + timer = threading.Timer(0.5, counter) + timer.start() + while not done: + signal.pause() t1 = time.time() - -try: - signal.signal(signal.SIGINT, sigIntHandler) - n = 0 - while True: - time.sleep(0.5) - n += 1 - print n -except WeAreDoneException: - pass - +intrptUNIX() tdelt = time.time() - t1 print 'Program has run for %5.3f seconds.' % tdelt diff --git a/Task/Handle-a-signal/Python/handle-a-signal-4.py b/Task/Handle-a-signal/Python/handle-a-signal-4.py new file mode 100644 index 0000000000..708305e655 --- /dev/null +++ b/Task/Handle-a-signal/Python/handle-a-signal-4.py @@ -0,0 +1,23 @@ +import time, signal + +class WeAreDoneException(Exception): + pass + +def sigIntHandler(signum, frame): + signal.signal(signal.SIGINT, signal.SIG_DFL) # resets to default handler + raise WeAreDoneException + +t1 = time.time() + +try: + signal.signal(signal.SIGINT, sigIntHandler) + n = 0 + while True: + time.sleep(0.5) + n += 1 + print n +except WeAreDoneException: + pass + +tdelt = time.time() - t1 +print 'Program has run for %5.3f seconds.' % tdelt diff --git a/Task/Handle-a-signal/Scala/handle-a-signal.scala b/Task/Handle-a-signal/Scala/handle-a-signal.scala new file mode 100644 index 0000000000..84ab7b1210 --- /dev/null +++ b/Task/Handle-a-signal/Scala/handle-a-signal.scala @@ -0,0 +1,20 @@ +import sun.misc.Signal +import sun.misc.SignalHandler + +object SignalHandl extends App { + val start = System.nanoTime() + var counter = 0 + + Signal.handle(new Signal("INT"), new SignalHandler() { + def handle(sig: Signal) { + println(f"\nProgram execution took ${(System.nanoTime() - start) / 1e9f}%f seconds\n") + exit(0) + } + }) + + while (true) { + counter += 1 + println(counter) + Thread.sleep(500) + } +} diff --git a/Task/Happy-numbers/Clojure/happy-numbers.clj b/Task/Happy-numbers/Clojure/happy-numbers.clj index 22a51896ff..9a67889518 100644 --- a/Task/Happy-numbers/Clojure/happy-numbers.clj +++ b/Task/Happy-numbers/Clojure/happy-numbers.clj @@ -1,13 +1,14 @@ -(defn- digit-to-num [d] (Character/digit d 10)) -(defn- square [n] (* n n)) - (defn happy? [n] (loop [n n, seen #{}] - (cond (= n 1) true - (seen n) false - :else - (recur (reduce + (map (comp square digit-to-num) (str n))) - (conj seen n))))) + (cond + (= n 1) true + (seen n) false + :else + (recur (->> (str n) + (map #(Character/digit % 10)) + (map #(* % %)) + (reduce +)) + (conj seen n))))) (def happy-numbers (filter happy? (iterate inc 1))) diff --git a/Task/Happy-numbers/D/happy-numbers-1.d b/Task/Happy-numbers/D/happy-numbers-1.d index 0475b0f7fe..83a1ebad3d 100644 --- a/Task/Happy-numbers/D/happy-numbers-1.d +++ b/Task/Happy-numbers/D/happy-numbers-1.d @@ -1,5 +1,3 @@ -import std.stdio, std.algorithm, std.range; - bool isHappy(int n) pure nothrow { int[int] past; @@ -19,5 +17,7 @@ bool isHappy(int n) pure nothrow { } void main() { - int.max.iota().filter!isHappy().take(8).writeln(); + import std.stdio, std.algorithm, std.range; + + int.max.iota.filter!isHappy.take(8).writeln; } diff --git a/Task/Happy-numbers/D/happy-numbers-2.d b/Task/Happy-numbers/D/happy-numbers-2.d index b208f11c9e..e0b20a790b 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; +import std.stdio, std.algorithm, std.range, std.conv, std.string; -bool isHappy(int n) pure /*nothrow*/ { +bool isHappy(int n) pure nothrow { int[int] seen; while (true) { - immutable t = n.text.map!q{(a - '0') ^^ 2}.sum; + immutable t = n.text.representation.map!q{(a - '0') ^^ 2}.sum; if (t == 1) return true; if (t in seen) diff --git a/Task/Happy-numbers/Eiffel/happy-numbers.e b/Task/Happy-numbers/Eiffel/happy-numbers.e new file mode 100644 index 0000000000..c5c2c3acd8 --- /dev/null +++ b/Task/Happy-numbers/Eiffel/happy-numbers.e @@ -0,0 +1,70 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + l_val: INTEGER + do + from + l_val := 1 + until + l_val > 100 + loop + if is_happy_number (l_val) then + print (l_val.out) + print ("%N") + end + l_val := l_val + 1 + end + end + +feature -- Happy number + + is_happy_number (a_number: INTEGER): BOOLEAN + -- Is `a_number' a happy number? + require + positive_number: a_number > 0 + local + l_number: INTEGER + l_set: ARRAYED_SET [INTEGER] + do + from + l_number := a_number + create l_set.make (10) + until + l_number = 1 or l_set.has (l_number) + loop + l_set.put (l_number) + l_number := square_sum_of_digits (l_number) + end + + Result := (l_number = 1) + end + +feature{NONE} -- Implementation + + square_sum_of_digits (a_number: INTEGER): INTEGER + -- Sum of the sqares of digits of `a_number'. + require + positive_number: a_number > 0 + local + l_number, l_digit: INTEGER + do + from + l_number := a_number + until + l_number = 0 + loop + l_digit := l_number \\ 10 + Result := Result + l_digit * l_digit + l_number := l_number // 10 + end + end + +end diff --git a/Task/Happy-numbers/Frege/happy-numbers.frege b/Task/Happy-numbers/Frege/happy-numbers.frege index 09e66890a5..4fefe2ecbb 100644 --- a/Task/Happy-numbers/Frege/happy-numbers.frege +++ b/Task/Happy-numbers/Frege/happy-numbers.frege @@ -2,16 +2,16 @@ module Happy where import Prelude.Math -- ugh, since Frege doesn't have Set, use Map instead -import Data.Map (member, insertMin, empty) +import Data.Map (member, insertMin, empty emptyMap) digitToInteger :: Char -> Integer digitToInteger c = fromInt $ (ord c) - (ord '0') isHappy :: Integer -> Bool -isHappy = p empty +isHappy = p emptyMap where p _ 1n = true p s n | n `member` s = false | otherwise = p (insertMin n () s) (f n) f = sum . map (sqr . digitToInteger) . unpacked . show -main _ = printStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n +main _ = putStrLn $ unwords $ map show $ take 8 $ filter isHappy $ iterate (+ 1n) 1n diff --git a/Task/Happy-numbers/Go/happy-numbers.go b/Task/Happy-numbers/Go/happy-numbers.go index 063dbafe9c..b74e179e1c 100644 --- a/Task/Happy-numbers/Go/happy-numbers.go +++ b/Task/Happy-numbers/Go/happy-numbers.go @@ -1,33 +1,29 @@ package main -import ( - "fmt" - "strconv" -) +import "fmt" func happy(n int) bool { - m := make(map[int]int) - for n > 1 { - m[n] = 0 - s := strconv.Itoa(n) - n = 0 - for _, d := range s { - x := int(d) - '0' - n += x * x - } - if _, ok := m[n]; ok { - return false - } - } - return true + m := make(map[int]bool) + for n > 1 { + m[n] = true + var x int + for x, n = n, 0; x > 0; x /= 10 { + d := x % 10 + n += d * d + } + if m[n] { + return false + } + } + return true } func main() { - for found, n := 0, 1; found < 8; n++ { - if happy(n) { - fmt.Print(n, " ") - found++ - } - } - fmt.Println("") + for found, n := 0, 1; found < 8; n++ { + if happy(n) { + fmt.Print(n, " ") + found++ + } + } + fmt.Println() } diff --git a/Task/Happy-numbers/Groovy/happy-numbers.groovy b/Task/Happy-numbers/Groovy/happy-numbers.groovy new file mode 100644 index 0000000000..9656d9566d --- /dev/null +++ b/Task/Happy-numbers/Groovy/happy-numbers.groovy @@ -0,0 +1,15 @@ +Number.metaClass.isHappy = { + def number = delegate as Long + def cycle = new HashSet() + while (number != 1 && !cycle.contains(number)) { + cycle << number + number = (number as String).collect { d = (it as Long); d * d }.sum() + } + number == 1 +} + +def matches = [] +for (int i = 0; matches.size() < 8; i++) { + if (i.happy) { matches << i } +} +println matches diff --git a/Task/Happy-numbers/MATLAB/happy-numbers.m b/Task/Happy-numbers/MATLAB/happy-numbers.m new file mode 100644 index 0000000000..94491c6bb7 --- /dev/null +++ b/Task/Happy-numbers/MATLAB/happy-numbers.m @@ -0,0 +1,22 @@ +function findHappyNumbers + nHappy = 0; + k = 1; + while nHappy < 8 + if isHappyNumber(k, []) + fprintf('%d ', k) + nHappy = nHappy+1; + end + k = k+1; + end + fprintf('\n') +end + +function hap = isHappyNumber(k, prev) + if k == 1 + hap = true; + elseif ismember(k, prev) + hap = false; + else + hap = isHappyNumber(sum((sprintf('%d', k)-'0').^2), [prev k]); + end +end diff --git a/Task/Happy-numbers/MAXScript/happy-numbers-1.max b/Task/Happy-numbers/MAXScript/happy-numbers-1.max new file mode 100644 index 0000000000..361a711f84 --- /dev/null +++ b/Task/Happy-numbers/MAXScript/happy-numbers-1.max @@ -0,0 +1,26 @@ +fn isHappyNumber n = +( + local pastNumbers = #() + while n != 1 do + ( + n = n as string + local newNumber = 0 + for i = 1 to n.count do + ( + local digit = n[i] as integer + newNumber += pow digit 2 + ) + n = newNumber + if (finditem pastNumbers n) != 0 do return false + append pastNumbers newNumber + ) + n == 1 +) +printed = 0 +for i in (for h in 1 to 500 where isHappyNumber h collect h) do +( + if printed == 8 do exit + print i as string + printed += 1 + +) diff --git a/Task/Happy-numbers/MAXScript/happy-numbers-2.max b/Task/Happy-numbers/MAXScript/happy-numbers-2.max new file mode 100644 index 0000000000..3270607a3c --- /dev/null +++ b/Task/Happy-numbers/MAXScript/happy-numbers-2.max @@ -0,0 +1,8 @@ +1 +7 +10 +13 +19 +23 +28 +31 diff --git a/Task/Happy-numbers/Mercury/happy-numbers.mercury b/Task/Happy-numbers/Mercury/happy-numbers.mercury new file mode 100644 index 0000000000..2afc0eaf39 --- /dev/null +++ b/Task/Happy-numbers/Mercury/happy-numbers.mercury @@ -0,0 +1,40 @@ +:- module happy. +:- interface. +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. +:- import_module int, list, set_tree234. + +main(!IO) :- + print_line(get_n_happy_numbers(8, 1), !IO). + +:- func get_n_happy_numbers(int, int) = list(int). + +get_n_happy_numbers(NumToFind, N) = + ( if NumToFind > 0 then + ( if is_happy(N, init) + then [N | get_n_happy_numbers(NumToFind - 1, N + 1)] + else get_n_happy_numbers(NumToFind, N + 1) + ) + else + [] + ). + +:- pred is_happy(int::in, set_tree234(int)::in) is semidet. + +is_happy(1, _). +is_happy(N, !.Seen) :- + not member(N, !.Seen), + insert(N, !Seen), + is_happy(sum_sqr_digits(N), !.Seen). + +:- func sum_sqr_digits(int) = int. + +sum_sqr_digits(N) = + ( if N < 10 then sqr(N) else sqr(N mod 10) + sum_sqr_digits(N div 10) ). + +:- func sqr(int) = int. + +sqr(X) = X * X. diff --git a/Task/Happy-numbers/Pascal/happy-numbers.pascal b/Task/Happy-numbers/Pascal/happy-numbers-1.pascal similarity index 100% rename from Task/Happy-numbers/Pascal/happy-numbers.pascal rename to Task/Happy-numbers/Pascal/happy-numbers-1.pascal diff --git a/Task/Happy-numbers/Pascal/happy-numbers-2.pascal b/Task/Happy-numbers/Pascal/happy-numbers-2.pascal new file mode 100644 index 0000000000..23fa4dd968 --- /dev/null +++ b/Task/Happy-numbers/Pascal/happy-numbers-2.pascal @@ -0,0 +1,171 @@ +Program HappyNumbers (output); +// NativeUInt: LongWord 32-Bit-OS/ Uint64 64-Bit-OS +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,Regvar,PEEPHOLE,CSE,ASMCSE} + {$CODEALIGN proc=32} +{$ELSE} + //for Delphi + {$APPLICATION CONSOLE} +{$ENDIF} +const + HighCache = 19*(9*9);//sum sqrdigt of Uint64 + cDigit = 1000; +type + tCache = array[0..HighCache] of Word; + tSqrdCache = array[0..cDigit] of Word; + tSqrdSumCache = array[0..HighCache] of Word; +var + Cache : tCache; + SqrdCache :tSqrdCache; + SqrdSumCache :tSqrdSumCache; + +function find(n: NativeUint;const cache: tCache): boolean; +var + i: NativeUint; +begin + find := false; + for i := low(cache) to high(cache) do + if cache[i] = n then + find := true; + writeln(i:10,n:10); +end; + +procedure InitSqrdCache; +var + i,n,sum,r: NativeUint; +begin + For i := 0 to cDigit do + Begin + sum := 0; + n := i; + while n > 0 do + begin + r := n; + n := n div 10; + r := r-10*n; + sum := sum + r*r; + end; + SqrdCache[i] := sum; + end; +end; + +function SumSqrdDgt(n: NativeUint): NativeUint; +var + sum,r: NativeUint; +begin + sum := 0; + while n > cDigit do + begin + r := n; + n := n div cDigit; + r := r-cDigit*n; + sum := sum + SqrdCache[r]; + end; + SumSqrdDgt := sum + SqrdCache[n]; +end; + + +procedure Inithappy; +var + n,s,p : NativeUint; +Begin + fillchar(SqrdSumCache,SizeOf(SqrdSumCache),#0); + InitSqrdCache; + fillChar(Cache,SizeOf(Cache),#0); + Cache[1] := 1; + For n := 1 to High(Cache) do + Begin + If Cache[n] = 0 then + Begin + //start a linked list + Cache[n] := n; + p := n; + s := SumSqrdDgt(p); + while Cache[s] = 0 do + Begin + Cache[s] := p; + p := s; + s := SumSqrdDgt(p); + end; + //mark linked list backwards as happy number + IF Cache[s] = 1 then + Begin + repeat + s := Cache[p]; + Cache[p] := 1; + p := s; + until s = n; + Cache[n] := 1; + end; + end; + end; +end; + +function nextCdigits(sqSum: NativeUint):NativeUint; +var + i,cnt : LongInt; +Begin + cnt:= SqrdSumCache[sqSum]; + If cnt = 0 then + Begin + For i := 0 to Cdigit-1 do + cnt := cnt + Ord(Cache[sqSum+SqrdCache[i]]=1); + //saving calculation->speed up x100 + SqrdSumCache[sqSum] := cnt; + end; + nextCdigits := cnt; +end; + +function is_happy(n: NativeUint): boolean;inline; +begin + is_happy := Cache[SumSqrdDgt(n)]=1 +end; + +function nthHappy(Limit: NativeUint):NativeUint; +var + n, + count : NativeUint; +begin + n:= 0; + count := 0; + // big steps + IF limit>cDigit then + repeat + inc(count,nextCdigits(SumSqrdDgt(n))); + inc(n,cDigit); + until count >= Limit-cDigit; + // small steps + repeat + if is_happy(n) then + inc(count); + inc(n); + until count >= Limit; + nthHappy:= n-1; +end; + +var + n, count,Limit: NativeUint; +begin + Inithappy; + n := 1; + count := 0; + while count < 8 do + begin + if is_happy(n) then + begin + inc(count); + write(n, ' '); + end; + inc(n); + end; + writeln; + + n := 1; + Limit := 10;// 1En + repeat + writeln('10e',n,' nth happy number ',nthHappy(limit):13); + inc(n); + Limit := limit*10; + until n> 8; +end. diff --git a/Task/Happy-numbers/Perl/happy-numbers-1.pl b/Task/Happy-numbers/Perl/happy-numbers-1.pl index 00663c1605..3368600abb 100644 --- a/Task/Happy-numbers/Perl/happy-numbers-1.pl +++ b/Task/Happy-numbers/Perl/happy-numbers-1.pl @@ -1,11 +1,12 @@ 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;}} +sub ishappy { + my $s = shift; + while ($s > 6 && $s != 89) { + $s = sum(map { $_*$_ } split(//,$s)); + } + $s == 1; +} -for (my ($n, $happy) = (1, 0) ; $happy < 8 ; ++$n) - {is_happy $n or next; - print "$n\n"; - ++$happy;} +my $n = 0; +print join(" ", map { 1 until ishappy(++$n); $n; } 1..8), "\n"; diff --git a/Task/Happy-numbers/REXX/happy-numbers-2.rexx b/Task/Happy-numbers/REXX/happy-numbers-2.rexx index cdd3ab39ff..3925cbad8f 100644 --- a/Task/Happy-numbers/REXX/happy-numbers-2.rexx +++ b/Task/Happy-numbers/REXX/happy-numbers-2.rexx @@ -3,31 +3,26 @@ 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 +@.=0; @.1=1; !.=@.; !.2=1; !.3=1; !.4=1 /*sparse array: @≡hap, !≡unhap*/ haps=0 /*count of happy numbers so far. */ -@.=0; !.=0 /*sparse array: happy&unhappy #s.*/ - do n=1 while hapssw then do /*maybe display the happy number.*/ - say strip(out) /*line is too long, tell it*/ - out= /*nullify the OUT (line).*/ - end - out=out n /*append the happy number to OUT.*/ - end /*n*/ - -if out\=='' then say strip(out) /*handle any residuals for OUT. */ + if !.s then iterate n /*Sum unhappy? Then Q is unhappy*/ + if @.s then leave /*we have found a happy number.*/ + q=s /*try the Q sum to see if happy.*/ + end /*until*/ + @.n=1 /*mark N as a happy number. */ + haps=haps+1 /*bump the count of happy numbers*/ + if hapssw then do /*if the list is too long, split */ + say strip($) /*and display what we've got.*/ + $=n /*set next line to overflow. */ + end /* [↑] now contains overlow.*/ + end /*n*/ +if $\='' then say strip($) /*display any residual happy nums*/ + /*stick a fork in it, we're done.*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Happy-numbers/Ruby/happy-numbers-2.rb b/Task/Happy-numbers/Ruby/happy-numbers-2.rb index 80bdddf1df..6d4480b031 100644 --- a/Task/Happy-numbers/Ruby/happy-numbers-2.rb +++ b/Task/Happy-numbers/Ruby/happy-numbers-2.rb @@ -1,10 +1,12 @@ def print_happy happy_numbers = [] - (1..Float::INFINITY).each do |i| + 1.step do |i| break if happy_numbers.length >= 8 happy_numbers << i if happy?(i) end p happy_numbers end + +print_happy diff --git a/Task/Happy-numbers/Ruby/happy-numbers-4.rb b/Task/Happy-numbers/Ruby/happy-numbers-4.rb new file mode 100644 index 0000000000..678495825c --- /dev/null +++ b/Task/Happy-numbers/Ruby/happy-numbers-4.rb @@ -0,0 +1,18 @@ +@memo = [0,1] +def happy(n) + sum = n.to_s.chars.map{|c| c.to_i**2}.inject(:+) + return @memo[sum] if @memo[sum]==0 or @memo[sum]==1 + @memo[sum] = 0 # for the cycle check + @memo[sum] = happy(sum) # return 1:Happy number, 0:other +end + +i = count = 0 +while count < 8 + i += 1 + puts i or count+=1 if happy(i)==1 +end + +puts +for i in 99999999999900..99999999999999 + puts i if happy(i)==1 +end diff --git a/Task/Happy-numbers/Rust/happy-numbers.rust b/Task/Happy-numbers/Rust/happy-numbers.rust new file mode 100644 index 0000000000..9b6647bd6e --- /dev/null +++ b/Task/Happy-numbers/Rust/happy-numbers.rust @@ -0,0 +1,36 @@ +#![feature(core)] + +fn sumsqd(mut n: i32) -> i32 { + let mut sq = 0; + while n > 0 { + let d = n % 10; + sq += d*d; + n /= 10 + } + sq +} + +use std::num::Int; +fn cycle(a: T, f: fn(T) -> T) -> T { + let mut t = a; + let mut h = f(a); + + while t != h { + t = f(t); + h = f(f(h)) + } + t +} + +fn ishappy(n: i32) -> bool { + cycle(n, sumsqd) == 1 +} + +fn main() { + let happy = std::iter::count(1, 1) + .filter(|&n| ishappy(n)) + .take(8) + .collect::>(); + + println!("{:?}", happy) +} diff --git a/Task/Harshad-or-Niven-series/00DESCRIPTION b/Task/Harshad-or-Niven-series/00DESCRIPTION index eed905856d..332183f0c2 100644 --- a/Task/Harshad-or-Niven-series/00DESCRIPTION +++ b/Task/Harshad-or-Niven-series/00DESCRIPTION @@ -1,5 +1,14 @@ -The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, 42 is a [[oeis:A005349|Harshad number]] as 42 is divisible by (4+2) without remainder. +{{omit from|Brlcad}} +{{omit from|Lilypond}} +{{omit from|Openscad}} +{{omit from|TPP}} + +The [http://mathworld.wolfram.com/HarshadNumber.html Harshad] or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. + +For example, 42 is a [[oeis:A005349|Harshad number]] as 42 is divisible by (4+2) without remainder. Assume that the series is defined as the numbers in increasing order. -The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000. +The task is to create a function/method/procedure to generate successive members of the Harshad sequence. +Use it to list the first twenty members of the sequence and list the first Harshad number greater than 1000. + Show your output here. diff --git a/Task/Harshad-or-Niven-series/ColdFusion/harshad-or-niven-series.cfm b/Task/Harshad-or-Niven-series/ColdFusion/harshad-or-niven-series.cfm new file mode 100644 index 0000000000..4095b653d5 --- /dev/null +++ b/Task/Harshad-or-Niven-series/ColdFusion/harshad-or-niven-series.cfm @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #harshadNum# + + + + +... #harshadNum# diff --git a/Task/Harshad-or-Niven-series/Common-Lisp/harshad-or-niven-series.lisp b/Task/Harshad-or-Niven-series/Common-Lisp/harshad-or-niven-series.lisp new file mode 100644 index 0000000000..44c8c75845 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Common-Lisp/harshad-or-niven-series.lisp @@ -0,0 +1,12 @@ +(defun harshadp (n) + (zerop (rem n (digit-sum n)))) + +(defun digit-sum (n &optional (a 0)) + (cond ((zerop n) a) + (t (digit-sum (floor n 10) (+ a (rem n 10)))))) + +(defun list-harshad (n &optional (i 1) (lst nil)) + "list the first n Harshad numbers starting from i (default 1)" + (cond ((= (length lst) n) (reverse lst)) + ((harshadp i) (list-harshad n (+ i 1) (cons i lst))) + (t (list-harshad n (+ i 1) lst)))) diff --git a/Task/Harshad-or-Niven-series/Eiffel/harshad-or-niven-series.e b/Task/Harshad-or-Niven-series/Eiffel/harshad-or-niven-series.e new file mode 100644 index 0000000000..b9c0b694b0 --- /dev/null +++ b/Task/Harshad-or-Niven-series/Eiffel/harshad-or-niven-series.e @@ -0,0 +1,76 @@ +note + description : "project application root class" + date : "$October 10, 2014$" + revision : "$Revision$" + +class + NIVEN_SERIES + +create + make + +feature + make + local + number : INTEGER + count : INTEGER + last : BOOLEAN + do + number := 1 + + from + number := 1 + last := false + + until + last = true + + loop + + if + (number \\ sum_of_digits(number) = 0) + then + count := count + 1 + + if + (count <= 20 ) + then + print("%N") + print(number) + end + + if + (number > 1000) + then + print("%N") + print(number) + last := true + end + end + + number := number + 1 + end + end + + sum_of_digits(no:INTEGER):INTEGER + + local + sum : INTEGER + num : INTEGER + do + sum := 0 + + from + num := no + + until + num = 0 + + loop + sum := sum + num \\ 10 + num := num // 10 + end + + Result := sum + end +end diff --git a/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink b/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink index 35414a455d..cada6da5d2 100644 --- a/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink +++ b/Task/Harshad-or-Niven-series/Frink/harshad-or-niven-series.frink @@ -1,4 +1,4 @@ -isHarshad[n] := n mod sum[parseInt[charList[toString[n]]]] == 0 +isHarshad[n] := n mod sum[integerDigits[n]] == 0 c = 0 i = 1 diff --git a/Task/Harshad-or-Niven-series/Pascal/harshad-or-niven-series.pascal b/Task/Harshad-or-Niven-series/Pascal/harshad-or-niven-series.pascal new file mode 100644 index 0000000000..b8b2b0a56f --- /dev/null +++ b/Task/Harshad-or-Niven-series/Pascal/harshad-or-niven-series.pascal @@ -0,0 +1,118 @@ +program Niven; +const + base = 10; +type + tNum = longword;{Uint64} +const + cntbasedigits = trunc(ln(High(tNum))/ln(base))+1; +type + tSumDigit = record + sdNumber : tNum; + sdDigits : array[0..cntbasedigits-1] of byte; + sdSumDig : byte; + sdIsNiven : boolean; + end; + +function InitSumDigit( n : tNum):tSumDigit; +var + sd : tSumDigit; + qt : tNum; + i : integer; +begin + with sd do + begin + sdNumber:= n; + fillchar(sdDigits,SizeOf(sdDigits),#0); + sdSumDig :=0; + sdIsNiven := false; + i := 0; + // calculate Digits und sum them up + while n > 0 do + begin + qt := n div base; + {n mod base} + sdDigits[i] := n-qt*base; + inc(sdSumDig,sdDigits[i]); + n:= qt; + inc(i); + end; + IF sdSumDig >0 then + sdIsNiven := (sdNumber MOD sdSumDig = 0); + end; + InitSumDigit:=sd; +end; + +procedure IncSumDigit(var sd:tSumDigit); +var + i,d: integer; +begin + i := 0; + with sd do + begin + inc(sdNumber); + repeat + d := sdDigits[i]; + inc(d); + inc(sdSumDig); + //base-1 times the repeat is left here + if d < base then + begin + sdDigits[i] := d; + BREAK; + end + else + begin + sdDigits[i] := 0; + dec(sdSumDig,base); + inc(i); + end; + until i > high( sdDigits); + sdIsNiven := (sdNumber MOD sdSumDig) = 0; + end; +end; + +var + MySumDig : tSumDigit; + ln : tNum; + cnt: integer; +begin + MySumDig:=InitSumDigit(0); + cnt := 0; + repeat + IncSumDigit(MySumDig); + IF MySumDig.sdIsNiven then + begin + write(MySumDig.sdNumber,'.'); + inc(cnt); + end; + until cnt >= 20; + write('....'); + MySumDig:=InitSumDigit(1000); + repeat + IncSumDigit(MySumDig); + until MySumDig.sdIsNiven; + writeln(MySumDig.sdNumber,'.'); +// searching for big gaps between two niven-numbers +// MySumDig:=InitSumDigit(18879989100-276); + MySumDig:=InitSumDigit(1); + cnt := 0; + ln:= MySumDig.sdNumber; + repeat + IncSumDigit(MySumDig); + if MySumDig.sdIsNiven then + begin + IF cnt < (MySumDig.sdNumber-ln) then + begin + cnt :=(MySumDig.sdNumber-ln); + writeln(ln,' --> ',MySumDig.sdNumber,' d=',cnt); + end; + ln:= MySumDig.sdNumber; + end; + until MySumDig.sdNumber= High(tNum); +{ +689988915 --> 689989050 d=135 +879987906 --> 879988050 d=144 +989888823 --> 989888973 d=150 +2998895823 --> 2998895976 d=153 +~ 24 Cpu-cycles per test i3- 4330 1..2^32-1} +end. diff --git a/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 b/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 index ee0969ad93..5ad27f71ef 100644 --- a/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 +++ b/Task/Harshad-or-Niven-series/Perl-6/harshad-or-niven-series.pl6 @@ -1,5 +1,4 @@ -my @harshad := gather for 1 .. * { take $_ if $_ %% [+] .comb } +constant harshad = grep { $_ %% [+] .comb }, 1 .. *; -say @harshad[^20]; - -say @harshad.first: * > 1000; +say harshad[^20]; +say harshad.first: * > 1000; diff --git a/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb b/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb index 1e783f49b3..7120f1de98 100644 --- a/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb +++ b/Task/Harshad-or-Niven-series/Ruby/harshad-or-niven-series.rb @@ -2,7 +2,8 @@ def digsum n n.to_s.chars.map(&:to_i).reduce(:+) end -harshad = (1..Float::INFINITY).lazy.select { |n| n % digsum(n) == 0 } +harshad = 1.step.lazy.select { |n| n % digsum(n) == 0 } +#harshad = (1..Float::INFINITY).lazy.select { |n| n % digsum(n) == 0 } # ver 2.0 -p harshad.take(20).to_a +p harshad.first(20) p harshad.find { |n| n > 1000 } diff --git a/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala b/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala index 124543d9b8..28cfcbc6bf 100644 --- a/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala +++ b/Task/Harshad-or-Niven-series/Scala/harshad-or-niven-series.scala @@ -1,8 +1,10 @@ object Harshad extends App { + import language.postfixOps import Stream._ - val fh: Stream[Int] => Stream[Int] = ints => ints.head#::fh((ints.tail) filter {i=>i%(i.toString.map(_.asDigit):\0)(_+_)==0}) + val fh: Stream[Int] => Stream[Int] = ints => + ints.head #:: fh((ints.tail) filter { i => i % (i.toString.map(_.asDigit) :\ 0)(_ + _) == 0 }) val harshads = fh(from(1)) println(harshads take 20 toList) - println(harshads filter (_>1000) head) + println(harshads filter (_ > 1000) head) } diff --git a/Task/Hash-from-two-arrays/00DESCRIPTION b/Task/Hash-from-two-arrays/00DESCRIPTION index 06b6894591..e46baf619e 100644 --- a/Task/Hash-from-two-arrays/00DESCRIPTION +++ b/Task/Hash-from-two-arrays/00DESCRIPTION @@ -1,3 +1,10 @@ -Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values) +{{omit from|BASIC}} +{{omit from|PowerBASIC}} +{{omit from|TI-83 BASIC}} +{{omit from|TI-89 BASIC}} + +Using two Arrays of equal length, create a Hash object +where the elements from one array (the keys) are linked +to the elements of the other (the values) Related task: [[Associative arrays/Creation]] diff --git a/Task/Hash-from-two-arrays/00META.yaml b/Task/Hash-from-two-arrays/00META.yaml index 659c8686af..cf16804e6f 100644 --- a/Task/Hash-from-two-arrays/00META.yaml +++ b/Task/Hash-from-two-arrays/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Data Structures note: Basic language learning diff --git a/Task/Hash-from-two-arrays/AWK/hash-from-two-arrays.awk b/Task/Hash-from-two-arrays/AWK/hash-from-two-arrays.awk index 95d0b8b809..25ad5a2976 100644 --- a/Task/Hash-from-two-arrays/AWK/hash-from-two-arrays.awk +++ b/Task/Hash-from-two-arrays/AWK/hash-from-two-arrays.awk @@ -1,8 +1,11 @@ -$ awk 'BEGIN{split("one two three",a); - split("1 2 3",b); - for(i=1;i in a;i++){c[a[i]]=b[i]}; - for(i in c)print i,c[i] - }' -three 3 -two 2 -one 1 +# usage: awk -v list1="i ii iii" -v list2="1 2 3" -f hash2.awk +BEGIN { + if(!list1) list1="one two three" + if(!list2) list2="1 2 3" + + split(list1, a); + split(list2, b); + for(i=1;i in a;i++) { c[a[i]] = b[i] }; + + for(i in c) print i,c[i] +} diff --git a/Task/Hash-from-two-arrays/D/hash-from-two-arrays.d b/Task/Hash-from-two-arrays/D/hash-from-two-arrays.d index 1a3c3f6165..75d4b18f61 100644 --- a/Task/Hash-from-two-arrays/D/hash-from-two-arrays.d +++ b/Task/Hash-from-two-arrays/D/hash-from-two-arrays.d @@ -1,5 +1,5 @@ -import std.array, std.range; - void main() { - auto hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray; + import std.array, std.range; + + immutable hash = ["a", "b", "c"].zip([1, 2, 3]).assocArray; } diff --git a/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays.js b/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-1.js similarity index 70% rename from Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays.js rename to Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-1.js index fad9b18300..6a5a22e307 100644 --- a/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays.js +++ b/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-1.js @@ -1,6 +1,6 @@ var keys = ['a', 'b', 'c']; var values = [1, 2, 3]; var map = {}; -for(var i in keys) { +for(var i = 0; i < keys.length; i += 1) { map[ keys[i] ] = values[i]; } diff --git a/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-2.js b/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-2.js new file mode 100644 index 0000000000..728ba5f6c7 --- /dev/null +++ b/Task/Hash-from-two-arrays/JavaScript/hash-from-two-arrays-2.js @@ -0,0 +1,7 @@ +function arrToObj(keys, vals) { + var map = {}; + keys.forEach(function (key, index) { + map[key] = val[index]; + }); + return map; +} diff --git a/Task/Hash-from-two-arrays/MATLAB/hash-from-two-arrays.m b/Task/Hash-from-two-arrays/MATLAB/hash-from-two-arrays.m new file mode 100644 index 0000000000..b324f081fa --- /dev/null +++ b/Task/Hash-from-two-arrays/MATLAB/hash-from-two-arrays.m @@ -0,0 +1,15 @@ +function s = StructFromArrays(allKeys, allVals) +% allKeys must be cell array of strings of valid field-names +% allVals can be cell array or array of numbers +% Assumes arrays are same size and valid types + s = struct; + if iscell(allVals) + for k = 1:length(allKeys) + s.(allKeys{k}) = allVals{k}; + end + else + for k = 1:length(allKeys) + s.(allKeys{k}) = allVals(k); + end + end +end diff --git a/Task/Hash-from-two-arrays/Maple/hash-from-two-arrays.maple b/Task/Hash-from-two-arrays/Maple/hash-from-two-arrays.maple new file mode 100644 index 0000000000..9d5fd2e17b --- /dev/null +++ b/Task/Hash-from-two-arrays/Maple/hash-from-two-arrays.maple @@ -0,0 +1,3 @@ +A := [1, 2, 3]; +B := ["one", "two", three"]; +T := table( zip( `=`, A, B ) ); diff --git a/Task/Hash-from-two-arrays/Oberon-2/hash-from-two-arrays.oberon-2 b/Task/Hash-from-two-arrays/Oberon-2/hash-from-two-arrays.oberon-2 new file mode 100644 index 0000000000..06cf56e455 --- /dev/null +++ b/Task/Hash-from-two-arrays/Oberon-2/hash-from-two-arrays.oberon-2 @@ -0,0 +1,35 @@ +MODULE HashFromArrays; +IMPORT + ADT:Dictionary, + Object:Boxed; +TYPE + Key= STRING; + Value= Boxed.LongInt; + + PROCEDURE Do; + VAR + a: ARRAY 128 OF Key; + b: ARRAY 128 OF Value; + hash: Dictionary.Dictionary(Key,Value); + i: INTEGER; + + BEGIN + hash := NEW(Dictionary.Dictionary(Key,Value)); + a[0] := "uno"; + a[1] := "dos"; + a[2] := "tres"; + a[3] := "cuatro"; + b[0] := Boxed.ParseLongInt("1"); + b[1] := Boxed.ParseLongInt("2"); + b[2] := Boxed.ParseLongInt("3"); + b[3] := Boxed.ParseLongInt("4"); + i := 0; + WHILE (i < LEN(a)) & (a[i] # NIL) DO + hash.Set(a[i],b[i]); + INC(i) + END; + + END Do; +BEGIN + Do; +END HashFromArrays. diff --git a/Task/Hash-from-two-arrays/REXX/hash-from-two-arrays.rexx b/Task/Hash-from-two-arrays/REXX/hash-from-two-arrays.rexx index 83542ddd14..4b8318759e 100644 --- a/Task/Hash-from-two-arrays/REXX/hash-from-two-arrays.rexx +++ b/Task/Hash-from-two-arrays/REXX/hash-from-two-arrays.rexx @@ -1,18 +1,18 @@ -/*REXX program demonstrate hashing of a stemmed array (from a key). */ +/*REXX program demonstrates hashing of a stemmed array (from a key). */ /*names of the 9 regular polygons*/ values='triangle quadrilateral pentagon hexagon heptagon octagon nonagon decagon dodecagon' keys ='thuhree vour phive sicks zeaven ate nein den duzun' - -/*superflous blanks added to humorous keys just 'cause it looks prettier*/ -call hash values,keys /*hash the keys to the values. */ -parse arg query . /*what was specified on cmd line.*/ -if query=='' then exit /*nothing, then let's leave Dodge*/ + /* [↑] superfluous blanks added to humorous */ + /* keys just because it looks prettier. */ +call hash values,keys /*nothing, then let's leave Dodge*/ /*hash the keys to the values. */ +parse arg query . /*get what was specified on C.L. */ +if query=='' then exit /*Nothing? Then leave Dodge City*/ pad=left('',30) /*used for padding the display. */ -say 'key:' query pad "value:" hash.query /*show & tell some stuff.*/ +say 'key:' query pad "value:" hash.query /*show some stuff.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────HASH subroutine─────────────────────*/ hash: procedure expose hash.; parse arg v,k,hash. - do j=1 until map=''; map=word(k,j) - hash.map=word(v,j) + do j=1 until map==''; map=word(k,j) + hash.map=word(v,j) end /*j*/ return diff --git a/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-1.rb b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-1.rb index 6d1d5d9f30..d12a9b7275 100644 --- a/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-1.rb +++ b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-1.rb @@ -1,12 +1,7 @@ -keys=['hal',666,[1,2,3]] -vals=['ibm','devil',123] +keys = ['hal',666,[1,2,3]] +vals = ['ibm','devil',123] -if RUBY_VERSION >= '1.8.7' - # Easy way, but needs Ruby 1.8.7 or later. - hash = Hash[keys.zip(vals)] -else - hash = keys.zip(vals).inject({}) {|h, kv| h.store(*kv); h } -end +hash = Hash[keys.zip(vals)] p hash # => {"hal"=>"ibm", 666=>"devil", [1, 2, 3]=>123} diff --git a/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-3.rb b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-3.rb new file mode 100644 index 0000000000..aa17e72cfe --- /dev/null +++ b/Task/Hash-from-two-arrays/Ruby/hash-from-two-arrays-3.rb @@ -0,0 +1,4 @@ +keys = ['hal', 666, [1,2,3]] +vals = ['ibm', 'devil', 123] + +keys.zip(vals).to_h diff --git a/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-1.txr b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-1.txr new file mode 100644 index 0000000000..5439da02ba --- /dev/null +++ b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-1.txr @@ -0,0 +1,2 @@ +$ txr -p '^#H(() ,*[zip #(a b c) #(1 2 3)])))' +#H(() (c 3) (b 2) (a 1)) diff --git a/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-2.txr b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-2.txr new file mode 100644 index 0000000000..d90ceea84d --- /dev/null +++ b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-2.txr @@ -0,0 +1,2 @@ +$ txr -p '(hash-construct nil [zip #(a b c) #(1 2 3)])))' +#H(() (c 3) (b 2) (a 1)) diff --git a/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-3.txr b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-3.txr new file mode 100644 index 0000000000..bbe0ccd0d9 --- /dev/null +++ b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays-3.txr @@ -0,0 +1,7 @@ +@(do + (defun hash-from-two (vec1 vec2 . hash-args) + (let ((table (hash . hash-args))) + (mapcar (do sethash table) vec1 vec2) + table)) + + (prinl (hash-from-two #(a b c) #(1 2 3)))) diff --git a/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays.txr b/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays.txr deleted file mode 100644 index b3a8674f87..0000000000 --- a/Task/Hash-from-two-arrays/TXR/hash-from-two-arrays.txr +++ /dev/null @@ -1,10 +0,0 @@ -@(do (defun hash-from-two (vec1 vec2 equal-based-p) - (let ((table (make-hash nil nil equal-based-p))) - (for ((i 0)) ((< i (length vec1)) table) ((inc i)) - (set (gethash table (vecref vec1 i) 0) - (vecref vec2 i)))))) -@(bind hash @(hash-from-two #(a b c) #(1 2 3) nil)) -@(bind (keys vals) @(let (k v) - (dohash (key val hash (list k v)) - (push key k) - (push val v)))) diff --git a/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-1.tcl b/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-1.tcl index 9b87add18c..28e6c4391d 100644 --- a/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-1.tcl +++ b/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-1.tcl @@ -1,4 +1,6 @@ -set keys [list fred bob joe] +set keys [list fred bob joe] set values [list barber plumber tailor] array set arr {} foreach a $keys b $values { set arr($a) $b } + +parray arr diff --git a/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-2.tcl b/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-2.tcl index 62d3a08d8f..4dd1713445 100644 --- a/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-2.tcl +++ b/Task/Hash-from-two-arrays/Tcl/hash-from-two-arrays-2.tcl @@ -1,3 +1,10 @@ +package require Tcl 8.5 + +set keys [list fred bob joe] +set values [list barber plumber tailor] + foreach a $keys b $values { dict set jobs $a $b } + +puts "jobs: [dict get $jobs]" diff --git a/Task/Hash-from-two-arrays/UNIX-Shell/hash-from-two-arrays.sh b/Task/Hash-from-two-arrays/UNIX-Shell/hash-from-two-arrays.sh new file mode 100644 index 0000000000..650ba3fbce --- /dev/null +++ b/Task/Hash-from-two-arrays/UNIX-Shell/hash-from-two-arrays.sh @@ -0,0 +1,11 @@ +keys=( foo bar baz ) +values=( 123 456 789 ) +declare -A hash + +for (( i = 0; i < ${#keys[@]}; i++ )); do + hash["${keys[i]}"]=${values[i]} +done + +for key in "${!hash[@]}"; do + printf "%s => %s\n" "$key" "${hash[$key]}" +done diff --git a/Task/Haversine-formula/00DESCRIPTION b/Task/Haversine-formula/00DESCRIPTION index 5b793aeb98..6e4fa4d0ed 100644 --- a/Task/Haversine-formula/00DESCRIPTION +++ b/Task/Haversine-formula/00DESCRIPTION @@ -1,6 +1,13 @@ -{{Wikipedia}}The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". +{{Wikipedia}}The '''haversine formula''' is an equation important in navigation, +giving great-circle distances between two points on a sphere +from their longitudes and latitudes. +It is a special case of a more general formula in spherical trigonometry, +the '''law of haversines''', relating the sides and angles of spherical "triangles". -'''Task:''' Implement a great-circle distance function, or use a library function, to show the great-circle distance between Nashville International Airport (BNA) in Nashville, TN, USA: N 36°7.2', W 86°40.2' (36.12, -86.67) and Los Angeles International Airport (LAX) in Los Angeles, CA, USA: N 33°56.4', W 118°24.0' (33.94, -118.40). +'''Task:''' Implement a great-circle distance function, or use a library function, +to show the great-circle distance between Nashville International Airport (BNA) +in Nashville, TN, USA: N 36°7.2', W 86°40.2' (36.12, -86.67) +and Los Angeles International Airport (LAX) in Los Angeles, CA, USA: N 33°56.4', W 118°24.0' (33.94, -118.40).
 User Kaimbridge clarified on the Talk page:
diff --git a/Task/Haversine-formula/ATS/haversine-formula.ats b/Task/Haversine-formula/ATS/haversine-formula.ats
new file mode 100644
index 0000000000..89a39e7d94
--- /dev/null
+++ b/Task/Haversine-formula/ATS/haversine-formula.ats
@@ -0,0 +1,36 @@
+#include
+"share/atspre_staload.hats"
+
+staload "libc/SATS/math.sats"
+staload _ = "libc/DATS/math.dats"
+staload "libc/SATS/stdio.sats"
+staload "libc/SATS/stdlib.sats"
+
+#define R 6372.8
+#define TO_RAD (3.1415926536 / 180)
+
+typedef d = double
+
+fun
+dist
+(
+  th1: d, ph1: d, th2: d, ph2: d
+) : d = let
+  val ph1 = ph1 - ph2
+  val ph1 = TO_RAD * ph1
+  val th1 = TO_RAD * th1
+  val th2 = TO_RAD * th2
+  val dz = sin(th1) - sin(th2)
+  val dx = cos(ph1) * cos(th1) - cos(th2)
+  val dy = sin(ph1) * cos(th1)
+in
+  asin(sqrt(dx*dx + dy*dy + dz*dz)/2)*2*R
+end // end of [dist]
+
+implement
+main0((*void*)) = let
+  val d = dist(36.12, ~86.67, 33.94, ~118.4);
+  /* Americans don't know kilometers */
+in
+  $extfcall(void, "printf", "dist: %.1f km (%.1f mi.)\n", d, d / 1.609344)
+end // end of [main0]
diff --git a/Task/Haversine-formula/CoffeeScript/haversine-formula.coffee b/Task/Haversine-formula/CoffeeScript/haversine-formula.coffee
new file mode 100644
index 0000000000..354891d2e6
--- /dev/null
+++ b/Task/Haversine-formula/CoffeeScript/haversine-formula.coffee
@@ -0,0 +1,10 @@
+haversine = (args...) ->
+  R = 6372.8; # km
+  radians = args.map (deg) -> deg/180.0 * Math.PI
+  lat1 = radians[0]; lon1 = radians[1]; lat2 = radians[2]; lon2 = radians[3]
+  dLat = lat2 - lat1
+  dLon = lon2 - lon1
+  a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.sin(dLon / 2) * Math.sin(dLon / 2) * Math.cos(lat1) * Math.cos(lat2)
+  R * 2 * Math.asin(Math.sqrt(a))
+
+console.log haversine(36.12, -86.67, 33.94, -118.40)
diff --git a/Task/Haversine-formula/D/haversine-formula-1.d b/Task/Haversine-formula/D/haversine-formula-1.d
index 01f7b2680c..56113f2fc6 100644
--- a/Task/Haversine-formula/D/haversine-formula-1.d
+++ b/Task/Haversine-formula/D/haversine-formula-1.d
@@ -1,9 +1,9 @@
 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;
+                       in real dth2, in real dph2)
+pure nothrow @nogc {
+    enum real R = 6371;
     enum real TO_RAD = PI / 180;
 
     alias imr = immutable real;
diff --git a/Task/Haversine-formula/D/haversine-formula-2.d b/Task/Haversine-formula/D/haversine-formula-2.d
index 68f08d3dce..f386c90841 100644
--- a/Task/Haversine-formula/D/haversine-formula-2.d
+++ b/Task/Haversine-formula/D/haversine-formula-2.d
@@ -1,24 +1,27 @@
 import std.stdio, std.math;
 
-real toRad(real degrees) {
+real toRad(in real degrees) pure nothrow @safe @nogc {
     return degrees * PI / 180;
 }
 
-real haversin(real theta) {
-    return (1 - cos(theta)) / 2;
+real haversin(in real theta) pure nothrow @safe @nogc {
+    return (1 - theta.cos) / 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));
+real greatCircleDistance(in real lat1, in real lng1,
+                         in real lat2, in real lng2,
+                         in real radius)
+pure nothrow @safe @nogc {
+    immutable h = haversin(lat2.toRad - lat1.toRad) +
+                  lat1.toRad.cos * lat2.toRad.cos *
+                  haversin(lng2.toRad - lng1.toRad);
+    return 2 * radius * h.sqrt.asin;
 }
 
 void main() {
-    const real earthRadius = 6372.8;   // average earth radius
+    enum real earthRadius = 6372.8L; // Average earth radius.
 
     writefln("Great circle distance: %.1f km",
-             greatCircleDistance(36.12, -86.67, 33.94, -118.4, earthRadius));
+             greatCircleDistance(36.12, -86.67, 33.94, -118.4,
+                                 earthRadius));
 }
diff --git a/Task/Haversine-formula/Fortran/haversine-formula.f b/Task/Haversine-formula/Fortran/haversine-formula.f
index 1cfa5bc33b..fa0a9c8436 100644
--- a/Task/Haversine-formula/Fortran/haversine-formula.f
+++ b/Task/Haversine-formula/Fortran/haversine-formula.f
@@ -27,7 +27,7 @@ contains
           lat1 = to_radian(deglat1)
           lat2 = to_radian(deglat2)
           a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2
-          c = 2*atan2(sqrt(a),sqrt(1-a))
+          c = 2*asin(sqrt(a))
           dist = radius*c
       end function haversine
 
diff --git a/Task/Haversine-formula/Haskell/haversine-formula.hs b/Task/Haversine-formula/Haskell/haversine-formula.hs
index 40cd59148b..3cd45d50f9 100644
--- a/Task/Haversine-formula/Haskell/haversine-formula.hs
+++ b/Task/Haversine-formula/Haskell/haversine-formula.hs
@@ -17,8 +17,8 @@ distDeg radius p1 p2 = distRad radius (deg2rad p1) (deg2rad p2)
   where deg2rad (t, u) = (d2r t, d2r u)
         d2r t = t * pi / 180
 
--- The approximate distance, in kilometers, between two points on Earth.  The
--- latitude and longtitude are assumed to be in degrees.
+-- The approximate distance, in kilometers, between two points on Earth.
+-- The latitude and longtitude are assumed to be in degrees.
 earthDist = distDeg 6372.8
 
 main = do
diff --git a/Task/Haversine-formula/JavaScript/haversine-formula.js b/Task/Haversine-formula/JavaScript/haversine-formula.js
new file mode 100644
index 0000000000..5caf2190d0
--- /dev/null
+++ b/Task/Haversine-formula/JavaScript/haversine-formula.js
@@ -0,0 +1,11 @@
+function haversine() {
+       var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; });
+       var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3];
+       var R = 6372.8; // km
+       var dLat = lat2 - lat1;
+       var dLon = lon2 - lon1;
+       var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2);
+       var c = 2 * Math.asin(Math.sqrt(a));
+       return R * c;
+}
+console.log(haversine(36.12, -86.67, 33.94, -118.40));
diff --git a/Task/Haversine-formula/MATLAB/haversine-formula.m b/Task/Haversine-formula/MATLAB/haversine-formula.m
index 9222ded026..0147d344c0 100644
--- a/Task/Haversine-formula/MATLAB/haversine-formula.m
+++ b/Task/Haversine-formula/MATLAB/haversine-formula.m
@@ -1,6 +1,6 @@
 function rad = radians(degree)
 % degrees to radians
-    rad = degree * pi / 180;
+    rad = degree .* pi / 180;
 end;
 
 function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
@@ -9,9 +9,9 @@ function [a,c,dlat,dlon]=haversine(lat1,lon1,lat2,lon2)
     dlon = radians(lon2-lon1);
     lat1 = radians(lat1);
     lat2 = radians(lat2);
-    a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2;
-    c = 2 * atan2(sqrt(a),sqrt(1-a));
-    printf("distance: %.4f km\n",6372.8 * c);
-end
+    a = (sin(dlat./2)).^2 + cos(lat1) .* cos(lat2) .* (sin(dlon./2)).^2;
+    c = 2 .* asin(sqrt(a));
+    arrayfun(@(x) printf("distance: %.4f km\n",6372.8 * x), c);
+end;
 
 [a,c,dlat,dlon] = haversine(36.12,-86.67,33.94,-118.40); % BNA to LAX
diff --git a/Task/Haversine-formula/Oberon-2/haversine-formula.oberon-2 b/Task/Haversine-formula/Oberon-2/haversine-formula.oberon-2
new file mode 100644
index 0000000000..d701f67998
--- /dev/null
+++ b/Task/Haversine-formula/Oberon-2/haversine-formula.oberon-2
@@ -0,0 +1,27 @@
+MODULE Haversines;
+IMPORT
+  LRealMath,
+  Out;
+
+  PROCEDURE Distance(lat1,lon1,lat2,lon2: LONGREAL): LONGREAL;
+  CONST
+    r = 6372.8D0; (* Earth radius as LONGREAL *)
+    to_radians = LRealMath.pi / 180.0D0;
+  VAR
+    d,ph1,th1,th2: LONGREAL;
+    dz,dx,dy: LONGREAL;
+  BEGIN
+    d := lon1 - lon2;
+    ph1 := d * to_radians;
+    th1 := lat1 * to_radians;
+    th2 := lat2 * to_radians;
+
+    dz := LRealMath.sin(th1) - LRealMath.sin(th2);
+    dx := LRealMath.cos(ph1) * LRealMath.cos(th1) - LRealMath.cos(th2);
+    dy := LRealMath.sin(ph1) * LRealMath.cos(th1);
+
+    RETURN LRealMath.arcsin(LRealMath.sqrt(LRealMath.power(dx,2.0) + LRealMath.power(dy,2.0) + LRealMath.power(dz,2.0)) / 2.0) * 2.0 * r;
+  END Distance;
+BEGIN
+  Out.LongRealFix(Distance(36.12,-86.67,33.94,-118.4),6,10);Out.Ln
+END Haversines.
diff --git a/Task/Haversine-formula/PL-I/haversine-formula.pli b/Task/Haversine-formula/PL-I/haversine-formula.pli
index 93dfd579e5..42aedda282 100644
--- a/Task/Haversine-formula/PL-I/haversine-formula.pli
+++ b/Task/Haversine-formula/PL-I/haversine-formula.pli
@@ -22,7 +22,7 @@ haversine: procedure (deglat1, deglon1, deglat2, deglon2) returns (float);
    lat1 = degrees_to_radians(deglat1);
    lat2 = degrees_to_radians(deglat2);
    a = (sin(dlat/2))**2 + cos(lat1)*cos(lat2)*(sin(dlon/2))**2;
-   c = 2*atan(sqrt(a),sqrt(1-a));
+   c = 2*asin(sqrt(a));
    return ( radius*c );
 end haversine;
 
diff --git a/Task/Haversine-formula/Python/haversine-formula.py b/Task/Haversine-formula/Python/haversine-formula.py
index 29516ad46a..6c6d387553 100644
--- a/Task/Haversine-formula/Python/haversine-formula.py
+++ b/Task/Haversine-formula/Python/haversine-formula.py
@@ -1,18 +1,16 @@
-from math import radians, sin, cos, sqrt, atan2
+from math import radians, sin, cos, sqrt, asin
 
 def haversine(lat1, lon1, lat2, lon2):
 
-  R = 6372.8
-
-# In kilometers
+  R = 6372.8 # Earth radius in kilometers
 
   dLat = radians(lat2 - lat1)
   dLon = radians(lon2 - lon1)
   lat1 = radians(lat1)
   lat2 = radians(lat2)
 
-  a = sin(dLat/2.)*sin(dLat/2.) + sin(dLon/2.)*sin(dLon/2.)*cos(lat1)*cos(lat2)
-  c = 2.*atan2(sqrt(a),sqrt(1-a))
+  a = sin(dLat/2)**2 + cos(lat1)*cos(lat2)*sin(dLon/2)**2
+  c = 2*asin(sqrt(a))
 
   return R * c
 
diff --git a/Task/Haversine-formula/REXX/haversine-formula.rexx b/Task/Haversine-formula/REXX/haversine-formula-1.rexx
similarity index 64%
rename from Task/Haversine-formula/REXX/haversine-formula.rexx
rename to Task/Haversine-formula/REXX/haversine-formula-1.rexx
index 5f3c432de7..fb8c6e1d08 100644
--- a/Task/Haversine-formula/REXX/haversine-formula.rexx
+++ b/Task/Haversine-formula/REXX/haversine-formula-1.rexx
@@ -63,27 +63,3 @@ $pi: return ,
 '3.1415926535897932384626433832795028841971693993751058209749445923078'||,
 '164062862089986280348253421170679821480865132823066470938446095505822'||,
 '3172535940812848111745028410270193852110555964462294895493038196'
-/*┌───────────────────────────────────────────────────────────────────────┐
-  │ A note on built-in functions.  REXX doesn't have a lot of mathmatical │
-  │ or  (particularly) trigomentric  functions,  so REXX programmers have │
-  │ to write their own.  Usually, this is done once, or most likely,  one │
-  │ is borrowed from another program.  Knowing this, the one that is used │
-  │ has a lot of boilerplate in it.  Once coded and throughly debugged, I │
-  │ put those commonly-used subroutines into the  "1-line sub"  section.  │
-  │                                                                       │
-  │ Programming note:  the  "general 1-line"  subroutines are taken from  │
-  │ other programs that I wrote, but I broke up their one line of source  │
-  │ so it can be viewed without shifting the viewing window.              │
-  │                                                                       │
-  │ The  "er 81"  [which won't happen here]  just shows an error telling  │
-  │ the legal range for  ARCxxx  functions   (in this case:  -1 ──► +1).  │
-  │                                                                       │
-  │ Similarly,  the   SQRT   function checks for a negative argument      │
-  │ [which again, won't happen here].                                     │
-  │                                                                       │
-  │ The pi constant (as used here) is actually a much more robust function│
-  │ and will return up to one million digits in the real version.         │
-  │                                                                       │
-  │ One bad side effect is that, like a automobile without a hood, you see│
-  │ all the dirty stuff going on.    Also, don't visit a sausage factory. │
-  └───────────────────────────────────────────────────────────────────────┘ */
diff --git a/Task/Haversine-formula/REXX/haversine-formula-2.rexx b/Task/Haversine-formula/REXX/haversine-formula-2.rexx
new file mode 100644
index 0000000000..b8d0790a04
--- /dev/null
+++ b/Task/Haversine-formula/REXX/haversine-formula-2.rexx
@@ -0,0 +1,24 @@
+  ┌───────────────────────────────────────────────────────────────────────┐
+  │ A note on built-in functions.  REXX doesn't have a lot of mathmatical │
+  │ or  (particularly) trigomentric  functions,  so REXX programmers have │
+  │ to write their own.  Usually, this is done once, or most likely,  one │
+  │ is borrowed from another program.  Knowing this, the one that is used │
+  │ has a lot of boilerplate in it.  Once coded and throughly debugged, I │
+  │ put those commonly-used subroutines into the  "1-line sub"  section.  │
+  │                                                                       │
+  │ Programming note:  the  "general 1-line"  subroutines are taken from  │
+  │ other programs that I wrote, but I broke up their one line of source  │
+  │ so it can be viewed without shifting the viewing window.              │
+  │                                                                       │
+  │ The  "er 81"  [which won't happen here]  just shows an error telling  │
+  │ the legal range for  ARCxxx  functions   (in this case:  -1 ──► +1).  │
+  │                                                                       │
+  │ Similarly,  the   SQRT   function checks for a negative argument      │
+  │ [which again, won't happen here].                                     │
+  │                                                                       │
+  │ The pi constant (as used here) is actually a much more robust function│
+  │ and will return up to one million digits in the real version.         │
+  │                                                                       │
+  │ One bad side effect is that, like a automobile without a hood, you see│
+  │ all the dirty stuff going on.    Also, don't visit a sausage factory. │
+  └───────────────────────────────────────────────────────────────────────┘
diff --git a/Task/Haversine-formula/SAS/haversine-formula.sas b/Task/Haversine-formula/SAS/haversine-formula.sas
new file mode 100644
index 0000000000..26750283f4
--- /dev/null
+++ b/Task/Haversine-formula/SAS/haversine-formula.sas
@@ -0,0 +1,51 @@
+options minoperator;
+
+%macro haver(lat1, long1, lat2, long2, type=D, dist=K);
+
+	%if %upcase(&type) in (D DEG DEGREE DEGREES) %then %do;
+		%let convert = constant('PI')/180;
+		%end;
+	%else %if %upcase(&type) in (R RAD RADIAN RADIANS) %then %do;
+		%let convert = 1;
+		%end;
+	%else %do;
+		%put ERROR - Enter RADIANS or DEGREES for type.;
+		%goto exit;
+		%end;
+
+	%if %upcase(&dist) in (M MILE MILES) %then %do;
+		%let distrat = 1.609344;
+		%end;
+	%else %if %upcase(&dist) in (K KM KILOMETER KILOMETERS) %then %do;
+		%let distrat = 1;
+		%end;
+	%else %do;
+		%put ERROR - Enter M on KM for dist;
+		%goto exit;
+		%end;
+		
+		data _null_;
+			convert = &convert;
+			lat1 = &lat1 * convert;
+			lat2 = &lat2 * convert;
+			long1 = &long1 * convert;
+			long2 = &long2 * convert;
+
+			diff1 = lat2 - lat1;
+			diff2 = long2 - long1;
+
+			part1 = sin(diff1/2)**2;
+			part2 = cos(lat1)*cos(lat2);
+			part3 = sin(diff2/2)**2;
+
+			root = sqrt(part1 + part2*part3);
+
+			dist = 2 * 6372.8 / &distrat * arsin(root);
+
+			put "Distance is " dist "%upcase(&dist)";
+		run;
+
+	%exit:
+%mend;
+
+%haver(36.12, -86.67, 33.94, -118.40);
diff --git a/Task/Haversine-formula/UBASIC/haversine-formula.ubasic b/Task/Haversine-formula/UBASIC/haversine-formula.ubasic
new file mode 100644
index 0000000000..aa38110362
--- /dev/null
+++ b/Task/Haversine-formula/UBASIC/haversine-formula.ubasic
@@ -0,0 +1,13 @@
+   10  Point 7    'Sets decimal display to 32 places (0+.1^56)
+   20  Rf=#pi/180 'Degree -> Radian Conversion
+  100 ?Using(,7),.DxH(36+7.2/60,-(86+40.2/60),33+56.4/60,-(118+24/60));" km"
+  999  End
+ 1000 '*** Haversine Distance Function ***
+ 1010 .DxH(Lat_s,Long_s,Lat_f,Long_f)
+ 1020  L_s=Lat_s*rf:L_f=Lat_f*rf:LD=L_f-L_s:MD=(Long_f-Long_s)*rf
+ 1030  Return(12745.6*asin( (sin(.5*LD)^2+cos(L_s)*cos(L_f)*sin(.5*MD)^2)^.5))
+ '' ''
+
+ Run
+  2887.2599506 km
+ OK
diff --git a/Task/Hello-world-Graphical/00META.yaml b/Task/Hello-world-Graphical/00META.yaml
index 04942ee47c..da9464e4c2 100644
--- a/Task/Hello-world-Graphical/00META.yaml
+++ b/Task/Hello-world-Graphical/00META.yaml
@@ -1,6 +1,7 @@
 ---
 category:
 - Basic language learning
+- Simple
 note: GUI
 requires:
 - Graphics
diff --git a/Task/Hello-world-Graphical/ATS/hello-world-graphical.ats b/Task/Hello-world-Graphical/ATS/hello-world-graphical.ats
index 6632bb1ebe..f943908308 100644
--- a/Task/Hello-world-Graphical/ATS/hello-world-graphical.ats
+++ b/Task/Hello-world-Graphical/ATS/hello-world-graphical.ats
@@ -1,35 +1,101 @@
+//
+#include
+"share/atspre_define.hats"
+#include
+"share/atspre_staload.hats"
+//
+(* ****** ****** *)
+
+staload UN = $UNSAFE
+
+(* ****** ****** *)
+
+staload "{$GLIB}/SATS/glib.sats"
+
+(* ****** ****** *)
+
+staload "{$GTK}/SATS/gdk.sats"
+staload "{$GTK}/SATS/gtk.sats"
+staload "{$GLIB}/SATS/glib-object.sats"
+
+(* ****** ****** *)
+
 %{^
-extern
-ats_void_type
-mainats (ats_int_type argc, ats_ptr_type argv);
-%}
+typedef char **charpp ;
+%} ;
+abstype charpp = $extype"charpp"
 
-staload "contrib/glib/SATS/glib.sats"
-staload "contrib/glib/SATS/glib-object.sats"
-staload "contrib/GTK/SATS/gtk.sats"
+(* ****** ****** *)
 
-extern fun main1 (): void = "main1"
+fun hello
+(
+  widget: !GtkWidget1, _: gpointer
+) : void = print ("Goodbye, world!\n")
 
-implement main1 () = () where {
-  val window = gtk_window_new (GTK_WINDOW_TOPLEVEL)
-  val (pf | title) = gstring_of_string ("Goodbye, World!")
-  val () = gtk_window_set_title (window, title)
-  prval () = pf (title)
-  val _sid = g_signal_connect
-    (window, (gsignal)"delete-event", (G_CALLBACK)gtk_main_quit, (gpointer)null)
-  val () = gtk_widget_show (window)
-  val () = gtk_main ()
-  val () = gtk_widget_destroy0 (window)
-}
+fun on_delete_event
+(
+  widget: !GtkWidget1
+, event: &GdkEvent, udata: gpointer
+) : gboolean = let
+  val () = print ("delete event occurred\n")
+in
+  GTRUE // handling of delete-event is finished
+end // end of [on_delete_event]
 
-implement main_dummy () = ()
+fun on_destroy
+  (widget: !GtkWidget1, _: gpointer): void = gtk_main_quit ()
+// end of [on_destroy]
 
-%{$
-ats_void_type
-mainats (ats_int_type argc, ats_ptr_type argv)
+(* ****** ****** *)
+
+macdef nullp = the_null_ptr
+
+(* ****** ****** *)
+
+implement
+main0 (argc, argv) =
 {
-  gtk_init ((int*)&argc, (char***)&argv);
-  main1 ();
-  return;
-}
-%}
+//
+var argc: int = argc
+var argv: charpp = $UN.castvwtp1{charpp}(argv)
+//
+val () = $extfcall (void, "gtk_init", addr@(argc), addr@(argv))
+//
+val window =
+  gtk_window_new (GTK_WINDOW_TOPLEVEL)
+val () = assertloc (ptrcast(window) > 0)
+//
+val _(*id*) =
+g_signal_connect (
+  window, (gsignal)"destroy", (G_CALLBACK)on_destroy, (gpointer)nullp
+) (* end of [val] *)
+val _(*id*) =
+g_signal_connect (
+  window, (gsignal)"delete_event", (G_CALLBACK)on_delete_event, (gpointer)nullp
+) (* end of [val] *)
+//
+val () = gtk_container_set_border_width (window, (guint)10)
+val button = gtk_button_new_with_label (gstring("Goodbye, world!"))
+val () = assertloc (ptrcast(button) > 0)
+//
+val () = gtk_widget_show (button)
+val () = gtk_container_add (window, button)
+val () = gtk_widget_show (window)
+//
+val _(*id*) =
+g_signal_connect
+(
+  button, (gsignal)"clicked", (G_CALLBACK)hello, (gpointer)nullp
+)
+val _(*id*) =
+g_signal_connect_swapped
+(
+  button, (gsignal)"clicked", (G_CALLBACK)gtk_widget_destroy, window
+)
+//
+val () = g_object_unref (button)
+val () = g_object_unref (window) // ref-count becomes 1!
+//
+val ((*void*)) = gtk_main ()
+//
+} (* end of [main0] *)
diff --git a/Task/Hello-world-Graphical/AWK/hello-world-graphical.awk b/Task/Hello-world-Graphical/AWK/hello-world-graphical.awk
new file mode 100644
index 0000000000..2e0bb87b4c
--- /dev/null
+++ b/Task/Hello-world-Graphical/AWK/hello-world-graphical.awk
@@ -0,0 +1,2 @@
+# Usage:  awk -f hi_win.awk
+BEGIN { system("msg * Goodbye, Msgbox !") }
diff --git a/Task/Hello-world-Graphical/C++/hello-world-graphical-3.cpp b/Task/Hello-world-Graphical/C++/hello-world-graphical-3.cpp
index 98a6970bf7..ad1a3f45bf 100644
--- a/Task/Hello-world-Graphical/C++/hello-world-graphical-3.cpp
+++ b/Task/Hello-world-Graphical/C++/hello-world-graphical-3.cpp
@@ -4,7 +4,7 @@
 
 int main(int argc, char **argv) {
   Fl_Window *window = new Fl_Window(300,180);
-  Fl_Box *box = new Fl_Box(20,40,260,100,"Goodby, World!");
+  Fl_Box *box = new Fl_Box(20,40,260,100,"Goodbye, World!");
   box->box(FL_UP_BOX);
   box->labelsize(36);
   box->labelfont(FL_BOLD+FL_ITALIC);
diff --git a/Task/Hello-world-Graphical/Forth/hello-world-graphical.fth b/Task/Hello-world-Graphical/Forth/hello-world-graphical-1.fth
similarity index 100%
rename from Task/Hello-world-Graphical/Forth/hello-world-graphical.fth
rename to Task/Hello-world-Graphical/Forth/hello-world-graphical-1.fth
diff --git a/Task/Hello-world-Graphical/Forth/hello-world-graphical-2.fth b/Task/Hello-world-Graphical/Forth/hello-world-graphical-2.fth
new file mode 100644
index 0000000000..e23c0fccda
--- /dev/null
+++ b/Task/Hello-world-Graphical/Forth/hello-world-graphical-2.fth
@@ -0,0 +1 @@
+ s" Goodbye, World!" MsgBox
diff --git a/Task/Hello-world-Graphical/Lua/hello-world-graphical.lua b/Task/Hello-world-Graphical/Lua/hello-world-graphical-1.lua
similarity index 100%
rename from Task/Hello-world-Graphical/Lua/hello-world-graphical.lua
rename to Task/Hello-world-Graphical/Lua/hello-world-graphical-1.lua
diff --git a/Task/Hello-world-Graphical/Lua/hello-world-graphical-2.lua b/Task/Hello-world-Graphical/Lua/hello-world-graphical-2.lua
new file mode 100644
index 0000000000..badc1a107c
--- /dev/null
+++ b/Task/Hello-world-Graphical/Lua/hello-world-graphical-2.lua
@@ -0,0 +1,3 @@
+function love.draw()
+    love.graphics.print("Goodbye, World!", 400, 300)
+end
diff --git a/Task/Hello-world-Graphical/Perl/hello-world-graphical-4.pl b/Task/Hello-world-Graphical/Perl/hello-world-graphical-4.pl
index d20da06afb..189a6f625f 100644
--- a/Task/Hello-world-Graphical/Perl/hello-world-graphical-4.pl
+++ b/Task/Hello-world-Graphical/Perl/hello-world-graphical-4.pl
@@ -1,5 +1,8 @@
 use strict;
 use warnings;
-use XUL::Gui;
+use QtGui4;
 
-display Label 'Goodbye, World!';
+my $app = Qt::Application(\@ARGV);
+my $label = Qt::Label('Goodbye, World');
+$label->show;
+exit $app->exec;
diff --git a/Task/Hello-world-Graphical/Perl/hello-world-graphical-5.pl b/Task/Hello-world-Graphical/Perl/hello-world-graphical-5.pl
index 260ed3d35e..d20da06afb 100644
--- a/Task/Hello-world-Graphical/Perl/hello-world-graphical-5.pl
+++ b/Task/Hello-world-Graphical/Perl/hello-world-graphical-5.pl
@@ -2,6 +2,4 @@ use strict;
 use warnings;
 use XUL::Gui;
 
-display Button
-    label => 'Goodbye, World!',
-    oncommand => sub {quit};
+display Label 'Goodbye, World!';
diff --git a/Task/Hello-world-Graphical/Perl/hello-world-graphical-6.pl b/Task/Hello-world-Graphical/Perl/hello-world-graphical-6.pl
new file mode 100644
index 0000000000..260ed3d35e
--- /dev/null
+++ b/Task/Hello-world-Graphical/Perl/hello-world-graphical-6.pl
@@ -0,0 +1,7 @@
+use strict;
+use warnings;
+use XUL::Gui;
+
+display Button
+    label => 'Goodbye, World!',
+    oncommand => sub {quit};
diff --git a/Task/Hello-world-Graphical/Python/hello-world-graphical-5.py b/Task/Hello-world-Graphical/Python/hello-world-graphical-5.py
index de1eb03618..57de9d4d5d 100644
--- a/Task/Hello-world-Graphical/Python/hello-world-graphical-5.py
+++ b/Task/Hello-world-Graphical/Python/hello-world-graphical-5.py
@@ -1,6 +1,53 @@
-import wx
+# HelloWorld for VPython - HaJo Gurt - 2014-09-20
+from visual import *
 
-app = wx.App(False)
-frame = wx.Frame(None, wx.ID_ANY, "Hello, World")
-frame.Show(True)
-app.MainLoop()
+scene.title = "VPython Demo"
+scene.background = color.gray(0.2)
+
+scene.width  = 600
+scene.height = 400
+scene.range  = 4
+#scene.autocenter = True
+
+S = sphere(pos=(0,0,0), radius=1, material=materials.earth)
+rot=0.005
+
+txPos=(0, 1.2, 0)
+
+from visual.text import *
+# Old 3D text machinery (pre-Visual 5.3): numbers and uppercase letters only:
+T1 = text(pos=txPos, string='HELLO', color=color.red, depth=0.3, justify='center')
+
+import vis
+# new text object, can render text from any font (default: "sans") :
+T2 = vis.text(pos=txPos, text="Goodbye", color=color.green, depth=-0.3, align='center')
+T2.visible=False
+
+Lbl_w = label(pos=(0,0,0), text='World', color=color.cyan,
+              xoffset=80, yoffset=-40)     # in screen-pixels
+
+L1 = label(pos=(0,-1.5,0), text='Drag with right mousebutton to rotate view',   box=0)
+L2 = label(pos=(0,-1.9,0), text='Drag up+down with middle mousebutton to zoom', box=0)
+L3 = label(pos=(0,-2.3,0), text='Left-click to change', color=color.orange,     box=0)
+
+print "Hello World"     # Console
+
+
+cCount = 0
+def change():
+    global rot, cCount
+    cCount=cCount+1
+    print "change:", cCount
+    rot=-rot
+    if T1.visible:
+        T1.visible=False
+        T2.visible=True
+    else:
+        T1.visible=True
+        T2.visible=False
+
+scene.bind( 'click', change )
+
+while True:
+  rate(100)
+  S.rotate( angle=rot, axis=(0,1,0) )
diff --git a/Task/Hello-world-Graphical/Python/hello-world-graphical-6.py b/Task/Hello-world-Graphical/Python/hello-world-graphical-6.py
new file mode 100644
index 0000000000..de1eb03618
--- /dev/null
+++ b/Task/Hello-world-Graphical/Python/hello-world-graphical-6.py
@@ -0,0 +1,6 @@
+import wx
+
+app = wx.App(False)
+frame = wx.Frame(None, wx.ID_ANY, "Hello, World")
+frame.Show(True)
+app.MainLoop()
diff --git a/Task/Hello-world-Graphical/REALbasic/hello-world-graphical.realbasic b/Task/Hello-world-Graphical/REALbasic/hello-world-graphical.realbasic
new file mode 100644
index 0000000000..10aac5feb8
--- /dev/null
+++ b/Task/Hello-world-Graphical/REALbasic/hello-world-graphical.realbasic
@@ -0,0 +1 @@
+MsgBox("Goodbye, World!")
diff --git a/Task/Hello-world-Graphical/VBScript/hello-world-graphical.vb b/Task/Hello-world-Graphical/VBScript/hello-world-graphical.vb
new file mode 100644
index 0000000000..10aac5feb8
--- /dev/null
+++ b/Task/Hello-world-Graphical/VBScript/hello-world-graphical.vb
@@ -0,0 +1 @@
+MsgBox("Goodbye, World!")
diff --git a/Task/Hello-world-Graphical/XSLT/hello-world-graphical-1.xslt b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-1.xslt
new file mode 100644
index 0000000000..33cab23eea
--- /dev/null
+++ b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-1.xslt
@@ -0,0 +1,21 @@
+
+	
+	
+		
+		
+			
+			
+			
+				
+				
+			
+		
+	
+
diff --git a/Task/Hello-world-Graphical/XSLT/hello-world-graphical-2.xslt b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-2.xslt
new file mode 100644
index 0000000000..5bf9017dab
--- /dev/null
+++ b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-2.xslt
@@ -0,0 +1 @@
+Goodbye, World!
diff --git a/Task/Hello-world-Graphical/XSLT/hello-world-graphical-3.xslt b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-3.xslt
new file mode 100644
index 0000000000..6f488e072e
--- /dev/null
+++ b/Task/Hello-world-Graphical/XSLT/hello-world-graphical-3.xslt
@@ -0,0 +1,8 @@
+
+	
+	
+	Goodbye, World!
+
diff --git a/Task/Hello-world-Line-printer/00DESCRIPTION b/Task/Hello-world-Line-printer/00DESCRIPTION
index 22f4289b73..61a0487a52 100644
--- a/Task/Hello-world-Line-printer/00DESCRIPTION
+++ b/Task/Hello-world-Line-printer/00DESCRIPTION
@@ -1,3 +1,8 @@
+{{omit from|PARI/GP}}
+{{omit from|ML/I|Does not have printer-related functions}}
+
 Cause a line printer attached to the computer to print a line containing the message Hello World!
 
-'''Note:''' A line printer is not the same as standard output. A [[wp:line printer|line printer]] was an older-style printer which prints one line at a time to a continuous ream of paper. With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
+'''Note:''' A line printer is not the same as standard output.
+A [[wp:line printer|line printer]] was an older-style printer which prints one line at a time to a continuous ream of paper.
+With some systems, a line printer can be any device attached to an appropriate port (such as a parallel port).
diff --git a/Task/Hello-world-Line-printer/00META.yaml b/Task/Hello-world-Line-printer/00META.yaml
new file mode 100644
index 0000000000..3ceef0c01e
--- /dev/null
+++ b/Task/Hello-world-Line-printer/00META.yaml
@@ -0,0 +1,4 @@
+---
+category:
+- Hardware
+- Printer
diff --git a/Task/Hello-world-Line-printer/C-sharp/hello-world-line-printer.cs b/Task/Hello-world-Line-printer/C-sharp/hello-world-line-printer.cs
new file mode 100644
index 0000000000..f5cb05b163
--- /dev/null
+++ b/Task/Hello-world-Line-printer/C-sharp/hello-world-line-printer.cs
@@ -0,0 +1,60 @@
+[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
+public class DOCINFOA
+{
+    [MarshalAs(UnmanagedType.LPStr)]
+    public string pDocName;
+    [MarshalAs(UnmanagedType.LPStr)]
+    public string pOutputFile;
+    [MarshalAs(UnmanagedType.LPStr)]
+    public string pDataType;
+}
+
+[DllImport("winspool.Drv", EntryPoint = "OpenPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool OpenPrinter([MarshalAs(UnmanagedType.LPStr)] string szPrinter, out IntPtr hPrinter, IntPtr pd);
+
+[DllImport("winspool.Drv", EntryPoint = "StartDocPrinterA", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In, MarshalAs(UnmanagedType.LPStruct)] DOCINFOA di);
+
+[DllImport("winspool.Drv", EntryPoint = "StartPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool StartPagePrinter(IntPtr hPrinter);
+
+[DllImport("winspool.Drv", EntryPoint = "EndPagePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool EndPagePrinter(IntPtr hPrinter);
+
+[DllImport("winspool.Drv", EntryPoint = "EndDocPrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool EndDocPrinter(IntPtr hPrinter);
+
+[DllImport("winspool.Drv", EntryPoint = "ClosePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool ClosePrinter(IntPtr hPrinter);
+
+[DllImport("winspool.Drv", EntryPoint = "WritePrinter", CharSet = CharSet.Ansi, ExactSpelling = true)]
+public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, Int32 dwCount, out Int32 dwWritten);
+
+public void HelloWorld()
+{
+    IntPtr hPrinter;
+    bool openSuccessful = OpenPrinter("My Printer", out hPrinter, IntPtr.Zero);
+    if (openSuccessful)
+    {
+        DOCINFOA docInfo = new DOCINFOA();
+        docInfo.pDocName = "Hello World Example";
+        docInfo.pOutputFile = null;
+        docInfo.pDataType = "RAW";
+
+        if (StartDocPrinter(hPrinter, 1, docInfo))
+        {
+            StartPagePrinter(hPrinter);
+
+            const string helloWorld = "Hello World!";
+            IntPtr buf = Marshal.StringToCoTaskMemAnsi(helloWorld);
+
+            int bytesWritten;
+            WritePrinter(hPrinter, buf, helloWorld.Length, out bytesWritten);
+
+            Marshal.FreeCoTaskMem(buf);
+        }
+        if (EndPagePrinter(hPrinter))
+            if (EndDocPrinter(hPrinter))
+                ClosePrinter(hPrinter);
+    }
+}
diff --git a/Task/Hello-world-Line-printer/Icon/hello-world-line-printer.icon b/Task/Hello-world-Line-printer/Icon/hello-world-line-printer.icon
new file mode 100644
index 0000000000..3db2b2c92d
--- /dev/null
+++ b/Task/Hello-world-Line-printer/Icon/hello-world-line-printer.icon
@@ -0,0 +1,3 @@
+procedure main()
+    write(open("/dev/lp0","w"),"Hello, world!")
+end
diff --git a/Task/Hello-world-Line-printer/PL-I/hello-world-line-printer.pli b/Task/Hello-world-Line-printer/PL-I/hello-world-line-printer.pli
index 34c25352a9..97ae755be7 100644
--- a/Task/Hello-world-Line-printer/PL-I/hello-world-line-printer.pli
+++ b/Task/Hello-world-Line-printer/PL-I/hello-world-line-printer.pli
@@ -1,3 +1,3 @@
-hello: procedure options (main);
-   put ('Hello world.');
+hello: procedure options(main);
+   put skip list('Hello world.');
 end hello;
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
index b10abe9054..98bfab7ad7 100644
--- 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
@@ -1,12 +1,15 @@
 import java.awt.print.PrinterException
-import javax.swing.JTextPane
+import scala.swing.TextArea
 
-object LinePrinter0 extends App {
-  val show = false
-  val text = """Hello, World! in printing."""
+object LinePrinter extends App {
+  val (show, context) = (false, "Hello, World!")
   try // Default Helvetica, 12p
-    new JTextPane() { setText(text) }.print(null, null, show, null, null, show)
+    new TextArea(context) {
+      append(" in printing.")
+      peer.print(null, null, show, null, null, show)
+    }
   catch {
     case ex: PrinterException => ex.getMessage()
   }
+  println("Document printed.")
 }
diff --git a/Task/Hello-world-Line-printer/Seed7/hello-world-line-printer.seed7 b/Task/Hello-world-Line-printer/Seed7/hello-world-line-printer.seed7
new file mode 100644
index 0000000000..a645be7898
--- /dev/null
+++ b/Task/Hello-world-Line-printer/Seed7/hello-world-line-printer.seed7
@@ -0,0 +1,10 @@
+$ include "seed7_05.s7i";
+
+const proc: main is func
+  local
+    var file: lp is STD_NULL;
+  begin
+    lp := open("/dev/lp0", "w");
+    writeln(lp, "Hello world!");
+    close(lp);
+  end func;
diff --git a/Task/Hello-world-Line-printer/Simula/hello-world-line-printer.simula b/Task/Hello-world-Line-printer/Simula/hello-world-line-printer.simula
new file mode 100644
index 0000000000..5ac2d90b7e
--- /dev/null
+++ b/Task/Hello-world-Line-printer/Simula/hello-world-line-printer.simula
@@ -0,0 +1,4 @@
+BEGIN
+   OUTTEXT("Hello World!");
+   OUTIMAGE
+END
diff --git a/Task/Hello-world-Newline-omission/ATS/hello-world-newline-omission.ats b/Task/Hello-world-Newline-omission/ATS/hello-world-newline-omission.ats
index 78de4a035e..1b25a84227 100644
--- a/Task/Hello-world-Newline-omission/ATS/hello-world-newline-omission.ats
+++ b/Task/Hello-world-Newline-omission/ATS/hello-world-newline-omission.ats
@@ -1 +1 @@
-implement main () = print "Goodbye, World!"
+implement main0 () = print "Goodbye, World!"
diff --git a/Task/Hello-world-Newline-omission/C++/hello-world-newline-omission.cpp b/Task/Hello-world-Newline-omission/C++/hello-world-newline-omission.cpp
index c00bf0dc09..79ff580b39 100644
--- a/Task/Hello-world-Newline-omission/C++/hello-world-newline-omission.cpp
+++ b/Task/Hello-world-Newline-omission/C++/hello-world-newline-omission.cpp
@@ -1,5 +1,6 @@
-#include 
+#include 
 
-int main(int argc, char *argv[]) {
+int main() {
   std::cout << "Goodbye, World!";
+  return 0;
 }
diff --git a/Task/Hello-world-Newline-omission/C/hello-world-newline-omission.c b/Task/Hello-world-Newline-omission/C/hello-world-newline-omission.c
index f20a3152e5..2c4228692f 100644
--- a/Task/Hello-world-Newline-omission/C/hello-world-newline-omission.c
+++ b/Task/Hello-world-Newline-omission/C/hello-world-newline-omission.c
@@ -1,4 +1,5 @@
 #include 
+#include 
 
 int main(int argc, char *argv[]) {
   (void) printf("Goodbye, World!");    /* No automatic newline */
diff --git a/Task/Hello-world-Newline-omission/Dylan.NET/hello-world-newline-omission-2.dylan.net b/Task/Hello-world-Newline-omission/Dylan.NET/hello-world-newline-omission-2.dylan.net
index 10814d63fc..ad9f184766 100644
--- a/Task/Hello-world-Newline-omission/Dylan.NET/hello-world-newline-omission-2.dylan.net
+++ b/Task/Hello-world-Newline-omission/Dylan.NET/hello-world-newline-omission-2.dylan.net
@@ -1,13 +1,13 @@
-//compile using the new dylan.NET v, 11.3.1.3 or later
+//compile using the new dylan.NET v, 11.5.1.2 or later
 //use mono to run the compiler
 #refstdasm mscorlib.dll
 
 import System
 
 assembly gdbyeex exe
-ver 1.1.0.0
+ver 1.2.0.0
 
-class public auto ansi Module1
+class public Program
 
    method public static void main()
       Console::Write("Goodbye, World!")
diff --git a/Task/Hello-world-Newline-omission/Elixir/hello-world-newline-omission.elixir b/Task/Hello-world-Newline-omission/Elixir/hello-world-newline-omission.elixir
new file mode 100644
index 0000000000..d3f29a0347
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Elixir/hello-world-newline-omission.elixir
@@ -0,0 +1 @@
+IO.write "Goodbye, World!"
diff --git a/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-1.falcon b/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-1.falcon
new file mode 100644
index 0000000000..b4f3181031
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-1.falcon
@@ -0,0 +1 @@
+print("Goodbye, World!")
diff --git a/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-2.falcon b/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-2.falcon
new file mode 100644
index 0000000000..e4a8b90448
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Falcon/hello-world-newline-omission-2.falcon
@@ -0,0 +1 @@
+>> "Goodbye, World!"
diff --git a/Task/Hello-world-Newline-omission/OOC/hello-world-newline-omission.ooc b/Task/Hello-world-Newline-omission/OOC/hello-world-newline-omission.ooc
new file mode 100644
index 0000000000..2a851c5f2f
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/OOC/hello-world-newline-omission.ooc
@@ -0,0 +1,3 @@
+main: func {
+  "Goodbye, World!" print()
+}
diff --git a/Task/Hello-world-Newline-omission/Oberon-2/hello-world-newline-omission.oberon-2 b/Task/Hello-world-Newline-omission/Oberon-2/hello-world-newline-omission.oberon-2
new file mode 100644
index 0000000000..7ee6f92bda
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Oberon-2/hello-world-newline-omission.oberon-2
@@ -0,0 +1,5 @@
+MODULE HelloWorld;
+IMPORT Out;
+BEGIN
+  Out.String("Hello World")
+END HelloWorld.
diff --git a/Task/Hello-world-Newline-omission/REBOL/hello-world-newline-omission.rebol b/Task/Hello-world-Newline-omission/REBOL/hello-world-newline-omission.rebol
new file mode 100644
index 0000000000..c79081c4ad
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/REBOL/hello-world-newline-omission.rebol
@@ -0,0 +1 @@
+prin "Goodbye, World!"
diff --git a/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust b/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust
new file mode 100644
index 0000000000..4ad3588602
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Rust/hello-world-newline-omission.rust
@@ -0,0 +1,3 @@
+fn main () {
+  print!("Goodbye, World!");
+}
diff --git a/Task/Hello-world-Newline-omission/Smalltalk/hello-world-newline-omission.st b/Task/Hello-world-Newline-omission/Smalltalk/hello-world-newline-omission.st
new file mode 100644
index 0000000000..ae3cca1225
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Smalltalk/hello-world-newline-omission.st
@@ -0,0 +1 @@
+Transcript show: 'Hello world'.
diff --git a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql
new file mode 100644
index 0000000000..4920e98776
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-1.sql
@@ -0,0 +1 @@
+ PRINT 'Goodby, World!'
diff --git a/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql
new file mode 100644
index 0000000000..e5f6de5326
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Transact-SQL/hello-world-newline-omission-2.sql
@@ -0,0 +1 @@
+ select 'Goodby, World!'
diff --git a/Task/Hello-world-Newline-omission/Vim-Script/hello-world-newline-omission.vim b/Task/Hello-world-Newline-omission/Vim-Script/hello-world-newline-omission.vim
new file mode 100644
index 0000000000..9f91926e13
--- /dev/null
+++ b/Task/Hello-world-Newline-omission/Vim-Script/hello-world-newline-omission.vim
@@ -0,0 +1 @@
+echon "Goodbye, World!"
diff --git a/Task/Hello-world-Standard-error/00DESCRIPTION b/Task/Hello-world-Standard-error/00DESCRIPTION
index d595c6ffbe..e7d19a7c7d 100644
--- a/Task/Hello-world-Standard-error/00DESCRIPTION
+++ b/Task/Hello-world-Standard-error/00DESCRIPTION
@@ -1,3 +1,21 @@
-{{selection|Short Circuit|Console Program Basics}}A common practice in computing is to send error messages to a different output stream than [[User Output - text|normal text console messages]]. The normal messages print to what is called "standard output" or "standard out". The error messages print to "standard error". This separation can be used to redirect error messages to a different place than normal messages.
+ {{selection|Short Circuit|Console Program Basics}}
+[[Category:Streams]]
+{{omit from|Applesoft BASIC}}
+{{omit from|bc|Always prints to standard output.}}
+{{omit from|Brainf***}}
+{{omit from|dc|Always prints to standard output.}}
+{{omit from|GUISS|Cannot customize error messages}}
+{{omit from|Integer BASIC}}
+{{omit from|TI-83 BASIC|Same reason as TI-89.}}
+{{omit from|TI-89 BASIC|no analogue to stderr, unless you count graph display vs. program IO}}
+{{omit from|Unlambda|No concept of standard error (or alternate output streams in general).}}
+
+A common practice in computing is to send error messages
+to a different output stream than [[User Output - text|normal text console messages]].
+
+The normal messages print to what is called "standard output" or "standard out".
+The error messages print to "standard error".
+
+This separation can be used to redirect error messages to a different place than normal messages.
 
 Show how to print a message to standard error by printing "Goodbye, World!" on that stream.
diff --git a/Task/Hello-world-Standard-error/ATS/hello-world-standard-error.ats b/Task/Hello-world-Standard-error/ATS/hello-world-standard-error.ats
index 8a8a439936..64ce7152de 100644
--- a/Task/Hello-world-Standard-error/ATS/hello-world-standard-error.ats
+++ b/Task/Hello-world-Standard-error/ATS/hello-world-standard-error.ats
@@ -1 +1 @@
-implement main () = fprint (stderr_ref, "Goodbye, World!\n")
+implement main0 () = fprint (stderr_ref, "Goodbye, World!\n")
diff --git a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp
index b4b871c450..9326f1286f 100644
--- a/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp
+++ b/Task/Hello-world-Standard-error/C++/hello-world-standard-error.cpp
@@ -1,10 +1,5 @@
 #include 
 
-using std::cerr;
-using std::endl;
-
 int main () {
-  cerr << "Goodbye, World!" << endl;
-
-  return cerr.bad();
+  std::cerr << "Goodbye, World!\n";
 }
diff --git a/Task/Hello-world-Standard-error/Dylan.NET/hello-world-standard-error-2.dylan.net b/Task/Hello-world-Standard-error/Dylan.NET/hello-world-standard-error-2.dylan.net
index 7c9f2baa63..9df8145202 100644
--- a/Task/Hello-world-Standard-error/Dylan.NET/hello-world-standard-error-2.dylan.net
+++ b/Task/Hello-world-Standard-error/Dylan.NET/hello-world-standard-error-2.dylan.net
@@ -1,4 +1,4 @@
-//compile using the new dylan.NET v, 11.2.8.2 or later
+//compile using the new dylan.NET v, 11.5.1.2 or later
 //use mono to run the compiler
 #refstdasm mscorlib.dll
 
@@ -7,7 +7,7 @@ import System
 assembly stderrex exe
 ver 1.1.0.0
 
-class public auto ansi Module1
+class public Program
 
    method public static void main()
       Console::get_Error()::WriteLine("Goodbye World!")
diff --git a/Task/Hello-world-Standard-error/Frink/hello-world-standard-error.frink b/Task/Hello-world-Standard-error/Frink/hello-world-standard-error.frink
new file mode 100644
index 0000000000..95f0609585
--- /dev/null
+++ b/Task/Hello-world-Standard-error/Frink/hello-world-standard-error.frink
@@ -0,0 +1 @@
+staticJava["java.lang.System","err"].println["Goodbye, World!"]
diff --git a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-2.rexx b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-2.rexx
index 2d546acdaa..fb0ce5439f 100644
--- a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-2.rexx
+++ b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-2.rexx
@@ -1 +1 @@
-say "Goodbye, World!"
+call lineout 'STDERR', "Goodbye, World!"
diff --git a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-3.rexx b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-3.rexx
index 989e73ff9e..cc51ebfe35 100644
--- a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-3.rexx
+++ b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-3.rexx
@@ -1 +1,2 @@
-call lineout ,"Goodbye, World!"
+msgText = 'Goodbye, World!'
+call charout 'STDERR', msgText
diff --git a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx
index 442de3fc47..5d1d4f463b 100644
--- a/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx
+++ b/Task/Hello-world-Standard-error/REXX/hello-world-standard-error-4.rexx
@@ -1 +1,14 @@
-call charout ,"Goodbye, World!"
+/* REXX ---------------------------------------------------------------
+* 07.07.2014 Walter Pachl
+* enter the appropriate command shown in a command prompt.
+*    "rexx serr.rex 2>err.txt"
+* or "regina serr.rex 2>err.txt"
+* 2>file will redirect the stderr stream to the specified file.
+* I don't know any other way to catch this stream
+*--------------------------------------------------------------------*/
+Parse Version v
+Say v
+Call lineout 'stderr','Good bye, world!'
+Call lineout ,'Hello, world!'
+Say 'and this is the error output:'
+'type err.txt'
diff --git a/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust
new file mode 100644
index 0000000000..929082b400
--- /dev/null
+++ b/Task/Hello-world-Standard-error/Rust/hello-world-standard-error.rust
@@ -0,0 +1,7 @@
+#![allow(unused_must_use)]
+use std::io;
+
+fn main() {
+    let mut stderr = io::stderr();
+    stderr.write(bytes!("Goodbye, World!\n"));
+}
diff --git a/Task/Hello-world-Standard-error/Transact-SQL/hello-world-standard-error.sql b/Task/Hello-world-Standard-error/Transact-SQL/hello-world-standard-error.sql
new file mode 100644
index 0000000000..544b3c54e4
--- /dev/null
+++ b/Task/Hello-world-Standard-error/Transact-SQL/hello-world-standard-error.sql
@@ -0,0 +1 @@
+ RAISERROR 'Goodbye, World!', 16, 1
diff --git a/Task/Hello-world-Text/00DESCRIPTION b/Task/Hello-world-Text/00DESCRIPTION
index ce80791888..135fd15110 100644
--- a/Task/Hello-world-Text/00DESCRIPTION
+++ b/Task/Hello-world-Text/00DESCRIPTION
@@ -1,4 +1,6 @@
-{{selection|Short Circuit|Console Program Basics}}In this User Output task, the goal is to display the string "Goodbye, World!" [sic] on a text console.
+{{selection|Short Circuit|Console Program Basics}}
+[[Category:Simple]]
+In this User Output task, the goal is to display the string "Goodbye, World!" [sic] on a text console.
 
 '''See also'''
 * [[Hello world/Graphical]]
diff --git a/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360 b/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360
new file mode 100644
index 0000000000..08160f58b9
--- /dev/null
+++ b/Task/Hello-world-Text/360-Assembly/hello-world-text-1.360
@@ -0,0 +1,8 @@
+         LA    1,MSGAREA     Point Register 1 to message area
+         SVC   35            Invoke SVC 35 (Write to Operator)
+         BR    14            Return
+MSGAREA  EQU   *             Message Area
+         DC    AL2(19)       Total area length = 19 (Prefix length:4 + Data Length:15)
+         DC    XL2'00'       2 bytes binary of zeros
+         DC    C'Goodbye, World!'  Text to be written to system console
+         END
diff --git a/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360 b/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360
new file mode 100644
index 0000000000..fd4f81d79f
--- /dev/null
+++ b/Task/Hello-world-Text/360-Assembly/hello-world-text-2.360
@@ -0,0 +1,3 @@
+         WTO   'Goodbye, World!'
+         BR    14            Return
+         END
diff --git a/Task/Hello-world-Text/360-Assembly/hello-world-text.360 b/Task/Hello-world-Text/360-Assembly/hello-world-text.360
deleted file mode 100644
index a46d728e82..0000000000
--- a/Task/Hello-world-Text/360-Assembly/hello-world-text.360
+++ /dev/null
@@ -1,16 +0,0 @@
-{using native SVC (Supervisor Call) to write to system console}
-
- LA  1,MSGAREA Point Register 1 to message area
- SVC 35        Invoke SVC 35 (Write to Operator)
- BR  14        Return
-MSGAREA EQU *  Message Area
- DC AL2(19)    Total area length = 19 (Prefix length:4 + Data Length:15)
- DC XL2'00'    2 bytes binary of zeros
- DC C'Goodbye, World!'  Text to be written to system console
- END
-
-{using WTO Macro to generate SVC 35 and message area}
-
- WTO 'Goodbye, World!'
- BR  14        Return
- END
diff --git a/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg b/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg
new file mode 100644
index 0000000000..4ccd0c9ee1
--- /dev/null
+++ b/Task/Hello-world-Text/ALGOL-60/hello-world-text.alg
@@ -0,0 +1,4 @@
+'BEGIN'
+    OUTSTRING(1,'('GOODBYE, WORLD!')');
+    SYSACT(1,14,1)
+'END'
diff --git a/Task/Hello-world-Text/ATS/hello-world-text.ats b/Task/Hello-world-Text/ATS/hello-world-text.ats
index 88d840645a..cad6057a6a 100644
--- a/Task/Hello-world-Text/ATS/hello-world-text.ats
+++ b/Task/Hello-world-Text/ATS/hello-world-text.ats
@@ -1 +1 @@
-implement main () = print "Goodbye, World!\n"
+implement main0 () = print "Goodbye, World!\n"
diff --git a/Task/Hello-world-Text/Aime/hello-world-text-1.aime b/Task/Hello-world-Text/Aime/hello-world-text-1.aime
index a1bbc80dd8..076aad6f4a 100644
--- a/Task/Hello-world-Text/Aime/hello-world-text-1.aime
+++ b/Task/Hello-world-Text/Aime/hello-world-text-1.aime
@@ -1 +1 @@
-o_text("GOODBYE, WORLD!\n");
+o_text("Goodbye, World!\n");
diff --git a/Task/Hello-world-Text/Aime/hello-world-text-2.aime b/Task/Hello-world-Text/Aime/hello-world-text-2.aime
index d508bdf296..913833c72c 100644
--- a/Task/Hello-world-Text/Aime/hello-world-text-2.aime
+++ b/Task/Hello-world-Text/Aime/hello-world-text-2.aime
@@ -1,7 +1,7 @@
 integer
 main(void)
 {
-    o_text("GOODBYE, WORLD!\n");
+    o_text("Goodbye, World!\n");
 
     return 0;
 }
diff --git a/Task/Hello-world-Text/Babel/hello-world-text.pb b/Task/Hello-world-Text/Babel/hello-world-text.pb
index 9a0d73ace9..99e79ce0f5 100644
--- a/Task/Hello-world-Text/Babel/hello-world-text.pb
+++ b/Task/Hello-world-Text/Babel/hello-world-text.pb
@@ -1 +1 @@
-main: { "Goodbye, World!" << }
+((main { "Goodbye, World!" << }))
diff --git a/Task/Hello-world-Text/C++/hello-world-text.cpp b/Task/Hello-world-Text/C++/hello-world-text.cpp
index 11018fdb05..705a64a10d 100644
--- a/Task/Hello-world-Text/C++/hello-world-text.cpp
+++ b/Task/Hello-world-Text/C++/hello-world-text.cpp
@@ -1,6 +1,5 @@
 #include 
 
 int main () {
-  std::cout << "Goodbye, World!" << std::endl;
-  return std::cout.bad();
+  std::cout << "Goodbye, World!\n";
 }
diff --git a/Task/Hello-world-Text/C/hello-world-text-3.c b/Task/Hello-world-Text/C/hello-world-text-3.c
new file mode 100644
index 0000000000..9b0dbef888
--- /dev/null
+++ b/Task/Hello-world-Text/C/hello-world-text-3.c
@@ -0,0 +1,7 @@
+#include
+
+int main()
+{
+  printf("\nGoodbye, World!");
+  return 0;
+}
diff --git a/Task/Hello-world-Text/CoffeeScript/hello-world-text.coffee b/Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee
similarity index 100%
rename from Task/Hello-world-Text/CoffeeScript/hello-world-text.coffee
rename to Task/Hello-world-Text/CoffeeScript/hello-world-text-1.coffee
diff --git a/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee b/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee
new file mode 100644
index 0000000000..a9f594ad30
--- /dev/null
+++ b/Task/Hello-world-Text/CoffeeScript/hello-world-text-2.coffee
@@ -0,0 +1 @@
+print "Goodbye, World!"
diff --git a/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net b/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net
index a85b9bb090..bcc476172c 100644
--- a/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net
+++ b/Task/Hello-world-Text/Dylan.NET/hello-world-text-2.dylan.net
@@ -1,4 +1,4 @@
-//compile using the new dylan.NET v, 11.2.8.2 or later
+//compile using the new dylan.NET v, 11.5.1.2 or later
 //use mono to run the compiler
 #refstdasm mscorlib.dll
 
@@ -7,7 +7,7 @@ import System
 assembly helloworld exe
 ver 1.2.0.0
 
-class public auto ansi Module1
+class public Program
 
    method public static void main()
       Console::WriteLine("Goodbye, World!")
diff --git a/Task/Hello-world-Text/Elena/hello-world-text-2.elena b/Task/Hello-world-Text/Elena/hello-world-text-2.elena
index 491fb4dca1..643327edad 100644
--- a/Task/Hello-world-Text/Elena/hello-world-text-2.elena
+++ b/Task/Hello-world-Text/Elena/hello-world-text-2.elena
@@ -1,6 +1,5 @@
 [[
-   #config vm_console #start;
-   #define start ::= "?" system'console .eval&writeLine($literal);
+   #define start ::= "?" < system'console.eval&writeLine( > $literal < ) >;
 ]]
 
-? "Hello World"
+? "Hello World!!"
diff --git a/Task/Hello-world-Text/Elixir/hello-world-text.elixir b/Task/Hello-world-Text/Elixir/hello-world-text.elixir
new file mode 100644
index 0000000000..c26d110595
--- /dev/null
+++ b/Task/Hello-world-Text/Elixir/hello-world-text.elixir
@@ -0,0 +1 @@
+IO.puts "Goodbye, World!"
diff --git a/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon b/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon
new file mode 100644
index 0000000000..2494f2a107
--- /dev/null
+++ b/Task/Hello-world-Text/Falcon/hello-world-text-1.falcon
@@ -0,0 +1 @@
+printl("Goodbye, World!")
diff --git a/Task/Hello-world-Text/Falcon/hello-world-text.falcon b/Task/Hello-world-Text/Falcon/hello-world-text-2.falcon
similarity index 100%
rename from Task/Hello-world-Text/Falcon/hello-world-text.falcon
rename to Task/Hello-world-Text/Falcon/hello-world-text-2.falcon
diff --git a/Task/Hello-world-Text/Fexl/hello-world-text.fexl b/Task/Hello-world-Text/Fexl/hello-world-text.fexl
index 3d0d857ec7..2d546acdaa 100644
--- a/Task/Hello-world-Text/Fexl/hello-world-text.fexl
+++ b/Task/Hello-world-Text/Fexl/hello-world-text.fexl
@@ -1 +1 @@
-print "Goodbye, World!";nl;
+say "Goodbye, World!"
diff --git a/Task/Hello-world-Text/GML/hello-world-text.gml b/Task/Hello-world-Text/GML/hello-world-text.gml
new file mode 100644
index 0000000000..31d117624e
--- /dev/null
+++ b/Task/Hello-world-Text/GML/hello-world-text.gml
@@ -0,0 +1,2 @@
+show_message("Goodbye, World!"); // displays a pop-up message
+show_debug_message("Goodbye, World!"); // sends text to the debug log or IDE
diff --git a/Task/Hello-world-Text/Gentee/hello-world-text.gentee b/Task/Hello-world-Text/Gentee/hello-world-text.gentee
new file mode 100644
index 0000000000..03575e8d23
--- /dev/null
+++ b/Task/Hello-world-Text/Gentee/hello-world-text.gentee
@@ -0,0 +1,4 @@
+func hello 
+{ + print("Goodbye, World!") +} diff --git a/Task/Hello-world-Text/Glee/hello-world-text.glee b/Task/Hello-world-Text/Glee/hello-world-text-1.glee similarity index 100% rename from Task/Hello-world-Text/Glee/hello-world-text.glee rename to Task/Hello-world-Text/Glee/hello-world-text-1.glee diff --git a/Task/Hello-world-Text/Glee/hello-world-text-2.glee b/Task/Hello-world-Text/Glee/hello-world-text-2.glee new file mode 100644 index 0000000000..ff76edc774 --- /dev/null +++ b/Task/Hello-world-Text/Glee/hello-world-text-2.glee @@ -0,0 +1 @@ +'Goodbye, World!' diff --git a/Task/Hello-world-Text/Glee/hello-world-text-3.glee b/Task/Hello-world-Text/Glee/hello-world-text-3.glee new file mode 100644 index 0000000000..aaa4b2518c --- /dev/null +++ b/Task/Hello-world-Text/Glee/hello-world-text-3.glee @@ -0,0 +1 @@ + '"Goodbye,World!"' diff --git a/Task/Hello-world-Text/Glee/hello-world-text-4.glee b/Task/Hello-world-Text/Glee/hello-world-text-4.glee new file mode 100644 index 0000000000..d381e500e6 --- /dev/null +++ b/Task/Hello-world-Text/Glee/hello-world-text-4.glee @@ -0,0 +1 @@ + "'Goodbye,World!'" diff --git a/Task/Hello-world-Text/Go/hello-world-text.go b/Task/Hello-world-Text/Go/hello-world-text.go index 4bd996ffba..bb44e8b725 100644 --- a/Task/Hello-world-Text/Go/hello-world-text.go +++ b/Task/Hello-world-Text/Go/hello-world-text.go @@ -1,3 +1,5 @@ package main -func main() { println("Goodbye, World!") } +import "fmt" + +func main() { fmt.Println("Goodbye, World!") } diff --git a/Task/Hello-world-Text/Haxe/hello-world-text.haxe b/Task/Hello-world-Text/Haxe/hello-world-text.haxe new file mode 100644 index 0000000000..f2c4a774ba --- /dev/null +++ b/Task/Hello-world-Text/Haxe/hello-world-text.haxe @@ -0,0 +1 @@ +trace("Goodbye, World!"); diff --git a/Task/Hello-world-Text/OOC/hello-world-text.ooc b/Task/Hello-world-Text/OOC/hello-world-text-1.ooc similarity index 100% rename from Task/Hello-world-Text/OOC/hello-world-text.ooc rename to Task/Hello-world-Text/OOC/hello-world-text-1.ooc diff --git a/Task/Hello-world-Text/OOC/hello-world-text-2.ooc b/Task/Hello-world-Text/OOC/hello-world-text-2.ooc new file mode 100644 index 0000000000..fb973c0dd9 --- /dev/null +++ b/Task/Hello-world-Text/OOC/hello-world-text-2.ooc @@ -0,0 +1,3 @@ +main: func { + println("Goodbye, World!") +} diff --git a/Task/Hello-world-Text/PL-I/hello-world-text.pli b/Task/Hello-world-Text/PL-I/hello-world-text.pli index 9e3eb79492..2e8a4f8e4e 100644 --- a/Task/Hello-world-Text/PL-I/hello-world-text.pli +++ b/Task/Hello-world-Text/PL-I/hello-world-text.pli @@ -1 +1,3 @@ -put ('Goodbye, World!'); +goodbye:proc options(main); + put list('Goodbye, World!'); +end goodbye; diff --git a/Task/Hello-world-Text/Ruby/hello-world-text-3.rb b/Task/Hello-world-Text/Ruby/hello-world-text-3.rb new file mode 100644 index 0000000000..26f1aea355 --- /dev/null +++ b/Task/Hello-world-Text/Ruby/hello-world-text-3.rb @@ -0,0 +1 @@ + STDOUT.write "Goodbye, World!\n" diff --git a/Task/Hello-world-Text/Rust/hello-world-text.rust b/Task/Hello-world-Text/Rust/hello-world-text.rust index e79210c5ef..5de77e6a8c 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() { - println("Goodbye, World!"); +fn main () { + println!("Goodbye, World!"); } diff --git a/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc b/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc new file mode 100644 index 0000000000..6661f252a4 --- /dev/null +++ b/Task/Hello-world-Text/SPARC-Assembly/hello-world-text.sparc @@ -0,0 +1,16 @@ + .section ".text" + .global _start +_start: + mov 4,%g1 ! 4 is SYS_write + mov 1,%o0 ! 1 is stdout + set .msg,%o1 ! pointer to buffer + mov (.msgend-.msg),%o2 ! length + ta 8 + + mov 1,%g1 ! 1 is SYS_exit + clr %o0 ! return status is 0 + ta 8 + +.msg: + .ascii "Goodbye, world!\n" +.msgend: diff --git a/Task/Hello-world-Text/Scheme/hello-world-text-4.ss b/Task/Hello-world-Text/Scheme/hello-world-text-4.ss new file mode 100644 index 0000000000..1ef3d1da78 --- /dev/null +++ b/Task/Hello-world-Text/Scheme/hello-world-text-4.ss @@ -0,0 +1,4 @@ +(import (scheme base) + (scheme write)) +(display "Hello, world!") +(newline) diff --git a/Task/Hello-world-Text/Simula/hello-world-text.simula b/Task/Hello-world-Text/Simula/hello-world-text.simula new file mode 100644 index 0000000000..c3e21c1749 --- /dev/null +++ b/Task/Hello-world-Text/Simula/hello-world-text.simula @@ -0,0 +1,4 @@ +BEGIN + OUTTEXT("Goodbye, World!"); + OUTIMAGE +END diff --git a/Task/Hello-world-Text/Vim-Script/hello-world-text.vim b/Task/Hello-world-Text/Vim-Script/hello-world-text.vim new file mode 100644 index 0000000000..4e4bcd978f --- /dev/null +++ b/Task/Hello-world-Text/Vim-Script/hello-world-text.vim @@ -0,0 +1 @@ +echo "Goodbye, World!\n" diff --git a/Task/Hello-world-Web-server/00DESCRIPTION b/Task/Hello-world-Web-server/00DESCRIPTION index 667642b316..fe46d63d0c 100644 --- a/Task/Hello-world-Web-server/00DESCRIPTION +++ b/Task/Hello-world-Web-server/00DESCRIPTION @@ -1,5 +1,18 @@ -The browser is the new [[GUI]]! +{{omit from|GUISS}} +{{omit from|Locomotive Basic|No sockets}} +{{omit from|Lotus 123 Macro Scripting}} +{{omit from|Maxima}} +{{omit from|ML/I|No sockets}} +{{omit from|Retro}} +{{omit from|TI-83 BASIC}} +{{omit from|ZX Spectrum Basic|No sockets}} -The task is to serve our standard text "Goodbye, World!" to http://localhost:8080/ so that it can be viewed with a web browser. The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. +The browser is the new [[GUI]] ! -Note that starting a web browser or opening a new window with this URL is not part of the task. Additionally, it is permissible to serve the provided page as a plain text file (there is no requirement to serve properly formatted [[HTML]] here). The browser will generally do the right thing with simple text like this. +The task is to serve our standard text "Goodbye, World!" to http://localhost:8080/ so that it can be viewed with a web browser.
+The provided solution must start or implement a server that accepts multiple client connections and serves text as requested. + +Note that starting a web browser or opening a new window with this URL +is not part of the task.
+Additionally, it is permissible to serve the provided page as a plain text file (there is no requirement to serve properly formatted [[HTML]] here). +The browser will generally do the right thing with simple text like this. diff --git a/Task/Hello-world-Web-server/00META.yaml b/Task/Hello-world-Web-server/00META.yaml index 688669690e..81cae82865 100644 --- a/Task/Hello-world-Web-server/00META.yaml +++ b/Task/Hello-world-Web-server/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Web note: Networking and Web Interaction diff --git a/Task/Hello-world-Web-server/C/hello-world-web-server.c b/Task/Hello-world-Web-server/C/hello-world-web-server.c index d6201c0ece..16dd5bb8a9 100644 --- a/Task/Hello-world-Web-server/C/hello-world-web-server.c +++ b/Task/Hello-world-Web-server/C/hello-world-web-server.c @@ -10,7 +10,7 @@ char response[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n\r\n" -"Bye-bye baby bye-bye" +"Bye-bye baby bye-bye" "" diff --git a/Task/Hello-world-Web-server/Clojure/hello-world-web-server.clj b/Task/Hello-world-Web-server/Clojure/hello-world-web-server.clj new file mode 100644 index 0000000000..4753e47f8c --- /dev/null +++ b/Task/Hello-world-Web-server/Clojure/hello-world-web-server.clj @@ -0,0 +1,12 @@ +(ns goodbye-world.handler + (:require [compojure.core :refer :all] + [compojure.handler :as handler] + [compojure.route :as route])) + +(defroutes app-routes + (GET "/" [] "Goodbye, World!") + (route/resources "/") + (route/not-found "Not Found")) + +(def app + (handler/site app-routes)) 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 index 35a9c51fce..241cad5bd0 100644 --- 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 @@ -19,19 +19,20 @@ (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 + (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/Rust/hello-world-web-server.rust b/Task/Hello-world-Web-server/Rust/hello-world-web-server.rust new file mode 100644 index 0000000000..88b15098c9 --- /dev/null +++ b/Task/Hello-world-Web-server/Rust/hello-world-web-server.rust @@ -0,0 +1,28 @@ +use std::io::net::tcp::{TcpListener, TcpStream}; +use std::io::net::ip::{Ipv4Addr, SocketAddr}; +use std::io::{Acceptor, Listener}; + +fn handle_client(mut stream: TcpStream) { + let response = bytes!("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n\r\nBye-bye baby bye-bye

Goodbye, world!

\r\n"); + match stream.write(response) { + Ok(()) => println!("Response send!"), + Err(e) => println!("Failed sending response: {}!", e), + } + drop(stream); +} + +fn main() { + let addr = SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8080 }; + let listener = TcpListener::bind(addr).unwrap(); + + let mut acceptor = listener.listen(); + println!("Listening for connections on port {}", addr.port); + + for stream in acceptor.incoming() { + spawn(proc() { + handle_client(stream.unwrap()); + }) + } + + drop(acceptor); +} diff --git a/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server.st b/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-1.st similarity index 100% rename from Task/Hello-world-Web-server/Smalltalk/hello-world-web-server.st rename to Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-1.st diff --git a/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-2.st b/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-2.st new file mode 100644 index 0000000000..2f1ff7a434 --- /dev/null +++ b/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-2.st @@ -0,0 +1,3 @@ +(ZnServer startDefaultOn: 1701) + onRequestRespond: [ :request | + ZnResponse ok: (ZnEntity text: 'Hello World!') ]. diff --git a/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-3.st b/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-3.st new file mode 100644 index 0000000000..ddf326fcc2 --- /dev/null +++ b/Task/Hello-world-Web-server/Smalltalk/hello-world-web-server-3.st @@ -0,0 +1 @@ +ZnServer stopDefault. diff --git a/Task/Hello-world-Web-server/Tcl/hello-world-web-server.tcl b/Task/Hello-world-Web-server/Tcl/hello-world-web-server-1.tcl similarity index 100% rename from Task/Hello-world-Web-server/Tcl/hello-world-web-server.tcl rename to Task/Hello-world-Web-server/Tcl/hello-world-web-server-1.tcl diff --git a/Task/Hello-world-Web-server/Tcl/hello-world-web-server-2.tcl b/Task/Hello-world-Web-server/Tcl/hello-world-web-server-2.tcl new file mode 100644 index 0000000000..add6223d45 --- /dev/null +++ b/Task/Hello-world-Web-server/Tcl/hello-world-web-server-2.tcl @@ -0,0 +1,8 @@ +set s [socket stream.server 127.0.0.1:8080] +$s readable { + set client [$s accept] + $client puts "HTTP/1.1 200 OK\nConnection: close\nContent-Type: text/plain\n" + $client puts "Hello, World!\n" + $client close +} +vwait done diff --git a/Task/Hello-world-Web-server/UNIX-Shell/hello-world-web-server.sh b/Task/Hello-world-Web-server/UNIX-Shell/hello-world-web-server.sh new file mode 100644 index 0000000000..3dc8e8765c --- /dev/null +++ b/Task/Hello-world-Web-server/UNIX-Shell/hello-world-web-server.sh @@ -0,0 +1 @@ +while true; do { echo -e 'HTTP/1.1 200 OK\r\n'; echo 'Hello, World!'; } | nc -l 8080; done diff --git a/Task/Here-document/00DESCRIPTION b/Task/Here-document/00DESCRIPTION index f5ff9ffd7c..b95c50e04f 100644 --- a/Task/Here-document/00DESCRIPTION +++ b/Task/Here-document/00DESCRIPTION @@ -1,4 +1,13 @@ {{omit from|BBC BASIC}} -A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used a here document is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the textblock. +{{omit from|Déjà Vu}} +{{omit from|Gambas}} +{{omit from|GW-BASIC}} +{{omit from|MATLAB|MATLAB has no multiline string literal functionality}} + +A here document (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. + +Depending on the language being used a here document is constructed using a command followed by "<<" (or some other symbol) followed by a token string. + +The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the textblock. The task is to demonstrate the use of here documents within the language. diff --git a/Task/Here-document/00META.yaml b/Task/Here-document/00META.yaml new file mode 100644 index 0000000000..7ce58b5b90 --- /dev/null +++ b/Task/Here-document/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Syntax elements diff --git a/Task/Here-document/C++/here-document.cpp b/Task/Here-document/C++/here-document.cpp new file mode 100644 index 0000000000..01e8beb910 --- /dev/null +++ b/Task/Here-document/C++/here-document.cpp @@ -0,0 +1,18 @@ +#include // Only for cout to demonstrate + +int main() +{ + std::cout << +R"EOF( A raw string begins with R, then a double-quote ("), then an optional +identifier (here I've used "EOF"), then an opening parenthesis ('('). If you +use an identifier, it cannot be longer than 16 characters, and it cannot +contain a space, either opening or closing parentheses, a backslash, a tab, a +vertical tab, a form feed, or a newline. + + It ends with a closing parenthesis (')'), the identifer (if you used one), +and a double-quote. + + All characters are okay in a raw string, no escape sequences are necessary +or recognized, and all whitespace is preserved. +)EOF"; +} diff --git a/Task/Here-document/Factor/here-document.factor b/Task/Here-document/Factor/here-document.factor new file mode 100644 index 0000000000..130c56ec68 --- /dev/null +++ b/Task/Here-document/Factor/here-document.factor @@ -0,0 +1,8 @@ +" a multiline +string\n(with escape sequences: \u{greek-capital-letter-sigma}) +" +"""this is "easier"..""" +HEREDOC: EOF + this + is not \n escaped at all +EOF diff --git a/Task/Here-document/Scala/here-document.scala b/Task/Here-document/Scala/here-document.scala new file mode 100644 index 0000000000..0b951a5784 --- /dev/null +++ b/Task/Here-document/Scala/here-document.scala @@ -0,0 +1,27 @@ +object temp { +val MemoriesOfHolland= + """Thinking of Holland + |I see broad rivers + |slowly chuntering + |through endless lowlands, + |rows of implausibly + |airy poplars + |standing like tall plumes + |against the horizon; + |and sunk in the unbounded + |vastness of space + |homesteads and boweries + |dotted across the land, + |copses, villages, + |couchant towers, + |churches and elm-trees, + |bound in one great unity. + |There the sky hangs low, + |and steadily the sun + |is smothered in a greyly + |iridescent smirr, + |and in every province + |the voice of water + |with its lapping disasters + |is feared and hearkened.""".stripMargin +} diff --git a/Task/Here-document/Tcl/here-document.tcl b/Task/Here-document/Tcl/here-document.tcl index 2feede3bf1..ebf1ef04df 100644 --- a/Task/Here-document/Tcl/here-document.tcl +++ b/Task/Here-document/Tcl/here-document.tcl @@ -2,10 +2,12 @@ set hereDocExample { In Tcl, the {curly brace} notation is strictly a here-document style notation as it permits arbitrary content inside it *except* for an unbalanced brace. That is typically not a problem as seen in reality, as almost all content that -might be placed in a here-doc is either brace-free or balanced. The content -of the braces is not interpreted at all; no substitutions are performed on it. +might be placed in a here-doc is either brace-free or balanced. +The content of the braces is not interpreted at all; +no substitutions are performed on it. -The sole exception is that there is limited processing of backslashes; a single -backslash at the end of a line causes the end-of-line plus all whitespace at -the start of the next line to be compressed to a single space. +The sole exception is that there is limited processing of backslashes; +a single backslash at the end of a line causes the end-of-line +plus all whitespace at the start of the next line +to be compressed to a single space. } diff --git a/Task/Here-document/XSLT/here-document.xslt b/Task/Here-document/XSLT/here-document.xslt new file mode 100644 index 0000000000..8a84501ed9 --- /dev/null +++ b/Task/Here-document/XSLT/here-document.xslt @@ -0,0 +1,25 @@ + + + + + +, &, ", and ' +without any special treatment. + +The section is terminated by a three-character sequence consisting of two right +brackets ("]]") followed by a greater-than (">"). If this sequence appears in +your text, a workaround is to drop out of the CDATA section, output part of the +terminator, then start a new CDATA section and output the rest. Let's do this +now: + + ]]>]] + +Newlines and spacing are retained as well, as long as they're evaluated in a +context that bothers preserving them. Whether or not the spaces before and after +the CDATA section are also preserved may be application-dependent. + +]]> + + diff --git a/Task/Higher-order-functions/ATS/higher-order-functions.ats b/Task/Higher-order-functions/ATS/higher-order-functions.ats new file mode 100644 index 0000000000..d44359bbdf --- /dev/null +++ b/Task/Higher-order-functions/ATS/higher-order-functions.ats @@ -0,0 +1,13 @@ +#include +"share/atspre_staload.hats" + +fun app_to_0 (f: (int) -> int): int = f (0) + +implement +main0 () = +{ +// +val () = assertloc (app_to_0(lam(x) => x+1) = 1) +val () = assertloc (app_to_0(lam(x) => 10*(x+1)) = 10) +// +} (* end of [main0] *) diff --git a/Task/Higher-order-functions/AppleScript/higher-order-functions.applescript b/Task/Higher-order-functions/AppleScript/higher-order-functions.applescript new file mode 100644 index 0000000000..ea9cbcc149 --- /dev/null +++ b/Task/Higher-order-functions/AppleScript/higher-order-functions.applescript @@ -0,0 +1,25 @@ +-- This handler takes a script object (singer) +-- with another handler (call). +on sing about topic by singer + call of singer for "Of " & topic & " I sing" +end sing + +-- Define a handler in a script object, +-- then pass the script object. +script cellos + on call for what + say what using "Cellos" + end call +end script +sing about "functional programming" by cellos + +-- Pass a different handler. This one is a closure +-- that uses a variable (voice) from its context. +on hire for voice + script + on call for what + say what using voice + end call + end script +end hire +sing about "closures" by (hire for "Pipe Organ") diff --git a/Task/Higher-order-functions/Inform-7/higher-order-functions.inf b/Task/Higher-order-functions/Inform-7/higher-order-functions.inf index 6a88492b7a..0605936805 100644 --- a/Task/Higher-order-functions/Inform-7/higher-order-functions.inf +++ b/Task/Higher-order-functions/Inform-7/higher-order-functions.inf @@ -3,7 +3,7 @@ Higher Order Functions is a room. To decide which number is (N - number) added to (M - number) (this is addition): decide on N + M. -To decide which number is (N - number) multiplied by (M - number) (this is multiplication): +To decide which number is multiply (N - number) by (M - number) (this is multiplication): decide on N * M. To demonstrate (P - phrase (number, number) -> number) as (title - text): diff --git a/Task/Higher-order-functions/Oberon-2/higher-order-functions.oberon-2 b/Task/Higher-order-functions/Oberon-2/higher-order-functions.oberon-2 new file mode 100644 index 0000000000..bf49b1fd79 --- /dev/null +++ b/Task/Higher-order-functions/Oberon-2/higher-order-functions.oberon-2 @@ -0,0 +1,34 @@ +MODULE HOFuns; +IMPORT + NPCT:Tools, + Out; +TYPE + Formatter = PROCEDURE (s: STRING; len: LONGINT): STRING; +VAR + words: ARRAY 8 OF STRING; + + PROCEDURE PrintWords(w: ARRAY OF STRING; format: Formatter); + VAR + i: INTEGER; + BEGIN + i := 0; + WHILE (i < LEN(words)) DO + Out.Object(format(words[i],16)); + INC(i) + END; + Out.Ln + END PrintWords; +BEGIN + words[0] := "Al-Andalus"; + words[1] := "contributed"; + words[2] := "significantly"; + words[3] := "to"; + words[4] := "the"; + words[5] := "field"; + words[6] := "of"; + words[7] := "medicine"; + + PrintWords(words,Tools.AdjustLeft); + PrintWords(words,Tools.AdjustCenter); + PrintWords(words,Tools.AdjustRight) +END HOFuns. diff --git a/Task/History-variables/00DESCRIPTION b/Task/History-variables/00DESCRIPTION index 8b3ff2f31d..4c0401a214 100644 --- a/Task/History-variables/00DESCRIPTION +++ b/Task/History-variables/00DESCRIPTION @@ -1,9 +1,12 @@ -''Storing the history of objects in a program is a common task. Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' +''Storing the history of objects in a program is a common task. +Maintaining the history of an object in a program has traditionally required programmers either to write specific code for handling the historical data, or to use a library which supports history logging.'' ''History variables are variables in a programming language which store not only their current value, but also the values they have contained in the past. Some existing languages do provide support for history variables. However these languages typically have many limits and restrictions on use of history variables. '' -[http://www.bod.com/index.php?id=3435&objk_id=148050 "History Variables: The Semantics, Formal Correctness, and Implementation of History Variables in an Imperative Programming Language" by Mallon and Takaoka] +[http://www.bod.com/index.php?id=3435&objk_id=148050 "History Variables: +The Semantics, Formal Correctness, and Implementation of History Variables +in an Imperative Programming Language" by Mallon and Takaoka] Concept also discussed on [http://lambda-the-ultimate.org/node/3111 LtU] and [http://www.patents.com/us-7111283.html Patents.com]. @@ -15,4 +18,5 @@ Demonstrate History variable support: * non-destructively display the history * recall the three values. -For extra points, if the language of choice does not support history variables, demonstrate how this might be implemented. +For extra points, if the language of choice does not support history variables, +demonstrate how this might be implemented. diff --git a/Task/History-variables/Clojure/history-variables.clj b/Task/History-variables/Clojure/history-variables.clj new file mode 100644 index 0000000000..b961e985f1 --- /dev/null +++ b/Task/History-variables/Clojure/history-variables.clj @@ -0,0 +1,3 @@ +(def a (ref 0)) +(def a-history (atom [@a])) ; define a history vector to act as a stack for changes on variable a +(add-watch a :hist (fn [key ref old new] (swap! a-history conj new))) diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Clojure/hofstadter-conway-$10,000-sequence.clj b/Task/Hofstadter-Conway-$10,000-sequence/Clojure/hofstadter-conway-$10,000-sequence.clj index fe66f8def6..dd4b97c9d6 100644 --- a/Task/Hofstadter-Conway-$10,000-sequence/Clojure/hofstadter-conway-$10,000-sequence.clj +++ b/Task/Hofstadter-Conway-$10,000-sequence/Clojure/hofstadter-conway-$10,000-sequence.clj @@ -1,41 +1,24 @@ -(use 'clojure.contrib.math) ; for expt +(ns rosettacode.hofstader-conway + (:use [clojure.math.numeric-tower :only [expt]])) ;; A literal transcription of the definition, with memoize doing the heavy lifting (def conway - (memoize - (fn [x] - (if (< x 3) - 1 - (+ (conway (conway (dec x))) - (conway (- x (conway (dec x))))))))) + (memoize + (fn [x] + (if (< x 3) + 1 + (+ (-> x dec conway conway) + (->> x dec conway (- x) conway)))))) -(def N (drop 1 (range))) ; natural numbers - -;; This is enough to compute them all. The rest is grouping and max-finding -(def all-conways (map conway N)) - -;; All the powers of two -(def pow2 (map #(expt 2 %) N)) - -;; Find the lowest power of two > n -(defn lowest-pow-higher [n] - (some #(and (> % n) %) pow2)) - -;; Split the natural numbers into groups at each power of two -(def groups (partition-by lowest-pow-higher N)) - -;; The conway numbers of each number in the group -(def C (map #(map conway %) groups)) - -;; Each conway number divided by its index -(def ratios (map #(map / %1 %2) C groups)) - -;; The largest value in each group of ratios -(def maxima (map #(apply max %) ratios)) - -(take 4 maxima) ; no rounding errors: still using ratios -;; yields (1 2/3 2/3 7/11) - -(def first-20 (take 20 maxima)) -(apply >= first-20) ; yields true - the sequence is decreasing -(map double first-20) ; to get them in decimal form +(let [N (drop 1 (range)) + pow2 (map #(expt 2 %) N) + ; Split the natural numbers into groups at each power of two + groups (partition-by (fn [x] (filter #(> % x) pow2)) N) + maxima (->> (map #(map conway %) groups) + (map #(map / %2 %1) groups) ; Each conway number divided by its index + (map #(apply max %))) + m20 (take 20 maxima)] + (println + (take 4 maxima) "\n" + (apply >= m20) "\n" + (map double m20))) ; output the decimal forms diff --git a/Task/Hofstadter-Conway-$10,000-sequence/Pascal/hofstadter-conway-$10,000-sequence.pascal b/Task/Hofstadter-Conway-$10,000-sequence/Pascal/hofstadter-conway-$10,000-sequence.pascal new file mode 100644 index 0000000000..a943b2877d --- /dev/null +++ b/Task/Hofstadter-Conway-$10,000-sequence/Pascal/hofstadter-conway-$10,000-sequence.pascal @@ -0,0 +1,120 @@ +program HofStadterConway; +const + Pot2 = 20;// tested with 30 -> 4 GB; +type + tfeld = array[0..1 shl Pot2] of LongWord; + tpFeld = ^tFeld; + tMaxPos = record + mpMax : double; + mpValue, + mpPos : longWord; + end; + tArrMaxPos = array[0..Pot2-1] of tMaxPos; +var + a : tpFeld; + MaxPos : tArrMaxPos; + +procedure Init(a:tpFeld); +var + n,k: LongWord; +begin + a^[1]:= 1; + a^[2]:= 1; + //a[n] := a[a[n-1]]+a[n-a[n-1]]; + //k := a[n-1] + k := a^[2]; + For n := 3 to High(a^) do + Begin + k := a^[k]+a^[n-k]; + a^[n] := k; + end; +end; + +function GetMax(a:tpFeld;starts,ends:LongWord):tMaxPos; +var + posMax : LongWord; + r, + max : double; +Begin + posMax:= starts; + max := 0.0; + repeat + r := a^[starts]/ starts; + IF max < r then + Begin + max := r; + posMax := starts; + end; + inc(starts); + until starts >= ends; + with GetMax do + Begin + mpPos:= posMax; + mpValue := a^[posMax]; + mpMax:= max; + end; +end; + +procedure SearchMax(a:tpFeld); +var + ends,idx : LongWord; +begin + idx := 0; + ends := 2; + while ends <= High(a^) do + Begin + MaxPos[idx]:=GetMax(a,ends shr 1,ends); + ends := 2*ends; + inc(idx); + end; +end; + +procedure OutputMax; +var + i : integer; +begin + For i := Low(MaxPos) to High(MaxPOs) do + with MaxPos[i] do + Begin + Write('Max between 2^',i:2,' and 2^',i+1:2); + writeln(mpMax:14:11,' at ',mpPos:9,' value :',mpValue:10); + end; + writeln; +end; + +function SearchLastPos(a:tpFeld;limit: double):LongInt; +var + i,l : LongInt; +Begin + Limit := limit; + IF (Limit>1.0 ) OR (Limit < 0.5) then + Begin + SearchLastPos := -1; + EXIT; + end; + + i := 0; + while (i<=High(MaxPos)) AND (MaxPos[i].mpMax > Limit) do + inc(i); + dec(i); + l := MaxPos[i].mpPos; + i := 1 shl (i+1); + while (l< i) AND (a^[i]/i < limit) do + dec(i); + SearchLastPos := i; +end; + +var + p : Pointer; + l : double; +Begin + //using getmem because FPCs new is limited to 2^31-1 Byte for the test 2^30 ) + getmem(p,SizeOf(tfeld)); + a := p; + Init(a); + SearchMax(a); + outputMax; + l:= 0.55; + writeln('Mallows number with limit ',l:10:8,' at ',SearchLastPos(a,l)); + freemem(p); +end. diff --git a/Task/Hofstadter-Q-sequence/Bracmat/hofstadter-q-sequence.bracmat b/Task/Hofstadter-Q-sequence/Bracmat/hofstadter-q-sequence.bracmat new file mode 100644 index 0000000000..0f14ba786a --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Bracmat/hofstadter-q-sequence.bracmat @@ -0,0 +1,32 @@ +( 0:?memocells +& tbl$(memo,!memocells+1) { allocate array } +& ( Q + = + . !arg:(1|2)&1 + | !arg:>2 + & ( !arg:>!memocells:?memocells { Array is too small. } + & tbl$(memo,!memocells+1) { Let array grow to needed size. } + | { Array is not too small. } + ) + & ( !(!arg$memo):>0 { Set index to !arg. Return value at index if > 0 } + | Q$(!arg+-1*Q$(!arg+-1))+Q$(!arg+-1*Q$(!arg+-2)) + : ?(!arg$?memo) { Set index to !arg. Store value just found. } + ) + ) +& 0:?i +& whl + ' (1+!i:~>10:?i&put$(str$(Q$!i " "))) +& put$\n +& whl'(1+!i:~>1000:?i&Q$!i) +& out$(Q$1000) +& 0:?previous:?lessThan:?i +& whl + ' ( 1+!i:~>100000:?i + & Q$!i + : ( = n (length cc)) + (loop for i from (length cc) below n do (q i)) + (vector-push-extend + (+ (aref cc (- n (aref cc (- n 1)))) + (aref cc (- n (aref cc (- n 2))))) + cc)) + (aref cc n))) diff --git a/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d b/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d index 76dea1e9ce..d2b59a205e 100644 --- a/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d +++ b/Task/Hofstadter-Q-sequence/D/hofstadter-q-sequence-2.d @@ -1,20 +1,14 @@ import std.stdio, std.algorithm, std.range, std.array; -struct Q { - __gshared static Appender!(uint[]) s; +uint Q(in int n) nothrow +in { + assert(n > 0); +} body { + __gshared static Appender!(int[]) s = [0, 1, 1]; - nothrow static this() { - s ~= [0, 1, 1]; - } - - static uint opCall(in int n) nothrow - in { - assert(n > 0); - } body { - foreach (immutable i; s.data.length .. n + 1) - s ~= s.data[i - s.data[i - 1]] + s.data[i - s.data[i - 2]]; - return s.data[n]; - } + foreach (immutable i; s.data.length .. n + 1) + s ~= s.data[i - s.data[i - 1]] + s.data[i - s.data[i - 2]]; + return s.data[n]; } void main() { diff --git a/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e b/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e new file mode 100644 index 0000000000..75962b195d --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Eiffel/hofstadter-q-sequence.e @@ -0,0 +1,51 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + local + count,i: INTEGER + do + io.put_string ("%NFirst ten numbers: %N") + test:=seq (10) + across test as ar loop io.put_string (ar.item.out + "%T") end + test:= seq (100000) + io.put_string ("1000th:%N") + io.put_integer (test[1000]) + io.put_string ("%NNumber of Flips:%N") + from i:=2 + until i>100000 + loop + if test[i ]< test[i-1] then + count:= count+1 + end + i:= i+1 + end + io.put_integer (count) + end + test: ARRAY[INTEGER] + + seq(lim: INTEGER): ARRAY[INTEGER] + require + lim_positive: lim>0 + local + q: ARRAY[INTEGER] + i: INTEGER + do + create q.make_filled(1, 1, lim) + q[1]:= 1 + q[2]:= 1 + from + i:= 3 + until + i> lim + loop + q[i]:= q[i-q[i-1]]+q[i-q[i-2]] + i:= i+1 + end + Result:= q + end +end diff --git a/Task/Hofstadter-Q-sequence/Oberon-2/hofstadter-q-sequence.oberon-2 b/Task/Hofstadter-Q-sequence/Oberon-2/hofstadter-q-sequence.oberon-2 new file mode 100644 index 0000000000..944fea4f3a --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Oberon-2/hofstadter-q-sequence.oberon-2 @@ -0,0 +1,36 @@ +MODULE Hofstadter; +IMPORT + Out; + +VAR + i,count,q,prev: LONGINT; + founds: ARRAY 100001 OF LONGINT; + + PROCEDURE Q(n: LONGINT): LONGINT; + BEGIN + IF founds[n] = 0 THEN + CASE n OF + 1 .. 2: + founds[n] := 1 + ELSE founds[n] := Q(n - Q(n - 1)) + Q(n - Q(n - 2)) + END + END; + RETURN founds[n] + END Q; + +BEGIN + (* first ten numbers in the sequence *) + FOR i := 1 TO 10 DO + Out.String("At ");Out.LongInt(i,0);Out.String(":> ");Out.LongInt(Q(i),4);Out.Ln + END; + + Out.String("1000th value: ");Out.LongInt(Q(1000),4);Out.Ln; + + prev := 1; + FOR i := 2 TO 100000 DO + q := Q(i); + IF q < prev THEN INC(count) END; + prev := q + END; + Out.String("terms less than the previous: ");Out.LongInt(count,4);Out.Ln +END Hofstadter. diff --git a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx index 0fc657096e..5947996488 100644 --- a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx +++ b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-1.rexx @@ -12,9 +12,9 @@ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────HofstadterQ subroutine──────────────*/ HofstadterQ: procedure expose q.; arg x 1 ox /*get the # to gen through*/ /*(above) OX is the same as X.*/ -x=abs(x) /*use the absolute value for X. */ +x=abs(x) /*use the absolute value for X. */ L=length(x) /*use for right justified output.*/ - do j=1 for x + do j=1 for x if j>2 then if q.j==1 then do; jm1=j-1; jm2=j-2 _1=j-q.jm1; _2=j-q.jm2 q.j=q._1+q._2 diff --git a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx index 86d7f25139..89aca28b27 100644 --- a/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx +++ b/Task/Hofstadter-Q-sequence/REXX/hofstadter-q-sequence-2.rexx @@ -14,7 +14,7 @@ HofstadterQ: procedure expose q.; arg x 1 ox /*get the # to gen through*/ /*(above) OX is the same as X.*/ x=abs(x) /*use the absolute value for X. */ L=length(x) /*use for right justified output.*/ - do j=1 for x + do j=1 for x if j>2 then if q.j==1 then q.j=q(j-q(j-1)) + q(j-q(j-2)) if ox>0 then say right(j,L) right(q.j,L) /*if X>0, tell*/ end /*j*/ diff --git a/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence.ss b/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence.ss new file mode 100644 index 0000000000..f3bb905a55 --- /dev/null +++ b/Task/Hofstadter-Q-sequence/Scheme/hofstadter-q-sequence.ss @@ -0,0 +1,47 @@ +(define qc '#(0 1 1)) +(define filled 3) +(define len 3) + +;; chicken scheme: vector-resize! +;; gambit: vector-append +(define (extend-qc) + (let* ((new-len (* 2 len)) + (new-qc (make-vector new-len))) + (let copy ((n 0)) + (if (< n len) + (begin + (vector-set! new-qc n (vector-ref qc n)) + (copy (+ 1 n))))) + (set! len new-len) + (set! qc new-qc))) + +(define (q n) + (let loop () + (if (>= filled len) (extend-qc)) + (if (>= n filled) + (begin + (vector-set! qc filled (+ (q (- filled (q (- filled 1)))) + (q (- filled (q (- filled 2)))))) + (set! filled (+ 1 filled)) + (loop)) + (vector-ref qc n)))) + +(display "Q(1 .. 10): ") +(let loop ((i 1)) + ;; (print) behave differently regarding newline across compilers + (display (q i)) + (display " ") + (if (< i 10) + (loop (+ 1 i)) + (newline))) + +(display "Q(1000): ") +(display (q 1000)) +(newline) + +(display "bumps up to 100000: ") +(display + (let loop ((s 0) (i 1)) + (if (>= i 100000) s + (loop (+ s (if (> (q i) (q (+ 1 i))) 1 0)) (+ 1 i))))) +(newline) diff --git a/Task/Holidays-related-to-Easter/Java/holidays-related-to-easter.java b/Task/Holidays-related-to-Easter/Java/holidays-related-to-easter.java new file mode 100644 index 0000000000..8ce29e6531 --- /dev/null +++ b/Task/Holidays-related-to-Easter/Java/holidays-related-to-easter.java @@ -0,0 +1,59 @@ +import java.text.DateFormatSymbols; +import java.util.*; + +public class EasterRelatedHolidays { + + final static Map holidayOffsets; + + static { + holidayOffsets = new LinkedHashMap<>(); + holidayOffsets.put("Easter", 0); + holidayOffsets.put("Ascension", 39); + holidayOffsets.put("Pentecost", 10); + holidayOffsets.put("Trinity", 7); + holidayOffsets.put("Corpus", 4); + } + + public static void main(String[] args) { + System.out.println("Christian holidays, related to Easter," + + " for each centennial from 400 to 2100 CE:"); + + for (int y = 400; y <= 2100; y += 100) + printEasterRelatedHolidays(y); + + System.out.println("\nChristian holidays, related to Easter," + + " for years from 2010 to 2020 CE:"); + for (int y = 2010; y < 2021; y++) + printEasterRelatedHolidays(y); + } + + static void printEasterRelatedHolidays(int year) { + final int a = year % 19; + final int b = year / 100; + final int c = year % 100; + final int d = b / 4; + final int e = b % 4; + final int f = (b + 8) / 25; + final int g = (b - f + 1) / 3; + final int h = (19 * a + b - d - g + 15) % 30; + final int i = c / 4; + final int k = c % 4; + final int l = (32 + 2 * e + 2 * i - h - k) % 7; + final int m = (a + 11 * h + 22 * l) / 451; + final int n = h + l - 7 * m + 114; + final int month = n / 31 - 1; + final int day = (n % 31) + 1; + + Calendar date = new GregorianCalendar(year, month, day); + String[] months = new DateFormatSymbols(Locale.US).getShortMonths(); + + System.out.printf("%4d ", year); + for (String hd : holidayOffsets.keySet()) { + date.add(Calendar.DATE, holidayOffsets.get(hd)); + System.out.printf("%s: %2d %s ", hd, + date.get(Calendar.DAY_OF_MONTH), + months[date.get(Calendar.MONTH)]); + } + System.out.println(); + } +} diff --git a/Task/Holidays-related-to-Easter/Ruby/holidays-related-to-easter.rb b/Task/Holidays-related-to-Easter/Ruby/holidays-related-to-easter.rb index 777bb3e660..19c2e459aa 100644 --- a/Task/Holidays-related-to-Easter/Ruby/holidays-related-to-easter.rb +++ b/Task/Holidays-related-to-Easter/Ruby/holidays-related-to-easter.rb @@ -4,39 +4,36 @@ def easter_date(year) # Anonymous Gregorian algorithm # http://en.wikipedia.org/wiki/Computus#Algorithms - a = year % 19 - b = year / 100 - c = year % 100 - d = b / 4 - e = b % 4 - f = (b + 8) / 25 - g = (b - f + 1) / 3 - h = (19*a +b - d - g + 15) % 30 - i = c / 4 - k = c % 4 - l = (32 + 2*e + 2*i - h - k) % 7 - m = (a + 11*h + 22*l) / 451 + a = year % 19 + b, c = year.divmod(100) + d, e = b.divmod(4) + f = (b + 8) / 25 + g = (b - f + 1) / 3 + h = (19*a + b - d - g + 15) % 30 + i, k = c.divmod(4) + l = (32 + 2*e + 2*i - h - k) % 7 + m = (a + 11*h + 22*l) / 451 numerator = h + l - 7*m + 114 month = numerator / 31 day = (numerator % 31) + 1 Date.new(year, month, day) end -OFFSETS = { - :easter => 0, - :ascension => 39, - :pentecost => 49, - :trinity => 56, - :corpus => 60, -} +OFFSETS = [ + [:easter, 0], + [:ascension, 39], + [:pentecost, 49], + [:trinity, 56], + [:corpus, 60], +] def emit_dates(year) e = easter_date year - dates = OFFSETS.collect {|(item, offset)| (e + offset).strftime("%e %b")} - puts "%4s: %s" % [year, dates.join(', ')] + dates = OFFSETS.collect {|item, offset| (e + offset).strftime(" %e %b")} + puts "%4s: %s" % [year, dates.join(', ')] end -puts "year: " + OFFSETS.keys.join(', ') +puts "year:" + OFFSETS.collect{|item, offset| "%9s" % item}.join(', ') 400.step(2100, 100).each {|year| emit_dates year} -puts "" +puts (2010 .. 2020).each {|year| emit_dates year} diff --git a/Task/Honeycombs/Haskell/honeycombs.hs b/Task/Honeycombs/Haskell/honeycombs.hs new file mode 100644 index 0000000000..7bf8f3f188 --- /dev/null +++ b/Task/Honeycombs/Haskell/honeycombs.hs @@ -0,0 +1,141 @@ +import Data.Char (toUpper) +import Data.Function (on) +import Data.List (zipWith4) +import System.Exit +import System.Random + +-- External libraries. +import Graphics.Gloss +import Graphics.Gloss.Data.Vector +import Graphics.Gloss.Geometry +import Graphics.Gloss.Interface.IO.Game +import System.Random.Shuffle + +-- A record of a hexagon-letter. +data Hex = + Hex + { hLetter :: Char -- The letter it holds. + , hSelected :: Bool -- The flag for if the hexagon has been selected. + , hPath :: Path -- The hexagon's vertices. + , hCenter :: Point -- The center of the hexagon. + } + +-- A record of the world state. +data World = + World + { wHexes :: [Hex] -- The hexagons to interact with. + , wString :: String -- An ordering of picked letters. + } + +-- Assorted helper functions. +addV, subV :: Vector -> Vector -> Vector +addV (a, b) (x, y) = (a + x, b + y) +subV (a, b) (x, y) = (a - x, b - y) + +translateP :: Vector -> Path -> Path +translateP v = map (addV v) + +translateV :: Vector -> Picture -> Picture +translateV (x, y) p = translate x y p + +lightblue, darkblue :: Color +lightblue = makeColor 0.5 0.5 1.0 1.0 +darkblue = makeColor 0.0 0.0 0.5 1.0 + +-- Create vertices for an n-gon with the given radius to a vertex +ngon :: Int -> Float -> Path +ngon n radius = + let angle = 2 * pi / fromIntegral n + in map (mulSV radius . unitVectorAtAngle . (* angle) . fromIntegral) + [0..(n - 1)] + +-- Determine if a point lies on or within a polygon. +inPolygon :: Point -> Path -> Bool +inPolygon point path = + all (>= 0) $ zipWith detV vas vbs + where + vas = zipWith subV (drop 1 $ cycle path) path + vbs = map (subV point) path + +-- Construct all of the hexagons transformed to their screen coordinates +-- to make mouse picking easier to solve. +mkHexes :: RandomGen g => g -> Float -> World +mkHexes gen radius = World hexes "" + where + letters = take 20 $ shuffle' ['A'..'Z'] 26 gen + xs = concatMap (replicate 4) [-2..2] + ys = cycle [-2..1] + inRad = radius * (cos $ degToRad 30) + yOff x = if ((floor x) :: Int) `mod` 2 == 0 then inRad else 0 + yStep = inRad * 2 + xStep = radius * 1.5 + centers = zipWith (\x y -> (x * xStep, yOff x + y * yStep)) xs ys + paths = map (flip translateP $ ngon 6 radius) centers + hexes = zipWith4 Hex letters (repeat False) paths centers + +-- Draw a single hexagon-letter. +drawHex :: Hex -> Picture +drawHex (Hex letter selected path center) = + pictures [hex, outline, letterPic] + where + hex = color hcolor $ polygon path + outline = color blue $ lineLoop path + letterPic = color lcolor + $ translateV (addV (-10, -10) center) + $ scale 0.25 0.25 + $ text [letter] + (hcolor, lcolor) = if selected + then (darkblue, white) + else (lightblue, black) + +-- Draw the whole scene. +drawWorld :: World -> Picture +drawWorld (World hexes string) = + pictures [pictures $ map drawHex hexes + ,pictures $ map drawHighHex hexes + ,color (light lightblue) $ textPic + ,scale 1.05 1.05 $ textPic] + where + drawHighHex hex = color black $ scale 1.05 1.05 $ lineLoop $ hPath hex + textPic = translateV (-130, -175) $ scale 0.15 0.15 $ text string + +-- Handle keyboard and mouse events and update the hexagons +-- accordingly. This function checks the hexagon states and +-- invokes a system exit when all are marked selected. +handleInput :: Event -> World -> IO World +handleInput event world@(World hexes string) = + case event of + EventKey key Down _ point -> + case key of + SpecialKey KeyEsc -> exitSuccess + Char char -> hCond (\hex -> hLetter hex == toUpper char) + MouseButton _ -> hCond (\hex -> inPolygon point $ hPath hex) + _ -> return world + _ -> + return world + where + checkWorld w = if all hSelected $ wHexes w then exitSuccess else return w + hCond cond = checkWorld $ World newHexes newString + where + newHexes = flip map hexes + (\hex -> if cond hex + then hex {hSelected = True} + else hex) + diff = map fst + $ filter (uncurry ((/=) `on` hSelected)) + $ zip hexes newHexes + newString = case diff of + [] -> string + (hex:_) -> string ++ [hLetter hex] + +main :: IO () +main = do + stdGen <- getStdGen + playIO + (InWindow "Honeycombs" (500, 500) (100, 100)) + white + 60 + (mkHexes stdGen 30) + (return . drawWorld) + handleInput + (\_ x -> return x) diff --git a/Task/Honeycombs/Java/honeycombs-1.java b/Task/Honeycombs/Java/honeycombs-1.java new file mode 100644 index 0000000000..c2ce1e2aa6 --- /dev/null +++ b/Task/Honeycombs/Java/honeycombs-1.java @@ -0,0 +1,134 @@ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; + +public class Honeycombs extends JFrame { + + HoneycombsPanel panel; + + public static void main(String[] args) { + JFrame f = new Honeycombs(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setVisible(true); + } + + public Honeycombs() { + Container content = getContentPane(); + content.setLayout(new BorderLayout()); + panel = new HoneycombsPanel(); + content.add(panel, BorderLayout.CENTER); + setTitle("Honeycombs"); + setResizable(false); + pack(); + setLocationRelativeTo(null); + } +} + +class HoneycombsPanel extends JPanel { + + Hexagon[] comb; + + public HoneycombsPanel() { + setPreferredSize(new Dimension(600, 500)); + setBackground(Color.white); + setFocusable(true); + + addMouseListener(new MouseAdapter() { + @Override + public void mousePressed(MouseEvent e) { + for (Hexagon hex : comb) + if (hex.contains(e.getX(), e.getY())) { + hex.setSelected(); + break; + } + repaint(); + } + }); + + addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + for (Hexagon hex : comb) + if (hex.letter == Character.toUpperCase(e.getKeyChar())) { + hex.setSelected(); + break; + } + repaint(); + } + }); + + char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); + comb = new Hexagon[20]; + + int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; + for (int i = 0; i < comb.length; i++) { + int x, y; + if (i < 12) { + x = x1 + (i % 3) * w; + y = y1 + (i / 3) * h; + } else { + x = x2 + (i % 2) * w; + y = y2 + ((i - 12) / 2) * h; + } + comb[i] = new Hexagon(x, y, w / 3, letters[i]); + } + + requestFocus(); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + + g.setFont(new Font("SansSerif", Font.BOLD, 30)); + g.setStroke(new BasicStroke(3)); + + for (Hexagon hex : comb) + hex.draw(g); + } +} + +class Hexagon extends Polygon { + final Color baseColor = Color.yellow; + final Color selectedColor = Color.magenta; + final char letter; + + private boolean hasBeenSelected; + + Hexagon(int x, int y, int halfWidth, char c) { + letter = c; + for (int i = 0; i < 6; i++) + addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), + (int) (y + halfWidth * Math.sin(i * Math.PI / 3))); + getBounds(); + } + + void setSelected() { + hasBeenSelected = true; + } + + void draw(Graphics2D g) { + g.setColor(hasBeenSelected ? selectedColor : baseColor); + g.fillPolygon(this); + + g.setColor(Color.black); + g.drawPolygon(this); + + g.setColor(hasBeenSelected ? Color.black : Color.red); + drawCenteredString(g, String.valueOf(letter)); + } + + void drawCenteredString(Graphics2D g, String s) { + FontMetrics fm = g.getFontMetrics(); + int asc = fm.getAscent(); + int dec = fm.getDescent(); + + int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; + int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); + + g.drawString(s, x, y); + } +} diff --git a/Task/Honeycombs/Java/honeycombs-2.java b/Task/Honeycombs/Java/honeycombs-2.java new file mode 100644 index 0000000000..84f41e2dca --- /dev/null +++ b/Task/Honeycombs/Java/honeycombs-2.java @@ -0,0 +1,184 @@ +package graphics; + +import java.awt.BasicStroke; +import java.awt.BorderLayout; +import java.awt.Container; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Polygon; +import java.awt.RenderingHints; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import javax.swing.JFrame; +import javax.swing.JPanel; + +import static java.util.Arrays.parallelSetAll; +import static java.util.Arrays.stream; +import static java.util.stream.IntStream.range; + +public class Honeycombs extends JFrame { + HoneycombsPanel panel; + + public static void main(String[] args) { + JFrame f = new Honeycombs(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setVisible(true); + } + + public Honeycombs() { + Container content = getContentPane(); + content.setLayout(new BorderLayout()); + panel = new HoneycombsPanel(); + content.add(panel, BorderLayout.CENTER); + setTitle("Honeycombs"); + setResizable(false); + pack(); + setLocationRelativeTo(null); + } +} + +class HoneycombsPanel extends JPanel { + Hexagon[] comb; + + @FunctionalInterface + private static interface MousePressed extends MouseListener { + public static MousePressed new_(MousePressed mousePressed) { + return mousePressed; + } + + @Override + public default void mouseClicked(MouseEvent mouseEvent) {} + + @Override + public default void mouseEntered(MouseEvent mouseEvent) {} + + @Override + public default void mouseExited(MouseEvent mouseEvent) {} + + @Override + public default void mouseReleased(MouseEvent mouseEvent) {} + } + + @FunctionalInterface + private static interface KeyPressed extends KeyListener { + public static KeyPressed new_(KeyPressed keyPressed) { + return keyPressed; + } + + @Override + public default void keyReleased(KeyEvent keyEvent) {} + + @Override + public default void keyTyped(KeyEvent keyEvent) {} + } + + public HoneycombsPanel() { + setPreferredSize(new Dimension(600, 500)); + setBackground(Color.white); + setFocusable(true); + + addMouseListener(MousePressed.new_(e -> { + stream(comb) + .filter(hex -> hex.contains(e.getX(), e.getY())) + .findFirst() + .ifPresent(hex -> hex.setSelected()) + ; + repaint(); + })); + + addKeyListener(KeyPressed.new_(e -> { + stream(comb) + .filter(hex -> hex.letter == Character.toUpperCase(e.getKeyChar())) + .findFirst() + .ifPresent(hex -> hex.setSelected()) + ; + repaint(); + })); + + char[] letters = "LRDGITPFBVOKANUYCESM".toCharArray(); + comb = new Hexagon[20]; + + int x1 = 150, y1 = 100, x2 = 225, y2 = 143, w = 150, h = 87; + parallelSetAll(comb, i -> { + int x, y; + if (i < 12) { + x = x1 + (i % 3) * w; + y = y1 + (i / 3) * h; + } else { + x = x2 + (i % 2) * w; + y = y2 + ((i - 12) / 2) * h; + } + return new Hexagon(x, y, w / 3, letters[i]); + }); + + requestFocus(); + } + + @Override + public void paintComponent(Graphics gg) { + super.paintComponent(gg); + Graphics2D g = (Graphics2D) gg; + g.setRenderingHint( + RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON + ); + + g.setFont(new Font("SansSerif", Font.BOLD, 30)); + g.setStroke(new BasicStroke(3)); + + stream(comb) + .forEach(hex -> hex.draw(g)) + ; + } +} + +class Hexagon extends Polygon { + final Color baseColor = Color.yellow; + final Color selectedColor = Color.magenta; + final char letter; + + private boolean hasBeenSelected; + + Hexagon(int x, int y, int halfWidth, char c) { + letter = c; + range(0, 6) + .forEach(i -> + addPoint((int) (x + halfWidth * Math.cos(i * Math.PI / 3)), + (int) (y + halfWidth * Math.sin(i * Math.PI / 3))) + ) + ; + getBounds(); + } + + void setSelected() { + hasBeenSelected = true; + } + + void draw(Graphics2D g) { + g.setColor(hasBeenSelected ? selectedColor : baseColor); + g.fillPolygon(this); + + g.setColor(Color.black); + g.drawPolygon(this); + + g.setColor(hasBeenSelected ? Color.black : Color.red); + drawCenteredString(g, String.valueOf(letter)); + } + + void drawCenteredString(Graphics2D g, String s) { + FontMetrics fm = g.getFontMetrics(); + int asc = fm.getAscent(); + int dec = fm.getDescent(); + + int x = bounds.x + (bounds.width - fm.stringWidth(s)) / 2; + int y = bounds.y + (asc + (bounds.height - (asc + dec)) / 2); + + g.drawString(s, x, y); + } +} diff --git a/Task/Honeycombs/MATLAB/honeycombs.m b/Task/Honeycombs/MATLAB/honeycombs.m new file mode 100644 index 0000000000..0460ed2a39 --- /dev/null +++ b/Task/Honeycombs/MATLAB/honeycombs.m @@ -0,0 +1,57 @@ +function Honeycombs + nRows = 4; % Number of rows + nCols = 5; % Number of columns + nHexs = nRows*nCols; % Number of hexagons + rOuter = 1; % Circumradius + startX = 0; % x-coordinate of upper left hexagon + startY = 0; % y-coordinate of upper left hexagon + delX = rOuter*1.5; % Horizontal distance between hexagons + delY = rOuter*sqrt(3); % Vertical distance between hexagons + offY = delY/2; % Vertical offset between columns + genHexX = rOuter.*cos(2.*pi.*(0:5).'./6); % x-coords of general hexagon + genHexY = rOuter.*sin(2.*pi.*(0:5).'./6); % y-coords of general hexagon + centX = zeros(1, nHexs); % x-coords of hexagon centers + centY = zeros(1, nHexs); % y-coords of hexagon centers + for c = 1:nCols + idxs = (c-1)*nRows+1:c*nRows; % Indeces of hexagons in that column + if mod(c, 2) % Odd numbered column - higher y-values + centY(idxs) = startY:-delY:startY-delY*(nRows-1); + else % Even numbered column - lower y-values + centY(idxs) = startY-offY:-delY:startY-offY-delY*(nRows-1); + end + centX(idxs) = (startX+(c-1)*delX).*ones(1, nRows); + end + [MCentX, MGenHexX] = meshgrid(centX, genHexX); + [MCentY, MGenHexY] = meshgrid(centY, genHexY); + HexX = MCentX+MGenHexX; % x-coords of hexagon vertices + HexY = MCentY+MGenHexY; % y-coords of hexagon vertices + figure + hold on + letters = char([65:90 97:122]); + randIdxs = randperm(26); + letters = [letters(randIdxs) letters(26+randIdxs)]; + hexH = zeros(1, nHexs); + for k = 1:nHexs % Create patches individually + hexH(k) = patch(HexX(:, k), HexY(:, k), [1 1 0]); + textH = text(centX(k), centY(k), letters(mod(k, length(letters))), ... + 'HorizontalAlignment', 'center', 'FontSize', 14, ... + 'FontWeight', 'bold', 'Color', [1 0 0], 'HitTest', 'off'); + set(hexH(k), 'UserData', textH) % Save to object for easy access + end + axis equal + axis off + set(gca, 'UserData', '') % List of clicked patch labels + set(hexH, 'ButtonDownFcn', @onClick) +end + +function onClick(obj, event) + axesH = get(obj, 'Parent'); + textH = get(obj, 'UserData'); + set(obj, 'FaceColor', [1 0 1]) % Change color + set(textH, 'Color', [0 0 0]) % Change label color + set(obj, 'HitTest', 'off') % Ignore future clicks + currList = get(axesH, 'UserData'); % Hexs already clicked + newList = [currList get(textH, 'String')]; % Update list + set(axesH, 'UserData', newList) + title(newList) +end diff --git a/Task/Honeycombs/Ruby/honeycombs.rb b/Task/Honeycombs/Ruby/honeycombs.rb index 23efc8e3c5..0b988bf5f0 100644 --- a/Task/Honeycombs/Ruby/honeycombs.rb +++ b/Task/Honeycombs/Ruby/honeycombs.rb @@ -1,7 +1,7 @@ -Shoes.app(:height => 700, :width => 800) do +Shoes.app(title: "Honeycombs", height: 700, width: 700) do C = Math::cos(Math::PI/3) S = Math::sin(Math::PI/3) - Radius = 60 + Radius = 60.0 letters = [ %w[L A R N D 1 2], %w[G U I Y T 3 4], @@ -11,11 +11,11 @@ Shoes.app(:height => 700, :width => 800) do ] def highlight(hexagon) - hexagon.style(:fill => magenta) + hexagon.style(fill: magenta) end def unhighlight(hexagon) - hexagon.style(:fill => yellow) + hexagon.style(fill: yellow) end def choose(hexagon) @@ -25,8 +25,8 @@ Shoes.app(:height => 700, :width => 800) do if chosen.size == @hexagons.size @chosen.text = 'Every hexagon has been chosen.' else - @chosen.text = "Chosen: #{chosen.sort.join(',')}" + - "\nLast Chosen: #{hexagon.letter}" + @chosen.text = "Chosen: #{chosen.sort.join(',')}\n" + + "Last Chosen: #{hexagon.letter}" end end @@ -36,23 +36,22 @@ Shoes.app(:height => 700, :width => 800) do letter_to_hex = {} # create the GUI - stack(:height => height, :width => width) do + stack(height: height, width: width) do @chosen = para("Chosen:\nLast chosen:") # draw the hexagrams - letters.size.times do |row| - letters[0].size.times do |column| - x = 60 + column * Radius * 0.75 + (1-S)*Radius - y = 80 + row * Radius * S + (column.odd? ? S * Radius * 0.5 : 0) + letters.each_index do |row| + letters[0].each_index do |column| + x = 60 + column * Radius * 0.75 + (1-S) * Radius + y = 80 + row * S * Radius + (column.odd? ? S * Radius * 0.5 : 0) h = shape(x-Radius, y-S*Radius) do - stroke red strokewidth 3 move_to(x-C*Radius, y-S*Radius) line_to(x+C*Radius, y-S*Radius) - line_to(x+Radius, y) + line_to(x+Radius, y) line_to(x+C*Radius, y+S*Radius) line_to(x-C*Radius, y+S*Radius) - line_to(x-Radius, y) + line_to(x-Radius, y) line_to(x-C*Radius, y-S*Radius) end @@ -65,26 +64,26 @@ Shoes.app(:height => 700, :width => 800) do def choose @state = :chosen end - def contains?(px,py) + def contains?(px, py) if @x-Radius < px and px <= @x-C*Radius - ratio = (px - @x + Radius).to_f/(Radius*(1-C)) - return (@y - ratio*S*Radius < py and py <= @y + ratio*S*Radius) + ratio = (px - @x + Radius)/(Radius*(1-C)) + @y - ratio*S*Radius < py and py <= @y + ratio*S*Radius elsif @x-C*Radius < px and px <= @x+C*Radius - return (@y - S*Radius < py and py < @y + S*Radius) + @y - S*Radius < py and py < @y + S*Radius elsif @x+C*Radius < px and px <= @x+Radius - ratio = (@x + Radius - px).to_f/(Radius*(1-C)) - return (@y - ratio*S*Radius < py and py <= @y + ratio*S*Radius) + ratio = (@x + Radius - px)/(Radius*(1-C)) + @y - ratio*S*Radius < py and py <= @y + ratio*S*Radius else - return false + false end end def inspect - '<%s,"%s",%s,%d@%d>' % [self.class, letter, chosen?, x, y] + %q(<%s,"%s",%s,%d@%d>) % [self.class, letter, chosen?, x, y] end end - h.x = x + x-Radius - h.y = y + y-S*Radius + h.x = x + x - Radius + h.y = y + y - S*Radius h.letter = letters[row][column] unhighlight h @@ -93,30 +92,29 @@ Shoes.app(:height => 700, :width => 800) do letter_to_hex[h.letter.upcase] = h # add the letter to the hexagon - para(h.letter) \ - .style(:size => 56, :stroke => red) \ - .move(h.x - C*Radius, h.y - S*Radius) + para(h.letter).style(size:56, stroke:red) \ + .move(h.x - C*Radius, h.y - S*Radius) end end # highlight the hexagon under the mouse - @hex_over = nil + hex_over = nil motion do |x, y| hex = @hexagons.find {|h| h.contains?(x,y)} unless hex.nil? or hex.chosen? highlight hex end - unless @hex_over == hex or @hex_over.nil? or @hex_over.chosen? - unhighlight @hex_over + unless hex_over == hex or hex_over.nil? or hex_over.chosen? + unhighlight hex_over end - @hex_over = hex + hex_over = hex end # handle mouse clicks click do |button, x, y| info("button #{button} clicked at (#{x}, #{y})") hexagon = @hexagons.find {|h| h.contains?(x,y)} - unless hexagon.nil? + if hexagon info("clicked hexagon #{hexagon}") choose hexagon end diff --git a/Task/Horizontal-sundial-calculations/Euphoria/horizontal-sundial-calculations.euphoria b/Task/Horizontal-sundial-calculations/Euphoria/horizontal-sundial-calculations.euphoria new file mode 100644 index 0000000000..cfa350aede --- /dev/null +++ b/Task/Horizontal-sundial-calculations/Euphoria/horizontal-sundial-calculations.euphoria @@ -0,0 +1,35 @@ +include std/console.e +include std/mathcons.e + +atom lat = prompt_number("Enter Latitude: ",{}) +atom lng = prompt_number("Enter Longitude: ",{}) +atom lm = prompt_number("Enter Legal Meridian: ",{}) +puts(1,'\n') + +atom ha, hla + +function D2R(atom degrees) + return degrees * PI / 180 +end function + +function R2D(atom radians) + return radians * 180 / PI +end function + +function atan2(atom y, atom x) + return 2*arctan((sqrt(power(x,2)+power(y,2)) - x)/y) +end function + +atom s_lat = sin(D2R(lat)) + +puts(1,"Hour, Sun Hour Angle, Dial Hour Line Angle\n") + +for hour = -6 to 6 do + ha = hour * 15 - lng + lm + atom s = sin(D2R(ha)) + atom c = cos(D2R(ha)) + hla = R2D(atan2(s_lat*s,c)) + printf(1,"%3d\t\t\t%7.3f\t\t\t%7.3f\n",{hour+12,ha,hla}) +end for + +if getc(0) then end if diff --git a/Task/Horners-rule-for-polynomial-evaluation/ATS/horners-rule-for-polynomial-evaluation.ats b/Task/Horners-rule-for-polynomial-evaluation/ATS/horners-rule-for-polynomial-evaluation.ats index e5b5c26692..23a36000a3 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/ATS/horners-rule-for-polynomial-evaluation.ats +++ b/Task/Horners-rule-for-polynomial-evaluation/ATS/horners-rule-for-polynomial-evaluation.ats @@ -1,16 +1,24 @@ -staload "prelude/SATS/list.sats" -staload "prelude/DATS/list.dats" +#include +"share/atspre_staload.hats" -fun horner (x: int, coeff: List int): int = let - val f = lam (a: int, b: int) = a + b*x +fun +horner +( + x: int, cs: List int +) : int = let +// +implement +list_foldright$fopr (a, b) = a + b * x +// in - list_fold_right_cloref (f, coeff, 0) -end + list_foldright (cs, 0) +end // end of [horner] -implement main () = let +implement +main0 () = let val x = 3 - val coeff = '[~19,7,~4,6] - val res = horner (x, coeff) + val cs = $list{int}(~19, 7, ~4, 6) + val res = horner (x, cs) in - print! (res, "\n") -end + println! (res) +end // end of [main0] diff --git a/Task/Horners-rule-for-polynomial-evaluation/Clojure/horners-rule-for-polynomial-evaluation.clj b/Task/Horners-rule-for-polynomial-evaluation/Clojure/horners-rule-for-polynomial-evaluation.clj index a932f6fbb7..3443e07333 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Clojure/horners-rule-for-polynomial-evaluation.clj +++ b/Task/Horners-rule-for-polynomial-evaluation/Clojure/horners-rule-for-polynomial-evaluation.clj @@ -1,4 +1,4 @@ (defn horner [coeffs x] - (reduce (fn [acc coeff] (+ (* acc x) coeff)) (reverse coeffs))) + (reduce #(-> %1 (* x) (+ %2)) (reverse coeffs))) (println (horner [-19 7 -4 6] 3)) diff --git a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-1.d b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-1.d index 2fc7d60ef4..07d4069ffb 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-1.d +++ b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-1.d @@ -1,5 +1,5 @@ -import std.stdio, std.math; - void main() { - writeln(poly(3.0, [-19, 7, -4, 6])); + import std.stdio, std.math; + + poly(3.0, [-19, 7, -4, 6]).writeln; } diff --git a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-2.d b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-2.d index dd9f53eaf3..770179de64 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-2.d +++ b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-2.d @@ -1,6 +1,6 @@ import std.stdio, std.traits; -CommonType!(U, V) horner(U, V)(U[] p, V x) { +CommonType!(U, V) horner(U, V)(U[] p, V x) pure nothrow @nogc { typeof(return) accumulator = 0; foreach_reverse (c; p) accumulator = accumulator * x + c; @@ -8,5 +8,5 @@ CommonType!(U, V) horner(U, V)(U[] p, V x) { } 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/D/horners-rule-for-polynomial-evaluation-3.d b/Task/Horners-rule-for-polynomial-evaluation/D/horners-rule-for-polynomial-evaluation-3.d index 5fedf09e8a..3798e43e2d 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,7 +1,7 @@ import std.stdio, std.algorithm, std.range; -auto horner(T, U)(in T[] p, in U x) pure nothrow { - return reduce!((a, b) => a * x + b)(cast(U)0, p.retro); +auto horner(T, U)(in T[] p, in U x) pure nothrow @nogc { + return reduce!((a, b) => a * x + b)(U(0), p.retro); } void main() { diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia new file mode 100644 index 0000000000..10e61c411a --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-1.julia @@ -0,0 +1,7 @@ + function horner(coef,x) + sum = coef[end] + for k = length(coef)-1:-1:1 + sum = coef[k] + x*sum + end + sum + end diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia new file mode 100644 index 0000000000..d54473fa0e --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-2.julia @@ -0,0 +1,2 @@ +julia> horner([-19,7,-4,6], 3) +128 diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-3.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-3.julia new file mode 100644 index 0000000000..f81bd00a36 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-3.julia @@ -0,0 +1 @@ +horner2(coef,x) = foldr((u,v) -> u + x*v, 0, coef) diff --git a/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-4.julia b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-4.julia new file mode 100644 index 0000000000..eaef6d1606 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/Julia/horners-rule-for-polynomial-evaluation-4.julia @@ -0,0 +1,2 @@ +julia> horner2([-19,7,-4,6], 3) +128 diff --git a/Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation.r b/Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.r similarity index 100% rename from Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation.r rename to Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-1.r diff --git a/Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-2.r b/Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-2.r new file mode 100644 index 0000000000..81dd324d29 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/R/horners-rule-for-polynomial-evaluation-2.r @@ -0,0 +1,5 @@ +horner <- function(x, v) { + Reduce(v, right=T, f=function(a, b) { + b * x + a + }) +} diff --git a/Task/Horners-rule-for-polynomial-evaluation/REBOL/horners-rule-for-polynomial-evaluation.rebol b/Task/Horners-rule-for-polynomial-evaluation/REBOL/horners-rule-for-polynomial-evaluation.rebol new file mode 100644 index 0000000000..0f3cc81ba6 --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/REBOL/horners-rule-for-polynomial-evaluation.rebol @@ -0,0 +1,11 @@ +REBOL [] + +horner: func [coeffs x] [ + result: 0 + foreach i reverse coeffs [ + result: (result * x) + i + ] + return result + ] + +print horner [-19 7 -4 6] 3 diff --git a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation.rexx b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx similarity index 64% rename from Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation.rexx rename to Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx index 0098590e53..7050cba02a 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation.rexx +++ b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-1.rexx @@ -1,15 +1,15 @@ /*REXX program shows using Horner's rule for polynomial evaluation.*/ numeric digits 30 /*use extra numeric precision. */ -parse arg x poly /*get value of X and coefficients*/ +parse arg x poly /*get value of X and coefficients*/ equ= /*start with equation clean slate*/ /*works for any degree equation. */ - do deg=0 until poly=='' /*get the equation's coefficients*/ - parse var poly c.deg poly /*get a equation coefficient.*/ - c.deg = (c.deg+0) / 1 /*normalize it (add 0, div by 1)*/ + do deg=0 until poly=='' /*get the equation's coefficients*/ + parse var poly c.deg poly /*get a equation coefficient.*/ + c.deg = c.deg / 1 /*normalize it (by dividing by 1)*/ if c.deg>=0 then c.deg = '+'c.deg /*if ¬ neg, then prefix a + sign.*/ equ=equ c.deg /*concatenate it to the equation.*/ - if deg\==0 & c.deg\=0 then /*if not the first coefficient & */ - equ = equ'∙x^'deg /* not 0, append power (^) of X.*/ + if deg\==0 & c.deg\=0 then equ= , /*if not the first coefficient & */ + equ'∙x^'deg /* not 0, append power (^) of X.*/ equ = equ ' ' /*insert some blanks, look pretty*/ end /*deg*/ @@ -22,5 +22,4 @@ a=c.deg a = a*x + c._ end /*j*/ say -say ' answer = ' a - /*stick a fork in it, we're done.*/ +say ' answer = ' a /*stick a fork in it, we're done.*/ diff --git a/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx new file mode 100644 index 0000000000..e565529a4c --- /dev/null +++ b/Task/Horners-rule-for-polynomial-evaluation/REXX/horners-rule-for-polynomial-evaluation-2.rexx @@ -0,0 +1,45 @@ +/* REXX --------------------------------------------------------------- +* 27.07.2012 Walter Pachl +* coefficients reversed to descending order of power +* I'm used to x**2+x-3 +* equation formatting prettified (coefficients 1 and 0) +*--------------------------------------------------------------------*/ + Numeric Digits 30 /* use extra numeric precision. */ + Parse Arg x poly /* get value of x and coefficients*/ + rpoly='' + Do p=0 To words(poly)-1 + rpoly=rpoly word(poly,words(poly)-p) + End + poly=rpoly + equ='' /* start with equation clean slate*/ + deg=words(poly)-1 + pdeg=deg + Do Until deg<0 /* get the equation's coefficients*/ + Parse Var poly c.deg poly /* in descending order of powers */ + c.deg=c.deg+0 /* normalize it */ + If c.deg>0 & deg0 Then /* build up the equation */ + equ=equ||prefix||term + deg=deg-1 + End + a=c.pdeg + Do p=pdeg To 1 By -1 /* apply Horner's rule. */ + pm1=p-1 + a=a*x+c.pm1 + End + Say ' x = ' x + Say ' degree = ' pdeg + Say ' equation = ' equ + Say ' ' + Say ' result = ' a diff --git a/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust b/Task/Horners-rule-for-polynomial-evaluation/Rust/horners-rule-for-polynomial-evaluation-2.rust index d467218103..5fb909779e 100644 --- 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 @@ -1,9 +1,11 @@ -// rust 0.9-pre +// rust 0.12-nightly + +std::num::zero; fn horner(cs:&[T], x:T) -> T { - cs.rev_iter().fold(std::num::zero::(), |acc, c| (acc*x) + (*c)) + cs.iter().rev().fold(zero::(), |acc, c| (acc*x) + (*c)) } fn main() { - println!("{}", horner([-19, 7, -4, 6], 3)); + println!("{}", horner([-19i, 7, -4, 6], 3i)); } diff --git a/Task/Host-introspection/00DESCRIPTION b/Task/Host-introspection/00DESCRIPTION index cbc30149a3..6709411336 100644 --- a/Task/Host-introspection/00DESCRIPTION +++ b/Task/Host-introspection/00DESCRIPTION @@ -1,3 +1,12 @@ +{{omit from|Brlcad}} +{{omit from|E}} +{{omit from|JavaScript}} +{{omit from|Maxima}} +{{omit from|ML/I}} +{{omit from|Openscad}} +{{omit from|TPP}} +{{omit from|Unlambda}} + Print the [[wp:Word_size#Word_size_choice|word size]] and [[wp:Endianness|endianness]] of the host machine. See also: [[Variable size/Get]] diff --git a/Task/Host-introspection/Go/host-introspection-1.go b/Task/Host-introspection/Go/host-introspection-1.go index c924b1e8ea..1a8b6685b1 100644 --- a/Task/Host-introspection/Go/host-introspection-1.go +++ b/Task/Host-introspection/Go/host-introspection-1.go @@ -1,38 +1,71 @@ package main import ( - "fmt" - "io/ioutil" - "strings" - "unsafe" + "fmt" + "io/ioutil" + "runtime" + "strconv" + "strings" + "unsafe" ) func main() { - // inspect an int variable to determine endianness - x := 1 - if *(*byte)(unsafe.Pointer(&x)) == 1 { - fmt.Println("little endian") - } else { - fmt.Println("big endian") - } - // inspect cpuinfo to determine word size (unix-like os only) - c, err := ioutil.ReadFile("/proc/cpuinfo") - if err != nil { - fmt.Println(err) - return - } - ls := strings.Split(string(c), "\n") - for _, l := range ls { - if strings.HasPrefix(l, "flags") { - for _, f := range strings.Fields(l) { - if f == "lm" { // "long mode" - fmt.Println("64 bit word size") - return - } - } - fmt.Println("32 bit word size") - return - } - } - fmt.Println("cpuinfo flags not found") + fmt.Println(runtime.Version(), runtime.GOOS, runtime.GOARCH) + + // Inspect a uint32 variable to determine endianness. + x := uint32(0x01020304) + switch *(*byte)(unsafe.Pointer(&x)) { + case 0x01: + fmt.Println("big endian") + case 0x04: + fmt.Println("little endian") + default: + fmt.Println("mixed endian?") + } + + // Usually one cares about the size the executible was compiled for + // rather than the actual underlying host's size. + + // There are several ways of determining the size of an int/uint. + fmt.Println(" strconv.IntSize =", strconv.IntSize) + // That uses the following definition we can also be done by hand + intSize := 32 << uint(^uint(0)>>63) + fmt.Println("32 << uint(^uint(0)>>63) =", intSize) + + // With Go 1.0, 64-bit architectures had 32-bit int and 64-bit + // uintptr. This was changed in Go 1.1. In general it would + // still be possible that int and uintptr (the type large enough + // to hold the bit pattern of any pointer) are of different sizes. + const bitsPerByte = 8 + fmt.Println(" sizeof(int) in bits:", unsafe.Sizeof(int(0))*bitsPerByte) + fmt.Println(" sizeof(uintptr) in bits:", unsafe.Sizeof(uintptr(0))*bitsPerByte) + // If we really want to know the architecture size the executable was + // compiled for and not the size of int it safest to take the max of those. + archSize := unsafe.Sizeof(int(0)) + if psize := unsafe.Sizeof(uintptr(0)); psize > archSize { + archSize = psize + } + fmt.Println(" compiled with word size:", archSize*bitsPerByte) + + // There are some *very* unportable ways to attempt to get the actual + // underlying hosts' word size. + // Inspect cpuinfo to determine word size (some unix-like OS' only). + c, err := ioutil.ReadFile("/proc/cpuinfo") + if err != nil { + fmt.Println(err) + return + } + ls := strings.Split(string(c), "\n") + for _, l := range ls { + if strings.HasPrefix(l, "flags") { + for _, f := range strings.Fields(l) { + if f == "lm" { // "long mode" + fmt.Println("64 bit word size") + return + } + } + fmt.Println("32 bit word size") + return + } + } } diff --git a/Task/Host-introspection/R/host-introspection.r b/Task/Host-introspection/R/host-introspection.r new file mode 100644 index 0000000000..6c701ccaed --- /dev/null +++ b/Task/Host-introspection/R/host-introspection.r @@ -0,0 +1,3 @@ +8 * .Machine$sizeof.long # e.g. 32 +Endianness +.Platform$endian # e.g. "little" diff --git a/Task/Host-introspection/Scala/host-introspection.scala b/Task/Host-introspection/Scala/host-introspection.scala new file mode 100644 index 0000000000..08984a43c3 --- /dev/null +++ b/Task/Host-introspection/Scala/host-introspection.scala @@ -0,0 +1,7 @@ +import java.nio.ByteOrder + +object ShowByteOrder extends App { + println(ByteOrder.nativeOrder()) + println(s"Word size: ${System.getProperty("sun.arch.data.model")}") + println(s"Endianness: ${System.getProperty("sun.cpu.endian")}") +} diff --git a/Task/Hostname/AppleScript/hostname.applescript b/Task/Hostname/AppleScript/hostname.applescript new file mode 100644 index 0000000000..4ca0231038 --- /dev/null +++ b/Task/Hostname/AppleScript/hostname.applescript @@ -0,0 +1 @@ +host name of (system info) diff --git a/Task/Hostname/Batch-File/hostname.bat b/Task/Hostname/Batch-File/hostname.bat new file mode 100644 index 0000000000..ecd88aee75 --- /dev/null +++ b/Task/Hostname/Batch-File/hostname.bat @@ -0,0 +1 @@ +hostname diff --git a/Task/Hostname/Factor/hostname.factor b/Task/Hostname/Factor/hostname.factor index 93baf2ba01..5b9ff9c0c2 100644 --- a/Task/Hostname/Factor/hostname.factor +++ b/Task/Hostname/Factor/hostname.factor @@ -1 +1,2 @@ +USE: io.sockets host-name diff --git a/Task/Hostname/Haskell/hostname.hs b/Task/Hostname/Haskell/hostname-1.hs similarity index 100% rename from Task/Hostname/Haskell/hostname.hs rename to Task/Hostname/Haskell/hostname-1.hs diff --git a/Task/Hostname/Haskell/hostname-2.hs b/Task/Hostname/Haskell/hostname-2.hs new file mode 100644 index 0000000000..fbbde8b3ff --- /dev/null +++ b/Task/Hostname/Haskell/hostname-2.hs @@ -0,0 +1,19 @@ +module GetHostName where + +import Foreign.Marshal.Array ( allocaArray0, peekArray0 ) +import Foreign.C.Types ( CInt(..), CSize(..) ) +import Foreign.C.String ( CString, peekCString ) +import Foreign.C.Error ( throwErrnoIfMinus1_ ) + +getHostName :: IO String +getHostName = do + let size = 256 + allocaArray0 size $ \ cstr -> do + throwErrnoIfMinus1_ "getHostName" $ c_gethostname cstr (fromIntegral size) + peekCString cstr + +foreign import ccall "gethostname" + c_gethostname :: CString -> CSize -> IO CInt + +main = do hostName <- getHostName + putStrLn hostName diff --git a/Task/Hostname/Oberon-2/hostname.oberon-2 b/Task/Hostname/Oberon-2/hostname.oberon-2 new file mode 100644 index 0000000000..f708dd7b83 --- /dev/null +++ b/Task/Hostname/Oberon-2/hostname.oberon-2 @@ -0,0 +1,7 @@ +MODULE HostName; +IMPORT + OS:ProcessParameters, + Out; +BEGIN + Out.Object("Host: " + ProcessParameters.GetEnv("HOSTNAME"));Out.Ln +END HostName. diff --git a/Task/Hostname/Vim-Script/hostname.vim b/Task/Hostname/Vim-Script/hostname.vim new file mode 100644 index 0000000000..080213c607 --- /dev/null +++ b/Task/Hostname/Vim-Script/hostname.vim @@ -0,0 +1 @@ +echo hostname() diff --git a/Task/Hough-transform/Haskell/hough-transform-1.hs b/Task/Hough-transform/Haskell/hough-transform-1.hs new file mode 100644 index 0000000000..1bdb14621f --- /dev/null +++ b/Task/Hough-transform/Haskell/hough-transform-1.hs @@ -0,0 +1,111 @@ +import Control.Monad (forM_, when) +import Data.Array ((!)) +import Data.Array.ST (newArray, writeArray, readArray, runSTArray) +import qualified Data.Foldable as F (maximum) +import System.Environment (getArgs, getProgName) + +-- Library JuicyPixels: +import Codec.Picture (DynamicImage(ImageRGB8, ImageRGBA8), Image, + PixelRGB8(PixelRGB8), PixelRGBA8(PixelRGBA8), + imageWidth, imageHeight, pixelAt, generateImage, + readImage, pixelMap, savePngImage) +import Codec.Picture.Types (extractLumaPlane, dropTransparency) + +dot :: Num a => (a, a) -> (a, a) -> a +dot (x1, y1) (x2, y2) = x1 * x2 + y1 * y2 + +mag :: Floating a => (a, a) -> a +mag a = sqrt $ dot a a + +sub :: Num a => (a, a) -> (a, a) -> (a, a) +sub (x1, y1) (x2, y2) = (x1 - x2, y1 - y2) + +fromIntegralP :: (Integral a, Num b) => (a, a) -> (b, b) +fromIntegralP (x, y) = (fromIntegral x, fromIntegral y) + +{- + Create a Hough space image with y+ measuring the distance from + the center of the input image on the range of 0 to half the hypotenuse + and x+ measuring from [0, 2 * pi]. + The origin is in the upper left, so y is increasing down. + The image is scaled according to thetaSize and distSize. +-} +hough :: Image PixelRGB8 -> Int -> Int -> Image PixelRGB8 +hough image thetaSize distSize = hImage + where + width = imageWidth image + height = imageHeight image + wMax = width - 1 + hMax = height - 1 + xCenter = wMax `div` 2 + yCenter = hMax `div` 2 + + lumaMap = extractLumaPlane image + + gradient x y = + let orig = pixelAt lumaMap x y + x' = pixelAt lumaMap (min (x + 1) wMax) y + y' = pixelAt lumaMap x (min (y + 1) hMax) + in fromIntegralP (orig - x', orig - y') + + gradMap = [((x, y), gradient x y) | x <- [0..wMax], y <- [0..hMax]] + + -- The longest distance from the center, half the hypotenuse of the image. + distMax :: Double + distMax = (sqrt . fromIntegral $ height ^ 2 + width ^ 2) / 2 + + {- + The accumulation bins of the polar values. + For each value in the gradient image, if the gradient length exceeds + some threshold, consider it evidence of a line and plot all of the + lines that go through that point in Hough space. + -} + accBin = runSTArray $ do + arr <- newArray ((0, 0), (thetaSize, distSize)) 0 + forM_ gradMap $ \((x, y), grad) -> do + let (x', y') = fromIntegralP $ (xCenter, yCenter) `sub` (x, y) + + when (mag grad > 127) $ + forM_ [0..thetaSize] $ \theta -> do + let theta' = (fromIntegral theta) * 360 / (fromIntegral thetaSize) + / 180 * pi :: Double + dist = (cos theta' * x' + sin theta' * y') + dist' = truncate $ dist * (fromIntegral distSize) / distMax + idx = (theta, dist') + + when (dist' >= 0 && dist' < distSize) $ do + old <- readArray arr idx + writeArray arr idx $ old + 1 + + return arr + + maxAcc = F.maximum accBin + + -- The image representation of the accumulation bins. + hTransform x y = + let l = 255 - (truncate $ (accBin ! (x, y)) / maxAcc * 255) + in PixelRGB8 l l l + + hImage = generateImage hTransform thetaSize distSize + +houghIO :: FilePath -> FilePath -> Int -> Int -> IO () +houghIO path outpath thetaSize distSize = do + image <- readImage path + case image of + Left err -> putStrLn err + Right (ImageRGB8 image') -> doImage image' + Right (ImageRGBA8 image') -> doImage $ pixelMap dropTransparency image' + _ -> putStrLn $ "Expecting RGB8 or RGBA8 image" + where + doImage image = do + let houghImage = hough image thetaSize distSize + savePngImage outpath $ ImageRGB8 houghImage + +main :: IO () +main = do + args <- getArgs + prog <- getProgName + case args of + [path, outpath, thetaSize, distSize] -> + houghIO path outpath (read thetaSize) (read distSize) + _ -> putStrLn $ "Usage: " ++ prog ++ " " diff --git a/Task/Hough-transform/Haskell/hough-transform-2.hs b/Task/Hough-transform/Haskell/hough-transform-2.hs new file mode 100644 index 0000000000..f85b4645ab --- /dev/null +++ b/Task/Hough-transform/Haskell/hough-transform-2.hs @@ -0,0 +1 @@ +HoughTransform Pentagon.png hough.png 360 360 diff --git a/Task/Huffman-coding/CoffeeScript/huffman-coding.coffee b/Task/Huffman-coding/CoffeeScript/huffman-coding.coffee new file mode 100644 index 0000000000..d8ebaa3963 --- /dev/null +++ b/Task/Huffman-coding/CoffeeScript/huffman-coding.coffee @@ -0,0 +1,85 @@ +huffman_encoding_table = (counts) -> + # counts is a hash where keys are characters and + # values are frequencies; + # return a hash where keys are codes and values + # are characters + + build_huffman_tree = -> + # returns a Huffman tree. Each node has + # cnt: total frequency of all chars in subtree + # c: character to be encoded (leafs only) + # children: children nodes (branches only) + q = min_queue() + for c, cnt of counts + q.enqueue cnt, + cnt: cnt + c: c + while q.size() >= 2 + a = q.dequeue() + b = q.dequeue() + cnt = a.cnt + b.cnt + node = + cnt: cnt + children: [a, b] + q.enqueue cnt, node + root = q.dequeue() + + root = build_huffman_tree() + + codes = {} + encode = (node, code) -> + if node.c? + codes[code] = node.c + else + encode node.children[0], code + "0" + encode node.children[1], code + "1" + + encode(root, "") + codes + +min_queue = -> + # This is very non-optimized; you could use a binary heap for better + # performance. Items with smaller priority get dequeued first. + arr = [] + enqueue: (priority, data) -> + i = 0 + while i < arr.length + if priority < arr[i].priority + break + i += 1 + arr.splice i, 0, + priority: priority + data: data + dequeue: -> + arr.shift().data + size: -> arr.length + _internal: -> + arr + +freq_count = (s) -> + cnts = {} + for c in s + cnts[c] ?= 0 + cnts[c] += 1 + cnts + +rpad = (s, n) -> + while s.length < n + s += ' ' + s + +examples = [ + "this is an example for huffman encoding" + "abcd" + "abbccccddddddddeeeeeeeee" +] + +for s in examples + console.log "---- #{s}" + counts = freq_count(s) + huffman_table = huffman_encoding_table(counts) + codes = (code for code of huffman_table).sort() + for code in codes + c = huffman_table[code] + console.log "#{rpad(code, 5)}: #{c} (#{counts[c]})" + console.log() diff --git a/Task/Huffman-coding/D/huffman-coding.d b/Task/Huffman-coding/D/huffman-coding.d index c9067702f5..5c54aea64a 100644 --- a/Task/Huffman-coding/D/huffman-coding.d +++ b/Task/Huffman-coding/D/huffman-coding.d @@ -1,21 +1,21 @@ -import std.stdio, std.algorithm, std.typecons, std.container,std.array; +import std.stdio, std.algorithm, std.typecons, std.container, std.array; -auto encode(T)(Group!("a == b", T[]) sf) { +auto encode(alias eq, R)(Group!(eq, R) sf) /*pure nothrow @safe*/ { auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], "")])) .array.heapify!q{b < a}; while (heap.length > 1) { auto lo = heap.front; heap.removeFront; auto hi = heap.front; heap.removeFront; - foreach (ref pair; lo[1]) pair[1] = '0' ~ pair[1]; - foreach (ref pair; hi[1]) pair[1] = '1' ~ pair[1]; + lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); + hi[1].each!((ref pair) => pair[1] = '1' ~ pair[1]); heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1])); } - return heap.front[1].schwartzSort!q{tuple(a[1].length, a[0])}; + return heap.front[1].schwartzSort!q{ tuple(a[1].length, a[0]) }; } -void main() { - auto s = "this is an example for huffman encoding"d; - foreach (p; s.dup.sort().release.group.encode) +void main() /*@safe*/ { + immutable s = "this is an example for huffman encoding"d; + foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); } diff --git a/Task/Huffman-coding/Eiffel/huffman-coding.e b/Task/Huffman-coding/Eiffel/huffman-coding.e new file mode 100644 index 0000000000..c1b0b5db2f --- /dev/null +++ b/Task/Huffman-coding/Eiffel/huffman-coding.e @@ -0,0 +1,188 @@ +class HUFFMAN_NODE[T -> COMPARABLE] +inherit + COMPARABLE + redefine + three_way_comparison + end +create + leaf_node, inner_node +feature {NONE} + leaf_node (a_probability: REAL_64; a_value: T) + do + probability := a_probability + value := a_value + is_leaf := true + + left := void + right := void + parent := void + end + + inner_node (a_left, a_right: HUFFMAN_NODE[T]) + do + left := a_left + right := a_right + + a_left.parent := Current + a_right.parent := Current + a_left.is_zero := true + a_right.is_zero := false + + probability := a_left.probability + a_right.probability + is_leaf := false + end + +feature + probability: REAL_64 + value: detachable T + + + is_leaf: BOOLEAN + is_zero: BOOLEAN assign set_is_zero + + set_is_zero (a_value: BOOLEAN) + do + is_zero := a_value + end + + left: detachable HUFFMAN_NODE[T] + right: detachable HUFFMAN_NODE[T] + parent: detachable HUFFMAN_NODE[T] assign set_parent + + set_parent (a_parent: detachable HUFFMAN_NODE[T]) + do + parent := a_parent + end + + is_root: BOOLEAN + do + Result := parent = void + end + + bit_value: INTEGER + do + if is_zero then + Result := 0 + else + Result := 1 + end + end +feature -- comparable implementation + is_less alias "<" (other: like Current): BOOLEAN + do + Result := three_way_comparison (other) = -1 + end + + three_way_comparison (other: like Current): INTEGER + do + Result := -probability.three_way_comparison (other.probability) + end +end + +class HUFFMAN +create + make +feature {NONE} + make(a_string: STRING) + require + non_empty_string: a_string.count > 0 + local + l_queue: HEAP_PRIORITY_QUEUE[HUFFMAN_NODE[CHARACTER]] + l_counts: HASH_TABLE[INTEGER, CHARACTER] + l_node: HUFFMAN_NODE[CHARACTER] + l_left, l_right: HUFFMAN_NODE[CHARACTER] + do + create l_queue.make (a_string.count) + create l_counts.make (10) + + across a_string as char + loop + if not l_counts.has (char.item) then + l_counts.put (0, char.item) + end + l_counts.replace (l_counts.at (char.item) + 1, char.item) + end + + create leaf_dictionary.make(l_counts.count) + + across l_counts as kv + loop + create l_node.leaf_node ((kv.item * 1.0) / a_string.count, kv.key) + l_queue.put (l_node) + leaf_dictionary.put (l_node, kv.key) + end + + from + until + l_queue.count <= 1 + loop + l_left := l_queue.item + l_queue.remove + l_right := l_queue.item + l_queue.remove + + create l_node.inner_node (l_left, l_right) + l_queue.put (l_node) + end + + root := l_queue.item + root.is_zero := false + end +feature + root: HUFFMAN_NODE[CHARACTER] + leaf_dictionary: HASH_TABLE[HUFFMAN_NODE[CHARACTER], CHARACTER] + + encode(a_value: CHARACTER): STRING + require + encodable: leaf_dictionary.has (a_value) + local + l_node: HUFFMAN_NODE[CHARACTER] + do + Result := "" + if attached leaf_dictionary.item (a_value) as attached_node then + l_node := attached_node + from + + until + l_node.is_root + loop + Result.append_integer (l_node.bit_value) + if attached l_node.parent as parent then + l_node := parent + end + end + + Result.mirror + end + end +end + +class + APPLICATION +create + make + +feature {NONE} + make -- entry point + local + l_str: STRING + huff: HUFFMAN + chars: BINARY_SEARCH_TREE_SET[CHARACTER] + do + l_str := "this is an example for huffman encoding" + + create huff.make (l_str) + + create chars.make + chars.fill (l_str) + + from + chars.start + until + chars.off + loop + print (chars.item.out + ": " + huff.encode (chars.item) + "%N") + chars.forth + end + end +end diff --git a/Task/Huffman-coding/Groovy/huffman-coding-1.groovy b/Task/Huffman-coding/Groovy/huffman-coding-1.groovy new file mode 100644 index 0000000000..8a2106e45a --- /dev/null +++ b/Task/Huffman-coding/Groovy/huffman-coding-1.groovy @@ -0,0 +1,50 @@ +import groovy.transform.* + +@Canonical +@Sortable(includes = ['freq', 'letter']) +class Node { + String letter + int freq + Node left + Node right + boolean isLeaf() { left == null && right == null } +} + +Map correspondance(Node n, Map corresp = [:], String prefix = '') { + if (n.isLeaf()) { + corresp[n.letter] = prefix ?: '0' + } else { + correspondance(n.left, corresp, prefix + '0') + correspondance(n.right, corresp, prefix + '1') + } + return corresp +} + +Map huffmanCode(String message) { + def queue = message.toList().countBy { it } // char frequencies + .collect { String letter, int freq -> // transformed into tree nodes + new Node(letter, freq) + } as TreeSet // put in a queue that maintains ordering + + while(queue.size() > 1) { + def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] + + queue << new Node( + freq: nodeLeft.freq + nodeRight.freq, + letter: nodeLeft.letter + nodeRight.letter, + left: nodeLeft, right: nodeRight + ) + } + + return correspondance(queue.pollFirst()) +} + +String encode(CharSequence msg, Map codeTable) { + msg.collect { codeTable[it] }.join() +} + +String decode(String codedMsg, Map codeTable, String decoded = '') { + def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } + pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) + : decoded +} diff --git a/Task/Huffman-coding/Groovy/huffman-coding-2.groovy b/Task/Huffman-coding/Groovy/huffman-coding-2.groovy new file mode 100644 index 0000000000..34c02f770b --- /dev/null +++ b/Task/Huffman-coding/Groovy/huffman-coding-2.groovy @@ -0,0 +1,10 @@ +def message = "this is an example for huffman encoding" + +def codeTable = huffmanCode(message) +codeTable.each { k, v -> println "$k: $v" } + +def encoded = encode(message, codeTable) +println encoded + +def decoded = decode(encoded, codeTable) +println decoded diff --git a/Task/Huffman-coding/Mathematica/huffman-coding.math b/Task/Huffman-coding/Mathematica/huffman-coding.math new file mode 100644 index 0000000000..aeaec95ae5 --- /dev/null +++ b/Task/Huffman-coding/Mathematica/huffman-coding.math @@ -0,0 +1,13 @@ +huffman[s_String] := huffman[Characters[s]]; +huffman[l_List] := Module[{merge, structure, rules}, + + (*merge front two branches. list is assumed to be sorted*) + merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; + + structure = FixedPoint[ + Composition[merge, SortBy[#, Last] &], + Tally[l]][[1, 1]]; + + rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; + + {Flatten[l /. rules], rules}]; diff --git a/Task/Huffman-coding/Objective-C/huffman-coding.m b/Task/Huffman-coding/Objective-C/huffman-coding.m index 9912d7bf4e..745d0bd159 100644 --- a/Task/Huffman-coding/Objective-C/huffman-coding.m +++ b/Task/Huffman-coding/Objective-C/huffman-coding.m @@ -4,13 +4,13 @@ @interface HuffmanTree : NSObject { int freq; } --(id)initWithFreq:(int)f; +-(instancetype)initWithFreq:(int)f; @property (nonatomic, readonly) int freq; @end @implementation HuffmanTree @synthesize freq; // the frequency of this tree --(id)initWithFreq:(int)f { +-(instancetype)initWithFreq:(int)f { if (self = [super init]) { freq = f; } @@ -41,12 +41,12 @@ CFComparisonResult HuffmanCompare(const void *ptr1, const void *ptr2, void *unus char value; // the character this leaf represents } @property (readonly) char value; --(id)initWithFreq:(int)f character:(char)c; +-(instancetype)initWithFreq:(int)f character:(char)c; @end @implementation HuffmanLeaf @synthesize value; --(id)initWithFreq:(int)f character:(char)c { +-(instancetype)initWithFreq:(int)f character:(char)c { if (self = [super initWithFreq:f]) { value = c; } @@ -59,12 +59,12 @@ CFComparisonResult HuffmanCompare(const void *ptr1, const void *ptr2, void *unus HuffmanTree *left, *right; // subtrees } @property (readonly) HuffmanTree *left, *right; --(id)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r; +-(instancetype)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r; @end @implementation HuffmanNode @synthesize left, right; --(id)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r { +-(instancetype)initWithLeft:(HuffmanTree *)l right:(HuffmanTree *)r { if (self = [super initWithFreq:l.freq+r.freq]) { left = l; right = r; diff --git a/Task/Huffman-coding/Perl/huffman-coding.pl b/Task/Huffman-coding/Perl/huffman-coding.pl new file mode 100644 index 0000000000..37053e5729 --- /dev/null +++ b/Task/Huffman-coding/Perl/huffman-coding.pl @@ -0,0 +1,57 @@ +use 5.10.0; +use strict; + +# produce encode and decode dictionary from a tree +sub walk { + my ($node, $code, $h, $rev_h) = @_; + + my $c = $node->[0]; + if (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 } + else { $h->{$c} = $code; $rev_h->{$code} = $c } + + $h, $rev_h +} + +# make a tree, and return resulting dictionaries +sub mktree { + my (%freq, @nodes); + $freq{$_}++ for split '', shift; + @nodes = map([$_, $freq{$_}], keys %freq); + + do { # poor man's priority queue + @nodes = sort {$a->[1] <=> $b->[1]} @nodes; + my ($x, $y) = splice @nodes, 0, 2; + push @nodes, [[$x, $y], $x->[1] + $y->[1]] + } while (@nodes > 1); + + walk($nodes[0], '', {}, {}) +} + +sub encode { + my ($str, $dict) = @_; + join '', map $dict->{$_}//die("bad char $_"), split '', $str +} + +sub decode { + my ($str, $dict) = @_; + my ($seg, @out) = (""); + + # append to current segment until it's in the dictionary + for (split '', $str) { + $seg .= $_; + my $x = $dict->{$seg} // next; + push @out, $x; + $seg = ''; + } + die "bad code" if length($seg); + join '', @out +} + +my $txt = 'this is an example for huffman encoding'; +my ($h, $rev_h) = mktree($txt); +for (keys %$h) { print "'$_': $h->{$_}\n" } + +my $enc = encode($txt, $h); +print "$enc\n"; + +print decode($enc, $rev_h), "\n"; diff --git a/Task/Huffman-coding/Scheme/huffman-coding.ss b/Task/Huffman-coding/Scheme/huffman-coding.ss new file mode 100644 index 0000000000..9bb9e2ec4b --- /dev/null +++ b/Task/Huffman-coding/Scheme/huffman-coding.ss @@ -0,0 +1,54 @@ +(define (char-freq port table) + (if + (eof-object? (peek-char port)) + table + (char-freq port (add-char (read-char port) table)))) + +(define (add-char char table) + (cond + ((null? table) (list (list char 1))) + ((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table))) + (#t (cons (car table) (add-char char (cdr table)))))) + +(define (nodeify table) + (map (lambda (x) (list x '() '())) table)) + +(define node-freq cadar) + +(define (huffman-tree nodes) + (let ((queue (sort nodes (lambda (x y) (< (node-freq x) (node-freq y)))))) + (if + (null? (cdr queue)) + (car queue) + (huffman-tree + (cons + (list + (list 'notleaf (+ (node-freq (car queue)) (node-freq (cadr queue)))) + (car queue) + (cadr queue)) + (cddr queue)))))) + +(define (list-encodings tree chars) + (for-each (lambda (c) (format #t "~a:~a~%" c (encode c tree))) chars)) + +(define (encode char tree) + (cond + ((null? tree) #f) + ((eq? (caar tree) char) '()) + (#t + (let ((left (encode char (cadr tree))) (right (encode char (caddr tree)))) + (cond + ((not (or left right)) #f) + (left (cons #\1 left)) + (right (cons #\0 right))))))) + +(define (decode digits tree) + (cond + ((not (eq? (caar tree) 'notleaf)) (caar tree)) + ((eq? (car digits) #\0) (decode (cdr digits) (cadr tree))) + (#t (decode (cdr digits) (caddr tree))))) + +(define input "this is an example for huffman encoding") +(define freq-table (char-freq (open-input-string input) '())) +(define tree (huffman-tree (nodeify freq-table))) +(list-encodings tree (map car freq-table)) diff --git a/Task/I-before-E-except-after-C/00DESCRIPTION b/Task/I-before-E-except-after-C/00DESCRIPTION index 8e79bca917..4501b9a851 100644 --- a/Task/I-before-E-except-after-C/00DESCRIPTION +++ b/Task/I-before-E-except-after-C/00DESCRIPTION @@ -1,7 +1,9 @@ -The phrase [[wp:I before E except after C|"I before E, except after C"]] is a widely known mnemonic which is supposed to help when spelling English words. +The phrase [[wp:I before E except after C|"I before E, except after C"]] is a +widely known mnemonic which is supposed to help when spelling English words. ;Task Description: -Using the word list from [http://www.puzzlers.org/pub/wordlists/unixdict.txt http://www.puzzlers.org/pub/wordlists/unixdict.txt], check if the two sub-clauses of the phrase are plausible individually: +Using the word list from [http://www.puzzlers.org/pub/wordlists/unixdict.txt http://www.puzzlers.org/pub/wordlists/unixdict.txt], check if the two sub-clauses +of the phrase are plausible individually: # ''"I before E when not preceded by C"'' # ''"E before I when preceded by C"'' 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 index 03ab88800b..cd6b57d388 100644 --- 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 @@ -1,15 +1,27 @@ -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"] +wordlist = + Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", + "Words"]; +Print["The number of words in unixdict.txt = " <> + ToString[Length[wordlist]]] +StringMatchQ[#, ___ ~~ "c" ~~ "i" ~~ "e" ~~ ___] & /@ wordlist ; +cie = Count[%, True]; +StringMatchQ[#, ___ ~~ "c" ~~ "e" ~~ "i" ~~ ___] & /@ wordlist ; +cei = Count[%, True]; +StringMatchQ[#, ___ ~~ "i" ~~ "e" ~~ ___] & /@ wordlist ; +ie = Count[%, True] - cie; +StringMatchQ[#, ___ ~~ "e" ~~ "i" ~~ ___] & /@ wordlist ; +ei = Count[%, True] - cei; +test1 = ie > 2 ei; +Print["The rule \"I before E when not preceded by C\" is " <> + If[test1, "PLAUSIBLE", "NOT PLAUSIBLE"]] +Print["There were " <> ToString[ie] <> " examples and " <> + ToString[ei] <> " counter examples, for a ratio of " <> + ToString[N[ie/ei]]] +test2 = cei > 2 cie; +Print["The rule \"E before I when preceded by C\" is " <> + If[test2, "PLAUSIBLE", "NOT PLAUSIBLE"]] +Print["There were " <> ToString[cei] <> " examples and " <> + ToString[cie] <> " counter examples, for a ratio of " <> + ToString[N[cei/cie]]] +Print["Overall the rule is " <> + If[test1 && test2, "PLAUSIBLE", "NOT 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 index 4ac2f42340..2cf7eee15c 100644 --- 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 @@ -1,6 +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 +The number of words in unixdict.txt = 25104 +The rule "I before E when not preceded by C" is PLAUSIBLE +There were 465 examples and 213 counter examples, for a ratio of 2.1831 +The rule "E before I when preceded by C" is NOT PLAUSIBLE +There were 13 examples and 24 counter examples, for a ratio of 0.541667 +Overall the rule is NOT PLAUSIBLE diff --git a/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala b/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala new file mode 100644 index 0000000000..657ff52a0d --- /dev/null +++ b/Task/I-before-E-except-after-C/Scala/i-before-e-except-after-c.scala @@ -0,0 +1,23 @@ +object I_before_E_except_after_C extends App { + val testIE1 = "(^|[^c])ie".r // i before e when not preceded by c + val testIE2 = "cie".r // i before e when preceded by c + var countsIE = (0,0) + + val testCEI1 = "cei".r // e before i when preceded by c + val testCEI2 = "(^|[^c])ei".r // e before i when not preceded by c + var countsCEI = (0,0) + + scala.io.Source.fromURL("http://www.puzzlers.org/pub/wordlists/unixdict.txt").getLines.map(_.toLowerCase).foreach{word => + if (testIE1.findFirstIn(word).isDefined) countsIE = (countsIE._1 + 1, countsIE._2) + if (testIE2.findFirstIn(word).isDefined) countsIE = (countsIE._1, countsIE._2 + 1) + if (testCEI1.findFirstIn(word).isDefined) countsCEI = (countsCEI._1 + 1, countsCEI._2) + if (testCEI2.findFirstIn(word).isDefined) countsCEI = (countsCEI._1, countsCEI._2 + 1) + } + + def plausible(counts: (Int,Int)) = counts._1 > (2 * counts._2) + def plausibility(plausible: Boolean) = if (plausible) "plausible" else "implausible" + def plausibility(counts: (Int, Int)): String = plausibility(plausible(counts)) + println("I before E when not preceded by C: "+plausibility(countsIE)) + println("E before I when preceded by C: "+plausibility(countsCEI)) + println("Overall: "+plausibility(plausible(countsIE) && plausible(countsCEI))) +} diff --git a/Task/Identity-matrix/00DESCRIPTION b/Task/Identity-matrix/00DESCRIPTION index 160237f501..663048ff07 100644 --- a/Task/Identity-matrix/00DESCRIPTION +++ b/Task/Identity-matrix/00DESCRIPTION @@ -1,4 +1,7 @@ -Build an [[wp:identity matrix|identity matrix]] of a size known at runtime. An identity matrix is a square matrix, of size ''n'' × ''n'', where the diagonal elements are all 1s, and the other elements are all 0s. +Build an [[wp:identity matrix|identity matrix]] of a size known at runtime. + +An identity matrix is a square matrix, of size ''n'' × ''n'', +where the diagonal elements are all 1s, and the other elements are all 0s. I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ diff --git a/Task/Identity-matrix/ATS/identity-matrix.ats b/Task/Identity-matrix/ATS/identity-matrix.ats new file mode 100644 index 0000000000..71fba3c895 --- /dev/null +++ b/Task/Identity-matrix/ATS/identity-matrix.ats @@ -0,0 +1,33 @@ +(* ****** ****** *) +// +// How to compile: +// +// patscc -DATS_MEMALLOC_LIBC -o idmatrix idmatrix.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +extern +fun +idmatrix{n:nat}(n: size_t(n)): matrixref(int, n, n) +implement +idmatrix(n) = +matrixref_tabulate_cloref (n, n, lam(i, j) => bool2int0(i = j)) + +(* ****** ****** *) + +implement +main0 () = +{ +// +val N = 5 +// +val M = idmatrix(i2sz(N)) +val () = fprint_matrixref_sep (stdout_ref, M, i2sz(N), i2sz(N), " ", "\n") +val () = fprint_newline (stdout_ref) +// +} (* end of [main0] *) diff --git a/Task/Identity-matrix/Eiffel/identity-matrix.e b/Task/Identity-matrix/Eiffel/identity-matrix.e new file mode 100644 index 0000000000..ffeeb3ee35 --- /dev/null +++ b/Task/Identity-matrix/Eiffel/identity-matrix.e @@ -0,0 +1,61 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + make + -- Run application. + local + dim : INTEGER -- Dimension of the identity matrix + do + from dim := 1 until dim > 10 loop + print_matrix( identity_matrix(dim) ) + dim := dim + 1 + io.new_line + end + + end + +feature -- Access + + identity_matrix(dim : INTEGER) : ARRAY2[REAL_64] + + require + dim > 0 + local + matrix : ARRAY2[REAL_64] + i : INTEGER + do + + create matrix.make_filled (0.0, dim, dim) + from i := 1 until i > dim loop + matrix.put(1.0, i, i) + i := i + 1 + end + + Result := matrix + end + + print_matrix(matrix : ARRAY2[REAL_64]) + local + i, j : INTEGER + do + from i := 1 until i > matrix.height loop + print("[ ") + from j := 1 until j > matrix.width loop + print(matrix.item (i, j)) + print(" ") + j := j + 1 + end + print("]%N") + i := i + 1 + end + end + +end diff --git a/Task/Identity-matrix/JavaScript/identity-matrix.js b/Task/Identity-matrix/JavaScript/identity-matrix.js new file mode 100644 index 0000000000..12d4e61c60 --- /dev/null +++ b/Task/Identity-matrix/JavaScript/identity-matrix.js @@ -0,0 +1,3 @@ +function im(n) { + return Array.apply(null, new Array(n)).map(function(x, i, a) { return a.map(function(y, k) { return i === k ? 1 : 0; }) }); +} diff --git a/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 b/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 new file mode 100644 index 0000000000..a0be623cce --- /dev/null +++ b/Task/Identity-matrix/Perl-6/identity-matrix-3.pl6 @@ -0,0 +1,3 @@ +sub identity-matrix($n) { + [1, 0 xx $n-1], *.rotate(-1).item ... *[*-1] == 1 +} diff --git a/Task/Identity-matrix/REXX/identity-matrix-1.rexx b/Task/Identity-matrix/REXX/identity-matrix-1.rexx index aef3b23ed6..f2a358af8b 100644 --- a/Task/Identity-matrix/REXX/identity-matrix-1.rexx +++ b/Task/Identity-matrix/REXX/identity-matrix-1.rexx @@ -1,28 +1,33 @@ -/*REXX program to create and display an identity matrix. */ -call identity_matrix 4 /*build and display a 4x4 matrix.*/ -call identity_matrix 5 /*build and display a 5x5 matrix.*/ +/*REXX program creates and displays any sized identity matrix. */ + do k=3 to 6 /* [↓] build & display a matrix.*/ + call identity_matrix k /*build and display a kxk matrix.*/ + end /*k*/ /* [↑] use general─purpose disp.*/ exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────IDENTITY_MATRIX subroutine───────*/ +/*──────────────────────────────────IDENTITY_MATRIX subroutine──────────*/ identity_matrix: procedure; parse arg n; $= - do r=1 for n /*build indentity matrix, by row,*/ - do c=1 for n /* and by cow.*/ - $=$ (r==c) /*append zero or one (if on diag)*/ - end /*c*/ - end /*r*/ + do r=1 for n /*build identity matrix, by row,*/ + do c=1 for n /* ··· and by col.*/ + $=$ (r==c) /*append zero or one (if on diag)*/ + end /*c*/ + end /*r*/ -call showMatrix 'identity matrix of size' n,$,n +call showMatrix 'identity matrix of size' n, $ return -/*─────────────────────────────────────TELL subroutine───&find the order*/ -showMatrix: procedure; parse arg hdr,x,order,sep; if sep=='' then sep='═' - width=2 /*width of field to be used to display the elements*/ -decPlaces=1 /*# decimal places to the right of decimal point. */ -say; say center(hdr,max(length(hdr)+6,(width+1)*words(x)%order),sep); say -#=0 - do row=1 for order; aLine= - do col=1 for order; #=#+1 - aLine=aLine right(format(word(x,#),,decPlaces)/1, width) - end /*col*/ /*dividing by 1 normalizes the #.*/ - say aLine - end /*row*/ +/*──────────────────────────────────SHOWMATRIX subroutine───────────────*/ +showMatrix: procedure; parse arg hdr,x; #=words(x) /*#: # of elements*/ +dp=0 /*DP: dec fraction width.*/ +w=0 /*W: integer part width.*/ + do n=1 until n*n>=#; _=word(x,n) /*find matrix order (size).*/ + parse var _ y '.' f; w=max(w, length(y)); dp=max(dp, length(f)) + end /*n*/ /* [↑] idiomatically find widths to align output*/ +w=w+1 +say; say center(hdr, max(length(hdr)+6, (w+1)*#%n), '─'); say +#=0 /*#: element #*/ + do row=1 for n; _=left('',n+w) /*indentation.*/ + do col=1 for n; #=#+1 /*bump element*/ + _=_ right(format(word(x, #), , dp)/1, w) + end /*col*/ /* [↑] division by 1 normalizes #*/ + say _ /*display one line of the matrix. */ + end /*row*/ return diff --git a/Task/Identity-matrix/Ruby/identity-matrix.rb b/Task/Identity-matrix/Ruby/identity-matrix-1.rb similarity index 100% rename from Task/Identity-matrix/Ruby/identity-matrix.rb rename to Task/Identity-matrix/Ruby/identity-matrix-1.rb diff --git a/Task/Identity-matrix/Ruby/identity-matrix-2.rb b/Task/Identity-matrix/Ruby/identity-matrix-2.rb new file mode 100644 index 0000000000..9770a29cce --- /dev/null +++ b/Task/Identity-matrix/Ruby/identity-matrix-2.rb @@ -0,0 +1,4 @@ +2.1.1 :001 > require "matrix" + => true +2.1.1 :002 > Matrix.identity(5) + => Matrix[[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]] diff --git a/Task/Image-convolution/D/image-convolution.d b/Task/Image-convolution/D/image-convolution.d index 6385b01cca..af0c2b853f 100644 --- a/Task/Image-convolution/D/image-convolution.d +++ b/Task/Image-convolution/D/image-convolution.d @@ -11,7 +11,7 @@ Image!Color convolve(Color)(in Image!Color im, in ConvolutionFilter filter) pure nothrow in { assert(im !is null); - assert(!isnan(filter.divisor) && !isnan(filter.offset_)); + assert(!filter.divisor.isNaN && !filter.offset_.isNaN); assert(filter.divisor != 0); assert(filter.kernel.length > 0 && filter.kernel[0].length > 0); foreach (const row; filter.kernel) // Is rectangular. diff --git a/Task/Image-convolution/MATLAB/image-convolution.m b/Task/Image-convolution/MATLAB/image-convolution.m new file mode 100644 index 0000000000..daae82a890 --- /dev/null +++ b/Task/Image-convolution/MATLAB/image-convolution.m @@ -0,0 +1,168 @@ +function testConvImage + Im = [1 2 1 5 5 ; ... + 1 2 7 9 9 ; ... + 5 5 5 5 5 ; ... + 5 2 2 2 2 ; ... + 1 1 1 1 1 ]; % Sample image for example illustration only + Ker = [1 2 1 ; ... + 2 4 2 ; ... + 1 2 1 ]; % Gaussian smoothing (without normalizing) + fprintf('Original image:\n') + disp(Im) + fprintf('Original kernal:\n') + disp(Ker) + fprintf('Padding with zeroes:\n') + disp(convImage(Im, Ker, 'zeros')) + fprintf('Padding with fives:\n') + disp(convImage(Im, Ker, 'value', 5)) + fprintf('Duplicating border pixels to pad image:\n') + disp(convImage(Im, Ker, 'extend')) + fprintf('Renormalizing kernal and using only values within image:\n') + disp(convImage(Im, Ker, 'partial')) + fprintf('Only processing inner (non-border) pixels:\n') + disp(convImage(Im, Ker, 'none')) +% Ker = [1 2 1 ; ... +% 2 4 2 ; ... +% 1 2 1 ]./16; +% Im = imread('testConvImageTestImage.png', 'png'); +% figure +% imshow(imresize(Im, 10)) +% title('Original image') +% figure +% imshow(imresize(convImage(Im, Ker, 'zeros'), 10)) +% title('Padding with zeroes') +% figure +% imshow(imresize(convImage(Im, Ker, 'value', 50), 10)) +% title('Padding with fifty: 50') +% figure +% imshow(imresize(convImage(Im, Ker, 'extend'), 10)) +% title('Duplicating border pixels to pad image') +% figure +% imshow(imresize(convImage(Im, Ker, 'partial'), 10)) +% title('Renormalizing kernal and using only values within image') +% figure +% imshow(imresize(convImage(Im, Ker, 'none'), 10)) +% title('Only processing inner (non-border) pixels') +end + +function ImOut = convImage(Im, Ker, varargin) +% ImOut = convImage(Im, Ker) +% Filters an image using sliding-window kernal convolution. +% Convolution is done layer-by-layer. Use rgb2gray if single-layer needed. +% Zero-padding convolution will be used if no border handling is specified. +% Im - Array containing image data (output from imread) +% Ker - 2-D array to convolve image, needs odd number of rows and columns +% ImOut - Filtered image, same dimensions and datatype as Im +% +% ImOut = convImage(Im, Ker, 'zeros') +% Image will be padded with zeros when calculating convolution +% (useful for magnitude calculations). +% +% ImOut = convImage(Im, Ker, 'value', padVal) +% Image will be padded with padVal when calculating convolution +% (possibly useful for emphasizing certain data with unusual kernal) +% +% ImOut = convImage(Im, Ker, 'extend') +% Image will be padded with the value of the closest image pixel +% (useful for smoothing or blurring filters). +% +% ImOut = convImage(Im, Ker, 'partial') +% Image will not be padded. Borders will be convoluted with only valid pixels, +% and convolution matrix will be renormalized counting only the pixels within +% the image (also useful for smoothing or blurring filters). +% +% ImOut = convImage(Im, Ker, 'none') +% Image will not be padded. Convolution will only be applied to inner pixels +% (useful for edge and corner detection filters) + + % Handle input + if mod(size(Ker, 1), 2) ~= 1 || mod(size(Ker, 2), 2) ~= 1 + eid = sprintf('%s:evenRowsCols', mfilename); + error(eid,'''Ker'' parameter must have odd number of rows and columns.') + elseif nargin > 4 + eid = sprintf('%s:maxrhs', mfilename); + error(eid, 'Too many input arguments.'); + elseif nargin == 4 && ~strcmp(varargin{1}, 'value') + eid = sprintf('%s:invalidParameterCombination', mfilename); + error(eid, ['The ''padVal'' parameter is only valid with the ' ... + '''value'' option.']) + elseif nargin < 4 && strcmp(varargin{1}, 'value') + eid = sprintf('%s:minrhs', mfilename); + error(eid, 'Not enough input arguments.') + elseif nargin < 3 + method = 'zeros'; + else + method = lower(varargin{1}); + if ~any(strcmp(method, {'zeros' 'value' 'extend' 'partial' 'none'})) + eid = sprintf('%s:invalidParameter', mfilename); + error(eid, 'Invalid option parameter. Must be one of:%s', ... + sprintf('\n\t\t%s', ... + 'zeros', 'value', 'extend', 'partial', 'none')) + end + end + + % Gather information and prepare for convolution + [nImRows, nImCols, nImLayers] = size(Im); + classIm = class(Im); + Im = double(Im); + ImOut = zeros(nImRows, nImCols, nImLayers); + [nKerRows, nKerCols] = size(Ker); + nPadRows = nImRows+nKerRows-1; + nPadCols = nImCols+nKerCols-1; + padH = (nKerRows-1)/2; + padW = (nKerCols-1)/2; + + % Convolute on a layer-by-layer basis + for k = 1:nImLayers + if strcmp(method, 'zeros') + ImOut(:, :, k) = conv2(Im(:, :, k), Ker, 'same'); + elseif strcmp(method, 'value') + padding = varargin{2}.*ones(nPadRows, nPadCols); + padding(padH+1:end-padH, padW+1:end-padW) = Im(:, :, k); + ImOut(:, :, k) = conv2(padding, Ker, 'valid'); + elseif strcmp(method, 'extend') + padding = zeros(nPadRows, nPadCols); + padding(padH+1:end-padH, padW+1:end-padW) = Im(:, :, k); % Middle + padding(1:padH, 1:padW) = Im(1, 1, k); % TopLeft + padding(end-padH+1:end, 1:padW) = Im(end, 1, k); % BotLeft + padding(1:padH, end-padW+1:end) = Im(1, end, k); % TopRight + padding(end-padH+1:end, end-padW+1:end) = Im(end, end, k);% BotRight + padding(padH+1:end-padH, 1:padW) = ... + repmat(Im(:, 1, k), 1, padW); % Left + padding(padH+1:end-padH, end-padW+1:end) = ... + repmat(Im(:, end, k), 1, padW); % Right + padding(1:padH, padW+1:end-padW) = ... + repmat(Im(1, :, k), padH, 1); % Top + padding(end-padH+1:end, padW+1:end-padW) = ... + repmat(Im(end, :, k), padH, 1); % Bottom + ImOut(:, :, k) = conv2(padding, Ker, 'valid'); + elseif strcmp(method, 'partial') + ImOut(padH+1:end-padH, padW+1:end-padW, k) = ... + conv2(Im(:, :, k), Ker, 'valid'); % Middle + unprocessed = true(nImRows, nImCols); + unprocessed(padH+1:end-padH, padW+1:end-padW) = false; % Border + for r = 1:nImRows + for c = 1:nImCols + if unprocessed(r, c) + limitedIm = Im(max(1, r-padH):min(nImRows, r+padH), ... + max(1, c-padW):min(nImCols, c+padW), k); + limitedKer = Ker(max(1, 2-r+padH): ... + min(nKerRows, nKerRows+nImRows-r-padH), ... + max(1, 2-c+padW):... + min(nKerCols, nKerCols+nImCols-c-padW)); + limitedKer = limitedKer.*sum(Ker(:))./ ... + sum(limitedKer(:)); + ImOut(r, c, k) = sum(sum(limitedIm.*limitedKer)); + end + end + end + else % method is 'none' + ImOut(:, :, k) = Im(:, :, k); + ImOut(padH+1:end-padH, padW+1:end-padW, k) = ... + conv2(Im(:, :, k), Ker, 'valid'); + end + end + + % Convert back to former image data type + ImOut = cast(ImOut, classIm); +end diff --git a/Task/Image-noise/00DESCRIPTION b/Task/Image-noise/00DESCRIPTION index 7ac81df3b7..0fd43fe6ad 100644 --- a/Task/Image-noise/00DESCRIPTION +++ b/Task/Image-noise/00DESCRIPTION @@ -1,4 +1,14 @@ -Generate a random black and white 320x240 image continuously, showing FPS (frames per second). +{{omit from|AWK}} +{{omit from|Bc}} +{{omit from|Blast}} +{{omit from|Ed}} +{{omit from|Lotus 123 Macro Scripting}} +{{omit from|MIRC Scripting Language}} +{{omit from|ML/I}} +{{omit from|Sed}} +[[Category:Raster graphics operations]] +Generate a random black and white 320x240 image continuously, +showing FPS (frames per second). Sample image: diff --git a/Task/Image-noise/00META.yaml b/Task/Image-noise/00META.yaml new file mode 100644 index 0000000000..76996c13ba --- /dev/null +++ b/Task/Image-noise/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Graphics diff --git a/Task/Image-noise/Common-Lisp/image-noise.lisp b/Task/Image-noise/Common-Lisp/image-noise.lisp index 7719da7dac..d270d59edd 100644 --- a/Task/Image-noise/Common-Lisp/image-noise.lisp +++ b/Task/Image-noise/Common-Lisp/image-noise.lisp @@ -9,7 +9,6 @@ (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) @@ -21,7 +20,7 @@ 20 20 :surface s :color sdl:*magenta*))) (defun main () - "main function, creates initializes the library and creates de display window" + "main function, 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 diff --git a/Task/Image-noise/Haskell/image-noise.hs b/Task/Image-noise/Haskell/image-noise.hs new file mode 100644 index 0000000000..dd9d6ef7f1 --- /dev/null +++ b/Task/Image-noise/Haskell/image-noise.hs @@ -0,0 +1,68 @@ +import qualified Graphics.Rendering.OpenGL as GL +import qualified Graphics.UI.GLFW as GLFW +import qualified Foreign as F +import qualified System.Random as R + +height = 240 +width = 320 +numbytes = height * width +imagesize = GL.Size (fromIntegral width) (fromIntegral height) + +main :: IO () +main = do + isInit <- GLFW.init + if isInit + then do + m <- GLFW.createWindow width height "" Nothing Nothing + case m of + Just win -> do + GLFW.makeContextCurrent m + GLFW.swapInterval 1 + GLFW.setKeyCallback win $ Just keyCallback + glLoop win + GLFW.destroyWindow win + Nothing -> return () + GLFW.terminate + else return () + +glLoop :: GLFW.Window -> IO () +glLoop win = do + foreignPixels <- F.mallocForeignPtrArray numbytes + F.withForeignPtr foreignPixels + (\pixels -> do + let pixelData = GL.PixelData GL.Luminance GL.UnsignedByte pixels + loop pixelData pixels 0) + where + loop pixelData pixels frames = do + close <- GLFW.windowShouldClose win + if close + then return () + else do + randomizePixels pixels + GL.drawPixels imagesize pixelData + GLFW.swapBuffers win + GLFW.pollEvents + time <- GLFW.getTime + let fps = + case time of + Just t -> show $ (fromIntegral frames) / t + Nothing -> "???" + GLFW.setWindowTitle win $ "FPS: " ++ fps + loop pixelData pixels $ frames + 1 + +randomizePixels :: F.Ptr GL.GLubyte -> IO () +randomizePixels ptr = iter 0 numbytes + where + iter index range + | index == range = return () + | otherwise = do + v <- R.randomRIO (0, 1) + F.pokeElemOff ptr index $ v * 255 + iter (index + 1) range + +keyCallback :: GLFW.Window -> GLFW.Key -> Int -> GLFW.KeyState -> + GLFW.ModifierKeys -> IO () +keyCallback win key _ action _ = + case key of + GLFW.Key'Q -> GLFW.setWindowShouldClose win True + _ -> return () diff --git a/Task/Image-noise/MAXScript/image-noise.max b/Task/Image-noise/MAXScript/image-noise.max new file mode 100644 index 0000000000..ad207b94d7 --- /dev/null +++ b/Task/Image-noise/MAXScript/image-noise.max @@ -0,0 +1,33 @@ +try destroydialog testRollout catch () + +fn randomBitmap width height = +( + local newBmp = bitmap width height + + for row = 0 to (height-1) do + ( + local pixels = for i in 1 to width collect (white*random 0 1) + setpixels newBmp [0,row] pixels + ) + + return newBmp +) + +rollout testRollout "Test" width:320 height:240 +( + bitmap image width:320 height:240 pos:[0,0] + timer updateTimer interval:1 active:true + + on updateTimer tick do + ( + local startTime = timestamp() + image.bitmap = randomBitmap 320 240 + local endTime = timestamp() + local fps = ((endTime-startTime)/1000.0)*60.0 + + if mod updatetimer.ticks 10 == 0 do (testRollout.title = ("Test (FPS: "+fps as string+")")) + + ) +) + +createdialog testrollout diff --git a/Task/Image-noise/Perl-6/image-noise.pl6 b/Task/Image-noise/Perl-6/image-noise.pl6 new file mode 100644 index 0000000000..e9ee3d0c31 --- /dev/null +++ b/Task/Image-noise/Perl-6/image-noise.pl6 @@ -0,0 +1,48 @@ +use NativeCall; + +class SDL_Window is repr('CStruct') {} +class SDL_Renderer is repr('CStruct') {} + +my ($w, $h) = 320, 240; +my SDL_Window $window; +my SDL_Renderer $renderer; + +constant $sdl-lib = 'libSDL2'; +constant SDL_INIT_VIDEO = 0x00000020; +constant SDL_WINDOWPOS_UNDEFINED_MASK = 0x1FFF0000; +constant SDL_WINDOW_SHOWN = 0x00000004; + +sub SDL_Init(int32 $flag) returns int32 is native($sdl-lib) {*} +sub SDL_Quit() is native($sdl-lib) {*} + +sub SDL_CreateWindow(Str $title, int $x, int $y, int $w, int $h, int32 $flag) returns SDL_Window is native($sdl-lib) {*} +sub SDL_CreateRenderer(SDL_Window $, int $, int $) returns SDL_Renderer is native($sdl-lib) {*} +sub SDL_SetRenderDrawColor(SDL_Renderer $, int $r, int $g, int $b, int $a) returns Int is native($sdl-lib) {*} +sub SDL_RenderClear(SDL_Renderer $) returns Int is native($sdl-lib) {*} +sub SDL_RenderDrawPoint( SDL_Renderer $, int $x, int $y ) returns Int is native($sdl-lib) {*} +sub SDL_RenderPresent(SDL_Renderer $) is native($sdl-lib) {*} + +sub render { + SDL_SetRenderDrawColor($renderer, 0, 0, 0, 0); + SDL_RenderClear($renderer); + SDL_SetRenderDrawColor($renderer, 255, 255, 255, 0); + for ^$w X ^$h -> $i, $j { + SDL_RenderDrawPoint( $renderer, $i, $j ) if rand < .5; + } + SDL_RenderPresent($renderer); +} + +SDL_Init(SDL_INIT_VIDEO); +$window = SDL_CreateWindow( + "some white noise", + SDL_WINDOWPOS_UNDEFINED_MASK, SDL_WINDOWPOS_UNDEFINED_MASK, + $w, $h, + SDL_WINDOW_SHOWN +); +$renderer = SDL_CreateRenderer( $window, -1, 1 ); +loop { + my $then = now; + render(); + note "{1 / (now - $then)} fps"; +} +END { SDL_Quit() } diff --git a/Task/Include-a-file/C/include-a-file.c b/Task/Include-a-file/C/include-a-file.c index 5de1f50d20..39cac797dd 100644 --- a/Task/Include-a-file/C/include-a-file.c +++ b/Task/Include-a-file/C/include-a-file.c @@ -1,5 +1,5 @@ - /* Standard library header names are enclosed using chevron enclosures */ - #include +/* Standard and other library header names are enclosed between chevrons */ +#include - /* User library header names are enclosed using doublequotes */ - #include "mylib.h" +/* User/in-project header names are usually enclosed between double-quotes */ +#include "myutil.h" diff --git a/Task/Include-a-file/JavaScript/include-a-file-3.js b/Task/Include-a-file/JavaScript/include-a-file-3.js new file mode 100644 index 0000000000..9a3fc70f0b --- /dev/null +++ b/Task/Include-a-file/JavaScript/include-a-file-3.js @@ -0,0 +1 @@ +require(["jquery"], function($) { /* ... */ }); diff --git a/Task/Include-a-file/JavaScript/include-a-file-4.js b/Task/Include-a-file/JavaScript/include-a-file-4.js new file mode 100644 index 0000000000..6db59390f1 --- /dev/null +++ b/Task/Include-a-file/JavaScript/include-a-file-4.js @@ -0,0 +1 @@ +var $ = require('$'); diff --git a/Task/Include-a-file/JavaScript/include-a-file-5.js b/Task/Include-a-file/JavaScript/include-a-file-5.js new file mode 100644 index 0000000000..4913f920e0 --- /dev/null +++ b/Task/Include-a-file/JavaScript/include-a-file-5.js @@ -0,0 +1 @@ +import $ from "jquery"; diff --git a/Task/Include-a-file/NewLISP/include-a-file.newlisp b/Task/Include-a-file/NewLISP/include-a-file.newlisp new file mode 100644 index 0000000000..0069d141fe --- /dev/null +++ b/Task/Include-a-file/NewLISP/include-a-file.newlisp @@ -0,0 +1,5 @@ +;; local file +(load "file.lsp") + +;; URLs (both http:// and file:// URLs are supported) +(load "http://www.newlisp.org/code/modules/ftp.lsp") diff --git a/Task/Include-a-file/REXX/include-a-file.rexx b/Task/Include-a-file/REXX/include-a-file.rexx new file mode 100644 index 0000000000..cd3b0b7f23 --- /dev/null +++ b/Task/Include-a-file/REXX/include-a-file.rexx @@ -0,0 +1 @@ +/*%INCLUDE member */ diff --git a/Task/Increment-a-numerical-string/00META.yaml b/Task/Increment-a-numerical-string/00META.yaml index 88eb5468ca..ac97287d53 100644 --- a/Task/Increment-a-numerical-string/00META.yaml +++ b/Task/Increment-a-numerical-string/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Text processing diff --git a/Task/Increment-a-numerical-string/AWK/increment-a-numerical-string.awk b/Task/Increment-a-numerical-string/AWK/increment-a-numerical-string.awk index b33effa513..1771353a68 100644 --- a/Task/Increment-a-numerical-string/AWK/increment-a-numerical-string.awk +++ b/Task/Increment-a-numerical-string/AWK/increment-a-numerical-string.awk @@ -1,2 +1,2 @@ -$ awk 'BEGIN{s="42";s++;print s"("length(s)")"}' +$ awk 'BEGIN{s="42"; s++; print s"("length(s)")" }' 43(2) diff --git a/Task/Increment-a-numerical-string/C/increment-a-numerical-string.c b/Task/Increment-a-numerical-string/C/increment-a-numerical-string.c new file mode 100644 index 0000000000..6f33f2acbd --- /dev/null +++ b/Task/Increment-a-numerical-string/C/increment-a-numerical-string.c @@ -0,0 +1,70 @@ +#include +#include +#include + +/* Constraints: input is in the form of (\+|-)?[0-9]+ + * and without leading zero (0 itself can be as "0" or "+0", but not "-0"); + * input pointer is realloc'able and may change; + * if input has leading + sign, return may or may not keep it. + * The constranits conform to sprintf("%+d") and this function's own output. + */ +char * incr(char *s) +{ + int i, begin, tail, len; + int neg = (*s == '-'); + char tgt = neg ? '0' : '9'; + + /* special case: "-1" */ + if (!strcmp(s, "-1")) { + s[0] = '0', s[1] = '\0'; + return s; + } + + len = strlen(s); + begin = (*s == '-' || *s == '+') ? 1 : 0; + + /* find out how many digits need to be changed */ + for (tail = len - 1; tail >= begin && s[tail] == tgt; tail--); + + if (tail < begin && !neg) { + /* special case: all 9s, string will grow */ + if (!begin) s = realloc(s, len + 2); + s[0] = '1'; + for (i = 1; i <= len - begin; i++) s[i] = '0'; + s[len + 1] = '\0'; + } else if (tail == begin && neg && s[1] == '1') { + /* special case: -1000..., so string will shrink */ + for (i = 1; i < len - begin; i++) s[i] = '9'; + s[len - 1] = '\0'; + } else { /* normal case; change tail to all 0 or 9, change prev digit by 1*/ + for (i = len - 1; i > tail; i--) + s[i] = neg ? '9' : '0'; + s[tail] += neg ? -1 : 1; + } + + return s; +} + +void string_test(const char *s) +{ + char *ret = malloc(strlen(s)); + strcpy(ret, s); + + printf("text: %s\n", ret); + printf(" ->: %s\n", ret = incr(ret)); + free(ret); +} + +int main() +{ + string_test("+0"); + string_test("-1"); + string_test("-41"); + string_test("+41"); + string_test("999"); + string_test("+999"); + string_test("109999999999999999999999999999999999999999"); + string_test("-100000000000000000000000000000000000000000000"); + + return 0; +} diff --git a/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e b/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e new file mode 100644 index 0000000000..aff985c367 --- /dev/null +++ b/Task/Increment-a-numerical-string/Eiffel/increment-a-numerical-string.e @@ -0,0 +1,17 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization +make + do + inc("23") + end + +inc(s:STRING) + do + io.put_string (s.to_integer.plus (1).out) + end +end diff --git a/Task/Increment-a-numerical-string/Frink/increment-a-numerical-string.frink b/Task/Increment-a-numerical-string/Frink/increment-a-numerical-string.frink index 9f890ac613..4cdc28fc26 100644 --- a/Task/Increment-a-numerical-string/Frink/increment-a-numerical-string.frink +++ b/Task/Increment-a-numerical-string/Frink/increment-a-numerical-string.frink @@ -1 +1,2 @@ -toString[parseInt["123"] + 1] +a = input["Enter number: "] +toString[eval[a] + 1] diff --git a/Task/Increment-a-numerical-string/Go/increment-a-numerical-string-2.go b/Task/Increment-a-numerical-string/Go/increment-a-numerical-string-2.go index 10de882b93..9ec38a2db8 100644 --- a/Task/Increment-a-numerical-string/Go/increment-a-numerical-string-2.go +++ b/Task/Increment-a-numerical-string/Go/increment-a-numerical-string-2.go @@ -1,7 +1,7 @@ package main import ( - "big" + "math/big" "fmt" "strconv" ) @@ -27,24 +27,24 @@ func main() { fmt.Println(err) _, err = strconv.Atoi("_1234") fmt.Println(err) - _, err = strconv.Atof64("12.D34") + _, err = strconv.ParseFloat("12.D34", 64) fmt.Println(err) // float fmt.Println() fs := "12.34" fmt.Println("original: ", fs) - f, err := strconv.Atof64(fs) + f, err := strconv.ParseFloat(fs, 64) if err != nil { fmt.Println(err) return } - // various options on Ftoa64 produce different formats. All are valid - // input to Atof64, so result format does not have to match original - // format. (Matching original format would take a lot of code.) - fs = strconv.Ftoa64(f+1, 'g', -1) + // various options on FormatFloat produce different formats. All are valid + // input to ParseFloat, so result format does not have to match original + // format. (Matching original format would take more code.) + fs = strconv.FormatFloat(f+1, 'g', -1, 64) fmt.Println("incremented:", fs) - fs = strconv.Ftoa64(f+1, 'e', 4) + fs = strconv.FormatFloat(f+1, 'e', 4, 64) fmt.Println("what format?", fs) // complex diff --git a/Task/Increment-a-numerical-string/Neko/increment-a-numerical-string.neko b/Task/Increment-a-numerical-string/Neko/increment-a-numerical-string.neko new file mode 100644 index 0000000000..dbfd3b1502 --- /dev/null +++ b/Task/Increment-a-numerical-string/Neko/increment-a-numerical-string.neko @@ -0,0 +1,4 @@ +var str = "123"; +var str = $string($int(str) + 1); + +$print(str); diff --git a/Task/Increment-a-numerical-string/NewLISP/increment-a-numerical-string.newlisp b/Task/Increment-a-numerical-string/NewLISP/increment-a-numerical-string.newlisp new file mode 100644 index 0000000000..c216b6a9ea --- /dev/null +++ b/Task/Increment-a-numerical-string/NewLISP/increment-a-numerical-string.newlisp @@ -0,0 +1 @@ +(string (++ (int "123"))) diff --git a/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-1.rexx b/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-1.rexx index 8eadaea118..3eb1678f9a 100644 --- a/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-1.rexx +++ b/Task/Increment-a-numerical-string/REXX/increment-a-numerical-string-1.rexx @@ -1,15 +1,21 @@ -count = "3" /*typeless variables are all character strings.*/ -count = 3 /*(same as above)*/ -count = count + 1 /*variables in a numerical context are treated as numbers.*/ -say count +/*REXX program demonstrates a method how to increment a numerical string*/ +count = "3" /*REXX variables (and constants) are character strings.*/ +count = 3 /*(identical to the above statement.) */ +count = count+1 /*strings in a numerical context are treated as numbers*/ +say 'sum=' count /*display the value of COUNT to the terminal (screen)*/ -/*------------------ The default numeric digits for REXX is 9 digits. */ -/*------------------ However, that can be increased with NUMERIC DIGITS.*/ +/*────────────────── The default numeric digits for REXX is 9 digits. */ +/*────────────────── However, that can be increased with NUMERIC DIGITS.*/ numeric digits 15000 /*let's go ka-razy with fifteen thousand digits. */ count=copies(2,15000) /*stressing REXX's brains with lots of two's, */ /*the above is considered a number in REXX. */ -count=count+3 /*make that last digit a "five". */ +count=count+3 /*make that last digit of COUNT a "5". */ +if 1==0 then /*let's not display this gihugeic number to term,*/ say 'count=' count /*ya most likely don't want to display this thing*/ + + /* [↓] show the six leftmost and rightmost digs.*/ +say 'count=' left(count,6)'···'right(count,6) + /*stick a fork in it, we're done.*/ diff --git a/Task/Increment-a-numerical-string/Rascal/increment-a-numerical-string.rascal b/Task/Increment-a-numerical-string/Rascal/increment-a-numerical-string.rascal new file mode 100644 index 0000000000..649f3d58e0 --- /dev/null +++ b/Task/Increment-a-numerical-string/Rascal/increment-a-numerical-string.rascal @@ -0,0 +1,3 @@ +import String; + +public str IncrNumStr(str s) = ""; diff --git a/Task/Infinity/Rust/infinity.rust b/Task/Infinity/Rust/infinity.rust new file mode 100644 index 0000000000..7cded29da7 --- /dev/null +++ b/Task/Infinity/Rust/infinity.rust @@ -0,0 +1,4 @@ +fn main() { + let inf : f32 = Float::infinity(); + println!("{}", inf); +} diff --git a/Task/Inheritance-Multiple/00DESCRIPTION b/Task/Inheritance-Multiple/00DESCRIPTION index e47531a15c..3d56b08e68 100644 --- a/Task/Inheritance-Multiple/00DESCRIPTION +++ b/Task/Inheritance-Multiple/00DESCRIPTION @@ -1,5 +1,9 @@ -Multiple inheritance allows to specify that one [[classes | class]] is a subclass of several other classes. Some languages allow multiple [[inheritance]] for arbitrary classes, others restrict it to interfaces, some don't allow it at all. +Multiple inheritance allows to specify that one [[classes | class]] is a subclass of several other classes. +Some languages allow multiple [[inheritance]] for arbitrary classes, +others restrict it to interfaces, some don't allow it at all. -Write two classes (or interfaces) Camera and MobilePhone, then write a class CameraPhone which is both a Camera and a MobilePhone. +Write two classes (or interfaces) Camera and MobilePhone, +then write a class CameraPhone which is both a Camera and +a MobilePhone. There is no need to implement any functions for those classes. diff --git a/Task/Inheritance-Multiple/Objective-C/inheritance-multiple.m b/Task/Inheritance-Multiple/Objective-C/inheritance-multiple.m index 8c8d584537..230de8f43c 100644 --- a/Task/Inheritance-Multiple/Objective-C/inheritance-multiple.m +++ b/Task/Inheritance-Multiple/Objective-C/inheritance-multiple.m @@ -20,7 +20,7 @@ @implementation CameraPhone --(id)init { +-(instancetype)init { if ((self = [super init])) { camera = [[Camera alloc] init]; phone = [[MobilePhone alloc] init]; @@ -38,6 +38,12 @@ [self doesNotRecognizeSelector:aSelector]; } +-(NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector { + return [camera methodSignatureForSelector:aSelector] + ?: [phone methodSignatureForSelector:aSelector] + ?: [super methodSignatureForSelector:aSelector]; +} + -(BOOL)respondsToSelector:(SEL)aSelector { return [camera respondsToSelector:aSelector] || [phone respondsToSelector:aSelector] diff --git a/Task/Inheritance-Single/Oberon-2/inheritance-single.oberon-2 b/Task/Inheritance-Single/Oberon-2/inheritance-single.oberon-2 new file mode 100644 index 0000000000..ebebf1507e --- /dev/null +++ b/Task/Inheritance-Single/Oberon-2/inheritance-single.oberon-2 @@ -0,0 +1,18 @@ +MODULE Animals; +TYPE + Animal = POINTER TO AnimalDesc; + AnimalDesc = RECORD [ABSTRACT] END; + + Cat = POINTER TO CatDesc; + CatDesc = RECORD (AnimalDesc) END; + + Dog = POINTER TO DogDesc; + DogDesc = RECORD (AnimalDesc) END; + + Lab = POINTER TO LabDesc; + LabDesc = RECORD (DogDesc) END; + + Collie = POINTER TO CollieDesc; + CollieDesc = RECORD (DogDesc) END; + +END Animals. diff --git a/Task/Input-loop/00DESCRIPTION b/Task/Input-loop/00DESCRIPTION index 2dc1f29d05..f132aaa12a 100644 --- a/Task/Input-loop/00DESCRIPTION +++ b/Task/Input-loop/00DESCRIPTION @@ -1 +1,7 @@ -{{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]]Read from a text stream either word-by-word or line-by-line until the stream runs out of data. The stream will have an unknown amount of data on it. + {{selection|Short Circuit|Console Program Basics}}[[Category:Basic language learning]] [[Category:Streams]] [[Category:Simple]] +{{omit from|PARI/GP|No access to streams other than input}} +{{omit from|TI-89 BASIC}} + +Read from a text stream either word-by-word or line-by-line +until the stream runs out of data.
+The stream will have an unknown amount of data on it. diff --git a/Task/Input-loop/Bracmat/input-loop.bracmat b/Task/Input-loop/Bracmat/input-loop.bracmat new file mode 100644 index 0000000000..7ca50edda1 --- /dev/null +++ b/Task/Input-loop/Bracmat/input-loop.bracmat @@ -0,0 +1,27 @@ +( put$("This is +a three line +text","test.txt",NEW) +& fil$("test.txt",r) +& fil$(,STR," \t\r\n") +& 0:?linenr +& whl + ' ( fil$:(?line.?breakchar) + & put + $ ( str + $ ( "breakchar:" + ( !breakchar:" "&SP + | !breakchar:\t&"\\t" + | !breakchar:\r&"\\r" + | !breakchar:\n&"\\n" + | !breakchar:&EOF + ) + ", word " + (1+!linenr:?linenr) + ":" + !line + \n + ) + ) + ) +& (fil$(,SET,-1)|out$"file closed") +); diff --git a/Task/Input-loop/D/input-loop-1.d b/Task/Input-loop/D/input-loop-1.d index 41bc6c67c8..fb73542590 100644 --- a/Task/Input-loop/D/input-loop-1.d +++ b/Task/Input-loop/D/input-loop-1.d @@ -1,8 +1,23 @@ -import tango.io.Console; -import tango.text.stream.LineIterator; +void main() { + import std.stdio; -void main (char[][] args) { - foreach (line; new LineIterator!(char)(Cin.input)) { - // do something with each line + immutable fileName = "input_loop1.d"; + + foreach (const line; fileName.File.byLine) { + pragma(msg, typeof(line)); // Prints: const(char[]) + // line is a transient slice, so if you need to + // retain it for later use, you have to .dup or .idup it. + line.writeln; // Do something with each line. + } + + // Keeping the line terminators: + foreach (const line; fileName.File.byLine(KeepTerminator.yes)) { + // line is a transient slice. + line.writeln; + } + + foreach (const string line; fileName.File.lines) { + // line is a transient slice. + line.writeln; } } diff --git a/Task/Input-loop/D/input-loop-2.d b/Task/Input-loop/D/input-loop-2.d index 894868721d..41bc6c67c8 100644 --- a/Task/Input-loop/D/input-loop-2.d +++ b/Task/Input-loop/D/input-loop-2.d @@ -1,8 +1,8 @@ import tango.io.Console; -import tango.text.stream.SimpleIterator; +import tango.text.stream.LineIterator; void main (char[][] args) { - foreach (word; new SimpleIterator!(char)(" ", Cin.input)) { - // do something with each word + foreach (line; new LineIterator!(char)(Cin.input)) { + // do something with each line } } diff --git a/Task/Input-loop/D/input-loop-3.d b/Task/Input-loop/D/input-loop-3.d new file mode 100644 index 0000000000..894868721d --- /dev/null +++ b/Task/Input-loop/D/input-loop-3.d @@ -0,0 +1,8 @@ +import tango.io.Console; +import tango.text.stream.SimpleIterator; + +void main (char[][] args) { + foreach (word; new SimpleIterator!(char)(" ", Cin.input)) { + // do something with each word + } +} diff --git a/Task/Input-loop/Go/input-loop-1.go b/Task/Input-loop/Go/input-loop-1.go new file mode 100644 index 0000000000..e71f1a4b13 --- /dev/null +++ b/Task/Input-loop/Go/input-loop-1.go @@ -0,0 +1,26 @@ +package main + +import ( + "bufio" + "io" + "log" + "os" +) + +func main() { + in := bufio.NewReader(os.Stdin) + for { + s, err := in.ReadString('\n') + if err != nil { + // io.EOF is expected, anything else + // should be handled/reported + if err != io.EOF { + log.Fatal(err) + } + break + } + // Do something with the line of text + // in string variable s. + _ = s + } +} diff --git a/Task/Input-loop/Go/input-loop-2.go b/Task/Input-loop/Go/input-loop-2.go new file mode 100644 index 0000000000..5dd7a102b3 --- /dev/null +++ b/Task/Input-loop/Go/input-loop-2.go @@ -0,0 +1,24 @@ +package main + +import ( + "bufio" + "log" + "os" +) + +func main() { + s := bufio.NewScanner(os.Stdin) + // Select the split function, other ones are available + // in bufio or you can provide your own. + s.Split(bufio.ScanWords) + for s.Scan() { + // Get and use the next 'token' + asBytes := s.Bytes() // Bytes does no alloaction + asString := s.Text() // Text returns a newly allocated string + _, _ = asBytes, asString + } + if err := s.Err(); err != nil { + // Handle/report any error (EOF will not be reported) + log.Fatal(err) + } +} diff --git a/Task/Input-loop/Go/input-loop.go b/Task/Input-loop/Go/input-loop.go deleted file mode 100644 index 17b00f40a4..0000000000 --- a/Task/Input-loop/Go/input-loop.go +++ /dev/null @@ -1,17 +0,0 @@ -package main - -import ( - "bufio" - "os" -) - -func main() { - in := bufio.NewReader(os.Stdin) - for { - s, err := in.ReadString('\n') - if err != nil { - break - } - _ = s - } -} diff --git a/Task/Input-loop/NetRexx/input-loop-1.netrexx b/Task/Input-loop/NetRexx/input-loop-1.netrexx index 5e76a11df0..36b07e232c 100644 --- a/Task/Input-loop/NetRexx/input-loop-1.netrexx +++ b/Task/Input-loop/NetRexx/input-loop-1.netrexx @@ -8,7 +8,7 @@ lineNo = 0 loop label ioloop forever inLine = ask - if inLine = null then leave ioloop -- stop on EOF + if inLine = null then leave ioloop -- stop on EOF (Try Ctrl-D on UNIX-like systems or Ctrl-Z on Windows) lineNo = lineNo + 1 lines[0] = lineNo lines[lineNo] = inLine diff --git a/Task/Input-loop/Oberon-2/input-loop.oberon-2 b/Task/Input-loop/Oberon-2/input-loop.oberon-2 new file mode 100644 index 0000000000..e12e89d584 --- /dev/null +++ b/Task/Input-loop/Oberon-2/input-loop.oberon-2 @@ -0,0 +1,18 @@ +MODULE InputLoop; +IMPORT + StdChannels, + Channel; +VAR + reader: Channel.Reader; + writer: Channel.Writer; + c: CHAR; +BEGIN + reader := StdChannels.stdin.NewReader(); + writer := StdChannels.stdout.NewWriter(); + + reader.ReadByte(c); + WHILE reader.res = Channel.done DO + writer.WriteByte(c); + reader.ReadByte(c) + END +END InputLoop. diff --git a/Task/Input-loop/PL-I/input-loop.pli b/Task/Input-loop/PL-I/input-loop.pli index 6214af3136..9027588eb7 100644 --- a/Task/Input-loop/PL-I/input-loop.pli +++ b/Task/Input-loop/PL-I/input-loop.pli @@ -4,6 +4,6 @@ open file (in) title ('/TEXT.DAT,type(text),recsize(200)' ); on endfile (in) stop; do forever; - get edit (line) (L); + get file(in) edit (line) (L); put skip list (line); end; diff --git a/Task/Input-loop/REXX/input-loop-2.rexx b/Task/Input-loop/REXX/input-loop-2.rexx index 70114a0f2b..740a35b0ab 100644 --- a/Task/Input-loop/REXX/input-loop-2.rexx +++ b/Task/Input-loop/REXX/input-loop-2.rexx @@ -1,5 +1,4 @@ -/* -- AREXX -- */ -do until eof(stdin) - l = readln(stdin) - say l -end +Do Until input='' + input=linein(stdin) + Call lineout ,input + End diff --git a/Task/Input-loop/REXX/input-loop-3.rexx b/Task/Input-loop/REXX/input-loop-3.rexx index 2e253c5ecd..70114a0f2b 100644 --- a/Task/Input-loop/REXX/input-loop-3.rexx +++ b/Task/Input-loop/REXX/input-loop-3.rexx @@ -1,6 +1,5 @@ -/*REXX program to read from the (console) default input stream until nul*/ - - do until _=='' - parse pull _ - end /*until ...*/ -exit /*stick a fork in it, we're done.*/ +/* -- AREXX -- */ +do until eof(stdin) + l = readln(stdin) + say l +end diff --git a/Task/Input-loop/REXX/input-loop-4.rexx b/Task/Input-loop/REXX/input-loop-4.rexx new file mode 100644 index 0000000000..32fa47743d --- /dev/null +++ b/Task/Input-loop/REXX/input-loop-4.rexx @@ -0,0 +1,6 @@ +/*REXX program reads from the (console) default input stream until null*/ + + do until _=='' + parse pull _ + end /*until ...*/ +exit /*stick a fork in it, we're done.*/ diff --git a/Task/Input-loop/REXX/input-loop-5.rexx b/Task/Input-loop/REXX/input-loop-5.rexx new file mode 100644 index 0000000000..2817f51b1c --- /dev/null +++ b/Task/Input-loop/REXX/input-loop-5.rexx @@ -0,0 +1,6 @@ +/*REXX program reads from the (console) default input stream until null*/ + + do until _=='' + _=linein() + end /*until ...*/ +exit /*stick a fork in it, we're done.*/ diff --git a/Task/Integer-comparison/00DESCRIPTION b/Task/Integer-comparison/00DESCRIPTION index 96936b168b..e996656c18 100644 --- a/Task/Integer-comparison/00DESCRIPTION +++ b/Task/Integer-comparison/00DESCRIPTION @@ -1,3 +1,5 @@ -{{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. +{{basic data operation}} [[Category:Simple]] +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]] +See also: [[String comparison]] diff --git a/Task/Integer-comparison/360-Assembly/integer-comparison.360 b/Task/Integer-comparison/360-Assembly/integer-comparison.360 new file mode 100644 index 0000000000..c8ada1ea11 --- /dev/null +++ b/Task/Integer-comparison/360-Assembly/integer-comparison.360 @@ -0,0 +1,33 @@ +INTCOMP PROLOG +* Reg1=Addr(Addr(argA),Addr(argB)) + L 2,0(1) Reg2=Addr(argA) + L 3,4(1) Reg3=Addr(argB) + L 4,0(2) Reg4=argA + L 5,0(3) Reg5=argA + ST 4,A Store R4 in A + ST 5,B Store R5 in B +* if (A < B) + L 0,A load R0 + C 0,B compare + BL LOWER branch if lower +* if (A = B) + L 0,A load R0 + C 0,B compare + BE EQUAL branch if equal +* if (A < B) + L 0,A load R0 + C 0,B compare + BH GREATER branch if higher +* other case ? + B RETURN +LOWER WTO 'AB' + B RETURN +* +RETURN EPILOG +A DS F 31-bit signed integer +B DS F 31-bit signed integer + END diff --git a/Task/Integer-comparison/BASIC/integer-comparison.basic b/Task/Integer-comparison/BASIC/integer-comparison-1.basic similarity index 100% rename from Task/Integer-comparison/BASIC/integer-comparison.basic rename to Task/Integer-comparison/BASIC/integer-comparison-1.basic diff --git a/Task/Integer-comparison/BASIC/integer-comparison-2.basic b/Task/Integer-comparison/BASIC/integer-comparison-2.basic new file mode 100644 index 0000000000..34aa9bdb9c --- /dev/null +++ b/Task/Integer-comparison/BASIC/integer-comparison-2.basic @@ -0,0 +1,5 @@ +10 INPUT "ENTER TWO INTEGERS: "; A%, B% +20 A$(0) = "NOT " +30 PRINT A% " IS " A$(A% < B%) "LESS THAN " B% +40 PRINT A% " IS " A$(A% = B%) "EQUAL TO " B% +50 PRINT A% " IS " A$(A% > B%) "GREATER THAN " B% diff --git a/Task/Integer-comparison/Brat/integer-comparison.brat b/Task/Integer-comparison/Brat/integer-comparison.brat new file mode 100644 index 0000000000..97d5cc4c47 --- /dev/null +++ b/Task/Integer-comparison/Brat/integer-comparison.brat @@ -0,0 +1,6 @@ +first = ask("First integer: ").to_i +second = ask("Second integer: ").to_i + +when { first > second } { p "#{first} is greater than #{second}" } + { first < second } { p "#{first} is less than #{second}" } + { first == second } { p "#{first} is equal to #{second}" } diff --git a/Task/Integer-comparison/Excel/integer-comparison-1.excel b/Task/Integer-comparison/Excel/integer-comparison-1.excel new file mode 100644 index 0000000000..e0b89f4dab --- /dev/null +++ b/Task/Integer-comparison/Excel/integer-comparison-1.excel @@ -0,0 +1 @@ +=IF($A1>$B1;concatenate($A1;" is greater than ";$B1);IF($A1<$B1;concatenate($A1;" is smaller than ";$B1);concatenate($A1;" is equal to ";$B1))) diff --git a/Task/Integer-comparison/Excel/integer-comparison-2.excel b/Task/Integer-comparison/Excel/integer-comparison-2.excel new file mode 100644 index 0000000000..55c6b6267f --- /dev/null +++ b/Task/Integer-comparison/Excel/integer-comparison-2.excel @@ -0,0 +1 @@ +=IF($A1>$B1,concatenate($A1," is greater than ",$B1),IF($A1<$B1,concatenate($A1," is smaller than ",$B1),concatenate($A1," is equal to ",$B1))) diff --git a/Task/Integer-comparison/Frink/integer-comparison.frink b/Task/Integer-comparison/Frink/integer-comparison.frink index 8b01fe46e5..11b79fc950 100644 --- a/Task/Integer-comparison/Frink/integer-comparison.frink +++ b/Task/Integer-comparison/Frink/integer-comparison.frink @@ -1,4 +1,4 @@ -[a,b] = input["Enter numbers",["a","b"]] +[a,b] = eval[input["Enter numbers",["a","b"]]] if a n2: fmt.Println(n1, "greater than", n2) - } + var n1, n2 int + if _, err := fmt.Scan(&n1); err != nil { + log.Fatal(err) + } + if _, err := fmt.Scan(&n2); err != nil { + log.Fatal(err) + } + switch { + case n1 < n2: + fmt.Println(n1, "less than", n2) + case n1 == n2: + fmt.Println(n1, "equal to", n2) + case n1 > n2: + fmt.Println(n1, "greater than", n2) + } } diff --git a/Task/Integer-comparison/Julia/integer-comparison.julia b/Task/Integer-comparison/Julia/integer-comparison.julia new file mode 100644 index 0000000000..5ff5ee2810 --- /dev/null +++ b/Task/Integer-comparison/Julia/integer-comparison.julia @@ -0,0 +1,10 @@ +function compare() +int1 = chomp(readline(STDIN)) +int2 = chomp(readline(STDIN)) +print(int1, " is ", + int1 < int2 ? "less than " : + int1 == int2 ? "equal to " : + int1 > int2 ? "greater than " : + "uncomparable to", + int2) +end diff --git a/Task/Integer-comparison/Rust/integer-comparison.rust b/Task/Integer-comparison/Rust/integer-comparison.rust new file mode 100644 index 0000000000..dbb3aec787 --- /dev/null +++ b/Task/Integer-comparison/Rust/integer-comparison.rust @@ -0,0 +1,15 @@ +use std::io; + +fn main() { + // #![allow(unstable)] // Currently required whilst Rust 1.0 is finalised + let a: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); + let b: i32 = from_str(io::stdin().read_line().unwrap().trim().as_slice()).unwrap(); + + let result = + match (a, b) { + (a, b) if a < b => format!("{0} is less than {1}" , a , b), + (a, b) if a == b => format!("{0} equals {1}" , a , b), + (a, b) => format!("{0} is greater than {1}" , a , b), + }; + println!("{0}" , result); +} diff --git a/Task/Integer-comparison/XPL0/integer-comparison.xpl0 b/Task/Integer-comparison/XPL0/integer-comparison.xpl0 index a28bf03c4d..b12921d643 100644 --- a/Task/Integer-comparison/XPL0/integer-comparison.xpl0 +++ b/Task/Integer-comparison/XPL0/integer-comparison.xpl0 @@ -2,7 +2,8 @@ code IntIn=10, Text=12; int A, B; [A:= IntIn(0); B:= IntIn(0); -if AB then Text(0, "A>B^M^J"); +if AB then Text(0, "A>B"); +CrLf(0); ] diff --git a/Task/Integer-sequence/C++/integer-sequence-1.cpp b/Task/Integer-sequence/C++/integer-sequence-1.cpp new file mode 100644 index 0000000000..5c87377026 --- /dev/null +++ b/Task/Integer-sequence/C++/integer-sequence-1.cpp @@ -0,0 +1,11 @@ +#include +#include +#include + +int main() +{ + auto i = std::uintmax_t{}; + + while (i < std::numeric_limits::max()) + std::cout << ++i << '\n'; +} diff --git a/Task/Integer-sequence/C++/integer-sequence-2.cpp b/Task/Integer-sequence/C++/integer-sequence-2.cpp new file mode 100644 index 0000000000..da0d3b448d --- /dev/null +++ b/Task/Integer-sequence/C++/integer-sequence-2.cpp @@ -0,0 +1,19 @@ +// Using the proposed unbounded integer library + +#include +#include + +int main() +{ + try + { + auto i = std::experimental::seminumeric::integer{}; + + while (true) + std::cout << ++i << '\n'; + } + catch (...) + { + // Do nothing + } +} diff --git a/Task/Integer-sequence/C++/integer-sequence.cpp b/Task/Integer-sequence/C++/integer-sequence.cpp deleted file mode 100644 index eac0ac9837..0000000000 --- a/Task/Integer-sequence/C++/integer-sequence.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include - -int main() -{ - uint32_t i = 0; - while(true) - std::cout << ++i << std::endl; - - return 0; -} diff --git a/Task/Integer-sequence/NewLISP/integer-sequence.newlisp b/Task/Integer-sequence/NewLISP/integer-sequence.newlisp new file mode 100644 index 0000000000..6486a1a0ec --- /dev/null +++ b/Task/Integer-sequence/NewLISP/integer-sequence.newlisp @@ -0,0 +1 @@ +(while (println (++ i))) diff --git a/Task/Integer-sequence/Oberon-2/integer-sequence.oberon-2 b/Task/Integer-sequence/Oberon-2/integer-sequence.oberon-2 new file mode 100644 index 0000000000..819743bbdb --- /dev/null +++ b/Task/Integer-sequence/Oberon-2/integer-sequence.oberon-2 @@ -0,0 +1,27 @@ +MODULE IntegerSeq; +IMPORT + Out, + Object:BigInt; + + PROCEDURE IntegerSequence*; + VAR + i: LONGINT; + BEGIN + FOR i := 0 TO MAX(LONGINT) DO + Out.LongInt(i,0);Out.String(", ") + END; + Out.Ln + END IntegerSequence; + + PROCEDURE BigIntSequence*; + VAR + i: BigInt.BigInt; + BEGIN + i := BigInt.zero; + LOOP + Out.Object(i.ToString() + ", "); + i := i.Add(BigInt.one); + END + END BigIntSequence; + +END IntegerSeq. diff --git a/Task/Integer-sequence/Perl/integer-sequence.pl b/Task/Integer-sequence/Perl/integer-sequence-1.pl similarity index 100% rename from Task/Integer-sequence/Perl/integer-sequence.pl rename to Task/Integer-sequence/Perl/integer-sequence-1.pl diff --git a/Task/Integer-sequence/Perl/integer-sequence-2.pl b/Task/Integer-sequence/Perl/integer-sequence-2.pl new file mode 100644 index 0000000000..5db502958c --- /dev/null +++ b/Task/Integer-sequence/Perl/integer-sequence-2.pl @@ -0,0 +1,2 @@ +use bigint; +my $i = 0; print ++$i, "\n" while 1; diff --git a/Task/Integer-sequence/R/integer-sequence.r b/Task/Integer-sequence/R/integer-sequence.r new file mode 100644 index 0000000000..8b0d86f448 --- /dev/null +++ b/Task/Integer-sequence/R/integer-sequence.r @@ -0,0 +1,5 @@ +z <- 0 +repeat { + print(z) + z <- z + 1 +} diff --git a/Task/Integer-sequence/REXX/integer-sequence.rexx b/Task/Integer-sequence/REXX/integer-sequence.rexx index c92e9d6e67..c9bef60ca2 100644 --- a/Task/Integer-sequence/REXX/integer-sequence.rexx +++ b/Task/Integer-sequence/REXX/integer-sequence.rexx @@ -9,15 +9,15 @@ │ where it started, and this computer program will still be counting.│ │ │ │ │ - │ According to Sir Author Eddington in 1938 at his Tamer Lecture at │ - │ Trinity Collecge (Cambridge), he postulated that there are exactly │ + │ According to Sir Arthur Eddington in 1938 at his Tamer Lecture at │ + │ Trinity College (Cambridge), he postulated that there are exactly │ │ │ - │ 136 ∙ 2^245 │ + │ 136 ∙ 2^256 │ │ │ │ protons in the universe and the same number of electrons, which is │ │ equal to around 1.57477e+79. │ │ │ - │ Although, a modern extimate is around 10^80. │ + │ Although, a modern estimate is around 10^80. │ │ │ │ │ │ One estimate of the age of the universe is 13.7 billion years, │ diff --git a/Task/Integer-sequence/Ruby/integer-sequence.rb b/Task/Integer-sequence/Ruby/integer-sequence.rb index de3a61cc99..ce9b988d7b 100644 --- a/Task/Integer-sequence/Ruby/integer-sequence.rb +++ b/Task/Integer-sequence/Ruby/integer-sequence.rb @@ -1,2 +1 @@ -i = 0 -puts(i += 1) while true +1.step{|n| puts n} diff --git a/Task/Interactive-programming/CoffeeScript/interactive-programming.coffee b/Task/Interactive-programming/CoffeeScript/interactive-programming.coffee new file mode 100644 index 0000000000..20d9012673 --- /dev/null +++ b/Task/Interactive-programming/CoffeeScript/interactive-programming.coffee @@ -0,0 +1,5 @@ +$ coffee -n +coffee> f = (a, b, c) -> a + c + c + b +[Function] +coffee> f "Rosetta", "Code", ":" +"Rosetta::Code" diff --git a/Task/Introspection/D/introspection.d b/Task/Introspection/D/introspection.d index ce70838c92..b9a4a8b44f 100644 --- a/Task/Introspection/D/introspection.d +++ b/Task/Introspection/D/introspection.d @@ -25,7 +25,8 @@ void main() { int tot = 0; /*static*/ foreach (name; __traits(allMembers, mixin(__MODULE__))) - static if (is(int == Unqual!(typeof(mixin("." ~ name))))) + static if (name != "object" && + is(int == Unqual!(typeof(mixin("." ~ name))))) tot += mixin("." ~ name); writeln("Total of the module-level ints (could overflow): ", tot); } diff --git a/Task/Introspection/Forth/introspection.fth b/Task/Introspection/Forth/introspection-1.fth similarity index 100% rename from Task/Introspection/Forth/introspection.fth rename to Task/Introspection/Forth/introspection-1.fth diff --git a/Task/Introspection/Forth/introspection-2.fth b/Task/Introspection/Forth/introspection-2.fth new file mode 100644 index 0000000000..db655d573b --- /dev/null +++ b/Task/Introspection/Forth/introspection-2.fth @@ -0,0 +1,11 @@ +[hex] 362 [decimal] 4TH# - [if] [abort] [then] + +-32 value bloop +[defined] bloop [if] + [defined] abs [if] + bloop abs . cr + [then] +[then] + +0 last cell+ first over over - .( User variables: ) . +?do i @ + loop .( Sum: ) . cr diff --git a/Task/Introspection/Julia/introspection.julia b/Task/Introspection/Julia/introspection.julia new file mode 100644 index 0000000000..da74b68602 --- /dev/null +++ b/Task/Introspection/Julia/introspection.julia @@ -0,0 +1,5 @@ +julia> VERSION +v"0.3.2" + +julia> VERSION > v"0.3.1" +true diff --git a/Task/Introspection/UNIX-Shell/introspection-1.sh b/Task/Introspection/UNIX-Shell/introspection-1.sh new file mode 100644 index 0000000000..ec9e8eb9d7 --- /dev/null +++ b/Task/Introspection/UNIX-Shell/introspection-1.sh @@ -0,0 +1,22 @@ +case ${.sh.version} in + *93[[:alpha:]]+*) :;; #this appears to be ksh93, we're OK + *) echo "version appears to be too old" + exit # otherwise, bail out + ;; +esac + +if [[ -z ${bloop+bloop has a value} ]]; then + print "no bloop variable" +elsif (( abs(1) )); then + print -- $(( abs(bloop) )) +fi + +typeset -a int_vars +set | while IFS='=' read -r var value; do + if [[ $value == +([[:digit:]]) ]]; then + int_vars[n++]=$var + let sum += $value + fi +done +print "${int_vars[*]}" +print -- $sum diff --git a/Task/Introspection/UNIX-Shell/introspection-2.sh b/Task/Introspection/UNIX-Shell/introspection-2.sh new file mode 100644 index 0000000000..2cd20f94fa --- /dev/null +++ b/Task/Introspection/UNIX-Shell/introspection-2.sh @@ -0,0 +1,26 @@ +if [[ $BASH_VERSION < "4.2" ]]; then + echo "version is too old" + exit +fi + +if [[ ! -v bloop ]]; then + echo "no bloop variable" +elif [[ $(type -t abs 2>/dev/null) != function ]]; then + echo "abs is not a shell function" +else + echo $(abs $bloop) +fi + +# need to populate the variables and use them within the same subshell in a pipeline. +set | { + shopt -s extglob + int_vars=() + while IFS='=' read -r var value; do + if [[ $value == +([[:digit:]]) ]]; then + int_vars+=($var) + (( sum += value )) + fi + done + echo "${int_vars[*]}" + echo $sum +} diff --git a/Task/Inverted-index/Scala/inverted-index.scala b/Task/Inverted-index/Scala/inverted-index.scala new file mode 100644 index 0000000000..98feab8e17 --- /dev/null +++ b/Task/Inverted-index/Scala/inverted-index.scala @@ -0,0 +1,31 @@ +object InvertedIndex extends App { + import java.io.File + + // indexer + val WORD = raw"(\w+)".r + def parse(s: String) = WORD.findAllIn(s).map(_.toString.toLowerCase) + def invertedIndex(files: Seq[File]): Map[String,Set[File]] = { + var i = Map[String,Set[File]]() withDefaultValue Set.empty + files.foreach{f => scala.io.Source.fromFile(f).getLines flatMap parse foreach + (w => i = i + (w -> (i(w) + f)))} + i + } + + // user interface + args match { + case _ if args.length < 2 => println("Usage: InvertedIndex ALLSEARCHWORDS FILENAME...") + case Array(searchwords, filenames @ _*) => + val queries = parse(searchwords).toList + val files = filenames.map(new File(_)).filter{f => if (!f.exists) println(s"Ignoring $f"); f.exists} + (queries, files) match { + case (q, _) if q.isEmpty => println("Missing search words") + case (_, f) if f.isEmpty => println("Missing extant files") + case _ => val index = invertedIndex(files) + println(s"""Searching for ${queries map ("\""+_+"\"") mkString " and "} in ${files.size} files:""") + queries.map(index).foldLeft(files.toSet)(_ intersect _) match { + case m if m.isEmpty => println("No matching files") + case m => println(m mkString "\n") + } + } + } +} diff --git a/Task/Inverted-syntax/C++/inverted-syntax.cpp b/Task/Inverted-syntax/C++/inverted-syntax.cpp new file mode 100644 index 0000000000..12012dbde9 --- /dev/null +++ b/Task/Inverted-syntax/C++/inverted-syntax.cpp @@ -0,0 +1,22 @@ +class invertedAssign { + int data; +public: + invertedAssign(int data):data(data){} + int getData(){return data;} + void operator=(invertedAssign& other) const { + other.data = this->data; + } +}; + + +#include + +int main(){ + invertedAssign a = 0; + invertedAssign b = 42; + std::cout << a.getData() << ' ' << b.getData() << '\n'; + + b = a; + + std::cout << a.getData() << ' ' << b.getData() << '\n'; +} diff --git a/Task/JSON/00DESCRIPTION b/Task/JSON/00DESCRIPTION index 1ed462ca48..d03823f513 100644 --- a/Task/JSON/00DESCRIPTION +++ b/Task/JSON/00DESCRIPTION @@ -1,2 +1,5 @@ -Load a [[wp:JSON|JSON]] string into a data structure. Also create a new data structure and serialize it into JSON. -Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (http://www.jsonlint.com/). +Load a [[wp:JSON|JSON]] string into a data structure. +Also create a new data structure and serialize it into JSON. + +Use objects and arrays (as appropriate for your language) +and make sure your JSON is valid (http://www.jsonlint.com/). diff --git a/Task/JSON/Bracmat/json-1.bracmat b/Task/JSON/Bracmat/json-1.bracmat new file mode 100644 index 0000000000..e3ec50c00b --- /dev/null +++ b/Task/JSON/Bracmat/json-1.bracmat @@ -0,0 +1 @@ +put$(jsn$(get$("input.json",JSN)),"output.JSN,NEW) diff --git a/Task/JSON/Bracmat/json-2.bracmat b/Task/JSON/Bracmat/json-2.bracmat new file mode 100644 index 0000000000..0a5624aeee --- /dev/null +++ b/Task/JSON/Bracmat/json-2.bracmat @@ -0,0 +1 @@ +get$("myfile.json",JSN) diff --git a/Task/JSON/Bracmat/json-3.bracmat b/Task/JSON/Bracmat/json-3.bracmat new file mode 100644 index 0000000000..c07fe4939e --- /dev/null +++ b/Task/JSON/Bracmat/json-3.bracmat @@ -0,0 +1 @@ +get$("[1,2,3]",JSN,MEM) diff --git a/Task/JSON/Bracmat/json-4.bracmat b/Task/JSON/Bracmat/json-4.bracmat new file mode 100644 index 0000000000..5bb54c0276 --- /dev/null +++ b/Task/JSON/Bracmat/json-4.bracmat @@ -0,0 +1 @@ +jsn$(,1 2 3) diff --git a/Task/JSON/Bracmat/json-5.bracmat b/Task/JSON/Bracmat/json-5.bracmat new file mode 100644 index 0000000000..870b097167 --- /dev/null +++ b/Task/JSON/Bracmat/json-5.bracmat @@ -0,0 +1 @@ +put$("[1,2,3]","array.json",NEW) diff --git a/Task/JSON/Bracmat/json-6.bracmat b/Task/JSON/Bracmat/json-6.bracmat new file mode 100644 index 0000000000..a8f7ae4aa4 --- /dev/null +++ b/Task/JSON/Bracmat/json-6.bracmat @@ -0,0 +1,4 @@ +( get$("rosetta.json",JSN):?json +& lst$(json,"json.bra",NEW) +& put$(jsn$!json,"rosetta-roundtrip.json",NEW) +) diff --git a/Task/JSON/D/json.d b/Task/JSON/D/json.d index 216d2db471..da25b34036 100644 --- a/Task/JSON/D/json.d +++ b/Task/JSON/D/json.d @@ -1,6 +1,6 @@ import std.stdio, std.json; void main() { - auto j = parseJSON("{ \"foo\": 1, \"bar\": [10, \"apples\"] }"); + auto j = parseJSON(`{ "foo": 1, "bar": [10, "apples"] }`); writeln(toJSON(&j)); } diff --git a/Task/JSON/Haskell/json.hs b/Task/JSON/Haskell/json-1.hs similarity index 100% rename from Task/JSON/Haskell/json.hs rename to Task/JSON/Haskell/json-1.hs diff --git a/Task/JSON/Haskell/json-2.hs b/Task/JSON/Haskell/json-2.hs new file mode 100644 index 0000000000..35b16483d8 --- /dev/null +++ b/Task/JSON/Haskell/json-2.hs @@ -0,0 +1,16 @@ +{-# LANGUAGE TemplateHaskell, OverloadedStrings #-} +import Data.Aeson +import Data.Aeson.TH + +data Person = Person { firstName :: String + , lastName :: String + , age :: Maybe Int + } deriving (Show, Eq) + +$(deriveJSON defaultOptions ''Person) + +main = do + let test1 = "{\"firstName\":\"Bob\", \"lastName\":\"Smith\"}" + test2 = "{\"firstName\":\"Miles\", \"lastName\":\"Davis\", \"age\": 45}" + print (decode test1 :: Maybe Person) + print (decode test2 :: Maybe Person) diff --git a/Task/JSON/Lua/json.lua b/Task/JSON/Lua/json.lua new file mode 100644 index 0000000000..7c0064a40b --- /dev/null +++ b/Task/JSON/Lua/json.lua @@ -0,0 +1,38 @@ +local json = require("json") + +local json_data = [=[[ + 42, + 3.14159, + [ 2, 4, 8, 16, 32, 64, "apples", "bananas", "cherries" ], + { "H": 1, "He": 2, "X": null, "Li": 3 }, + null, + true, + false +]]=] + +print("Original JSON: " .. json_data) +local data = json.decode(json_data) +json.util.printValue(data, 'Lua') +print("JSON re-encoded: " .. json.encode(data)) + +local data = { + 42, + 3.14159, + { + 2, 4, 8, 16, 32, 64, + "apples", + "bananas", + "cherries" + }, + { + H = 1, + He = 2, + X = json.util.null(), + Li = 3 + }, + json.util.null(), + true, + false +} + +print("JSON from new Lua data: " .. json.encode(data)) diff --git a/Task/JSON/PowerShell/json-1.psh b/Task/JSON/PowerShell/json-1.psh new file mode 100644 index 0000000000..c81014a485 --- /dev/null +++ b/Task/JSON/PowerShell/json-1.psh @@ -0,0 +1,7 @@ +# JSON input is being stored in ordered hashtable. +# Ordered hashtable is available in PowerShell v3 and higher. +[ordered]@{ "foo"= 1; "bar"= 10, "apples" } | ConvertTo-Json + +# ConvertFrom-Json converts a JSON-formatted string to a custom object. +# If you use the Invoke-RestMethod cmdlet there is not need for the ConvertFrom-Json cmdlet +Invoke-WebRequest -Uri "http://date.jsontest.com" | ConvertFrom-Json diff --git a/Task/JSON/PowerShell/json-2.psh b/Task/JSON/PowerShell/json-2.psh new file mode 100644 index 0000000000..b9f1b708ff --- /dev/null +++ b/Task/JSON/PowerShell/json-2.psh @@ -0,0 +1,11 @@ +{ + "foo": 1, + "bar": [ + 10, + "apples" + ] +} + +time milliseconds_since_epoch date +---- ------------------------ ---- +12:25:25 PM 1414326325923 10-26-2014 diff --git a/Task/JSON/Prolog/json-1.pro b/Task/JSON/Prolog/json-1.pro new file mode 100644 index 0000000000..37f9440be3 --- /dev/null +++ b/Task/JSON/Prolog/json-1.pro @@ -0,0 +1,22 @@ +:- use_module([ library(http/json), + library(func) ]). + +test_json('{"widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" }}}'). + +reading_JSON_term :- + atom_json_dict(test_json(~), Dict, []), %% This accomplishes reading in the JSON data + writeln( 'JSON as Prolog dict: ~w~n' + $ Dict), + writeln( 'Access field "widget.text.data": ~s~n' + $ Dict.widget.text.data), + writeln( 'Alter field "widget": ~w~n' + $ Dict.put(widget, "Altered")). + +searalize_a_JSON_term :- + Dict = _{book:_{title:"To Mock a Mocking Bird", + author:_{first_name:"Ramond", + last_name:"Smullyan"}, + publisher:"Alfred A. Knopf", + year:1985 + }}, + json_write(current_output, Dict). %% This accomplishes serializing the JSON object. diff --git a/Task/JSON/Prolog/json-2.pro b/Task/JSON/Prolog/json-2.pro new file mode 100644 index 0000000000..2bca93a841 --- /dev/null +++ b/Task/JSON/Prolog/json-2.pro @@ -0,0 +1,19 @@ +?- reading_JSON_term. +JSON as Prolog dict: _G5217{widget:_G5207{debug:on,image:_G5123{alignment:center,hOffset:250,name:sun1,src:Images/Sun.png,vOffset:250},text:_G5189{alignment:center,data:Click Here,hOffset:250,name:text1,onMouseUp:sun1.opacity = (sun1.opacity / 100) * 90;,size:36,style:bold,vOffset:100},window:_G5077{height:500,name:main_window,title:Sample Konfabulator Widget,width:500}}} + +Access field "widget.text.data": Click Here + +Alter field "widget": _G5217{widget:Altered} + +true. + +?- searalize_a_JSON_term. +{ + "book": { + "author": {"first_name":"Ramond", "last_name":"Smullyan"}, + "publisher":"Alfred A. Knopf", + "title":"To Mock a Mocking Bird", + "year":1985 + } +} +true. diff --git a/Task/JSON/Rust/json.rust b/Task/JSON/Rust/json.rust new file mode 100644 index 0000000000..a88ddd250a --- /dev/null +++ b/Task/JSON/Rust/json.rust @@ -0,0 +1,14 @@ +extern crate serialize; +use serialize::json; +#[deriving(Decodable, Encodable)] +struct Penguin { + name : String, + born : i16 +} +fn main() { + let pengu = Penguin { name : "pengu".to_string(), born : 1999 }; + println!("{}", json::encode(&pengu)); + let pingu : Penguin = json::decode(r##"{"name":"pingu","born":2001}"##).unwrap(); + assert_eq!(pingu.name.as_slice(), "pingu"); + assert_eq!(pingu.born, 2001); +} diff --git a/Task/JSON/Smalltalk/json.st b/Task/JSON/Smalltalk/json.st new file mode 100644 index 0000000000..7d0171127f --- /dev/null +++ b/Task/JSON/Smalltalk/json.st @@ -0,0 +1 @@ +NeoJSONReader fromString: '{ "foo": 1, "bar": [10, "apples"] }'. diff --git a/Task/Jensens-Device/D/jensens-device.d b/Task/Jensens-Device/D/jensens-device.d index c81e95445e..b378066b82 100644 --- a/Task/Jensens-Device/D/jensens-device.d +++ b/Task/Jensens-Device/D/jensens-device.d @@ -1,7 +1,5 @@ -import std.stdio; - double sum(ref int i, in int lo, in int hi, lazy double term) -pure @safe { +pure @safe /*nothrow @nogc*/ { double result = 0.0; for (i = lo; i <= hi; i++) result += term(); @@ -9,6 +7,8 @@ pure @safe { } void main() { + import std.stdio; + int i; - writeln(sum(i, 1, 100, 1.0/i)); + sum(i, 1, 100, 1.0/i).writeln; } diff --git a/Task/Jensens-Device/REXX/jensens-device.rexx b/Task/Jensens-Device/REXX/jensens-device.rexx index bd8d1f9776..1bd8e1cefa 100644 --- a/Task/Jensens-Device/REXX/jensens-device.rexx +++ b/Task/Jensens-Device/REXX/jensens-device.rexx @@ -4,8 +4,7 @@ numeric digits 50 /*might as well get some accuracy*/ say sum( 'i', "1", '100', "1/i" ) /*invoke SUM (100th harmonic num)*/ exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────SUM subroutine──────────────────────*/ sum: procedure; parse arg i,start,finish,term; sum=0 -interpret 'do' i '=' start 'to' finish'; sum=sum+'term'; end' +interpret 'do' i "=" start 'to' finish"; sum=sum+" term '; end' return sum diff --git a/Task/Josephus-problem/00DESCRIPTION b/Task/Josephus-problem/00DESCRIPTION index b36b26724d..c2427e14ce 100644 --- a/Task/Josephus-problem/00DESCRIPTION +++ b/Task/Josephus-problem/00DESCRIPTION @@ -1,8 +1,18 @@ -[[wp:Josephus problem|Josephus problem]] is a math puzzle with a grim description: n prisoners are standing on a circle, sequentially numbered from 0 to n-1. An executioner walks along the circle, starting from prisoner 0, removing every k-th prisoner and killing him. As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed. For example, if there are n=5 prisoners and k=2, the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2. +[[wp:Josephus problem|Josephus problem]] is a math puzzle with a grim description: n prisoners are standing on a circle, sequentially numbered from 0 to n-1. -'''Task''' Given any n, k > 0, find out which prisoner will be the final survivor. In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (k=3). Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale. Which number was he? +An executioner walks along the circle, starting from prisoner 0, +removing every k-th prisoner and killing him. -'''Extra''' The captors may be especially kind and let m survivors free, and Josephus might just have m-1 friends to save. Provide a way to calculate which prisoner is at any given position on the killing sequence. +As the process goes on, the circle becomes smaller and smaller, until only one prisoner remains, who is then freed.
+For example, if there are n=5 prisoners and k=2, the order the prisoners are killed in (let's call it the "killing sequence") will be 1, 3, 0, and 4, and the survivor will be #2. + +'''Task''' Given any n, k > 0, find out which prisoner will be the final survivor. In one such incident, there were 41 prisoners and every 3rd prisoner was being killed (k=3). +Among them was a clever chap name Josephus who worked out the problem, stood at the surviving position, and lived on to tell the tale. +Which number was he? + +'''Extra''' The captors may be especially kind and let m survivors free, +and Josephus might just have m-1 friends to save. +Provide a way to calculate which prisoner is at any given position on the killing sequence. '''Notes''' # You can always play the executioner and follow the procedure exactly as described, walking around the circle, counting (and cutting off) heads along the way. This would yield the complete killing sequence and answer the above questions, with a complexity of probably O(kn). However, individually it takes no more than O(m) to find out which prisoner is the m-th to die. diff --git a/Task/Josephus-problem/D/josephus-problem.d b/Task/Josephus-problem/D/josephus-problem.d index 2680bfb656..4c9ffda9aa 100644 --- a/Task/Josephus-problem/D/josephus-problem.d +++ b/Task/Josephus-problem/D/josephus-problem.d @@ -1,16 +1,15 @@ import std.stdio, std.algorithm, std.array, std.string, std.range; -T pop(T)(ref T[] items, in size_t i) pure { +T pop(T)(ref T[] items, in size_t i) pure /*nothrow*/ @safe /*@nogc*/ { auto aux = items[i]; - items.remove(i); - items.length--; + items = items.remove(i); return aux; } -string josephus(in int n, in int k) pure { +string josephus(in int n, in int k) pure /*nothrow*/ @safe { auto p = n.iota.array; int i; - int[] seq; + immutable(int)[] seq; while (!p.empty) { i = (i + k - 1) % p.length; seq ~= p.pop(i); @@ -21,7 +20,7 @@ string josephus(in int n, in int k) pure { seq[0 .. $ - 1].chunks(20), seq[$ - 1]); } -void main() { +void main() /*@safe*/ { josephus(5, 2).writeln; writeln; josephus(41, 3).writeln; diff --git a/Task/Josephus-problem/PL-I/josephus-problem.pli b/Task/Josephus-problem/PL-I/josephus-problem.pli index b4d258aade..293ed3117f 100644 --- a/Task/Josephus-problem/PL-I/josephus-problem.pli +++ b/Task/Josephus-problem/PL-I/josephus-problem.pli @@ -15,7 +15,7 @@ n=41; /* number of alive prisoners */ nn=n; /* wrap around boundary */ w=3; /* killing count */ - s=1; /* nuber of survivors */ + s=1; /* number of survivors */ p=-1; /* start here */ Do Until(n=s); /* until one alive prisoner */ found=0; /* start looking */ diff --git a/Task/Josephus-problem/Python/josephus-problem.py b/Task/Josephus-problem/Python/josephus-problem-1.py similarity index 100% rename from Task/Josephus-problem/Python/josephus-problem.py rename to Task/Josephus-problem/Python/josephus-problem-1.py diff --git a/Task/Josephus-problem/Python/josephus-problem-2.py b/Task/Josephus-problem/Python/josephus-problem-2.py new file mode 100644 index 0000000000..2d8568cffa --- /dev/null +++ b/Task/Josephus-problem/Python/josephus-problem-2.py @@ -0,0 +1,11 @@ +>>>def josephus(n, k): + r = 0 + for i in xrange(1, n+1): + r = (r+k)%i + return 'Survivor: %d' %r + +>>> print(josephus(5, 2)) +Survivor: 2 +>>> print(josephus(41, 3)) +Survivor: 30 +>>> diff --git a/Task/Josephus-problem/Python/josephus-problem-3.py b/Task/Josephus-problem/Python/josephus-problem-3.py new file mode 100644 index 0000000000..8a5bb143cf --- /dev/null +++ b/Task/Josephus-problem/Python/josephus-problem-3.py @@ -0,0 +1,19 @@ +def josephus(n, k): + a = list(range(1, n + 1)) + a[n - 1] = 0 + p = 0 + v = [] + while a[p] != p: + for i in range(k - 2): + p = a[p] + v.append(a[p]) + a[p] = a[a[p]] + p = a[p] + v.append(p) + return v + +josephus(10, 2) +[1, 3, 5, 7, 9, 2, 6, 0, 8, 4] + +josephus(41, 3)[-1] +30 diff --git a/Task/Joystick-position/00DESCRIPTION b/Task/Joystick-position/00DESCRIPTION index 3130b012eb..9780c966cf 100644 --- a/Task/Joystick-position/00DESCRIPTION +++ b/Task/Joystick-position/00DESCRIPTION @@ -1,6 +1,20 @@ The task is to determine the joystick position and represent this on the display via a crosshair. -For a centred joystick, the crosshair should appear in the centre of the screen. If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. If the joystick is pushed forward or pulled back, then the crosshair should move up or down according to the extent that that joystick is pushed or pulled. The edges -of the display represent maximum extents for joystick movement. For example, a joystick pushed fully forward would raise the crosshair to the top centre of the screen. A joystick pulled backwards and to the right would move the crosshair to the bottom right of the screen (except for a small area reserved to show joystick status). Implementations can use a graphical display method to produce the crosshair, or alternatively represent the crosshair using a plus symbol on -a terminal, and move the plus symbol position according to the joystick. The bottom part of the display can hide or show an alphanumeric sequence to represent the buttons pressed. For example, if pushbuttons 1,4 and 10 are depressed, we could display "1 4 A". The implemented code should continue to redraw the crosshair according to the joystick position and show the current pushbutton statuses until the task is terminated. Digital joysticks that produce no extent data, should have their position indicated as full extent movement of the crosshair. +For a centred joystick, the crosshair should appear in the centre of the screen. +If the joystick is pushed left or right, then the cross hair should move left or right according to the extent that the joystick is pushed. -For the purpose of this task, we assume that the joystick is calibrated and that the first joystick is being used. The task implementer could at their option provide a solution that includes a joystick selection facility, enabling the user to choose which joystick is to be used for this task. +If the joystick is pushed forward or pulled back, then the crosshair should move up or down according to the extent that that joystick is pushed or pulled. +The edges of the display represent maximum extents for joystick movement. + +For example, a joystick pushed fully forward would raise the crosshair to the top centre of the screen. + +A joystick pulled backwards and to the right would move the crosshair to the bottom right of the screen (except for a small area reserved to show joystick status). Implementations can use a graphical display method to produce the crosshair, or alternatively represent the crosshair using a plus symbol on +a terminal, and move the plus symbol position according to the joystick. +The bottom part of the display can hide or show an alphanumeric sequence to represent the buttons pressed. + +For example, if pushbuttons 1,4 and 10 are depressed, we could display "1 4 A". + +The implemented code should continue to redraw the crosshair according to the joystick position and show the current pushbutton statuses until the task is terminated. +Digital joysticks that produce no extent data, should have their position indicated as full extent movement of the crosshair. + +For the purpose of this task, we assume that the joystick is calibrated and that the first joystick is being used.
+The task implementer could at their option provide a solution that includes a joystick selection facility, enabling the user to choose which joystick is to be used for this task. diff --git a/Task/Joystick-position/00META.yaml b/Task/Joystick-position/00META.yaml index 645589ca0a..3dae931bfc 100644 --- a/Task/Joystick-position/00META.yaml +++ b/Task/Joystick-position/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Hardware note: Joystick diff --git a/Task/K-means++-clustering/D/k-means++-clustering.d b/Task/K-means++-clustering/D/k-means++-clustering.d index 0d57e9359f..fcb8757165 100644 --- a/Task/K-means++-clustering/D/k-means++-clustering.d +++ b/Task/K-means++-clustering/D/k-means++-clustering.d @@ -39,7 +39,7 @@ in { struct ClusterCenter { double x, y; - void opAssign(in ref Point p) pure nothrow { + void opAssign(in ref Point p) pure nothrow @nogc { this.x = p.x; this.y = p.y; } @@ -62,7 +62,7 @@ in { /// Distance and index of the closest cluster center. static Tuple!(size_t, double) nearestClusterCenter(in ref Point point, - in ClusterCenter[] centers) pure nothrow + in ClusterCenter[] centers) pure nothrow @nogc in { assert(centers.length > 0); } out(result) { @@ -72,7 +72,7 @@ in { assert(feqrel(cast()result[1], cast()d) > 45); // Arbitrary. } body { static double sqrDistance2D(in ref ClusterCenter a, - in ref Point b) pure nothrow { + in ref Point b) pure nothrow @nogc{ return (a.x - b.x) ^^ 2 + (a.y - b.y) ^^ 2; } @@ -175,7 +175,7 @@ in { foreach (const ref cc; centers) assert(!cc.x.isNaN && !cc.y.isNaN); } body { - auto findBoundingBox() nothrow { + auto findBoundingBox() nothrow @nogc { double min_x, max_x, min_y, max_y; max_x = max_y = -double.max; min_x = min_y = double.max; diff --git a/Task/K-means++-clustering/Mathematica/k-means++-clustering.math b/Task/K-means++-clustering/Mathematica/k-means++-clustering.math new file mode 100644 index 0000000000..c346f5f73c --- /dev/null +++ b/Task/K-means++-clustering/Mathematica/k-means++-clustering.math @@ -0,0 +1,24 @@ +initM[list_List, k_Integer, distFunc_Symbol] := + Module[{m = {RandomChoice[list]}, n, d}, + While[Length[m] < k, + n = RandomChoice@Nearest[m, #] & /@ list; + d = Apply[distFunc, Transpose[{n, list}], {1}]; + m = Append[m, RandomChoice[d -> list]] + ]; + m + ]; +kmeanspp[list_, k_, + opts : OptionsPattern[{DistanceFunction -> + SquaredEuclideanDistance, "RandomSeed" -> {}}]] := + BlockRandom[SeedRandom[OptionValue["RandomSeed"]]; + Module[{m = initM[list, k, OptionValue[DistanceFunction]], update, + partition, clusters}, update[] := m = Mean /@ clusters; + partition[_] := (clusters = + GatherBy[list, + RandomChoice@ + Nearest[m, #, (# -> OptionValue[#] &@DistanceFunction)] &]; + update[]); + FixedPoint[partition, list]; + {clusters, m} + ] + ]; diff --git a/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6 b/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6 new file mode 100644 index 0000000000..c2fa4143ff --- /dev/null +++ b/Task/K-means++-clustering/Perl-6/k-means++-clustering.pl6 @@ -0,0 +1,24 @@ +sub infix:«-means++»(Int $K, @data) { + my @means = @data.pick; + until @means == $K { + my @cumulD2 = [\+] @data.map: -> $x { + min @means.map: { abs($x - $_)**2 } + } + my $rand = rand * @cumulD2[*-1]; + @means.push: @data[ + (^@data).first: { @cumulD2[$_] > $rand } + ]; + } + sub cluster { @data.classify: -> $x { @means.min: { abs($_ - $x) } } } + loop ( + my %cluster; + 1e-10 < [+] (@means Z- keys (%cluster = cluster))».abs X** 2; + @means = %cluster.values.map( { .elems R/ [+] @$_ } ) + ) { ; } + return @means; +} + +my @centers = 0, 5, 3 + 2i; +my @data = @centers.map: { ($_ + .5 - rand + (.5 - rand) * i) xx 100 } +@data.=pick(*); +.say for 3-means++ @data; diff --git a/Task/Kaprekar-numbers/00DESCRIPTION b/Task/Kaprekar-numbers/00DESCRIPTION index 51b8be9835..94bfe18087 100644 --- a/Task/Kaprekar-numbers/00DESCRIPTION +++ b/Task/Kaprekar-numbers/00DESCRIPTION @@ -1,6 +1,8 @@ A positive integer is a [[wp:Kaprekar number|Kaprekar number]] if: * It is 1 -* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. +* The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. +Note that a split resulting in a part consisting purely of 0s is not valid, +as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. @@ -18,10 +20,14 @@ Generate and show all Kaprekar numbers less than 10,000. Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: -The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: +The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); +if you can, show that Kaprekar numbers exist in other bases too. + +For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; -* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:
225   d4  a52g  a5 + 2g
+* Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. +For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:
225   d4  a52g  a5 + 2g
;Reference: * [http://www.cs.uwaterloo.ca/journals/JIS/VOL3/iann2a.html The Kaprekar Numbers] by Douglas E. Iannucci (2000). [http://pictor.math.uqam.ca/~plouffe/OEIS/jis/The%20Kaprekar%20Numbers.pdf PDF version] diff --git a/Task/Kaprekar-numbers/C-sharp/kaprekar-numbers.cs b/Task/Kaprekar-numbers/C-sharp/kaprekar-numbers.cs new file mode 100644 index 0000000000..cb4d74c4bd --- /dev/null +++ b/Task/Kaprekar-numbers/C-sharp/kaprekar-numbers.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; + +public class KaprekarNumbers { + + /// + /// The entry point of the program, where the program control starts and ends. + /// + public static void Main() { + int count = 0; + + foreach ( ulong i in _kaprekarGenerator(999999) ) { + Console.WriteLine(i); + count++; + } + + Console.WriteLine("There are {0} Kaprekar numbers less than 1000000.", count); + } + + /// + /// Generator function which generates the Kaprekar numbers. + /// + /// The generator. + /// The maximum value of the numbers generated. + private static IEnumerable _kaprekarGenerator(ulong max) { + + ulong next = 1; + + // 1 is always a Kaprekar number. + yield return next; + + for ( next = 2; next <= max; next++ ) { + + ulong square = next * next; + + for ( ulong check = 10; check <= 10000000000000000000; check *= 10 ) { + // Check the square against each power of 10 from 10^1 to 10^19 (highest which can be + // represented by a ulong) + + // If the power of 10 to be checked against is greater than or equal to the square, stop checking + if ( square <= check ) + break; + + // Given a power of 10 as 10^n, the remainder when dividing the square number by that power + // of 10 is equal to the last n digits of the number (starting from the right) and the + // quotient gives the remaining digits. + // If the last n digits are all zeroes, then the remainder will be zero, which is not + // accepted. + + ulong r = square % check; + ulong q = (square - r) / check; + + if ( r != 0 && q + r == next ) { + yield return next; + break; + } + } + + } + + } + +} diff --git a/Task/Kaprekar-numbers/D/kaprekar-numbers-1.d b/Task/Kaprekar-numbers/D/kaprekar-numbers-1.d index 8587e1ad3e..f2f4b4dc8c 100644 --- a/Task/Kaprekar-numbers/D/kaprekar-numbers-1.d +++ b/Task/Kaprekar-numbers/D/kaprekar-numbers-1.d @@ -1,6 +1,6 @@ import std.stdio, std.conv, std.algorithm, std.range; -bool isKaprekar(in long n) pure /*nothrow*/ +bool isKaprekar(in long n) pure /*nothrow*/ @safe in { assert(n > 0, "isKaprekar(n) is defined for n > 0."); } body { @@ -8,7 +8,7 @@ in { return true; immutable sn = text(n ^^ 2); - foreach (i; 1 .. sn.length) { + foreach (immutable i; 1 .. sn.length) { immutable a = sn[0 .. i].to!long; immutable b = sn[i .. $].to!long; if (b && a + b == n) diff --git a/Task/Kaprekar-numbers/D/kaprekar-numbers-2.d b/Task/Kaprekar-numbers/D/kaprekar-numbers-2.d index 4180676b24..da1274e28d 100644 --- a/Task/Kaprekar-numbers/D/kaprekar-numbers-2.d +++ b/Task/Kaprekar-numbers/D/kaprekar-numbers-2.d @@ -1,4 +1,4 @@ -bool isKaprekar(in uint n) pure nothrow { +bool isKaprekar(in uint n) pure nothrow @nogc @safe { ulong powr = n ^^ 2UL; ulong r, l, tens = 10; while (r < n) { @@ -13,8 +13,9 @@ bool isKaprekar(in uint n) pure nothrow { void main() { import std.stdio; + int count = 1; - foreach (i; 1 .. 1_000_000) - if (isKaprekar(i)) + foreach (immutable i; 1 .. 1_000_000) + if (i.isKaprekar) writefln("%d: %d", count++, i); } diff --git a/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia new file mode 100644 index 0000000000..8327e545c9 --- /dev/null +++ b/Task/Kaprekar-numbers/Julia/kaprekar-numbers.julia @@ -0,0 +1,6 @@ +function iskaprekar (n) + str = string(n^2) + n == 1 ? true : + any([ n == int(str[1:i]) + int(str[i+1:end]) && int(str[i+1:end]) != 0 + for i = 1:length(str)-1]) +end diff --git a/Task/Kaprekar-numbers/Perl/kaprekar-numbers-1.pl b/Task/Kaprekar-numbers/Perl/kaprekar-numbers-1.pl new file mode 100644 index 0000000000..2958046fd9 --- /dev/null +++ b/Task/Kaprekar-numbers/Perl/kaprekar-numbers-1.pl @@ -0,0 +1,17 @@ +sub isKap { + my $k = shift; + return if $k*($k-1) % 9; # Fast return "casting out nines" + my($k2, $p) = ($k*$k, 10); + do { + my $i = int($k2/$p); + my $j = $k2 % $p; + return 1 if $j && $i+$j == $k; + $p *= 10; + } while $p <= $k2; + 0; +} + +print "[", join(" ", grep { isKap($_) } 1..9999), "]\n\n"; +my @kaprekar; +isKap($_) && push @kaprekar,$_ for 1..1_000_000; +print "Kaprekar Numbers below 1000000: ", scalar(@kaprekar), "\n"; diff --git a/Task/Kaprekar-numbers/Perl/kaprekar-numbers-2.pl b/Task/Kaprekar-numbers/Perl/kaprekar-numbers-2.pl new file mode 100644 index 0000000000..faea8e1183 --- /dev/null +++ b/Task/Kaprekar-numbers/Perl/kaprekar-numbers-2.pl @@ -0,0 +1,17 @@ +use ntheory qw/fordivisors gcd invmod/; + +my %kap; +for my $n (1..15) { + my $np = int(10**$n)-1; + fordivisors { + my($d, $dp) = ($_, $np/$_); + $kap{ $dp==1 ? $d : invmod($d,$dp)*$d }++ + if gcd($d, $dp) == 1; + } $np; +} +my @kap = sort { $a<=>$b } keys %kap; +for my $n (6 .. 14) { + my $np = int(10**$n)-1; + printf "Kaprekar numbers <= 10^%2d: %5d\n", + $n, scalar(grep { $_ <= $np } @kap); +} diff --git a/Task/Kaprekar-numbers/Perl/kaprekar-numbers.pl b/Task/Kaprekar-numbers/Perl/kaprekar-numbers.pl deleted file mode 100644 index 79fe33829c..0000000000 --- a/Task/Kaprekar-numbers/Perl/kaprekar-numbers.pl +++ /dev/null @@ -1,11 +0,0 @@ -sub is_kaprekar { - my $n = shift; - return 1 if $n == 1; - my $s = $n * $n; - for (1 .. length($s)) { - return 1 if substr($s, 0, $_) + (0 + substr($s, $_) || return) == $n; - } -} - -# one million is a small number, let's brute force it -is_kaprekar($_) and print "$_\n" for 1 .. 1_000_000; diff --git a/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx b/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx index 43ecf651ff..50f432f9e0 100644 --- a/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx +++ b/Task/Kaprekar-numbers/REXX/kaprekar-numbers.rexx @@ -1,19 +1,19 @@ -/*REXX program to generate Kaprekar numbers using cast-out-nines test.*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ generate (any maybe show) Kaprekar numbers (and their count). │ - │ │ - │ Kaprekar numbers were thought of by the mathematician from India, │ - │ Shri Dattathreya Ramachardra Kaprekar (1905-1986). │ - └────────────────────────────────────────────────────────────────────┘*/ -call kaprekar 10000 /*gen Kaprekar #s and & echo #*/ -call kaprekar -1000000 /*gen Kaprekar #s and & no echo #*/ +/*REXX program generates Kaprekar numbers using cast-out-nines test.*/ +/*╔════════════════════════════════════════════════════════════════════╗ + ║ generate (any maybe show) Kaprekar numbers (and their count). ║ + ║ ║ + ║ Kaprekar numbers were thought of by the mathematician from India, ║ + ║ Shri Dattathreya Ramachardra Kaprekar (1905─1986). ║ + ╚════════════════════════════════════════════════════════════════════╝*/ +call Kaprekar 10000 /*gen Kaprekar #s and & echo #*/ +call Kaprekar -1000000 /*gen Kaprekar #s and & no echo #*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────Kaprekar subroutine─────────────────*/ -kaprekar: procedure; arg limit; #=0; if 1<=abs(limit) then call tell 1 +Kaprekar: procedure; arg limit; #=0; if abs(limit)>=1 then call tell 1 numeric digits max(10,2*length(limit**2)) /*insure enough digs for ².*/ - do j=2 to abs(limit)-1; s=j*j - if j//9 \== s//9 then iterate /*didn't pass cast-out-9s test ? */ + do j=2 to abs(limit)-1; s=j*j + if j//9 \== s//9 then iterate /*didn't pass cast-out-9s test ? */ /*cast-out-9s test is much faster*/ do k=1 for length(s) % 2 if j==left(s,k)+substr(s,k+1) then call tell j /*Eureka! */ diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/00DESCRIPTION b/Task/Keyboard-input-Flush-the-keyboard-buffer/00DESCRIPTION index 242f204e1b..443e6a8de3 100644 --- a/Task/Keyboard-input-Flush-the-keyboard-buffer/00DESCRIPTION +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/00DESCRIPTION @@ -1,2 +1,10 @@ -Flush the [[input device::keyboard]] buffer. This reads characters from the keyboard input and discards them until there are no more currently buffered, and then allows the program to continue. ''The program must not wait for users to type anything.'' -[[user input::task| ]] + [[user input::task| ]] +{{omit from|ACL2}} +{{omit from|GUISS}} +{{omit from|PARI/GP}} + +Flush the [[input device::keyboard]] buffer. +This reads characters from the keyboard input and discards them +until there are no more currently buffered, +and then allows the program to continue.
+''The program must not wait for users to type anything.'' diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/00META.yaml b/Task/Keyboard-input-Flush-the-keyboard-buffer/00META.yaml index e05e55cc9e..0272a465d4 100644 --- a/Task/Keyboard-input-Flush-the-keyboard-buffer/00META.yaml +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/00META.yaml @@ -1,2 +1,6 @@ --- +category: +- Hardware +- Terminal control +- Simple note: Keyboard input diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-1.basic b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-1.basic index 941417c027..d68ccdd40b 100644 --- a/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-1.basic +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-1.basic @@ -1 +1 @@ -10 CLEAR INPUT +10 IF PEEK (49152) > 127 THEN C = PEEK (49168): GOTO 10 diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-2.basic b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-2.basic index 80c9afe81d..941417c027 100644 --- a/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-2.basic +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-2.basic @@ -1 +1 @@ -10 IF INKEY$ <> "" THEN GO TO 10 +10 CLEAR INPUT diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-3.basic b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-3.basic new file mode 100644 index 0000000000..80c9afe81d --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/BASIC/keyboard-input-flush-the-keyboard-buffer-3.basic @@ -0,0 +1 @@ +10 IF INKEY$ <> "" THEN GO TO 10 diff --git a/Task/Keyboard-input-Flush-the-keyboard-buffer/Go/keyboard-input-flush-the-keyboard-buffer.go b/Task/Keyboard-input-Flush-the-keyboard-buffer/Go/keyboard-input-flush-the-keyboard-buffer.go new file mode 100644 index 0000000000..15d5ee0f71 --- /dev/null +++ b/Task/Keyboard-input-Flush-the-keyboard-buffer/Go/keyboard-input-flush-the-keyboard-buffer.go @@ -0,0 +1,16 @@ +package main + +import ( + "log" + + gc "code.google.com/p/goncurses" +) + +func main() { + _, err := gc.Init() + if err != nil { + log.Fatal("init:", err) + } + defer gc.End() + gc.FlushInput() +} diff --git a/Task/Keyboard-input-Keypress-check/00DESCRIPTION b/Task/Keyboard-input-Keypress-check/00DESCRIPTION index 6201a57721..e9d3bcecfd 100644 --- a/Task/Keyboard-input-Keypress-check/00DESCRIPTION +++ b/Task/Keyboard-input-Keypress-check/00DESCRIPTION @@ -1,2 +1,3 @@ -Determine if a key has been pressed and store this in a variable. If no key has been pressed, the program should continue without waiting. +Determine if a key has been pressed and store this in a variable. +If no key has been pressed, the program should continue without waiting. [[user input::task| ]] diff --git a/Task/Keyboard-input-Keypress-check/Go/keyboard-input-keypress-check.go b/Task/Keyboard-input-Keypress-check/Go/keyboard-input-keypress-check.go new file mode 100644 index 0000000000..ace96941ca --- /dev/null +++ b/Task/Keyboard-input-Keypress-check/Go/keyboard-input-keypress-check.go @@ -0,0 +1,41 @@ +package main + +import ( + "log" + "time" + + gc "code.google.com/p/goncurses" +) + +func main() { + s, err := gc.Init() + if err != nil { + log.Fatal("init:", err) + } + defer gc.End() + gc.Cursor(0) + s.Move(20, 0) + s.Print("Key check in ") + for i := 3; i >= 1; i-- { + s.MovePrint(20, 13, i) + s.Refresh() + time.Sleep(500 * time.Millisecond) + } + s.Println() + gc.Echo(false) + + // task requirement next two lines + s.Timeout(0) + k := s.GetChar() + + if k == 0 { + s.Println("No key pressed") + } else { + s.Println("You pressed", gc.KeyString(k)) + } + s.Refresh() + s.Timeout(-1) + gc.FlushInput() + gc.Cursor(1) + s.GetChar() +} diff --git a/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py b/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py index 1ce610086f..3d8253efb8 100644 --- a/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py +++ b/Task/Keyboard-input-Keypress-check/Python/keyboard-input-keypress-check.py @@ -5,9 +5,9 @@ import time try: - from msvcrt import getch + from msvcrt import getch # try to import Windows version except ImportError: - def getch(): + def getch(): # define non-Windows version import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/00DESCRIPTION b/Task/Keyboard-input-Obtain-a-Y-or-N-response/00DESCRIPTION index 5ed3e9a68c..1b97cc33ae 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/00DESCRIPTION +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/00DESCRIPTION @@ -1,2 +1,4 @@ [[user input::task| ]] -Obtain a valid Y or N response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding keypresses are removed, preventing any existing Y or N keypress from being evaluated. The response should be obtained as soon as Y or N are pressed, and there should be no need to press an enter key. +Obtain a valid Y or N response from the [[input device::keyboard]]. +The keyboard should be flushed, so that any outstanding keypresses are removed, preventing any existing Y or N keypress from being evaluated. +The response should be obtained as soon as Y or N are pressed, and there should be no need to press an enter key. diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/00META.yaml b/Task/Keyboard-input-Obtain-a-Y-or-N-response/00META.yaml new file mode 100644 index 0000000000..df58a6932c --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Simple diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/keyboard-input-obtain-a-y-or-n-response.go b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/keyboard-input-obtain-a-y-or-n-response.go new file mode 100644 index 0000000000..e93fc2f9b2 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/Go/keyboard-input-obtain-a-y-or-n-response.go @@ -0,0 +1,30 @@ +package main + +import ( + "log" + + gc "code.google.com/p/goncurses" +) + +func main() { + s, err := gc.Init() + if err != nil { + log.Fatal("init:", err) + } + defer gc.End() + var k gc.Key + for { + gc.FlushInput() + s.MovePrint(20, 0, "Press y/n ") + s.Refresh() + switch k = s.GetChar(); k { + default: + continue + case 'y', 'Y', 'n', 'N': + } + break + } + s.Printf("\nThanks for the %c!\n", k) + s.Refresh() + s.GetChar() +} diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-1.rexx b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-1.rexx index 6f53de7902..cfe63fa026 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-1.rexx +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-1.rexx @@ -1,11 +1,12 @@ -/*REXX program to test for a Y or N key when entered after a prompt.*/ +/*REXX program tests for a Y or N key when entered after a prompt.*/ do queued(); pull; end /*flush stack if anything queued. */ -prompt = 'Please enter Y or N for verification:' /*PROMPT msg.*/ - /* [↓] keep prompting til answered*/ - do until pos(ans,'NY')\==0 & length(space(ans,0))==1 /*··· Y | N ?*/ - say; say prompt /*show blank line, show the prompt*/ +prompt = 'Please enter Y or N for verification:' /*PROMPT msg.*/ + + do until pos(ans,'NY')\==0 & length(ans)==1 /*··· Y | N ?*/ + say; say prompt /*show blank line, show the prompt*/ pull ans /*get the answer(s) & uppercase it*/ + ans = space(ans,0) /*elide all blanks. */ end /*until*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-2.rexx b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-2.rexx index ae4e8e9b8e..eb31210942 100644 --- a/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-2.rexx +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-2.rexx @@ -1,8 +1,8 @@ /*REXX program to test for a Y or N key when pressed. */ -prompt='Press Y or N for some reason.' /*the PROMPT message.*/ +prompt = 'Please press Y or N for verification:' /*PROMPT msg.*/ - do until pos(ans,'NY')\==0 /*keep prompting until user answers Y | N*/ + do until pos(ans,'NYny')\==0 /*keep prompting until answer = Y N y n */ say; say prompt /*show blank line, then show the prompt. */ - ans=inkey('wait'); upper ans /*get the answer(s), also, uppercase it. */ + ans=inkey('wait') /*get the answer(s) from the terminal. */ end /*until*/ /*stick a fork in it, we're all done. */ diff --git a/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-3.rexx b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-3.rexx new file mode 100644 index 0000000000..52c990e072 --- /dev/null +++ b/Task/Keyboard-input-Obtain-a-Y-or-N-response/REXX/keyboard-input-obtain-a-y-or-n-response-3.rexx @@ -0,0 +1,8 @@ +/*REXX program to test for a Y or N key when pressed. */ +prompt = 'Please press Y or N for verification:' /*PROMPT msg.*/ + + do until pos(ans,'NY')\==0 /*keep prompting until user answers Y | N*/ + say; say prompt /*show blank line, then show the prompt. */ + ans=inkey('wait'); upper ans /*get the answer(s), also, uppercase it. */ + end /*until*/ + /*stick a fork in it, we're all done. */ diff --git a/Task/Keyboard-macros/Icon/keyboard-macros.icon b/Task/Keyboard-macros/Icon/keyboard-macros.icon new file mode 100644 index 0000000000..8094f56c9f --- /dev/null +++ b/Task/Keyboard-macros/Icon/keyboard-macros.icon @@ -0,0 +1,21 @@ +global kMap + +procedure main() + kMap := table() + kMap["1"] := italicsOn + kMap["2"] := italicsOff + kMap["\x4"] := exit # ^D terminates + while writes(exec(getch())) +end + +procedure exec(c) + return (\kMap[c])() | c +end + +procedure italicsOn() + return "" +end + +procedure italicsOff() + return "<\\i>" +end diff --git a/Task/Knapsack-problem-0-1/00DESCRIPTION b/Task/Knapsack-problem-0-1/00DESCRIPTION index 291c0237fd..887a342bb5 100644 --- a/Task/Knapsack-problem-0-1/00DESCRIPTION +++ b/Task/Knapsack-problem-0-1/00DESCRIPTION @@ -1,4 +1,9 @@ -A tourist wants to make a good trip at the weekend with his friends. They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it and it will have to last the whole day. He creates a list of what he wants to bring for the trip but the total weight of all items is too much. He then decides to add columns to his initial list detailing their weights and a numerical value representing how important the item is for the trip. +{{omit from|GUISS}} +A tourist wants to make a good trip at the weekend with his friends. +They will go to the mountains to see the wonders of nature, so he needs to pack well for the trip. +He has a good knapsack for carrying things, but knows that he can carry a maximum of only 4kg in it and it will have to last the whole day. +He creates a list of what he wants to bring for the trip but the total weight of all items is too much. +He then decides to add columns to his initial list detailing their weights and a numerical value representing how important the item is for the trip. Here is the list: @@ -54,9 +59,13 @@ Here is the list: | knapsack || ≤400 dag || ? |} -The tourist can choose to take any combination of items from the list, but only one of each item is available. He may not cut or diminish the items, so he can only take whole units of any item. +The tourist can choose to take any combination of items from the list, +but only one of each item is available. +He may not cut or diminish the items, so he can only take whole units of any item. -'''Which items does the tourist carry in his knapsack so that their total weight does not exceed 400 dag [4 kg], and their total value is maximised?''' +'''Which items does the tourist carry in his knapsack +so that their total weight does not exceed 400 dag [4 kg], +and their total value is maximised?''' [dag = decagram = 10 grams] diff --git a/Task/Knapsack-problem-0-1/00META.yaml b/Task/Knapsack-problem-0-1/00META.yaml index c2c6c8e10d..1e150c0f5c 100644 --- a/Task/Knapsack-problem-0-1/00META.yaml +++ b/Task/Knapsack-problem-0-1/00META.yaml @@ -1,4 +1,5 @@ --- category: - Memoization +- Puzzles note: Classic CS problems and programs 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 index e2f9c949ba..19c6a0b89f 100644 --- 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 @@ -2,8 +2,8 @@ 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 { +Item[] knapsack01DinamicProgramming(immutable Item[] items, in int limit) +pure nothrow @safe { auto tab = new int[][](items.length + 1, limit + 1); foreach (immutable i, immutable it; items) @@ -22,7 +22,7 @@ pure nothrow { return result; } -void main() { +void main() @safe { enum int limit = 400; immutable Item[] items = [ {"apple", 39, 40}, {"banana", 27, 60}, 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 index 827f4cc472..24432db781 100644 --- 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 @@ -17,7 +17,8 @@ immutable Item[] items = [ 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 { +void solve(in int weight, in int idx, ref Solution s) +pure nothrow @nogc @safe { if (idx < 0) { s.bits = s.value = 0; return; @@ -38,8 +39,9 @@ void solve(in int weight, in int idx, ref Solution s) pure nothrow { s = (v1.value >= v2.value) ? v1 : v2; } -void main() { +void main() @safe { import std.stdio; + auto s = Solution(0, 0); solve(400, items.length - 1, s); @@ -50,5 +52,5 @@ void main() { writeln(" ", it.name); w += it.weight; } - writeln("\nTotal value: %d; weight: %d", s.value, w); + writefln("\nTotal value: %d; weight: %d", s.value, w); } diff --git a/Task/Knapsack-problem-0-1/JavaScript/knapsack-problem-0-1.js b/Task/Knapsack-problem-0-1/JavaScript/knapsack-problem-0-1.js new file mode 100644 index 0000000000..286093b79d --- /dev/null +++ b/Task/Knapsack-problem-0-1/JavaScript/knapsack-problem-0-1.js @@ -0,0 +1,202 @@ +/*global portviz:false, _:false */ +/* + * 0-1 knapsack solution, recursive, memoized, approximate. + * + * credits: + * + * the Go implementation here: + * http://rosettacode.org/mw/index.php?title=Knapsack_problem/0-1 + * + * approximation details here: + * http://math.mit.edu/~goemans/18434S06/knapsack-katherine.pdf + */ +portviz.knapsack = {}; +(function() { + this.combiner = function(items, weightfn, valuefn) { + // approximation guarantees result >= (1-e) * optimal + var _epsilon = 0.01; + var _p = _.max(_.map(items,valuefn)); + var _k = _epsilon * _p / items.length; + + var _memo = (function(){ + var _mem = {}; + var _key = function(i, w) { + return i + '::' + w; + }; + return { + get: function(i, w) { + return _mem[_key(i,w)]; + }, + put: function(i, w, r) { + _mem[_key(i,w)]=r; + return r; + } + }; + })(); + + var _m = function(i, w) { + + i = Math.round(i); + w = Math.round(w); + + + if (i < 0 || w === 0) { + // empty base case + return {items: [], totalWeight: 0, totalValue: 0}; + } + + var mm = _memo.get(i,w); + if (!_.isUndefined(mm)) { + return mm; + } + + var item = items[i]; + if (weightfn(item) > w) { + //item does not fit, try the next item + return _memo.put(i, w, _m(i-1, w)); + } + // this item could fit. + // are we better off excluding it? + var excluded = _m(i-1, w); + // or including it? + var included = _m(i-1, w - weightfn(item)); + if (included.totalValue + Math.floor(valuefn(item)/_k) > excluded.totalValue) { + // better off including it + // make a copy of the list + var i1 = included.items.slice(); + i1.push(item); + return _memo.put(i, w, + {items: i1, + totalWeight: included.totalWeight + weightfn(item), + totalValue: included.totalValue + Math.floor(valuefn(item)/_k)}); + } + //better off excluding it + return _memo.put(i,w, excluded); + }; + return { + /* one point */ + one: function(maxweight) { + var scaled = _m(items.length - 1, maxweight); + return { + items: scaled.items, + totalWeight: scaled.totalWeight, + totalValue: scaled.totalValue * _k + }; + }, + /* the entire EF */ + ef: function(maxweight, step) { + return _.map(_.range(0, maxweight+1, step), function(weight) { + var scaled = _m(items.length - 1, weight); + return { + items: scaled.items, + totalWeight: scaled.totalWeight, + totalValue: scaled.totalValue * _k + }; + }); + } + }; + }; +}).apply(portviz.knapsack); + +/*global portviz:false, _:false */ +/* + * after rosettacode.org/mw/index.php?title=Knapsack_problem/0-1 + */ +var allwants = [ + {name:"map", weight:9, value: 150}, + {name:"compass", weight:13, value: 35}, + {name:"water", weight:153, value: 200}, + {name:"sandwich", weight: 50, value: 160}, + {name:"glucose", weight:15, value: 60}, + {name:"tin", weight:68, value: 45}, + {name:"banana", weight:27, value: 60}, + {name:"apple", weight:39, value: 40}, + {name:"cheese", weight:23, value: 30}, + {name:"beer", weight:52, value: 10}, + {name:"suntan cream", weight:11, value: 70}, + {name:"camera", weight:32, value: 30}, + {name:"T-shirt", weight:24, value: 15}, + {name:"trousers", weight:48, value: 10}, + {name:"umbrella", weight:73, value: 40}, + {name:"waterproof trousers", weight:42, value: 70}, + {name:"waterproof overclothes", weight:43, value: 75}, + {name:"note-case", weight:22, value: 80}, + {name:"sunglasses", weight:7, value: 20}, + {name:"towel", weight:18, value: 12}, + {name:"socks", weight:4, value: 50}, + {name:"book", weight:30, value: 10} +]; + +var near = function(actual, expected, tolerance) { + if (expected === 0 && actual === 0) return true; + if (expected === 0) { + return Math.abs(expected - actual) / actual < tolerance; + } + return Math.abs(expected - actual) / expected < tolerance; +}; + +test("one knapsack", function() { + var combiner = + portviz.knapsack.combiner(allwants, + function(x){return x.weight;}, + function(x){return x.value;}); + var oneport = combiner.one(400); + ok(near(oneport.totalValue, 1030, 0.01), "correct total value"); + ok(near(oneport.totalValue, 1030, 0.01), "correct total value"); + equal(oneport.totalWeight, 396, "correct total weight"); +}); + +test("frontier", function() { + var combiner = + portviz.knapsack.combiner(allwants, + function(x){return x.weight;}, + function(x){return x.value;}); + var ef = combiner.ef(400, 1); + equal(ef.length, 401, "401 because it includes the endpoints"); + ef = combiner.ef(400, 40); + equal(ef.length, 11, "11 because it includes the endpoints"); + var expectedTotalValue = [ + 0, + 330, + 445, + 590, + 685, + 755, + 810, + 860, + 902, + 960, + 1030 + ] ; + _.each(ef, function(element, index) { + // 15% error! bleah! + ok(near(element.totalValue, expectedTotalValue[index], 0.15), + 'actual ' + element.totalValue + ' expected ' + expectedTotalValue[index]); + }); + deepEqual(_.pluck(ef, 'totalWeight'), [ + 0, + 39, + 74, + 118, + 158, + 200, + 236, + 266, + 316, + 354, + 396 + ]); + deepEqual(_.map(ef, function(x){return x.items.length;}), [ + 0, + 4, + 6, + 7, + 9, + 10, + 10, + 12, + 14, + 11, + 12 + ]); +}); diff --git a/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-1.max b/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-1.max new file mode 100644 index 0000000000..f2244637f1 --- /dev/null +++ b/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-1.max @@ -0,0 +1,63 @@ +global globalItems = #() +global usedMass = 0 +global neededItems = #() +global totalValue = 0 +struct kn_item +( + item, weight, value +) + +itemStrings = #("map#9#150","compass#13#35","water#153#200", \ + "sandwich#50#160","glucose#15#60","tin#68#45", \ + "banana#27#60","apple#39#40","cheese#23#30", \ + "beer#52#10","suntan cream#11#70","camera#32#30", \ + "T-shirt#24#15","trousers#48#10","umbrella#73#40", \ + "waterproof trousers#42#70","waterproof overclothes#43#75", \ + "note-case#22#80","sunglasses#7#20", "towel#18#12", \ + "socks#4#50","book#30#10") + +fn sortByValue a b = +( + if a[1].value > b[1].value then return -1 + else + ( + if a[1].value == b[1].value then return 0 + else return 1 + ) +) +fn chooseBestItem maximumWeight: items: = +( + local itemsCopy = deepcopy items + local possibleItems = #() + for i = 1 to itemsCopy.count do + ( + if itemsCopy[i].weight <= maximumWeight do append possibleItems (#(itemsCopy[i],i)) + ) + qsort possibleItems sortByValue + if possibleItems.count > 0 then return possibleItems[1] else return 0 +) + +for i = 1 to itemStrings.count do +( + local split = filterstring itemStrings[i] "#" + local itemStruct = kn_item item:split[1] weight:(split[2] as integer) \ + value:(split[3] as integer) + appendifunique globalItems itemstruct +) + +while usedMass < 400 do +( + local item = chooseBestItem maximumweight:(400-usedMass) items:(globalItems) + if item != 0 then + ( + deleteitem globalItems (item[2]) + appendifunique neededItems item[1] + usedMass += item[1].weight + ) else exit +) +for i in neededitems do +( + format "Item name: %, weight: %, value:%\n" i.item i.weight i.value + totalValue += i.value +) +format "Total mass: %, Total Value: %\n" usedMass totalValue diff --git a/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-2.max b/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-2.max new file mode 100644 index 0000000000..7079e06959 --- /dev/null +++ b/Task/Knapsack-problem-0-1/MAXScript/knapsack-problem-0-1-2.max @@ -0,0 +1,15 @@ +Item name: water, weight: 153, value:200 +Item name: sandwich, weight: 50, value:160 +Item name: map, weight: 9, value:150 +Item name: note-case, weight: 22, value:80 +Item name: waterproof overclothes, weight: 43, value:75 +Item name: suntan cream, weight: 11, value:70 +Item name: waterproof trousers, weight: 42, value:70 +Item name: glucose, weight: 15, value:60 +Item name: banana, weight: 27, value:60 +Item name: socks, weight: 4, value:50 +Item name: compass, weight: 13, value:35 +Item name: sunglasses, weight: 7, value:20 +OK +Total mass: 396, Total Value: 1030 +OK diff --git a/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx b/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx index 67b2369b0d..6134a87900 100644 --- a/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx +++ b/Task/Knapsack-problem-0-1/REXX/knapsack-problem-0-1.rexx @@ -1,27 +1,26 @@ /*REXX pgm solves a knapsack problem (22 items with weight restriction).*/ -@.= -@.1 = 'map 9 150' -@.2 = 'compass 13 35' -@.3 = 'water 153 200' -@.4 = 'sandwich 50 160' -@.5 = 'glucose 15 60' -@.6 = 'tin 68 45' -@.7 = 'banana 27 60' -@.8 = 'apple 39 40' -@.9 = 'cheese 23 30' -@.10 = 'beer 52 10' -@.11 = 'suntan_cream 11 70' -@.12 = 'camera 32 30' -@.13 = 'T-shirt 24 15' -@.14 = 'trousers 48 10' -@.15 = 'umbrella 73 40' -@.16 = 'waterproof_trousers 42 70' -@.17 = 'waterproof_overclothes 43 75' -@.18 = 'note-case 22 80' -@.19 = 'sunglasses 7 20' -@.20 = 'towel 18 12' -@.21 = 'socks 4 50' -@.22 = 'book 30 10' +@.=; @.1 = 'map 9 150' + @.2 = 'compass 13 35' + @.3 = 'water 153 200' + @.4 = 'sandwich 50 160' + @.5 = 'glucose 15 60' + @.6 = 'tin 68 45' + @.7 = 'banana 27 60' + @.8 = 'apple 39 40' + @.9 = 'cheese 23 30' + @.10 = 'beer 52 10' + @.11 = 'suntan_cream 11 70' + @.12 = 'camera 32 30' + @.13 = 'T-shirt 24 15' + @.14 = 'trousers 48 10' + @.15 = 'umbrella 73 40' + @.16 = 'waterproof_trousers 42 70' + @.17 = 'waterproof_overclothes 43 75' + @.18 = 'note-case 22 80' + @.19 = 'sunglasses 7 20' + @.20 = 'towel 18 12' + @.21 = 'socks 4 50' + @.22 = 'book 30 10' maxWeight=400 /*the maximum weight for knapsack*/ say; say 'maximum weight allowed for a knapsack:' comma(maxWeight); say maxL=length('item') /*maximum width for table names. */ @@ -53,7 +52,7 @@ obj=j-1 /*adjust for the DO loop index. */ highQ=max(highQ,q) items=items+1 /*bump the item counter. */ i.items=item; w.items=w; v.items=v; q.items=q - do k=2 to q; items=items+1 /*bump the item counter. */ + do k=2 to q; items=items+1 /*bump the item counter. */ i.items=item; w.items=w; v.items=v; q.items=q Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 end /*k*/ @@ -72,100 +71,72 @@ call hdr 'item'; do j=1 for obj /*show all choices, nice format. */ end /*j*/ say; say 'number of items:' items; say -/*─────────────────────────────────────examine the possible choices. */ +/*─────────────────────────────────────examine all the possible choices.*/ h=items; ho=h+1; m=maxWeight; $=0; call sim22 /*─────────────────────────────────────show the best choice (weight,val)*/ do h-1; ?=strip(strip(?),"L",0); end bestC=?; bestW=0; bestV=$; highQ=0; totP=words(bestC) call hdr 'best choice' - do j=1 to totP /*J is modified within DO loop. */ - _=word(bestC,j); _w=w._; _v=v._; q=1 - if _==0 then iterate - do k=j+1 to totP - __=word(bestC,k); if i._\==i.__ then leave - j=j+1; w._=w._+_w; v._=v._+_v; q=q+1 - end /*k*/ - call show i._,w._,v._,q; bestW=bestw+w._ - end /*j*/ + do j=1 to totP /*J is modified within DO loop. */ + _=word(bestC,j); _w=w._; _v=v._; q=1 + if _==0 then iterate + do k=j+1 to totP + __=word(bestC,k); if i._\==i.__ then leave + j=j+1; w._=w._+_w; v._=v._+_v; q=q+1 + end /*k*/ + call show i._,w._,v._,q; bestW=bestw+w._ + end /*j*/ call hdr2; say call show 'best weight' ,bestW /*show a nicely formatted winnerW*/ call show 'best value' ,,bestV /*show a nicely formatted winnerV*/ call show 'knapsack items',,,totP /*show a nicely formatted pieces.*/ exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────COMMA subroutine──────────────────────*/ -comma: procedure; parse arg _,c,p,t;arg ,cu;c=word(c ",",1) - if cu=='BLANK' then c=' ';o=word(p 3,1);p=abs(o);t=word(t 999999999,1) - if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _;n=_'.9' - #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _ - e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M") - e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end - do j=e to b by -p while k4 then return _ +n=_'.9'; #=123456789; if o<0 then do; b=verify(_,' '); if b==0 then return _ +e=length(_)-verify(reverse(_),' ')+1; end; else do; b=verify(n,#,"M") +e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end;do j=e to b by -p while k$ then call j? 1 -do j2=j1+(j1\==0) to h -if w.j2+w1>m then iterate j1;w2=w1+w.j2;v2=v1+v.j2;if v2>$ then call j? 2 -do j3=j2+(j2\==0) to h -if w.j3+w2>m then iterate j2;w3=w2+w.j3;v3=v2+v.j3;if v3>$ then call j? 3 -do j4=j3+(j3\==0) to h -if w.j4+w3>m then iterate j3;w4=w3+w.j4;v4=v3+v.j4;if v4>$ then call j? 4 -do j5=j4+(j4\==0) to h -if w.j5+w4>m then iterate j4;w5=w4+w.j5;v5=v4+v.j5;if v5>$ then call j? 5 -do j6=j5+(j5\==0) to h -if w.j6+w5>m then iterate j5;w6=w5+w.j6;v6=v5+v.j6;if v6>$ then call j? 6 -do j7=j6+(j6\==0) to h -if w.j7+w6>m then iterate j6;w7=w6+w.j7;v7=v6+v.j7;if v7>$ then call j? 7 -do j8=j7+(j7\==0) to h -if w.j8+w7>m then iterate j7;w8=w7+w.j8;v8=v7+v.j8;if v8>$ then call j? 8 -do j9=j8+(j8\==0) to h -if w.j9+w8>m then iterate j8;w9=w8+w.j9;v9=v8+v.j9;if v9>$ then call j? 9 -do j10=j9+(j9\==0) to h -if w.j10+w9>m then iterate j9;w10=w9+w.j10;v10=v9+v.j10;if v10>$ then call j? 10 -do j11=j10+(j10\==0) to h -if w.j11+w10>m then iterate j10;w11=w10+w.j11;v11=v10+v.j11;if v11>$ then call j? 11 -do j12=j11+(j11\==0) to h -if w.j12+w11>m then iterate j11;w12=w11+w.j12;v12=v11+v.j12;if v12>$ then call j? 12 -do j13=j12+(j12\==0) to h -if w.j13+w12>m then iterate j12;w13=w12+w.j13;v13=v12+v.j13;if v13>$ then call j? 13 -do j14=j13+(j13\==0) to h -if w.j14+w13>m then iterate j13;w14=w13+w.j14;v14=v13+v.j14;if v14>$ then call j? 14 -do j15=j14+(j14\==0) to h -if w.j15+w14>m then iterate j14;w15=w14+w.j15;v15=v14+v.j15;if v15>$ then call j? 15 -do j16=j15+(j15\==0) to h -if w.j16+w15>m then iterate j15;w16=w15+w.j16;v16=v15+v.j16;if v16>$ then call j? 16 -do j17=j16+(j16\==0) to h -if w.j17+w16>m then iterate j16;w17=w16+w.j17;v17=v16+v.j17;if v17>$ then call j? 17 -do j18=j17+(j17\==0) to h -if w.j18+w17>m then iterate j17;w18=w17+w.j18;v18=v17+v.j18;if v18>$ then call j? 18 -do j19=j18+(j18\==0) to h -if w.j19+w18>m then iterate j18;w19=w18+w.j19;v19=v18+v.j19;if v19>$ then call j? 19 -do j20=j19+(j19\==0) to h -if w.j20+w19>m then iterate j19;w20=w19+w.j20;v20=v19+v.j20;if v20>$ then call j? 20 -do j21=j20+(j20\==0) to h -if w.j21+w20>m then iterate j20;w21=w20+w.j21;v21=v20+v.j21;if v21>$ then call j? 21 -do j22=j21+(j21\==0) to h -if w.j22+w21>m then iterate j21;w22=w21+w.j22;v22=v21+v.j22;if v22>$ then call j? 22 -end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end +/*────────────────────────────────SIM22 subroutine───────────────────────────────────────────────────────────*/ +sim22: do j1=0 for h+1; w1=w.j1; v1 = v.j1; if v1>$ then call j? 1 + do j2 =j1 +(j1 \==0) to h;if w.j2 +w1>m then iterate j1; w2 =w1 +w.j2; v2 =v1 +v.j2; if v2>$ then call j? 2 + do j3 =j2 +(j2 \==0) to h;if w.j3 +w2>m then iterate j2; w3 =w2 +w.j3; v3 =v2 +v.j3; if v3>$ then call j? 3 + do j4 =j3 +(j3 \==0) to h;if w.j4 +w3>m then iterate j3; w4 =w3 +w.j4; v4 =v3 +v.j4; if v4>$ then call j? 4 + do j5 =j4 +(j4 \==0) to h;if w.j5 +w4>m then iterate j4; w5 =w4 +w.j5; v5 =v4 +v.j5; if v5>$ then call j? 5 + do j6 =j5 +(j5 \==0) to h;if w.j6 +w5>m then iterate j5; w6 =w5 +w.j6; v6 =v5 +v.j6; if v6>$ then call j? 6 + do j7 =j6 +(j6 \==0) to h;if w.j7 +w6>m then iterate j6; w7 =w6 +w.j7; v7 =v6 +v.j7; if v7>$ then call j? 7 + do j8 =j7 +(j7 \==0) to h;if w.j8 +w7>m then iterate j7; w8 =w7 +w.j8; v8 =v7 +v.j8; if v8>$ then call j? 8 + do j9 =j8 +(j8 \==0) to h;if w.j9 +w8>m then iterate j8; w9 =w8 +w.j9; v9 =v8 +v.j9; if v9>$ then call j? 9 + do j10=j9 +(j9 \==0) to h;if w.j10+w9>m then iterate j9; w10=w9 +w.j10;v10=v9 +v.j10;if v10>$ then call j? 10 + do j11=j10+(j10\==0) to h;if w.j11+w10>m then iterate j10;w11=w10+w.j11;v11=v10+v.j11;if v11>$ then call j? 11 + do j12=j11+(j11\==0) to h;if w.j12+w11>m then iterate j11;w12=w11+w.j12;v12=v11+v.j12;if v12>$ then call j? 12 + do j13=j12+(j12\==0) to h;if w.j13+w12>m then iterate j12;w13=w12+w.j13;v13=v12+v.j13;if v13>$ then call j? 13 + do j14=j13+(j13\==0) to h;if w.j14+w13>m then iterate j13;w14=w13+w.j14;v14=v13+v.j14;if v14>$ then call j? 14 + do j15=j14+(j14\==0) to h;if w.j15+w14>m then iterate j14;w15=w14+w.j15;v15=v14+v.j15;if v15>$ then call j? 15 + do j16=j15+(j15\==0) to h;if w.j16+w15>m then iterate j15;w16=w15+w.j16;v16=v15+v.j16;if v16>$ then call j? 16 + do j17=j16+(j16\==0) to h;if w.j17+w16>m then iterate j16;w17=w16+w.j17;v17=v16+v.j17;if v17>$ then call j? 17 + do j18=j17+(j17\==0) to h;if w.j18+w17>m then iterate j17;w18=w17+w.j18;v18=v17+v.j18;if v18>$ then call j? 18 + do j19=j18+(j18\==0) to h;if w.j19+w18>m then iterate j18;w19=w18+w.j19;v19=v18+v.j19;if v19>$ then call j? 19 + do j20=j19+(j19\==0) to h;if w.j20+w19>m then iterate j19;w20=w19+w.j20;v20=v19+v.j20;if v20>$ then call j? 20 + do j21=j20+(j20\==0) to h;if w.j21+w20>m then iterate j20;w21=w20+w.j21;v21=v20+v.j21;if v21>$ then call j? 21 + do j22=j21+(j21\==0) to h;if w.j22+w21>m then iterate j21;w22=w21+w.j22;v22=v21+v.j22;if v22>$ then call j? 22 + end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end; end return diff --git a/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-1.rb b/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-1.rb index 01befd3544..62593cfe63 100644 --- a/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-1.rb +++ b/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-1.rb @@ -1,16 +1,16 @@ KnapsackItem = Struct.new(:name, :weight, :value) potential_items = [ - KnapsackItem.new('map', 9, 150), KnapsackItem.new('compass', 13, 35), - KnapsackItem.new('water', 153, 200), KnapsackItem.new('sandwich', 50, 160), - KnapsackItem.new('glucose', 15, 60), KnapsackItem.new('tin', 68, 45), - KnapsackItem.new('banana', 27, 60), KnapsackItem.new('apple', 39, 40), - KnapsackItem.new('cheese', 23, 30), KnapsackItem.new('beer', 52, 10), - KnapsackItem.new('suntan cream', 11, 70), KnapsackItem.new('camera', 32, 30), - KnapsackItem.new('t-shirt', 24, 15), KnapsackItem.new('trousers', 48, 10), - KnapsackItem.new('umbrella', 73, 40), KnapsackItem.new('waterproof trousers', 42, 70), - KnapsackItem.new('waterproof overclothes', 43, 75), KnapsackItem.new('note-case', 22, 80), - KnapsackItem.new('sunglasses', 7, 20), KnapsackItem.new('towel', 18, 12), - KnapsackItem.new('socks', 4, 50), KnapsackItem.new('book', 30, 10), + KnapsackItem['map', 9, 150], KnapsackItem['compass', 13, 35], + KnapsackItem['water', 153, 200], KnapsackItem['sandwich', 50, 160], + KnapsackItem['glucose', 15, 60], KnapsackItem['tin', 68, 45], + KnapsackItem['banana', 27, 60], KnapsackItem['apple', 39, 40], + KnapsackItem['cheese', 23, 30], KnapsackItem['beer', 52, 10], + KnapsackItem['suntan cream', 11, 70], KnapsackItem['camera', 32, 30], + KnapsackItem['t-shirt', 24, 15], KnapsackItem['trousers', 48, 10], + KnapsackItem['umbrella', 73, 40], KnapsackItem['waterproof trousers', 42, 70], + KnapsackItem['waterproof overclothes', 43, 75], KnapsackItem['note-case', 22, 80], + KnapsackItem['sunglasses', 7, 20], KnapsackItem['towel', 18, 12], + KnapsackItem['socks', 4, 50], KnapsackItem['book', 30, 10], ] knapsack_capacity = 400 @@ -19,39 +19,25 @@ class Array def power_set yield [] if block_given? self.inject([[]]) do |ps, elem| - r = [] - ps.each do |i| + ps.each_with_object([]) do |i,r| r << i new_subset = i + [elem] yield new_subset if block_given? r << new_subset end - r end end end -maxval = 0 -solutions = [] - -potential_items.power_set do |subset| - weight = subset.inject(0) {|w, elem| w += elem.weight} - next if weight > knapsack_capacity - - value = subset.inject(0) {|v, elem| v += elem.value} - if value == maxval - solutions << subset - elsif value > maxval - maxval = value - solutions = [subset] - end -end +maxval, solutions = potential_items.power_set.group_by {|subset| + weight = subset.inject(0) {|w, elem| w + elem.weight} + weight>knapsack_capacity ? 0 : subset.inject(0){|v, elem| v + elem.value} +}.max puts "value: #{maxval}" solutions.each do |set| - items = [] - wt = 0 + wt, items = 0, [] set.each {|elem| wt += elem.weight; items << elem.name} puts "weight: #{wt}" - puts "items: #{items.sort.join(',')}" + puts "items: #{items.join(',')}" end diff --git a/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-2.rb b/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-2.rb index 553abbc18b..6668425a49 100644 --- a/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-2.rb +++ b/Task/Knapsack-problem-0-1/Ruby/knapsack-problem-0-1-2.rb @@ -1,84 +1,63 @@ -KnapsackItem = Struct.new(:name, :cost, :value) -KnapsackProblem = Struct.new(:items, :max_cost) +KnapsackItem = Struct.new(:name, :weight, :value) -def dynamic_programming_knapsack(problem) - num_items = problem.items.size - items = problem.items - max_cost = problem.max_cost - - cost_matrix = zeros(num_items, max_cost+1) +def dynamic_programming_knapsack(items, max_weight) + num_items = items.size + cost_matrix = Array.new(num_items){Array.new(max_weight+1, 0)} num_items.times do |i| - (max_cost + 1).times do |j| - if(items[i].cost > j) + (max_weight + 1).times do |j| + if(items[i].weight > j) cost_matrix[i][j] = cost_matrix[i-1][j] else - cost_matrix[i][j] = [cost_matrix[i-1][j], items[i].value + cost_matrix[i-1][j-items[i].cost]].max + cost_matrix[i][j] = [cost_matrix[i-1][j], items[i].value + cost_matrix[i-1][j-items[i].weight]].max end end end - - cost_matrix + used_items = get_used_items(items, cost_matrix) + [get_list_of_used_items_names(items, used_items), # used items names + items.zip(used_items).map{|item,used| item.weight*used}.inject(:+), # total weight + cost_matrix.last.last] # total value end -def get_used_items(problem, cost_matrix) +def get_used_items(items, cost_matrix) i = cost_matrix.size - 1 currentCost = cost_matrix[0].size - 1 - marked = Array.new(cost_matrix.size, 0) + marked = cost_matrix.map{0} while(i >= 0 && currentCost >= 0) if(i == 0 && cost_matrix[i][currentCost] > 0 ) || (cost_matrix[i][currentCost] != cost_matrix[i-1][currentCost]) marked[i] = 1 - currentCost -= problem.items[i].cost + currentCost -= items[i].weight end i -= 1 end marked end -def get_list_of_used_items_names(problem, cost_matrix) - items = problem.items - used_items = get_used_items(problem, cost_matrix) - - result = [] - - used_items.each_with_index do |item,i| - if item > 0 - result << items[i].name - end - end - - result.sort.join(', ') -end - -def zeros(rows, cols) - Array.new(rows) do |row| - Array.new(cols, 0) - end +def get_list_of_used_items_names(items, used_items) + items.zip(used_items).map{|item,used| item.name if used>0}.compact.join(', ') end if $0 == __FILE__ + items = [ + KnapsackItem['map' , 9, 150], KnapsackItem['compass' , 13, 35], + KnapsackItem['water' , 153, 200], KnapsackItem['sandwich' , 50, 160], + KnapsackItem['glucose' , 15, 60], KnapsackItem['tin' , 68, 45], + KnapsackItem['banana' , 27, 60], KnapsackItem['apple' , 39, 40], + KnapsackItem['cheese' , 23, 30], KnapsackItem['beer' , 52, 10], + KnapsackItem['suntan cream' , 11, 70], KnapsackItem['camera' , 32, 30], + KnapsackItem['t-shirt' , 24, 15], KnapsackItem['trousers' , 48, 10], + KnapsackItem['umbrella' , 73, 40], KnapsackItem['waterproof trousers', 42, 70], + KnapsackItem['waterproof overclothes', 43, 75], KnapsackItem['note-case' , 22, 80], + KnapsackItem['sunglasses' , 7, 20], KnapsackItem['towel' , 18, 12], + KnapsackItem['socks' , 4, 50], KnapsackItem['book' , 30, 10] + ] - items = [ - KnapsackItem.new('map' , 9 , 150) , KnapsackItem.new('compass' , 13 , 35) , - KnapsackItem.new('water' , 153 , 200) , KnapsackItem.new('sandwich' , 50 , 160) , - KnapsackItem.new('glucose' , 15 , 60) , KnapsackItem.new('tin' , 68 , 45) , - KnapsackItem.new('banana' , 27 , 60) , KnapsackItem.new('apple' , 39 , 40) , - KnapsackItem.new('cheese' , 23 , 30) , KnapsackItem.new('beer' , 52 , 10) , - KnapsackItem.new('suntan cream' , 11 , 70) , KnapsackItem.new('camera' , 32 , 30) , - KnapsackItem.new('t-shirt' , 24 , 15) , KnapsackItem.new('trousers' , 48 , 10) , - KnapsackItem.new('umbrella' , 73 , 40) , KnapsackItem.new('waterproof trousers' , 42 , 70) , - KnapsackItem.new('waterproof overclothes' , 43 , 75) , KnapsackItem.new('note-case' , 22 , 80) , - KnapsackItem.new('sunglasses' , 7 , 20) , KnapsackItem.new('towel' , 18 , 12) , - KnapsackItem.new('socks' , 4 , 50) , KnapsackItem.new('book' , 30 , 10) - ] - - problem = KnapsackProblem.new(items, 400) - - cost_matrix = dynamic_programming_knapsack problem + names, weight, value = dynamic_programming_knapsack(items, 400) puts puts 'Dynamic Programming:' puts - puts 'Found solution: ' + get_list_of_used_items_names(problem, cost_matrix) - puts 'With value: ' + cost_matrix.last.last.to_s + puts "Found solution: #{names}" + puts "total weight: #{weight}" + puts "total value: #{value}" end diff --git a/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust b/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust new file mode 100644 index 0000000000..ae14360bf6 --- /dev/null +++ b/Task/Knapsack-problem-0-1/Rust/knapsack-problem-0-1.rust @@ -0,0 +1,140 @@ +extern crate std; +use std::cmp::max; +use std::vec::Vec; + + +// This struct is used to store our items that we want in our knap-sack. +struct Want<'a> { + name: &'a str, + weight: uint, + value: uint +} + + +// Global, immutable allocation of our items. +static items : &'static [Want<'static>] = &[ + Want {name: "map", weight: 9, value: 150}, + Want {name: "compass", weight: 13, value: 35}, + Want {name: "water", weight: 153, value: 200}, + Want {name: "sandwich", weight: 50, value: 160}, + Want {name: "glucose", weight: 15, value: 60}, + Want {name: "tin", weight: 68, value: 45}, + Want {name: "banana", weight: 27, value: 60}, + Want {name: "apple", weight: 39, value: 40}, + Want {name: "cheese", weight: 23, value: 30}, + Want {name: "beer", weight: 52, value: 10}, + Want {name: "suntancream", weight: 11, value: 70}, + Want {name: "camera", weight: 32, value: 30}, + Want {name: "T-shirt", weight: 24, value: 15}, + Want {name: "trousers", weight: 48, value: 10}, + Want {name: "umbrella", weight: 73, value: 40}, + Want {name: "waterproof trousers", weight: 42, value: 70}, + Want {name: "waterproof overclothes", weight: 43, value: 75}, + Want {name: "note-case", weight: 22, value: 80}, + Want {name: "sunglasses", weight: 7, value: 20}, + Want {name: "towel", weight: 18, value: 12}, + Want {name: "socks", weight: 4, value: 50}, + Want {name: "book", weight: 30, value: 10} +]; + + +// This is a bottom-up dynamic programming solution to the 0-1 knap-sack problem. +// maximize value +// subject to weights <= max_weight +fn knap_01_dp<'a>(xs: &[Want<'a>], max_weight: uint) -> Vec> { + + // Save this value, so we don't have to make repeated calls. + let xs_len = xs.len(); + + // Imagine we wrote a recursive function(item, max_weight) that returns a + // uint corresponding to the maximum cumulative value by considering a + // subset of items such that the combined weight <= max_weight. + // + // fn best_value(item: uint, max_weight: uint) -> uint{ + // if item == 0 { + // return 0; + // } + // if xs[item - 1].weight > max_weight { + // return best_value(item - 1, max_weight); + // } + // return max(best_value(item - 1, max_weight), + // best_value(item - 1, max_weight - xs[item - 1].weight) + // + xs[item - 1].value); + // } + // + // best_value(xs_len, max_weight) is equal to the maximum value that we + // can add to the bag. + // + // The problem with using this function is that it performs redundant + // calculations. + // + // The dynamic programming solution is to precompute all of the values we + // need and put them into a 2D array. + // + // In a similar vein, the top-down solution would be to memoize the + // function then compute the results on demand. + + let zero_vec = Vec::from_elem(max_weight + 1, 0 as uint); + let mut best_value = Vec::from_elem(xs_len + 1, zero_vec); + + // loop over the items + for i in range(0, xs_len) { + // loop over the weights + for w in range(1, max_weight + 1) { + // do we have room in our knapsack? + if xs[i].weight > w { + // if we don't, then we'll say that the value doesn't change + // when considering this item + *best_value.get_mut(i + 1).get_mut(w) = best_value.get(i).get(w).clone(); + } else { + // if we do, then we have to see if the value we gain by adding + // the item, given the weight, is better than not adding the item + *best_value.get_mut(i + 1).get_mut(w) = + max(best_value.get(i).get(w).clone(), + best_value.get(i).get(w - xs[i].weight) + xs[i].value); + } + } + } + + // a variable representing the weight left in the bag + let mut left_weight = max_weight.clone(); + + // a possibly over-allocated dynamically sized vector to push results to + let mut result = Vec::with_capacity(xs_len); + + // we built up the solution space through a forward pass over the data, + // now we have to traverse backwards to get the solution + for i in range(1, xs_len+1).rev() { + // We can check if an item should be added to the knap-sack by comparing + // best_value with and without this item. If best_value added this + // item then so should we. + if best_value.get(i).get(left_weight) != best_value.get(i - 1).get(left_weight) { + result.push(xs[i - 1]); + // we remove the weight of the object from the remaining weight + // we can add to the bag + left_weight -= xs[i - 1].weight; + } + } + + return result; +} + + +fn main () { + let xs = knap_01_dp(items, 400); + + // Print the items. We have to reverse the order because we solved the + // problem backward. + for i in xs.iter().rev() { + println!("Item: {}, Weight: {}, Value: {}", i.name, i.weight, i.value); + } + + // Print the sum of weights. + let weights = xs.iter().fold(0, |a, &b| a + b.weight); + println!("Total Weight: {}", weights); + + // Print the sum of the values. + let values = xs.iter().fold(0, |a, &b| a + b.value); + println!("Total Value: {}", values); + +} diff --git a/Task/Knapsack-problem-0-1/Scala/knapsack-problem-0-1.scala b/Task/Knapsack-problem-0-1/Scala/knapsack-problem-0-1.scala index 70a19f73fd..4a1fe8602f 100644 --- a/Task/Knapsack-problem-0-1/Scala/knapsack-problem-0-1.scala +++ b/Task/Knapsack-problem-0-1/Scala/knapsack-problem-0-1.scala @@ -10,7 +10,14 @@ object Knapsack extends App { val tv:Set[Item]=>Int=ps=>(ps:\0)((a,b)=>a.value+b) //total value val pis = (loi.toSet.subsets).toList.filterNot(_==Set()) - val res = pis.map(ss=>Pair(ss,tw(ss))) + #[test] +fn test_dp_results() { + let dp_results = knap_01_dp(items, 400); + let dp_weights= dp_results.iter().fold(0, |a, &b| a + b.weight); + let dp_values = dp_results.iter().fold(0, |a, &b| a + b.value); + assert_eq!(dp_weights, 396); + assert_eq!(dp_values, 1030); +} val res = pis.map(ss=>Pair(ss,tw(ss))) .filter(p=>p._2>350 && p._2<401).map(p=>Pair(p,tv(p._1))) .sortWith((s,t)=>s._2.compareTo(t._2) < 0) .last diff --git a/Task/Knapsack-problem-Bounded/D/knapsack-problem-bounded.d b/Task/Knapsack-problem-Bounded/D/knapsack-problem-bounded.d index 07ef0c7fe9..9fd9b5e5dc 100644 --- a/Task/Knapsack-problem-Bounded/D/knapsack-problem-bounded.d +++ b/Task/Knapsack-problem-Bounded/D/knapsack-problem-bounded.d @@ -18,16 +18,15 @@ immutable Item[] items = [ {"sunglasses", 7, 20, 1}, {"towel", 18, 12, 2}, {"socks", 4, 50, 1}, {"book", 30, 10, 2}]; -Tuple!(int,const(int)[]) chooseItem(in int iWeight, in int idx) -nothrow { - alias memoize!chooseItem memoChooseItem; +Tuple!(int, const(int)[]) chooseItem(in int iWeight, in int idx) nothrow @safe { + alias memoChooseItem = memoize!chooseItem; if (idx < 0) - return typeof(return).init; + return typeof(return)(); int bestV; const(int)[] bestList; with (items[idx]) - foreach (i; 0 .. quantity + 1) { + foreach (immutable i; 0 .. quantity + 1) { immutable wlim = iWeight - i * weight; if (wlim < 0) break; @@ -48,7 +47,7 @@ void main() { const v_lst = chooseItem(400, items.length - 1); int w; - foreach (i, cnt; v_lst[1]) + foreach (immutable i, const cnt; v_lst[1]) if (cnt > 0) { writeln(cnt, " ", items[i].name); w += items[i].weight * cnt; diff --git a/Task/Knapsack-problem-Bounded/Go/knapsack-problem-bounded.go b/Task/Knapsack-problem-Bounded/Go/knapsack-problem-bounded.go index 420d0f2278..49a2031328 100644 --- a/Task/Knapsack-problem-Bounded/Go/knapsack-problem-bounded.go +++ b/Task/Knapsack-problem-Bounded/Go/knapsack-problem-bounded.go @@ -1,17 +1,13 @@ package main + import "fmt" type Item struct { - name string + name string weight, value, qty int } -type Solution struct { - v, w int - qty []int -} - -var items = []Item { +var items = []Item{ {"map", 9, 150, 1}, {"compass", 13, 35, 1}, {"water", 153, 200, 2}, @@ -36,37 +32,62 @@ var items = []Item { {"book", 30, 10, 2}, } -func choose(weight, pos int, cache map[string]*Solution) (int, int, []int) { - if pos < 0 || weight <= 0 { - return 0, 0, make([]int, len(items)) +type Chooser struct { + Items []Item + cache map[key]solution +} + +type key struct { + w, p int +} + +type solution struct { + v, w int + qty []int +} + +func (c Chooser) Choose(limit int) (w, v int, qty []int) { + c.cache = make(map[key]solution) + s := c.rchoose(limit, len(c.Items)-1) + c.cache = nil // allow cache to be garbage collected + return s.v, s.w, s.qty +} + +func (c Chooser) rchoose(limit, pos int) solution { + if pos < 0 || limit <= 0 { + return solution{0, 0, nil} } - str := fmt.Sprintf("%d,%d", weight, pos) - if s, ok := cache[str]; ok { - return s.v, s.w, s.qty + key := key{limit, pos} + if s, ok := c.cache[key]; ok { + return s } - best_v, best_i, best_w, best_sol := 0, 0, 0, []int(nil) - - for i := 0; i * items[pos].weight <= weight && i <= items[pos].qty; i++ { - v, w, sol := choose(weight - i * items[pos].weight, pos - 1, cache) - v += i * items[pos].value - if v > best_v { - best_i, best_v, best_w, best_sol = i, v, w, sol + best_i, best := 0, solution{0, 0, nil} + for i := 0; i*items[pos].weight <= limit && i <= items[pos].qty; i++ { + sol := c.rchoose(limit-i*items[pos].weight, pos-1) + sol.v += i * items[pos].value + if sol.v > best.v { + best_i, best = i, sol } } - taken := make([]int, len(items)) - copy(taken, best_sol) - taken[pos] = best_i - v, w := best_v, best_w + best_i * items[pos].weight - - cache[str] = &Solution{v, w, taken} - return v, w, taken + if best_i > 0 { + // best.qty is used in another cache entry, + // we need to duplicate it before modifying it to + // store as our cache entry. + old := best.qty + best.qty = make([]int, len(items)) + copy(best.qty, old) + best.qty[pos] = best_i + best.w += best_i * items[pos].weight + } + c.cache[key] = best + return best } func main() { - v, w, s := choose(400, len(items) - 1, make(map[string]*Solution)) + v, w, s := Chooser{Items: items}.Choose(400) fmt.Println("Taking:") for i, t := range s { diff --git a/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx b/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx index 05b79d8b25..e76c0ef877 100644 --- a/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx +++ b/Task/Knapsack-problem-Bounded/REXX/knapsack-problem-bounded.rexx @@ -1,202 +1,171 @@ /*REXX pgm solves a knapsack problem (22 items +repeats, wt. restriction*/ -@.= -@.1 ='map 9 150' -@.2 ='compass 13 35' -@.3 ='water 153 200 2' -@.4 ='sandwich 50 60 2' -@.5 ='glucose 15 60 2' -@.6 ='tin 68 45 3' -@.7 ='banana 27 60 3' -@.8 ='apple 39 40 3' -@.9 ='cheese 23 30' -@.10='beer 52 10 3' -@.11='suntan_cream 11 70' -@.12='camera 32 30' -@.13='T-shirt 24 15 2' -@.14='trousers 48 10 2' -@.15='umbrella 73 40' -@.16='waterproof_trousers 42 70' -@.17='waterproof_overclothes 43 75' -@.18='note-case 22 80' -@.19='sunglasses 7 20' -@.20='towel 18 12 2' -@.21='socks 4 50' -@.22='book 30 10 2' - +call @gen /*generate items &initializations*/ +call @sort /*sort items by decreasing weight*/ +call bOBJ /*build a list of choices. */ +call showOBJ /*display the list of choices. */ +call sim37 /*examine the possible choices. */ +call showBest /*show best choice (weight,value)*/ +exit /*stick a fork in it, we're done.*/ +/*────────────────────────────────@GEN subroutine───────────────────────*/ +@gen: @. = + @.1 = 'map 9 150' + @.2 = 'compass 13 35' + @.3 = 'water 153 200 2' + @.4 = 'sandwich 50 60 2' + @.5 = 'glucose 15 60 2' + @.6 = 'tin 68 45 3' + @.7 = 'banana 27 60 3' + @.8 = 'apple 39 40 3' + @.9 = 'cheese 23 30' + @.10 = 'beer 52 10 3' + @.11 = 'suntan_cream 11 70' + @.12 = 'camera 32 30' + @.13 = 'T-shirt 24 15 2' + @.14 = 'trousers 48 10 2' + @.15 = 'umbrella 73 40' + @.16 = 'waterproof_trousers 42 70' + @.17 = 'waterproof_overclothes 43 75' + @.18 = 'note-case 22 80' + @.19 = 'sunglasses 7 20' + @.20 = 'towel 18 12 2' + @.21 = 'socks 4 50' + @.22 = 'book 30 10 2' +highQ=0 /*max quantity specified (if any)*/ maxWeight=400 /*the maximum weight for knapsack*/ -say; say 'maximum weight allowed for a knapsack:' comma(maxWeight); say maxL=length('item') /*maximum width for table names. */ maxL=length('knapsack items') /*maximum width for table names. */ maxW=length('weight') /* " " " " weights*/ maxV=length('value') /* " " " " values.*/ maxQ=length('pieces') /* " " " " quant. */ -highQ=0 /*max quantity specified (if any)*/ -items=0; i.=; w.=0; v.=0; q.=0; Tw=0; Tv=0; Tq=0 /*initialize stuff.*/ -/*────────────────────────────────sort the choices by decreasing weight.*/ - /*this minimizes # combinations. */ - do j=1 while @.j\=='' /*process each choice and sort. */ - _=@.j; _wt=word(_,2) /*choose first item (arbitrary). */ - _wt=word(_,2) - do k=j+1 while @.k\=='' /*find a possible heavier item. */ - ?wt=word(@.k,2) - if ?wt>_wt then do; _=@.k; @.k=@.j; @.j=_; _wt=?wt; end - end /*k*/ - end /*j*/ +items=0; i.=; w.=0; v.=0; q.=0 /*initialize some stuff & things.*/ +Tw=0; Tv=0; Tq=0; m=maxWeight /* " more " " " */ +say; say 'maximum weight allowed for a knapsack: ' comma(maxWeight); say +return +/*────────────────────────────────@SORT subroutine──────────────────────*/ +@sort: do j=1 while @.j\=='' /*process each choice and sort. */ + _=space(@.j); @.j=_ /*remove any superfluous blanks. */ + _wt=word(_, 2) /*choose first item (arbitrary). */ + do k=j+1 while @.k\=='' /*find a possible heavier item. */ + ?wt=word(@.k, 2) + if ?wt>_wt then do; _=@.k; @.k=@.j; @.j=_; _wt=?wt; end + end /*k*/ + end /*j*/ /* [↑] minimizes # combinations.*/ obj=j-1 /*adjust for the DO loop index. */ -/*────────────────────────────────build list of choices.────────────────*/ - do j=1 for obj /*build a list of choices. */ - _=space(@.j) /*remove superfluous blanks. */ - parse var _ item w v q . /*parse original choice for table*/ - if w>maxWeight then iterate /*if the weight > maximum, ignore*/ - Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 /*add totals up (for alignment). */ - maxL=max(maxL,length(item)) /*find maximum width for item. */ - if q=='' then q=1 - highQ=max(highQ,q) +return +/*────────────────────────────────BOBJ subroutine───────────────────────*/ +bOBJ: do j=1 for obj /*build a list of choices. */ + parse var @.j item w v q . /*parse original choice for table*/ + if w>maxWeight then iterate /*if the weight > maximum, ignore*/ + Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 /*add totals up (for alignment). */ + maxL=max(maxL, length(item)) /*find maximum width for item. */ + if q=='' then q=1 + highQ=max(highQ, q) items=items+1 /*bump the item counter. */ i.items=item; w.items=w; v.items=v; q.items=q - do k=2 to q; items=items+1 /*bump the item counter. */ - i.items=item; w.items=w; v.items=v; q.items=q - Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 - end /*k*/ - end /*j*/ + do k=2 to q; items=items+1 /*bump the item counter (pieces).*/ + i.items=item; w.items=w; v.items=v; q.items=q + Tw=Tw+w; Tv=Tv+v; Tq=Tq+1 + end /*k*/ + end /*j*/ -maxW=max(maxW,length(comma(Tw))) /*find maximum width for weight. */ -maxV=max(maxV,length(comma(Tv))) /* " " " " value. */ -maxQ=max(maxQ,length(comma(Tq))) /* " " " " quantity*/ -maxL=maxL+maxL%4+4 /*extend width of name for table.*/ -/*────────────────────────────────show the list of choices.─────────────*/ -call hdr 'item'; do j=1 for obj /*show all choices, nice format. */ - parse var @.j item weight value q . - if highq==1 then q= - else if q=='' then q=1 - call show item,weight,value,q - end /*j*/ - -say; say 'number of items:' items; say -/*─────────────────────────────────────examine the possible choices. */ -h=items; m=maxWeight; $=0; call sim37 -/*─────────────────────────────────────show the best choice (weight,val)*/ - do h-1; ?=strip(strip(?),"L",0); end -bestC=?; bestW=0; bestV=$; highQ=0; totP=words(bestC) +maxW=max(maxW, length(comma(Tw))) /*find maximum width for weight. */ +maxV=max(maxV, length(comma(Tv))) /* " " " " value. */ +maxQ=max(maxQ, length(comma(Tq))) /* " " " " quantity*/ +maxL=maxL + maxL %4 + 4 /*extend width of name for table.*/ +return /* [↑] % is integer division.*/ +/*────────────────────────────────COMMA subroutine────────────────────────────────────────────────────────────*/ +comma: procedure; parse arg _,c,p,t; arg ,u; c=word(c ",",1); if u=='BLANK' then c=' '; o=word(p 3,1); p=abs(o) +t=word(t 999999999,1); if \datatype(p,'W')|\datatype(t,'W')|p==0|arg()>4 then return _; n=_'.9';#=123456789; k=0 +if o<0 then do; b=verify(_,' '); if b==0 then return _; e=length(_)-verify(reverse(_),' ')+1; end + else do; b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end + do j=e to b by -p while k4 then return _;n=_'.9' - #=123456789;k=0;if o<0 then do;b=verify(_,' ');if b==0 then return _ - e=length(_)-verify(reverse(_),' ')+1;end;else do;b=verify(n,#,"M") - e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1;end - do j=e to b by -p while k$ then call j? 1 -do j2=j1+(j1\==0) to h -if w.j2+w1>m then iterate j1;w2=w1+w.j2;v2=v1+v.j2;if v2>$ then call j? 2 -do j3=j2+(j2\==0) to h -if w.j3+w2>m then iterate j2;w3=w2+w.j3;v3=v2+v.j3;if v3>$ then call j? 3 -do j4=j3+(j3\==0) to h -if w.j4+w3>m then iterate j3;w4=w3+w.j4;v4=v3+v.j4;if v4>$ then call j? 4 -do j5=j4+(j4\==0) to h -if w.j5+w4>m then iterate j4;w5=w4+w.j5;v5=v4+v.j5;if v5>$ then call j? 5 -do j6=j5+(j5\==0) to h -if w.j6+w5>m then iterate j5;w6=w5+w.j6;v6=v5+v.j6;if v6>$ then call j? 6 -do j7=j6+(j6\==0) to h -if w.j7+w6>m then iterate j6;w7=w6+w.j7;v7=v6+v.j7;if v7>$ then call j? 7 -do j8=j7+(j7\==0) to h -if w.j8+w7>m then iterate j7;w8=w7+w.j8;v8=v7+v.j8;if v8>$ then call j? 8 -do j9=j8+(j8\==0) to h -if w.j9+w8>m then iterate j8;w9=w8+w.j9;v9=v8+v.j9;if v9>$ then call j? 9 -do j10=j9+(j9\==0) to h -if w.j10+w9>m then iterate j9;w10=w9+w.j10;v10=v9+v.j10;if v10>$ then call j? 10 -do j11=j10+(j10\==0) to h -if w.j11+w10>m then iterate j10;w11=w10+w.j11;v11=v10+v.j11;if v11>$ then call j? 11 -do j12=j11+(j11\==0) to h -if w.j12+w11>m then iterate j11;w12=w11+w.j12;v12=v11+v.j12;if v12>$ then call j? 12 -do j13=j12+(j12\==0) to h -if w.j13+w12>m then iterate j12;w13=w12+w.j13;v13=v12+v.j13;if v13>$ then call j? 13 -do j14=j13+(j13\==0) to h -if w.j14+w13>m then iterate j13;w14=w13+w.j14;v14=v13+v.j14;if v14>$ then call j? 14 -do j15=j14+(j14\==0) to h -if w.j15+w14>m then iterate j14;w15=w14+w.j15;v15=v14+v.j15;if v15>$ then call j? 15 -do j16=j15+(j15\==0) to h -if w.j16+w15>m then iterate j15;w16=w15+w.j16;v16=v15+v.j16;if v16>$ then call j? 16 -do j17=j16+(j16\==0) to h -if w.j17+w16>m then iterate j16;w17=w16+w.j17;v17=v16+v.j17;if v17>$ then call j? 17 -do j18=j17+(j17\==0) to h -if w.j18+w17>m then iterate j17;w18=w17+w.j18;v18=v17+v.j18;if v18>$ then call j? 18 -do j19=j18+(j18\==0) to h -if w.j19+w18>m then iterate j18;w19=w18+w.j19;v19=v18+v.j19;if v19>$ then call j? 19 -do j20=j19+(j19\==0) to h -if w.j20+w19>m then iterate j19;w20=w19+w.j20;v20=v19+v.j20;if v20>$ then call j? 20 -do j21=j20+(j20\==0) to h -if w.j21+w20>m then iterate j20;w21=w20+w.j21;v21=v20+v.j21;if v21>$ then call j? 21 -do j22=j21+(j21\==0) to h -if w.j22+w21>m then iterate j21;w22=w21+w.j22;v22=v21+v.j22;if v22>$ then call j? 22 -do j23=j22+(j22\==0) to h -if w.j23+w22>m then iterate j22;w23=w22+w.j23;v23=v22+v.j23;if v23>$ then call j? 23 -do j24=j23+(j23\==0) to h -if w.j24+w23>m then iterate j23;w24=w23+w.j24;v24=v23+v.j24;if v24>$ then call j? 24 -do j25=j24+(j24\==0) to h -if w.j25+w24>m then iterate j24;w25=w24+w.j25;v25=v24+v.j25;if v25>$ then call j? 25 -do j26=j25+(j25\==0) to h -if w.j26+w25>m then iterate j25;w26=w25+w.j26;v26=v25+v.j26;if v26>$ then call j? 26 -do j27=j26+(j26\==0) to h -if w.j27+w26>m then iterate j26;w27=w26+w.j27;v27=v26+v.j27;if v27>$ then call j? 27 -do j28=j27+(j27\==0) to h -if w.j28+w27>m then iterate j27;w28=w27+w.j28;v28=v27+v.j28;if v28>$ then call j? 28 -do j29=j28+(j28\==0) to h -if w.j29+w28>m then iterate j28;w29=w28+w.j29;v29=v28+v.j29;if v29>$ then call j? 29 -do j30=j29+(j29\==0) to h -if w.j30+w29>m then iterate j29;w30=w29+w.j30;v30=v29+v.j30;if v30>$ then call j? 30 -do j31=j30+(j30\==0) to h -if w.j31+w30>m then iterate j30;w31=w30+w.j31;v31=v30+v.j31;if v31>$ then call j? 31 -do j32=j31+(j31\==0) to h -if w.j32+w31>m then iterate j31;w32=w31+w.j32;v32=v31+v.j32;if v32>$ then call j? 32 -do j33=j32+(j32\==0) to h -if w.j33+w32>m then iterate j32;w33=w32+w.j33;v33=v32+v.j33;if v33>$ then call j? 33 -do j34=j33+(j33\==0) to h -if w.j34+w33>m then iterate j33;w34=w33+w.j34;v34=v33+v.j34;if v34>$ then call j? 34 -do j35=j34+(j34\==0) to h -if w.j35+w34>m then iterate j34;w35=w34+w.j35;v35=v34+v.j35;if v35>$ then call j? 35 -do j36=j35+(j35\==0) to h -if w.j36+w35>m then iterate j35;w36=w35+w.j36;v36=v35+v.j36;if v36>$ then call j? 36 -do j37=j36+(j36\==0) to h -if w.j37+w36>m then iterate j36;w37=w36+w.j37;v37=v36+v.j37;if v37>$ then call j? 37 +/*─────────────────────────────────────SIM37 subroutine──────────────────────────────────────────────────────────────────────────────────────────*/ +sim37: h=items; $=0 +do j1 =0 for h+1; w1= w.j1 ; v1= v.j1 ; if v1>$ then call j? 1 +do j2 =j1 +(j1 \==0) to h; if w.j2 +w1 >m then iterate j1; w2=w1 +w.j2 ; v2=v1 +v.j2 ; if v2>$ then call j? 2 +do j3 =j2 +(j2 \==0) to h; if w.j3 +w2 >m then iterate j2; w3=w2 +w.j3 ; v3=v2 +v.j3 ; if v3>$ then call j? 3 +do j4 =j3 +(j3 \==0) to h; if w.j4 +w3 >m then iterate j3; w4=w3 +w.j4 ; v4=v3 +v.j4 ; if v4>$ then call j? 4 +do j5 =j4 +(j4 \==0) to h; if w.j5 +w4 >m then iterate j4; w5=w4 +w.j5 ; v5=v4 +v.j5 ; if v5>$ then call j? 5 +do j6 =j5 +(j5 \==0) to h; if w.j6 +w5 >m then iterate j5; w6=w5 +w.j6 ; v6=v5 +v.j6 ; if v6>$ then call j? 6 +do j7 =j6 +(j6 \==0) to h; if w.j7 +w6 >m then iterate j6; w7=w6 +w.j7 ; v7=v6 +v.j7 ; if v7>$ then call j? 7 +do j8 =j7 +(j7 \==0) to h; if w.j8 +w7 >m then iterate j7; w8=w7 +w.j8 ; v8=v7 +v.j8 ; if v8>$ then call j? 8 +do j9 =j8 +(j8 \==0) to h; if w.j9 +w8 >m then iterate j8; w9=w8 +w.j9 ; v9=v8 +v.j9 ; if v9>$ then call j? 9 +do j10=j9 +(j9 \==0) to h; if w.j10+w9 >m then iterate j9; w10=w9 +w.j10; v10=v9 +v.j10; if v10>$ then call j? 10 +do j11=j10+(j10\==0) to h; if w.j11+w10>m then iterate j10; w11=w10+w.j11; v11=v10+v.j11; if v11>$ then call j? 11 +do j12=j11+(j11\==0) to h; if w.j12+w11>m then iterate j11; w12=w11+w.j12; v12=v11+v.j12; if v12>$ then call j? 12 +do j13=j12+(j12\==0) to h; if w.j13+w12>m then iterate j12; w13=w12+w.j13; v13=v12+v.j13; if v13>$ then call j? 13 +do j14=j13+(j13\==0) to h; if w.j14+w13>m then iterate j13; w14=w13+w.j14; v14=v13+v.j14; if v14>$ then call j? 14 +do j15=j14+(j14\==0) to h; if w.j15+w14>m then iterate j14; w15=w14+w.j15; v15=v14+v.j15; if v15>$ then call j? 15 +do j16=j15+(j15\==0) to h; if w.j16+w15>m then iterate j15; w16=w15+w.j16; v16=v15+v.j16; if v16>$ then call j? 16 +do j17=j16+(j16\==0) to h; if w.j17+w16>m then iterate j16; w17=w16+w.j17; v17=v16+v.j17; if v17>$ then call j? 17 +do j18=j17+(j17\==0) to h; if w.j18+w17>m then iterate j17; w18=w17+w.j18; v18=v17+v.j18; if v18>$ then call j? 18 +do j19=j18+(j18\==0) to h; if w.j19+w18>m then iterate j18; w19=w18+w.j19; v19=v18+v.j19; if v19>$ then call j? 19 +do j20=j19+(j19\==0) to h; if w.j20+w19>m then iterate j19; w20=w19+w.j20; v20=v19+v.j20; if v20>$ then call j? 20 +do j21=j20+(j20\==0) to h; if w.j21+w20>m then iterate j20; w21=w20+w.j21; v21=v20+v.j21; if v21>$ then call j? 21 +do j22=j21+(j21\==0) to h; if w.j22+w21>m then iterate j21; w22=w21+w.j22; v22=v21+v.j22; if v22>$ then call j? 22 +do j23=j22+(j22\==0) to h; if w.j23+w22>m then iterate j22; w23=w22+w.j23; v23=v22+v.j23; if v23>$ then call j? 23 +do j24=j23+(j23\==0) to h; if w.j24+w23>m then iterate j23; w24=w23+w.j24; v24=v23+v.j24; if v24>$ then call j? 24 +do j25=j24+(j24\==0) to h; if w.j25+w24>m then iterate j24; w25=w24+w.j25; v25=v24+v.j25; if v25>$ then call j? 25 +do j26=j25+(j25\==0) to h; if w.j26+w25>m then iterate j25; w26=w25+w.j26; v26=v25+v.j26; if v26>$ then call j? 26 +do j27=j26+(j26\==0) to h; if w.j27+w26>m then iterate j26; w27=w26+w.j27; v27=v26+v.j27; if v27>$ then call j? 27 +do j28=j27+(j27\==0) to h; if w.j28+w27>m then iterate j27; w28=w27+w.j28; v28=v27+v.j28; if v28>$ then call j? 28 +do j29=j28+(j28\==0) to h; if w.j29+w28>m then iterate j28; w29=w28+w.j29; v29=v28+v.j29; if v29>$ then call j? 29 +do j30=j29+(j29\==0) to h; if w.j30+w29>m then iterate j29; w30=w29+w.j30; v30=v29+v.j30; if v30>$ then call j? 30 +do j31=j30+(j30\==0) to h; if w.j31+w30>m then iterate j30; w31=w30+w.j31; v31=v30+v.j31; if v31>$ then call j? 31 +do j32=j31+(j31\==0) to h; if w.j32+w31>m then iterate j31; w32=w31+w.j32; v32=v31+v.j32; if v32>$ then call j? 32 +do j33=j32+(j32\==0) to h; if w.j33+w32>m then iterate j32; w33=w32+w.j33; v33=v32+v.j33; if v33>$ then call j? 33 +do j34=j33+(j33\==0) to h; if w.j34+w33>m then iterate j33; w34=w33+w.j34; v34=v33+v.j34; if v34>$ then call j? 34 +do j35=j34+(j34\==0) to h; if w.j35+w34>m then iterate j34; w35=w34+w.j35; v35=v34+v.j35; if v35>$ then call j? 35 +do j36=j35+(j35\==0) to h; if w.j36+w35>m then iterate j35; w36=w35+w.j36; v36=v35+v.j36; if v36>$ then call j? 36 +do j37=j36+(j36\==0) to h; if w.j37+w36>m then iterate j36; w37=w36+w.j37; v37=v36+v.j37; if v37>$ then call j? 37 end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end;end return diff --git a/Task/Knapsack-problem-Continuous/Bracmat/knapsack-problem-continuous.bracmat b/Task/Knapsack-problem-Continuous/Bracmat/knapsack-problem-continuous.bracmat new file mode 100644 index 0000000000..6ebd174a54 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Bracmat/knapsack-problem-continuous.bracmat @@ -0,0 +1,50 @@ +( ( fixed {function to convert a rational number to fixed point notation. + The second argument is the number of decimals. } + = value decimals powerOf10 + . !arg:(?value.?decimals) + & 10^!decimals:?powerOf10 + & str + $ ( div$(!value.1) + "." + mod + $ (div$(!value+1/2*!powerOf10^-1.!powerOf10^-1).!powerOf10) + ) + ) +& (beef.38/10.36) + (pork.54/10.43) + (ham.36/10.90) + (greaves.24/10.45) + (flitch.40/10.30) + (brawn.25/10.56) + (welt.37/10.67) + (salami.30/10.95) + (sausage.59/10.98) + : ?items +& 0:?sorteditems +& whl + ' ( !items:(?name.?mass.?price) ?items + & (!mass*!price^-1.!mass.!name)+!sorteditems:?sorteditems + ) +& 0:?totalMass +& :?stolenItems +& whl + ' ( !sorteditems:(?massPerPriceunit.?mass.?name)+?sorteditems + & (!mass.!massPerPriceunit.!name) !stolenItems + : ?stolenItems + & !mass+!totalMass:?totalMass:~>15 + ) +& !stolenItems:(?mass.?massPerPriceunit.?name) ?stolenItems +& 15+!mass+-1*!totalMass:?mass +& (!mass.!massPerPriceunit.!name) !stolenItems:?stolenItems +& 0:?totalPrice +& ( !stolenItems + : ? + ( (?mass.?massPerPriceunit.?name) + & out$(fixed$(!mass.1) "kg of" !name) + & !mass*!massPerPriceunit^-1+!totalPrice:?totalPrice + & ~ + ) + ? + | out$(fixed$(!totalPrice.2)) + ) +); diff --git a/Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous.cpp b/Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-1.cpp similarity index 100% rename from Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous.cpp rename to Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-1.cpp diff --git a/Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-2.cpp b/Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-2.cpp new file mode 100644 index 0000000000..02d111a30b --- /dev/null +++ b/Task/Knapsack-problem-Continuous/C++/knapsack-problem-continuous-2.cpp @@ -0,0 +1,53 @@ +// C++11 version +#include +#include +#include +#include + +using namespace std; + +struct item_type +{ + double weight, value; + string name; +}; + +vector< item_type > items = +{ + { 3.8, 36, "beef" }, + { 5.4, 43, "pork" }, + { 3.6, 90, "ham" }, + { 2.4, 45, "greaves" }, + { 4.0, 30, "flitch" }, + { 2.5, 56, "brawn" }, + { 3.7, 67, "welt" }, + { 3.0, 95, "salami" }, + { 5.9, 98, "sausage" } +}; + +int main() +{ + sort + ( + begin( items ), end( items ), + [] (const item_type& a, const item_type& b) + { + return a.value / a.weight > b.value / b.weight; + } + ); + + double space = 15; + + for ( const auto& item : items ) + { + if ( space >= item.weight ) + cout << "Take all " << item.name << endl; + else + { + cout << "Take " << space << "kg of " << item.name << endl; + break; + } + + space -= item.weight; + } +} diff --git a/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj b/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj new file mode 100644 index 0000000000..2b7bdee5e2 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/Clojure/knapsack-problem-continuous.clj @@ -0,0 +1,48 @@ +; Solve Continuous Knapsdack Problem +; Nicolas Modrzyk +; January 2015 + +(def maxW 15.0) +(def items + {:beef [3.8 36] + :pork [5.4 43] + :ham [3.6 90] + :greaves [2.4 45] + :flitch [4.0 30] + :brawn [2.5 56] + :welt [3.7 67] + :salami [3.0 95] + :sausage [5.9 98]}) + +(defn rob [items maxW] + (let[ + val-item + (fn[key] + (- (/ (second (items key)) (first (items key ))))) + compare-items + (fn[key1 key2] + (compare (val-item key1) (val-item key2))) + sorted (into (sorted-map-by compare-items) items)] + + (loop [current (first sorted) + array (rest sorted) + value 0 + weight 0] + (let[new-weight (first (val current)) + new-value (second (val current))] + (if (> (- maxW weight new-weight) 0) + (do + (println "Take all " (key current)) + (recur + (first array) + (rest array) + (+ value new-value) + (+ weight new-weight))) + (let [t (- maxW weight)] ; else + (println + "Take " t " of " + (key current) "\n" + "Total Value is:" + (+ value (* t (/ new-value new-weight)))))))))) + +(rob items maxW) 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 4785b01030..ff65385afe 100644 --- a/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d +++ b/Task/Knapsack-problem-Continuous/D/knapsack-problem-continuous-1.d @@ -4,21 +4,21 @@ struct Item { string name; real amount, value; - @property real valuePerKG() @safe const pure nothrow { + @property real valuePerKG() @safe const pure nothrow @nogc { return value / amount; } - string toString() const /*pure nothrow*/ { + string toString() const pure /*nothrow*/ @safe { return format("%10s %7.2f %7.2f %7.2f", name, amount, value, valuePerKG); } } -real sumBy(string field)(in Item[] items) @safe pure nothrow { +real sumBy(string field)(in Item[] items) @safe pure nothrow @nogc { return reduce!("a + b." ~ field)(0.0L, items); } -void main() { +void main() /*@safe*/ { const items = [Item("beef", 3.8, 36.0), Item("pork", 5.4, 43.0), Item("ham", 3.6, 90.0), diff --git a/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f b/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f index e1f03ce382..bc5152d3e5 100644 --- a/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f +++ b/Task/Knapsack-problem-Continuous/Fortran/knapsack-problem-continuous.f @@ -23,7 +23,7 @@ program KNAPSACK_CONTINUOUS items(8) = Item("salami", 3.0, 95.0) items(9) = Item("sausage", 5.9, 98.0) - ! sort items in desending order of their value per unit weight + ! sort items in descending order of their value per unit weight do i = 2, size(items) j = i - 1 temp = items(i) diff --git a/Task/Knapsack-problem-Continuous/PL-I/knapsack-problem-continuous.pli b/Task/Knapsack-problem-Continuous/PL-I/knapsack-problem-continuous.pli new file mode 100644 index 0000000000..d60c1ff8a1 --- /dev/null +++ b/Task/Knapsack-problem-Continuous/PL-I/knapsack-problem-continuous.pli @@ -0,0 +1,75 @@ +*process source xref attributes; + KNAPSACK_CONTINUOUS: Proc Options(main); + /*-------------------------------------------------------------------- + * 19.09.2014 Walter Pachl translated from FORTRAN + *-------------------------------------------------------------------*/ + Dcl (divide,float,hbound,repeat) Builtin; + Dcl SYSPRINT Print; + + Dcl maxweight Dec Fixed(15,3); + maxweight = 15.0; + Dcl (total_weight,total_value) Dec Fixed(15,3) Init(0); + Dcl vpu Dec Float(15); + Dcl (i,j) Bin Fixed(31); + + Dcl 1 item(9), + 2 name Char(7), + 2 weight Dec Fixed(15,3), + 2 value Dec Fixed(15,3); + Dcl temp Like item; + + Call init_item(1,'beef', 3.8, 36.0); + Call init_item(2,'pork', 5.4, 43.0); + Call init_item(3,'ham', 3.6, 90.0); + Call init_item(4,'greaves', 2.4, 45.0); + Call init_item(5,'flitch', 4.0, 30.0); + Call init_item(6,'brawn', 2.5, 56.0); + Call init_item(7,'welt', 3.7, 67.0); + Call init_item(8,'salami', 3.0, 95.0); + Call init_item(9,'sausage', 5.9, 98.0); + + /* sort item in descending order of their value per unit weight */ + do i = 2 To hbound(item); + j = i - 1; + temp = item(i); + do while(j>=1&item(j).value/item(j).weight=maxW then f=(maxW-totW)/w.j /*calc fract*/ + totW=totW+w.j*f; totV=totV+v.j*f /*add──►tots*/ + call syf left(word('{all}',1+(f\==1)),5) n.j, w.j*f, v.j*f + end /*j*/ /*↑show item*/ +call sep; say /* [↓] $ supresses trailing Θs.*/ +call sy left('total weight',nL,'─'), $(format(totW,,d)) +call sy left('total value',nL,'─'), , $(format(totV,,d)) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines──────────────────────*/ +hdr: say; say; say center(arg(1),50,'─'); say; call title; call sep; return +sep: call sy copies('═',nL), copies("═",wL), copies('═',vL); return +show: call hdr arg(1); do j=1 for #; call syf n.j,w.j,v.j; end; return +sy: say left('',9) left(arg(1),nL) right(arg(2),wL) right(arg(3),vL); return +syf: call sy arg(1), $(format(arg(2),,d)), $(format(arg(3),,d)); return +title: call sy center('item',nL), center("weight",wL), center('value',vL); return +$:x=arg(1);if pos(.,x)>1 then x=left(strip(strip(x,'T',0),,.),length(x));return x +/*──────────────────────────────────SORTD subroutine───────────────────────────*/ +sortD: do sort=2 to #; _n=n.sort; _w=w.sort; _v=v.sort /*descending. */ + do k=sort-1 by -1 to 1 while v.k/w.k<_v/_w /*order items.*/ + p=k+1; n.p=n.k; w.p=w.k; v.p=v.k /*shuffle 'em.*/ + end /*k*/ /*[↓] last one*/ + a=k+1; n.a=_n; w.a=_w; v.a=_v /*place item. */ + end /*sort*/ +return /* ↑ ↑ ↑ algorithm is OK for smallish arrays.*/ diff --git a/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-2.rexx b/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-2.rexx new file mode 100644 index 0000000000..35c989665f --- /dev/null +++ b/Task/Knapsack-problem-Continuous/REXX/knapsack-problem-continuous-2.rexx @@ -0,0 +1,77 @@ + /*-------------------------------------------------------------------- + * 19.09.2014 Walter Pachl translated from FORTRAN + * While this program works with all REXX interpreters, + * see section ooRexx for a version that utilizes the ooRexx features + *-------------------------------------------------------------------*/ + maxweight = 15.0 + input.0=0 + Call init_input 'beef', 3.8, 36.0 + Call init_input 'pork', 5.4, 43.0 + Call init_input 'ham', 3.6, 90.0 + Call init_input 'greaves', 2.4, 45.0 + Call init_input 'flitch', 4.0, 30.0 + Call init_input 'brawn', 2.5, 56.0 + Call init_input 'welt', 3.7, 67.0 + Call init_input 'salami', 3.0, 95.0 + Call init_input 'sausage', 5.9, 98.0 + + /* sort the items by descending value per unit of weight */ + Do i = 1 to input.0 + Parse Var input.i name '*' weight '*' value + vpu=value/weight; + If i=1 Then Do + item.0=1 + item.1=input.1 + vpu.1=vpu + End + Else Do + Do ii=1 To item.0 + If vpu.ii 0 + puts "Take all #{item}" + value += price + else + puts "Take %gkg of %s" % [t=weight+maxW, item], "", + "Total value of swag is %g" % (value+(price/weight)*t) + break + end +end diff --git a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-1.d b/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-1.d index 002eb85273..503c9145a5 100644 --- a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-1.d +++ b/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-1.d @@ -1,22 +1,22 @@ -import std.stdio, std.algorithm, std.typecons; +void main() @safe /*@nogc*/ { + import std.stdio, std.algorithm, std.typecons, std.conv; -struct Bounty { - int value; - double weight, volume; -} + static struct Bounty { + int value; + double weight, volume; + } -void main() { immutable Bounty panacea = {3000, 0.3, 0.025}; immutable Bounty ichor = {1800, 0.2, 0.015}; immutable Bounty gold = {2500, 2.0, 0.002}; - immutable Bounty sack = { 0, 25.0, 0.25}; + immutable Bounty sack = { 0, 25.0, 0.25 }; - immutable maxPanacea = cast(int)(min(sack.weight / panacea.weight, - sack.volume / panacea.volume)); - immutable maxIchor = cast(int)(min(sack.weight / ichor.weight, - sack.volume / ichor.volume)); - immutable maxGold = cast(int)(min(sack.weight / gold.weight, - sack.volume / gold.volume)); + immutable maxPanacea = min(sack.weight / panacea.weight, + sack.volume / panacea.volume).to!int; + immutable maxIchor = min(sack.weight / ichor.weight, + sack.volume / ichor.volume).to!int; + immutable maxGold = min(sack.weight / gold.weight, + sack.volume / gold.volume).to!int; Bounty best = {0, 0, 0}; Tuple!(int, int, int) bestAmounts; @@ -38,16 +38,14 @@ void main() { if (current.value > best.value && current.weight <= sack.weight && current.volume <= sack.volume) { - best = Bounty(current.value, - current.weight, - current.volume); + best = Bounty(current.value, current.weight, current.volume); bestAmounts = tuple(nPanacea, nIchor, nGold); } } writeln("Maximum value achievable is ", best.value); writefln("This is achieved by carrying (one solution) %d" ~ - " panacea, %d ichor and %d gold", bestAmounts.tupleof); + " panacea, %d ichor and %d gold", bestAmounts[]); writefln("The weight to carry is %4.1f and the volume used is %5.3f", best.weight, best.volume); } diff --git a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-2.d b/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-2.d index 56f5fb56ea..eec4109a78 100644 --- a/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-2.d +++ b/Task/Knapsack-problem-Unbounded/D/knapsack-problem-unbounded-2.d @@ -1,38 +1,26 @@ -import std.stdio, std.algorithm, std.typecons, std.range; - -alias Bounty = Tuple!(int,"value", double,"weight", double,"volume"); - void main() { - immutable panacea = Bounty(3000, 0.3, 0.025); - immutable ichor = Bounty(1800, 0.2, 0.015); - immutable gold = Bounty(2500, 2.0, 0.002); - immutable sack = Bounty( 0, 25.0, 0.25); + import std.stdio, std.algorithm, std.typecons, std.range, std.conv; - immutable maxPanacea= cast(int)(min(sack.weight / panacea.weight, - sack.volume / panacea.volume)); - immutable maxIchor = cast(int)(min(sack.weight / ichor.weight, - sack.volume / ichor.volume)); - immutable maxGold = cast(int)(min(sack.weight / gold.weight, - sack.volume / gold.volume)); + alias Bounty = Tuple!(int,"value", double,"weight", double,"volume"); - immutable best = + immutable panacea = Bounty(3000, 0.3, 0.025); + immutable ichor = Bounty(1800, 0.2, 0.015); + immutable gold = Bounty(2500, 2.0, 0.002); + immutable sack = Bounty( 0, 25.0, 0.25); + + immutable maxPanacea = min(sack.weight / panacea.weight, sack.volume / panacea.volume).to!int; + immutable maxIchor = min(sack.weight / ichor.weight, sack.volume / ichor.volume).to!int; + immutable maxGold = min(sack.weight / gold.weight, sack.volume / gold.volume).to!int; + + immutable best = cartesianProduct(maxPanacea.iota, maxIchor.iota, maxGold.iota) - .map!(t => tuple(Bounty(t[0] * panacea.value - + t[1] * ichor.value - + t[2] * gold.value, - t[0] * panacea.weight - + t[1] * ichor.weight - + t[2] * gold.weight, - t[0] * panacea.volume - + t[1] * ichor.volume - + t[2] * gold.volume), t)) - .filter!(t => t[0].weight <= sack.weight - && t[0].volume <= sack.volume) + .map!(t => tuple(Bounty(t[0] * panacea.value + t[1] * ichor.value + t[2] * gold.value, + t[0] * panacea.weight + t[1] * ichor.weight + t[2] * gold.weight, + t[0] * panacea.volume + t[1] * ichor.volume + t[2] * gold.volume), t)) + .filter!(t => t[0].weight <= sack.weight && t[0].volume <= sack.volume) .reduce!max; - writeln("Maximum value achievable is ", best[0].value); - writefln("This is achieved by carrying (one solution) %d" ~ - " panacea, %d ichor and %d gold", best[1].tupleof); - writefln("The weight to carry is %4.1f and the" ~ - " volume used is %5.3f", best[0].weight, best[0].volume); + writeln("Maximum value achievable is ", best[0].value); + writefln("This is achieved by carrying (one solution) %d panacea, %d ichor and %d gold", best[1][]); + writefln("The weight to carry is %4.1f and the volume used is %5.3f", best[0][1..$]); } diff --git a/Task/Knapsack-problem-Unbounded/Go/knapsack-problem-unbounded.go b/Task/Knapsack-problem-Unbounded/Go/knapsack-problem-unbounded.go index b22f8bc648..31c454c881 100644 --- a/Task/Knapsack-problem-Unbounded/Go/knapsack-problem-unbounded.go +++ b/Task/Knapsack-problem-Unbounded/Go/knapsack-problem-unbounded.go @@ -3,68 +3,64 @@ package main import "fmt" type Item struct { - Name string - Value int - Weight, Volume float64 + Name string + Value int + Weight, Volume float64 } type Result struct { - Counts []int - Sum int + Counts []int + Sum int } func min(a, b int) int { - if a < b { - return a - } - return b + if a < b { + return a + } + return b } -func Knapsack(items []Item, index int, weight, volume float64) (best *Result) { - if index == len(items) { - return &Result{make([]int, len(items)), 0} - } - itemValue := items[index].Value - itemWeight := items[index].Weight - itemVolume := items[index].Volume - maxCount := min(int(weight/itemWeight), int(volume/itemVolume)) - for count := 0; count <= maxCount; count++ { - sol := Knapsack(items, index+1, - weight-float64(count)*itemWeight, - volume-float64(count)*itemVolume) - if sol != nil { - sol.Counts[index] = count - sol.Sum += itemValue * count - if best == nil || sol.Sum > best.Sum { - best = sol - } - } - } - return +func Knapsack(items []Item, weight, volume float64) (best Result) { + if len(items) == 0 { + return + } + n := len(items) - 1 + maxCount := min(int(weight/items[n].Weight), int(volume/items[n].Volume)) + for count := 0; count <= maxCount; count++ { + sol := Knapsack(items[:n], + weight-float64(count)*items[n].Weight, + volume-float64(count)*items[n].Volume) + sol.Sum += items[n].Value * count + if sol.Sum > best.Sum { + sol.Counts = append(sol.Counts, count) + best = sol + } + } + return } func main() { - items := []Item{ - Item{"Panacea", 3000, 0.3, 0.025}, - Item{"Ichor", 1800, 0.2, 0.015}, - Item{"Gold", 2500, 2.0, 0.002}, - } - var sumCount, sumValue int - var sumWeight, sumVolume float64 + items := []Item{ + {"Panacea", 3000, 0.3, 0.025}, + {"Ichor", 1800, 0.2, 0.015}, + {"Gold", 2500, 2.0, 0.002}, + } + var sumCount, sumValue int + var sumWeight, sumVolume float64 - result := Knapsack(items, 0, 25, 0.25) + result := Knapsack(items, 25, 0.25) - for i := range result.Counts { - fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n", - items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]), - items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i]) + for i := range result.Counts { + fmt.Printf("%-8s x%3d -> Weight: %4.1f Volume: %5.3f Value: %6d\n", + items[i].Name, result.Counts[i], items[i].Weight*float64(result.Counts[i]), + items[i].Volume*float64(result.Counts[i]), items[i].Value*result.Counts[i]) - sumCount += result.Counts[i] - sumValue += items[i].Value * result.Counts[i] - sumWeight += items[i].Weight * float64(result.Counts[i]) - sumVolume += items[i].Volume * float64(result.Counts[i]) - } + sumCount += result.Counts[i] + sumValue += items[i].Value * result.Counts[i] + sumWeight += items[i].Weight * float64(result.Counts[i]) + sumVolume += items[i].Volume * float64(result.Counts[i]) + } - fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n", - sumCount, sumWeight, sumVolume, sumValue) + fmt.Printf("TOTAL (%3d items) Weight: %4.1f Volume: %5.3f Value: %6d\n", + sumCount, sumWeight, sumVolume, sumValue) } diff --git a/Task/Knapsack-problem-Unbounded/REXX/knapsack-problem-unbounded.rexx b/Task/Knapsack-problem-Unbounded/REXX/knapsack-problem-unbounded.rexx index 9322ef7350..404d8bf766 100644 --- a/Task/Knapsack-problem-Unbounded/REXX/knapsack-problem-unbounded.rexx +++ b/Task/Knapsack-problem-Unbounded/REXX/knapsack-problem-unbounded.rexx @@ -1,46 +1,45 @@ /*REXX program solves a knapsack/unbounded problem. */ -maxPanacea=0 -maxIchor =0 -maxGold =0 -max$ =0 -current. =0 +maxPanacea = 0 +maxIchor = 0 +maxGold = 0 +max$ = 0 +current. = 0 + /* value weight volume */ + /* ═══════ ═══════ ══════ */ + panacea.$ = 3000 ; panacea.w = 0.3 ; panacea.v = 0.025 + ichor.$ = 1800 ; ichor.w = 0.2 ; ichor.v = 0.015 + gold.$ = 2500 ; gold.w = 2 ; gold.v = 0.002 + sack.$ = 0 ; sack.w = 25 ; sack.v = 0.25 - /* value weight volume */ - /* ═══════ ═══════ ══════ */ -panacea.$= 3000 ; panacea.w= 0.3 ; panacea.v= 0.025 - ichor.$= 1800 ; ichor.w= 0.2 ; ichor.v= 0.015 - gold.$= 2500 ; gold.w= 2 ; gold.v= 0.002 - sack.$= 0 ; sack.w= 25 ; sack.v= 0.25 - -maxPanacea = min(sack.w/panacea.w, sack.v/panacea.v) -maxIchor = min(sack.w/ ichor.w, sack.v/ ichor.v) -maxGold = min(sack.w/ gold.w, sack.v/ gold.v) +maxPanacea = min(sack.w / panacea.w, sack.v / panacea.v) +maxIchor = min(sack.w / ichor.w, sack.v / ichor.v) +maxGold = min(sack.w / gold.w, sack.v / gold.v) do p=0 to maxpanacea do i=0 to maxichor do g=0 to maxgold - current.$=g*gold.$ + i*ichor.$ + p*panacea.$ - current.w=g*gold.w + i*ichor.w + p*panacea.w - current.v=g*gold.v + i*ichor.v + p*panacea.v - if current.w>sack.w | current.v>sack.v then iterate + current.$ = g*gold.$ + i*ichor.$ + p*panacea.$ + current.w = g*gold.w + i*ichor.w + p*panacea.w + current.v = g*gold.v + i*ichor.v + p*panacea.v + if current.w>sack.w | current.v>sack.v then iterate if current.$>max$ then do max$ = current.$ totalW = current.w totalV = current.v - maxP=p; maxI=i; maxG=g + maxP = p; maxI = i; maxG = g end end /*g (gold) */ end /*i (ichor) */ end /*p (panacea)*/ -cTot=maxP+maxI+maxG -L=length(cTot)+1 -say ' panacea in sack:' right(maxP,L) -say ' ichors in sack:' right(maxI,L) -say ' gold items in sack:' right(maxG,L) -say '════════════════════' copies('═',L) -say 'carrying a total of:' right(cTot,L) -say left('',40) 'total value: ' max$/1 -say left('',40) 'total weight: ' totalW/1 -say left('',40) 'total volume: ' totalV/1 +cTot = maxP + maxI + maxG + L = length(cTot) + 1 +say ' panacea in sack:' right(maxP,L) +say ' ichors in sack:' right(maxI,L) +say ' gold items in sack:' right(maxG,L) +say '════════════════════' copies('═',L) +say 'carrying a total of:' right(cTot,L) + say left('',40) 'total value: ' max$/1 + say left('',40) 'total weight: ' totalW/1 + say left('',40) 'total volume: ' totalV/1 /*stick a fork in it, we're done.*/ diff --git a/Task/Knapsack-problem-Unbounded/Ruby/knapsack-problem-unbounded.rb b/Task/Knapsack-problem-Unbounded/Ruby/knapsack-problem-unbounded.rb index 2e7e539916..6e417ec47f 100644 --- a/Task/Knapsack-problem-Unbounded/Ruby/knapsack-problem-unbounded.rb +++ b/Task/Knapsack-problem-Unbounded/Ruby/knapsack-problem-unbounded.rb @@ -15,8 +15,8 @@ solutions = [] 0.upto(max_items[ichor]) do |i| 0.upto(max_items[panacea]) do |p| 0.upto(max_items[gold]) do |g| - next if i*ichor.weight + p*panacea.weight + g*gold.weight > maximum.weight - next if i*ichor.volume + p*panacea.volume + g*gold.volume > maximum.volume + break if i*ichor.weight + p*panacea.weight + g*gold.weight > maximum.weight + break if i*ichor.volume + p*panacea.volume + g*gold.volume > maximum.volume val = i*ichor.value + p*panacea.value + g*gold.value if val > maxval maxval = val diff --git a/Task/Knapsack-problem-Unbounded/Visual-Basic/knapsack-problem-unbounded.vb b/Task/Knapsack-problem-Unbounded/Visual-Basic/knapsack-problem-unbounded.vb new file mode 100644 index 0000000000..9dd1183db4 --- /dev/null +++ b/Task/Knapsack-problem-Unbounded/Visual-Basic/knapsack-problem-unbounded.vb @@ -0,0 +1,25 @@ +Function Min(E1, E2): Min = IIf(E1 < E2, E1, E2): End Function 'small Helper-Function + +Sub Main() +Const Value = 0, Weight = 1, Volume = 2, PC = 3, IC = 4, GC = 5 +Dim P&, I&, G&, A&, M, Cur(Value To Volume) +Dim S As New Collection: S.Add Array(0) '<- init Solutions-Coll. + +Const SackW = 25, SackV = 0.25 +Dim Panacea: Panacea = Array(3000, 0.3, 0.025) +Dim Ichor: Ichor = Array(1800, 0.2, 0.015) +Dim Gold: Gold = Array(2500, 2, 0.002) + + For P = 0 To Int(Min(SackW / Panacea(Weight), SackV / Panacea(Volume))) + For I = 0 To Int(Min(SackW / Ichor(Weight), SackV / Ichor(Volume))) + For G = 0 To Int(Min(SackW / Gold(Weight), SackV / Gold(Volume))) + For A = Value To Volume: Cur(A) = G * Gold(A) + I * Ichor(A) + P * Panacea(A): Next + If Cur(Value) >= S(1)(Value) And Cur(Weight) <= SackW And Cur(Volume) <= SackV Then _ + S.Add Array(Cur(Value), Cur(Weight), Cur(Volume), P, I, G), , 1 + Next G, I, P + + Debug.Print "Value", "Weight", "Volume", "PanaceaCount", "IchorCount", "GoldCount" + For Each M In S '<- enumerate the Attributes of the Maxima + If M(Value) = S(1)(Value) Then Debug.Print M(Value), M(Weight), M(Volume), M(PC), M(IC), M(GC) + Next +End Sub diff --git a/Task/Knights-tour/00DESCRIPTION b/Task/Knights-tour/00DESCRIPTION index 99dbd26420..37366728b8 100644 --- a/Task/Knights-tour/00DESCRIPTION +++ b/Task/Knights-tour/00DESCRIPTION @@ -8,3 +8,7 @@ Output: move sequence ;Cf. * [[N-queens problem]] +* [[Solve a Hidato puzzle]] +* [[Solve a Holy Knight's tour]] +* [[Solve a Numbrix puzzle]] +* [[Solve a Hopido puzzle]] diff --git a/Task/Knights-tour/ALGOL-68/knights-tour.alg b/Task/Knights-tour/ALGOL-68/knights-tour.alg new file mode 100644 index 0000000000..75a2a1d859 --- /dev/null +++ b/Task/Knights-tour/ALGOL-68/knights-tour.alg @@ -0,0 +1,288 @@ +# Non-recursive Knight's Tour with Warnsdorff's algorithm # +# If there are multiple choices, backtrack if the first choice doesn't # +# find a solution # + +# the size of the board # +INT board size = 8; + + +# directions for moves # +INT nne = 1, nee = 2, see = 3, sse = 4, ssw = 5, sww = 6, nww = 7, nnw = 8; + +INT lowest move = nne; +INT highest move = nnw; + +# the vertical position changes of the moves # +# nne, nee, see, sse, ssw, sww, nww, nnw # +[]INT offset v = ( -2, -1, 1, 2, 2, 1, -1, -2 ); +# the horizontal position changes of the moves # +# nne, nee, see, sse, ssw, sww, nww, nnw # +[]INT offset h = ( 1, 2, 2, 1, -1, -2, -2, -1 ); + + +MODE SQUARE = STRUCT( INT move # the number of the move that caused # + # the knight to reach this square # + , INT direction # the direction of the move that # + # brought the knight here - one of # + # nne, nee, see, sse, ssw, sww, nww # + # or nnw - used for backtracking # + # zero for the first move # + ); + +# the board # +[ board size, board size ]SQUARE board; + +# initialises the board so there are no used squares # +PROC initialise board = VOID: + FOR row FROM 1 LWB board TO 1 UPB board + DO + FOR col FROM 2 LWB board TO 2 UPB board + DO + board[ row, col ] := ( 0, 0 ) + OD + OD; # initialise board # + + +INT iterations := 0; +INT backtracks := 0; + +# prints the board # +PROC print tour = VOID: +BEGIN + + print( ( " a b c d e f g h", newline ) ); + print( ( " +--------------------------------", newline ) ); + + FOR row FROM 1 UPB board BY -1 TO 1 LWB board + DO + print( ( whole( row, -3 ) ) ); + print( ( "|" ) ); + + FOR col FROM 2 LWB board TO 2 UPB board + DO + print( ( " " ) ); + print( ( whole( move OF board[ row, col ], -3 ) ) ) + OD; + print( ( newline ) ) + OD + +END; # print tour # + + +# determines whether a move to the specified row and column is possible # +PROC can move to = ( INT row, INT col )BOOL: + IF row > 1 UPB board + OR row < 1 LWB board + OR col > 2 UPB board + OR col < 2 LWB board + THEN + # the position is not on the board # + FALSE + ELSE + # the move is legal, check the square is unoccupied # + move OF board[ row, col ] = 0 + FI; + + +# used to hold counts of the number of moves that could be made in each # +# direction from the current square # +[ lowest move : highest move ]INT possible move count; + + +# sets the elements of possible move count to the number of moves that # +# could be made in each direction from the specified row and col # +PROC count moves in each direction from = ( INT row, INT col )VOID: + FOR move direction FROM lowest move TO highest move + DO + + INT new row = row + offset v[ move direction ]; + INT new col = col + offset h[ move direction ]; + + IF NOT can move to( new row, new col ) + THEN + # can't move to this square # + possible move count[ move direction ] := -1 + ELSE + # a move in this direction is possible # + # - count the number of moves that could be made from it # + + possible move count[ move direction ] := 0; + + FOR subsequent move FROM lowest move TO highest move + DO + IF can move to( new row + offset v[ subsequent move ] + , new col + offset h[ subsequent move ] + ) + THEN + # have a possible subsequent move # + possible move count[ move direction ] +:= 1 + FI + OD + FI + + OD; + + + +# update the board to the first knight's tour found starting from # +# "start row" and "start col". # +# return TRUE if one was found, FALSE otherwise # +PROC find tour = ( INT start row, INT start col )BOOL: +BEGIN + + initialise board; + + BOOL result := TRUE; + + INT move number := 1; + INT row := start row; + INT col := start col; + + # the tour will be complete when we have made as many moves # + # as there squares on the board # + INT final move = ( ( ( 1 UPB board ) + 1 ) - 1 LWB board ) + * ( ( ( 2 UPB board ) + 1 ) - 2 LWB board ) + ; + + # the first move is to place the knight on the starting square # + board[ row, col ] := ( move number, lowest move - 1 ); + # start off with an unknown direction for the best move # + INT best direction := lowest move - 1; + + # attempt to find a sequence of moves that will reach each square once # + WHILE + move number < final move AND result + DO + + iterations +:= 1; + + # count the number of moves possible from each possible move # + # from this square # + count moves in each direction from( row, col ); + + # find the direction with the lowest number of subsequent moves # + + IF best direction < lowest move + THEN + # must find the best direction to move in # + + INT lowest move count := highest move + 1; + + FOR move direction FROM lowest move TO highest move + DO + IF possible move count[ move direction ] >= 0 + AND possible move count[ move direction ] < lowest move count + THEN + # have a move with fewer possible subsequent moves # + best direction := move direction; + lowest move count := possible move count[ move direction ] + FI + OD + + ELSE + # following a backtrack - find an alternative with the same # + # lowest number of possible moves - if there are any # + # if there aren't, we will backtrack again # + + INT lowest move count := possible move count[ best direction ]; + + WHILE + best direction +:= 1; + IF best direction > highest move + THEN + # no more possible moves with the lowest number of # + # subsequent moves # + FALSE + ELSE + # keep looking if the number of moves from this square # + # isn't the lowest # + possible move count[ best direction ] /= lowest move count + FI + DO + SKIP + OD + + FI; + + IF best direction <= highest move + AND best direction >= lowest move + THEN + # we found a best possible move # + + INT new row = row + offset v[ best direction ]; + INT new col = col + offset h[ best direction ]; + + row := new row; + col := new col; + move number +:= 1; + board[ row, col ] := ( move number, best direction ); + + best direction := lowest move - 1 + + ELSE + # no more moves from this position - backtrack # + + IF move number = 1 + THEN + # at the starting position - no solution # + result := FALSE + + ELSE + # not at the starting position - undo the latest move # + + backtracks +:= 1; + + move number -:= 1; + + INT curr row := row; + INT curr col := col; + + best direction := direction OF board[ curr row, curr col ]; + + row -:= offset v[ best direction ]; + col -:= offset h[ best direction ]; + + # reset the square we just backtracked from # + board[ curr row, curr col ] := ( 0, 0 ) + + FI + + FI + + OD; + + result +END; # find tour # + + +main:( + + # get the starting position # + + CHAR row; + CHAR col; + + WHILE + print( ( "Enter starting row(1-8) and col(a-h): " ) ); + read ( ( row, col, newline ) ); + row < "1" OR row > "8" OR col < "a" OR col > "h" + DO + SKIP + OD; + + # calculate the tour from that position, if possible # + + IF find tour( ABS row - ABS "0", ( ABS col - ABS "a" ) + 1 ) + THEN + # found a solution # + print tour + ELSE + # couldn't find a solution # + print( ( "Solution not found - iterations: ", iterations + , ", backtracks: ", backtracks + , newline + ) + ) + FI + +) diff --git a/Task/Knights-tour/AWK/knights-tour.awk b/Task/Knights-tour/AWK/knights-tour.awk new file mode 100644 index 0000000000..fb496d2629 --- /dev/null +++ b/Task/Knights-tour/AWK/knights-tour.awk @@ -0,0 +1,68 @@ +# syntax: GAWK -f KNIGHTS_TOUR.AWK [-v sr=x] [-v sc=x] +# +# examples: +# GAWK -f KNIGHTS_TOUR.AWK (default) +# GAWK -f KNIGHTS_TOUR.AWK -v sr=1 -v sc=1 start at top left (default) +# GAWK -f KNIGHTS_TOUR.AWK -v sr=1 -v sc=8 start at top right +# GAWK -f KNIGHTS_TOUR.AWK -v sr=8 -v sc=8 start at bottom right +# GAWK -f KNIGHTS_TOUR.AWK -v sr=8 -v sc=1 start at bottom left +# +BEGIN { + N = 8 # board size + if (sr == "") { sr = 1 } # starting row + if (sc == "") { sc = 1 } # starting column + split("2 2 -2 -2 1 1 -1 -1",X," ") + split("1 -1 1 -1 2 -2 2 -2",Y," ") + printf("\n%dx%d board: starting row=%d col=%d\n",N,N,sr,sc) + move(sr,sc,0) + exit(1) +} +function move(x,y,m) { + if (cantMove(x,y)) { + return(0) + } + P[x,y] = ++m + if (m == N ^ 2) { + printBoard() + exit(0) + } + tryBestMove(x,y,m) +} +function cantMove(x,y) { + return( P[x,y] || x<1 || x>N || y<1 || y>N ) +} +function tryBestMove(x,y,m, i) { + i = bestMove(x,y) + move(x+X[i],y+Y[i],m) +} +function bestMove(x,y, arg1,arg2,c,i,min,out) { +# Warnsdorff's rule: go to where there are fewest next moves + min = N ^ 2 + 1 + for (i in X) { + arg1 = x + X[i] + arg2 = y + Y[i] + if (!cantMove(arg1,arg2)) { + c = countNext(arg1,arg2) + if (c < min) { + min = c + out = i + } + } + } + return(out) +} +function countNext(x,y, i,out) { + for (i in X) { + out += (!cantMove(x+X[i],y+Y[i])) + } + return(out) +} +function printBoard( i,j,leng) { + leng = length(N*N) + for (i=1; i<=N; i++) { + for (j=1; j<=N; j++) { + printf(" %*d",leng,P[i,j]) + } + printf("\n") + } +} diff --git a/Task/Knights-tour/Ada/knights-tour-1.ada b/Task/Knights-tour/Ada/knights-tour-1.ada index 170aa71bf4..b69f784e73 100644 --- a/Task/Knights-tour/Ada/knights-tour-1.ada +++ b/Task/Knights-tour/Ada/knights-tour-1.ada @@ -4,13 +4,19 @@ package Knights_Tour is subtype Index is Integer range 1 .. Size; type Tour is array (Index, Index) of Natural; + Empty: Tour := (others => (others => 0)); - function Get_Tour(Start_X, Start_Y: Index) return Tour; + function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) return Tour; -- finds tour via backtracking - -- either no tour has been found, (Get_Tour(X, Y)=0 for all X, Y in Index) + -- either no tour has been found, i.e., Get_Tour returns Scene -- or the Result(X,Y)=K if and only if I,J is visited at the K-th move + -- for all X, Y, Scene(X,Y) must be either 0 or Natural'Last, + -- where Scene(X,Y)=Natural'Last means "don't visit coordiates (X,Y)!" - procedure Tour_IO(The_Tour: Tour); + function Count_Moves(Board: Tour) return Natural; + -- counts the number of possible moves, i.e., the number of 0's on the board + + procedure Tour_IO(The_Tour: Tour; Width: Natural := 4); -- writes The_Tour to the output using Ada.Text_IO; end Knights_Tour; diff --git a/Task/Knights-tour/Ada/knights-tour-2.ada b/Task/Knights-tour/Ada/knights-tour-2.ada index d0abe752ca..48f65cbf53 100644 --- a/Task/Knights-tour/Ada/knights-tour-2.ada +++ b/Task/Knights-tour/Ada/knights-tour-2.ada @@ -2,25 +2,43 @@ with Ada.Text_IO, Ada.Integer_Text_IO; package body Knights_Tour is - Visited: Tour; - -- Visited(I, J)=0: Not yet visited - -- Visited(I, J)=K: Visited during the k-th move type Pair is array(1..2) of Integer; type Pair_Array is array (Positive range <>) of Pair; Pairs: constant Pair_Array (1..8) := ((-2,1),(-1,2),(1,2),(2,1),(2,-1),(1,-2),(-1,-2),(-2,-1)); - -- possible places to visit if Done + -- places for the night to go (relative to the current position) - function Get_Tour(Start_X, Start_Y: Index) return Tour is + function Count_Moves(Board: Tour) return Natural is + N: Natural := 0; + begin + for I in Index loop + for J in Index loop + if Board(I,J) < Natural'Last then + N := N + 1; + end if; + end loop; + end loop; + return N; + end Count_Moves; + + function Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) + return Tour is + Done: Boolean; + Move_Count: Natural := Count_Moves(Scene); + Visited: Tour; + + -- Visited(I, J) = 0: not yet visited + -- Visited(I, J) = K: visited at the k-th move + -- Visited(I, J) = Integer'Last: never visit procedure Visit(X, Y: Index; Move_Number: Positive; Found: out Boolean) is XX, YY: Integer; begin Found := False; Visited(X, Y) := Move_Number; - if Move_Number = Integer(Index'Last * Index'Last) then + if Move_Number = Move_Count then Found := True; else for P in Pairs'Range loop @@ -38,28 +56,30 @@ package body Knights_Tour is end if; end Visit; - Done: Boolean; begin - Visited := (others => (others => 0)); + Visited := Scene; Visit(Start_X, Start_Y, 1, Done); if not Done then - Visited := (others => (others => 0)); + Visited := Scene; end if; return Visited; end Get_Tour; - procedure Tour_IO(The_Tour: Tour) is + procedure Tour_IO(The_Tour: Tour; Width: Natural := 4) is begin - if The_Tour(1, 1) /= 0 then for I in Index loop for J in Index loop - Ada.Integer_Text_IO.Put(The_Tour(I, J), 4); + if The_Tour(I, J) < Integer'Last then + Ada.Integer_Text_IO.Put(The_Tour(I, J), Width); + else + for W in 1 .. Width-1 loop + Ada.Text_IO.Put(" "); + end loop; + Ada.Text_IO.Put("-"); -- deliberately not visited + end if; end loop; Ada.Text_IO.New_Line; end loop; - else - Ada.Text_IO.Put_Line("No Solution"); - end if; end Tour_IO; end Knights_Tour; diff --git a/Task/Knights-tour/Ada/knights-tour-4.ada b/Task/Knights-tour/Ada/knights-tour-4.ada index 1d22e0f86c..0edfffbf72 100644 --- a/Task/Knights-tour/Ada/knights-tour-4.ada +++ b/Task/Knights-tour/Ada/knights-tour-4.ada @@ -1,3 +1,4 @@ - function Warnsdorff_Get_Tour(Start_X, Start_Y: Index) return Tour; + function Warnsdorff_Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) + return Tour; -- uses Warnsdorff heurisitic to find a tour faster -- same interface as Get_Tour diff --git a/Task/Knights-tour/Ada/knights-tour-5.ada b/Task/Knights-tour/Ada/knights-tour-5.ada index a95083b07c..0727140245 100644 --- a/Task/Knights-tour/Ada/knights-tour-5.ada +++ b/Task/Knights-tour/Ada/knights-tour-5.ada @@ -1,5 +1,8 @@ - function Warnsdorff_Get_Tour(Start_X, Start_Y: Index) return Tour is + function Warnsdorff_Get_Tour(Start_X, Start_Y: Index; Scene: Tour := Empty) + return Tour is Done: Boolean; + Visited: Tour; -- see comments from Get_Tour above + Move_Count: Natural := Count_Moves(Scene); function Neighbors(X, Y: Index) return Natural is Result: Natural := 0; @@ -45,7 +48,7 @@ begin Found := False; Visited(X, Y) := Move; - if Move = Integer(Index'Last * Index'Last) then + if Move = Move_Count then Found := True; else -- consider all possible places to go @@ -74,10 +77,10 @@ end Visit; begin - Visited := (others => (others => 0)); + Visited := Scene; Visit(Start_X, Start_Y, 1, Done); if not Done then - Visited := (others => (others => 0)); + Visited := Scene; end if; return Visited; end Warnsdorff_Get_Tour; diff --git a/Task/Knights-tour/D/knights-tour.d b/Task/Knights-tour/D/knights-tour-1.d similarity index 100% rename from Task/Knights-tour/D/knights-tour.d rename to Task/Knights-tour/D/knights-tour-1.d diff --git a/Task/Knights-tour/D/knights-tour-2.d b/Task/Knights-tour/D/knights-tour-2.d new file mode 100644 index 0000000000..e3d5fdfd8c --- /dev/null +++ b/Task/Knights-tour/D/knights-tour-2.d @@ -0,0 +1,27 @@ +import std.stdio, std.math, std.algorithm, std.range, std.typecons; + +alias Square = Tuple!(int,"x", int,"y"); + +const(Square)[] knightTour(in Square[] board, in Square[] moves) pure @safe nothrow { + enum findMoves = (in Square sq) pure nothrow @safe => + cartesianProduct([1, -1, 2, -2], [1, -1, 2, -2]) + .filter!(ij => ij[0].abs != ij[1].abs) + .map!(ij => Square(sq.x + ij[0], sq.y + ij[1])) + .filter!(s => board.canFind(s) && !moves.canFind(s)); + auto newMoves = findMoves(moves.back); + if (newMoves.empty) + return moves; + //alias warnsdorff = min!(s => findMoves(s).walkLength); + //immutable newSq = newMoves.dropOne.fold!warnsdorff(newMoves.front); + auto pairs = newMoves.map!(s => tuple(findMoves(s).walkLength, s)); + immutable newSq = reduce!min(pairs.front, pairs.dropOne)[1]; + return board.knightTour(moves ~ newSq); +} + +void main(in string[] args) { + enum toSq = (in string xy) => Square(xy[0] - '`', xy[1] - '0'); + immutable toAlg = (in Square s) => [dchar(s.x + '`'), dchar(s.y + '0')]; + immutable sq = toSq((args.length == 2) ? args[1] : "e5"); + const board = iota(1, 9).cartesianProduct(iota(1, 9)).map!Square.array; + writefln("%(%-(%s -> %)\n%)", board.knightTour([sq]).map!toAlg.chunks(8)); +} diff --git a/Task/Knights-tour/Prolog/knights-tour.pro b/Task/Knights-tour/Prolog/knights-tour-1.pro similarity index 100% rename from Task/Knights-tour/Prolog/knights-tour.pro rename to Task/Knights-tour/Prolog/knights-tour-1.pro diff --git a/Task/Knights-tour/Prolog/knights-tour-2.pro b/Task/Knights-tour/Prolog/knights-tour-2.pro new file mode 100644 index 0000000000..7ca58d132b --- /dev/null +++ b/Task/Knights-tour/Prolog/knights-tour-2.pro @@ -0,0 +1,57 @@ +:- initialization(main). + + +board_size(8). +in_board(X*Y) :- board_size(N), between(1,N,Y), between(1,N,X). + + +% express jump-graph in dynamic "move"-rules +make_graph :- + findall(_, (in_board(P), assert_moves(P)), _). + + % where + assert_moves(P) :- + findall(_, (can_move(P,Q), asserta(move(P,Q))), _). + + can_move(X*Y,Q) :- + ( one(X,X1), two(Y,Y1) ; two(X,X1), one(Y,Y1) ) + , Q = X1*Y1, in_board(Q) + . % where + one(M,N) :- succ(M,N) ; succ(N,M). + two(M,N) :- N is M + 2 ; N is M - 2. + + + +hamiltonian(P,Pn) :- + board_size(N), Size is N * N + , hamiltonian(P,Size,[],Ps), enumerate(Size,Ps,Pn) + . + % where + enumerate(_, [] , [] ). + enumerate(N, [P|Ps], [N:P|Pn]) :- succ(M,N), enumerate(M,Ps,Pn). + + +hamiltonian(P,N,Ps,Res) :- + N =:= 1 -> Res = [P|Ps] + ; warnsdorff(Ps,P,Q), succ(M,N) + , hamiltonian(Q,M,[P|Ps],Res) + . + % where + warnsdorff(Ps,P,Q) :- + moves(Ps,P,Qs), maplist(next_moves(Ps), Qs, Xs) + , keysort(Xs,Ys), member(_-Q,Ys) + . + next_moves(Ps,Q,L-Q) :- moves(Ps,Q,Rs), length(Rs,L). + + moves(Ps,P,Qs) :- + findall(Q, (move(P,Q), \+ member(Q,Ps)), Qs). + + + +show_path(Pn) :- findall(_, (in_board(P), show_cell(Pn,P)), _). + % where + show_cell(Pn,X*Y) :- + member(N:X*Y,Pn), format('%3.0d',[N]), board_size(X), nl. + + +main :- make_graph, hamiltonian(5*3,Pn), show_path(Pn), halt. diff --git a/Task/Knights-tour/REXX/knights-tour.rexx b/Task/Knights-tour/REXX/knights-tour.rexx index e1612986e0..ca075c4d00 100644 --- a/Task/Knights-tour/REXX/knights-tour.rexx +++ b/Task/Knights-tour/REXX/knights-tour.rexx @@ -1,33 +1,36 @@ -/*REXX pgm to solve the knight's tour problem for a NxN chessboard. */ -parse arg N .; if N=='' | N==',' then N=8 /*user can specify board size.*/ -NoNo= "No knight's tour solution for" NxN'.'; @.= - /*define the outside of the board*/ -NN=N**2; NxN='a ' N"x"N ' chessboard' /* [↓] R=rank, F=file. */ - do r=1 for N; do f=1 for N; @.r.f=0; end /*f*/; end /*r*/ - /*[↑] zero out the NxN chessboard*/ +/*REXX program solves the knight's tour problem for a NxN chessboard.*/ +parse arg N sRank sFile . /*boardsize, starting position. */ +if N=='' | N==',' then N=8 /*Boardsize specified? Default. */ +if sRank=='' then sRank=N /*starting rank given? Default. */ +if sFile=='' then sFile=1 /* " file " " */ +!=left('', 9*(n<18)) /*used for indentation of board. */ +NN=N**2; NxN='a ' N"x"N ' chessboard' /* [↓] r=Rank, f=File.*/ +@.=; do r=1 for N; do f=1 for N; @.r.f=' '; end /*f*/; end /*r*/ + /*[↑] zero the NxN chessboard.*/ Kr = '2 1 -1 -2 -2 -1 1 2' /*legal "rank" move for a knight.*/ Kf = '1 2 2 1 -1 -2 -2 -1' /* " "file" " " " " */ - do i=1 for 8 /*legal knight moves*/ - Kr.i = word(Kr,i); Kf.i = word(Kf,i) - end /*i*/ /*for fast indexing.*/ -@.1.1 = 1 /*the knight's starting position.*/ -if \(N==1) & \move(2,1,1) then do; say NoNo; exit; end -say "A solution for the knight's tour on" NxN':';!=left('',9*(n<18)) + do i=1 for words(Kr) /*legal knight moves*/ + Kr.i = word(Kr,i); Kf.i = word(Kf,i) + end /*i*/ /*for fast indexing.*/ +@.sRank.sFile=1 /*the knight's starting position.*/ +if \move(2,sRank,sFile) & , + \(N==1) then say "No knight's tour solution for" NxN'.' + else say "A solution for the knight's tour on" NxN':' _=substr(copies("┼───",N),2); say; say ! translate('┌'_"┐", '┬', "┼") do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@. do f=1 for N; L=L'│'centre(@.r.f,3) /*preserve squareness.*/ - end /*f*/ - say ! L'│' /*show a rank of the chessboard. */ + end /*f*/ /*done with a rank on chessboard.*/ + say ! L'│' /*show a rank of the chessboard.*/ end /*r*/ /*80 cols can view 19x19 chessbrd*/ -say ! translate('└'_"┘", '┴', "┼") /*show the last rank of the board*/ +say ! translate('└'_"┘", '┴', "┼") /*show the last rank of the board*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────MOVE subroutine─────────────────────*/ -move: procedure expose @. Kr. Kf. N NN; parse arg #,rank,file - do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t - if @.nr.nf==0 then do; @.nr.nf=# /*Kn move*/ - if #==NN then return 1 /*last 1?*/ - if move(#+1,nr,nf) then return 1 - @.nr.nf=0 /*undo the above move. */ - end - end /*t*/ -return 0 +move: procedure expose @. Kr. Kf. N NN; parse arg #,rank,file; b=' ' + do t=1 for 8; nr=rank+Kr.t; nf=file+Kf.t + if @.nr.nf==b then do; @.nr.nf=# /*Kn move.*/ + if #==NN then return 1 /*last mv?*/ + if move(#+1,nr,nf) then return 1 /* " " */ + @.nr.nf=b /*undo the above move. */ + end /*try different move. */ + end /*t*/ /* [↑] all moves tried.*/ +return 0 /*the tour not possible.*/ diff --git a/Task/Knights-tour/Ruby/knights-tour.rb b/Task/Knights-tour/Ruby/knights-tour.rb index 846b3a9880..9107fe425a 100644 --- a/Task/Knights-tour/Ruby/knights-tour.rb +++ b/Task/Knights-tour/Ruby/knights-tour.rb @@ -1,54 +1,72 @@ -# Solve a Knight's Tour -# -# Nigel_Galloway -# May 6th., 2012. +class Board + Cell = Struct.new(:value, :adj) do + def self.end=(end_val) + @@end = end_val + end -class Cell - Adjust = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]] - def initialize(row=0, col=0, value=nil) - @adj = Adjust.map{|r,c| [row+r,col+c]} - @t = false - $zbl[value] = false unless value.nil? - @value = value - end - def try(value=1) - return true if value > $e - return false if @t - return false if @value > 0 and @value != value - return false if @value == 0 and not $zbl[value] - @t = true - h = Hash.new - @adj.each_with_index{|(row, col), n| - cell = $board[row][col] - h[cell.wdof*100+n] = cell if cell.value - } - h.sort.each{|key,cell| - if cell.try(value+1) - @value = value - return true + def try(seq_num) + self.value = seq_num + return true if seq_num==@@end + a = [] + adj.each_with_index do |cell, n| + a << [wdof(cell.adj)*10+n, cell] if cell.value.zero? end - } - @t = false - end - def wdon - (@value.nil? or @value > 0 or @t) ? 0 : 1 - end - def wdof - @adj.inject(0){|res, (row, col)| res += $board[row][col].wdon} - end - attr_reader :value -end + a.sort.each {|_, cell| return true if cell.try(seq_num+1)} + self.value = 0 + false + end -def knight_tour(rows, cols, x, y) - $e = rows * cols - $zbl = Array.new($e+1,true) - $board = Array.new(rows+2) do |i| - Array.new(cols+2) do |j| - (i= x (* X Y))))) rules))) + (if (null? possible) + (begin (set! forbiddened (cons (car dictionary) forbiddened)) + (set! dictionary (cdr dictionary)) + (set! counter (- counter 1)) + (car dictionary)) + (begin (set! dictionary (cons (car possible) dictionary)) + (set! forbiddened dictionary) + (set! counter (+ counter 1)) + (car possible)))) +;;go to search +(define (go position) + (if (= counter (* X Y)) + (begin + (set! result (reverse dictionary)) + (display (map (lambda(x) (decode x)) result))) + (go (renew position)))) diff --git a/Task/Knuth-shuffle/00DESCRIPTION b/Task/Knuth-shuffle/00DESCRIPTION index 144434b6e7..8132214a94 100644 --- a/Task/Knuth-shuffle/00DESCRIPTION +++ b/Task/Knuth-shuffle/00DESCRIPTION @@ -1 +1,2 @@ -Implement the [[wp:Knuth shuffle|Knuth shuffle]] (a.k.a. the Fisher-Yates shuffle) for an integer array (or, if possible, an array of any type). The Knuth shuffle is used to create a random permutation of an array. +Implement the [[wp:Knuth shuffle|Knuth shuffle]] (a.k.a. the Fisher-Yates shuffle) for an integer array (or, if possible, an array of any type). +The Knuth shuffle is used to create a random permutation of an array. diff --git a/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e b/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e new file mode 100644 index 0000000000..92a77d5a7f --- /dev/null +++ b/Task/Knuth-shuffle/Eiffel/knuth-shuffle.e @@ -0,0 +1,46 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature {NONE} -- Initialization + + make + do + test:= <<1,2,3,4,5,6,7>> + io.put_string ("Initial: ") + across test as t loop io.put_string (t.item.out + " ") end + create testresult.make_empty + testresult:= shuffle (test) + io.put_string ("%NShuffled: ") + across testresult as t loop io.put_string (t.item.out + " ") end + + end + + test: ARRAY[INTEGER] + testresult: ARRAY[INTEGER] + + shuffle(ar:ARRAY[INTEGER]): ARRAY[INTEGER] + local + i,j:INTEGER + ith: INTEGER + random: V_RANDOM + do + create random + from + i:=ar.count + until + i=2 + loop + j:=random.bounded_item (1, i) + ith:= ar[i] + ar[i]:= ar[j] + ar[j]:= ith + random.forth + i:=i-1 + end + Result:= ar + end +end diff --git a/Task/Knuth-shuffle/Frink/knuth-shuffle.frink b/Task/Knuth-shuffle/Frink/knuth-shuffle.frink new file mode 100644 index 0000000000..c3b66680e6 --- /dev/null +++ b/Task/Knuth-shuffle/Frink/knuth-shuffle.frink @@ -0,0 +1,2 @@ +a = [1,2,3] +a.shuffle[] diff --git a/Task/Knuth-shuffle/GAP/knuth-shuffle.gap b/Task/Knuth-shuffle/GAP/knuth-shuffle.gap index a77f99f244..12a0cf443a 100644 --- a/Task/Knuth-shuffle/GAP/knuth-shuffle.gap +++ b/Task/Knuth-shuffle/GAP/knuth-shuffle.gap @@ -1,19 +1,19 @@ # 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; + 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. -PermShuffle := n -> PermListList([1 .. n], Shuffle([1 .. n])); +PermShuffle := n -> PermList(ShuffleAlt([1 .. n])); ShuffleAlt([1 .. 10]); # [ 4, 7, 1, 5, 8, 2, 6, 9, 10, 3 ] diff --git a/Task/Knuth-shuffle/Objective-C/knuth-shuffle.m b/Task/Knuth-shuffle/Objective-C/knuth-shuffle.m new file mode 100644 index 0000000000..5739b32f24 --- /dev/null +++ b/Task/Knuth-shuffle/Objective-C/knuth-shuffle.m @@ -0,0 +1,22 @@ +#import + +@interface NSMutableArray (KnuthShuffle) +- (void)knuthShuffle; +@end +@implementation NSMutableArray (KnuthShuffle) +- (void)knuthShuffle { + for (NSUInteger i = self.count-1; i > 0; i--) { + NSUInteger j = arc4random_uniform(i+1); + [self exchangeObjectAtIndex:i withObjectAtIndex:j]; + } +} +@end + +int main() { + @autoreleasepool { + NSMutableArray *x = [NSMutableArray arrayWithObjects:@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, nil]; + [x knuthShuffle]; + NSLog(@"%@", x); + } + return 0; +} diff --git a/Task/Knuth-shuffle/UNIX-Shell/knuth-shuffle.sh b/Task/Knuth-shuffle/UNIX-Shell/knuth-shuffle.sh index 73a46ce066..228152f2d0 100644 --- a/Task/Knuth-shuffle/UNIX-Shell/knuth-shuffle.sh +++ b/Task/Knuth-shuffle/UNIX-Shell/knuth-shuffle.sh @@ -15,7 +15,6 @@ function shuffle { done } - # Test program. set -A array 11 22 33 44 55 66 77 88 99 110 shuffle diff --git a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d index fba425f48e..838c2edf48 100644 --- a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d +++ b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-1.d @@ -8,7 +8,7 @@ auto sofN_creator(in int n) { i++; if (i <= n) sample ~= item; - else if (uniform(0.0, 1.0) < (double(n) / i)) + else if (uniform01 < (double(n) / i)) sample[uniform(0, n)] = item; return sample; }; 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 3d51ad1787..b37b90c69f 100644 --- a/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d +++ b/Task/Knuths-algorithm-S/D/knuths-algorithm-s-2.d @@ -1,11 +1,5 @@ import std.stdio, std.random, std.algorithm; -double random01(ref Xorshift rng) { - immutable r = rng.front / double(rng.max); - rng.popFront; - return r; -} - struct SOfN(size_t n) { size_t i; int[n] sample = void; @@ -14,7 +8,7 @@ struct SOfN(size_t n) { i++; if (i <= n) sample[i - 1] = item; - else if (rng.random01 < (double(n) / i)) + else if (rng.uniform01 < (double(n) / i)) sample[uniform(0, n, rng)] = item; return sample[0 .. min(i, $)]; } diff --git a/Task/LU-decomposition/00DESCRIPTION b/Task/LU-decomposition/00DESCRIPTION index 5f5dbf8eec..12b5e10f1a 100644 --- a/Task/LU-decomposition/00DESCRIPTION +++ b/Task/LU-decomposition/00DESCRIPTION @@ -1,10 +1,16 @@ -Every square matrix A can be decomposed into a product of a lower triangular matrix L and a upper triangular matrix U, as described in [[wp:LU decomposition|LU decomposition]]. +Every square matrix A can be decomposed into a product of a lower triangular matrix L and a upper triangular matrix U, +as described in [[wp:LU decomposition|LU decomposition]]. :A = LU -It is a modified form of Gaussian elimination. While the [[Cholesky decomposition]] only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix. +It is a modified form of Gaussian elimination. +While the [[Cholesky decomposition]] only works for symmetric, +positive definite matrices, the more general LU decomposition +works for any square matrix. -There are several algorithms for calculating L and U. To derive ''Crout's algorithm'' for a 3x3 example, we have to solve the following system: +There are several algorithms for calculating L and U. +To derive ''Crout's algorithm'' for a 3x3 example, +we have to solve the following system: : A = @@ -88,7 +94,7 @@ and then for L :l_{ij} = \frac{1}{u_{jj}} (a_{ij} - \sum_{k=1}^{j-1} u_{kj}l_{ik}) -We see in the second formula that to get the l_{ij} below the diagonal, we have to divide by the diagonal element (pivot) u_{ij}, so we get problems when u_{ij} is either 0 or very small, which leads to numerical instability. +We see in the second formula that to get the l_{ij} below the diagonal, we have to divide by the diagonal element (pivot) u_{jj}, so we get problems when u_{jj} is either 0 or very small, which leads to numerical instability. The solution to this problem is ''pivoting'' A, which means rearranging the rows of A, prior to the LU decomposition, in a way that the largest element of each column gets onto the diagonal of A. Rearranging the columns means to multiply A by a permutation matrix P: @@ -119,7 +125,9 @@ The decomposition algorithm is then applied on the rearranged matrix so that '''Task description''' -The task is to implement a routine which will take a square nxn matrix A and return a lower triangular matrix L, a upper triangular matrix U and a permutation matrix P, so that the above equation is fullfilled. You should then test it on the following two examples and include your output. +The task is to implement a routine which will take a square nxn matrix A and return a lower triangular matrix L, a upper triangular matrix U and a permutation matrix P, +so that the above equation is fullfilled. +You should then test it on the following two examples and include your output. Example 1:
diff --git a/Task/LU-decomposition/D/lu-decomposition.d b/Task/LU-decomposition/D/lu-decomposition.d
index cc940f59a1..70d564ef8c 100644
--- a/Task/LU-decomposition/D/lu-decomposition.d
+++ b/Task/LU-decomposition/D/lu-decomposition.d
@@ -1,11 +1,11 @@
 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 @nogc {
     return m.all!(r => r.length == m[0].length);
 }
 
-bool isSquare(T)(in T[][] m) pure nothrow {
+bool isSquare(T)(in T[][] m) pure nothrow @nogc {
     return m.isRectangular && m[0].length == m.length;
 }
 
@@ -34,7 +34,7 @@ in {
 } body {
     immutable n = m.length;
     auto id = iota(n)
-              .map!((in j) => n.iota.map!(i => cast(T)(i == j)).array)
+              .map!((in j) => n.iota.map!(i => T(i == j)).array)
               .array;
 
     foreach (immutable i; 0 .. n) {
diff --git a/Task/LU-decomposition/Fortran/lu-decomposition.f b/Task/LU-decomposition/Fortran/lu-decomposition.f
index dce38f85d9..1b5e187d1c 100644
--- a/Task/LU-decomposition/Fortran/lu-decomposition.f
+++ b/Task/LU-decomposition/Fortran/lu-decomposition.f
@@ -1,75 +1,66 @@
 program lu1
-implicit none
-
-real*8     :: a1(3,3), a2(4,4)
-
-a1 = reshape((/real*8::1,2,1,3,4,1,5,7,0/),(/3,3/))
-call check(a1)
-
-a2 = reshape((/real*8::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1/),(/4,4/))
-call check(a2)
+  implicit none
+  call check( reshape([real(8)::1,2,1,3,4,1,5,7,0                  ],[3,3]) )
+  call check( reshape([real(8)::11,1,3,2,9,5,17,5,24,2,18,7,2,6,1,1],[4,4]) )
 
 contains
 
-subroutine lu(a,p)
-! in situ decomposition, correspondes to LAPACK's dgebtrf
-implicit none
-real*8, intent(inout) :: a(:,:)
-integer, intent(out)  :: p(:)
-integer               :: n, i,j,k,ii
-n = ubound(a,1)
-p = (/ ( i, i=1,n ) /)
-do k = 1,n-1
-    ii = k-1+maxloc(abs(a(p(k:),k)),1)
-    if (ii /= k )  then
-        p((/k, ii/)) = p((/ii, k/))
-    end if
-    a(p(k+1:),k) = a(p(k+1:),k)/a(p(k),k)
-    forall (j = k+1:n)
-        a(p(k+1:),j) = a(p(k+1:),j)-a(p(k+1:),k)*a(p(k),j)
+  subroutine check(a)
+    real(8), intent(in)   :: a(:,:)
+    integer               :: i,j,n
+    real(8), allocatable  :: aa(:,:),l(:,:),u(:,:)
+    integer, allocatable  :: p(:,:)
+    integer, allocatable  :: ipiv(:)
+    n = size(a,1)
+    allocate(aa(n,n),l(n,n),u(n,n),p(n,n),ipiv(n))
+    forall (j=1:n,i=1:n)
+      aa(i,j) = a(i,j)
+      u (i,j) = 0d0
+      p (i,j) = merge(1  ,0  ,i.eq.j)
+      l (i,j) = merge(1d0,0d0,i.eq.j)
     end forall
-end do
-end subroutine
+    call lu(aa, ipiv)
+    do i = 1,n
+       l(i, :i-1) = aa(ipiv(i), :i-1)
+       u(i,i:   ) = aa(ipiv(i),i:   )
+    end do
+    p(ipiv,:) = p
+    call mat_print('a',a)
+    call mat_print('p',p)
+    call mat_print('l',l)
+    call mat_print('u',u)
+    print *, "residual"
+    print *, "|| P.A - L.U || =  ", maxval(abs(matmul(p,a)-matmul(l,u)))
+  end subroutine
 
-subroutine check(a)
-implicit none
-real*8, intent(in) :: a(:,:)
-real*8             :: aa(ubound(a,1), ubound(a,2))
-real*8             :: l(ubound(a,1), ubound(a,2))
-real*8             :: u(ubound(a,1), ubound(a,2))
-integer            :: p(ubound(a,1), ubound(a,2)), ipiv(ubound(a,1))
-integer            :: i,  n
-character(len=100) :: fmt
+  subroutine lu(a,p)
+!   in situ decomposition, corresponds to LAPACK's dgebtrf
+    real(8), intent(inout) :: a(:,:)
+    integer, intent(out  ) :: p(:)
+    integer                :: n, i,j,k,kmax
+    n = size(a,1)
+    p = [ ( i, i=1,n ) ]
+    do k = 1,n-1
+        kmax = maxloc(abs(a(p(k:),k)),1) + k-1
+        if (kmax /= k ) p([k, kmax]) = p([kmax, k])
+        a(p(k+1:),k) = a(p(k+1:),k) / a(p(k),k)
+        forall (j=k+1:n) a(p(k+1:),j) = a(p(k+1:),j) - a(p(k+1:),k) * a(p(k),j)
+    end do
+  end subroutine
 
-n = ubound(a,1)
-aa = a ! work with a copy
-p = 0; l=0; u = 0
-forall (i=1:n)
-    p(i,i) = 1d0; l(i,i) = 1d0 ! convert permutation vector a matrix
-end forall
+  subroutine mat_print(amsg,a)
+    character(*), intent(in) :: amsg
+    class    (*), intent(in) :: a(:,:)
+    integer                  :: i
+    print*,' '
+    print*,amsg
+    do i=1,size(a,1)
+      select type (a)
+        type is (real(8)) ; print'(100f8.2)',a(i,:)
+        type is (integer) ; print'(100i8  )',a(i,:)
+      end select
+    end do
+    print*,' '
+  end subroutine
 
-call lu(aa, ipiv)
-do i = 1,n
-   l(i,:i-1) = aa(ipiv(i),:i-1)
-   u(i,i:) = aa(ipiv(i),i:)
-end do
-p(ipiv,:) = p
-write (fmt,"(a,i1,a)") "(",n,"(f8.2,1x))"
-
-print *, "a"
-print fmt, transpose(a)
-
-print *, "p"
-print fmt, transpose(dble(p))
-
-print *, "l"
-print fmt, transpose(l)
-
-print *, "u"
-print fmt, transpose(u)
-
-print *, "residual"
-print *, "|| P.A - L.U || =  ", maxval(abs(matmul(p,a)-matmul(l,u)))
-
-end subroutine
-end program>
+end program
diff --git a/Task/LU-decomposition/Ruby/lu-decomposition.rb b/Task/LU-decomposition/Ruby/lu-decomposition-1.rb
similarity index 62%
rename from Task/LU-decomposition/Ruby/lu-decomposition.rb
rename to Task/LU-decomposition/Ruby/lu-decomposition-1.rb
index e67cc3a00f..a55d9d90f1 100644
--- a/Task/LU-decomposition/Ruby/lu-decomposition.rb
+++ b/Task/LU-decomposition/Ruby/lu-decomposition-1.rb
@@ -10,10 +10,10 @@ class Matrix
       (0 ... row_size).each do |j|
         if j >= i
           # upper
-          u[i][j] = tmp[i,j] - (0 .. i-1).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}
+          u[i][j] = tmp[i,j] - (0 ... i).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}
         else
           # lower
-          l[i][j] = (tmp[i,j] - (0 .. j-1).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j]
+          l[i][j] = (tmp[i,j] - (0 ... j).inject(0.0) {|sum, k| sum + u[k][j] * l[i][k]}) / u[j][j]
         end
       end
     end
@@ -37,29 +37,29 @@ class Matrix
     Matrix[*id]
   end
 
-  def pretty_print(format)
-    each_with_index do |val, i, j|
-      print "#{format} " % val
-      puts "" if j==column_size-1
-    end
+  def pretty_print(format, head=nil)
+    puts head if head
+    puts each_slice(column_size).map{|row| format*row_size % row}
   end
 end
 
+puts "Example 1:"
 a = Matrix[[1,  3,  5],
            [2,  4,  7],
            [1,  1,  0]]
-puts "A"; a.pretty_print("%2d")
+a.pretty_print(" %2d", "A")
 l, u, p = a.lu_decomposition
-puts "U"; u.pretty_print("%8.5f")
-puts "L"; l.pretty_print("%8.5f")
-puts "P"; p.pretty_print("%d")
+l.pretty_print(" %8.5f", "L")
+u.pretty_print(" %8.5f", "U")
+p.pretty_print(" %d",    "P")
 
+puts "\nExample 2:"
 a = Matrix[[11, 9,24,2],
            [ 1, 5, 2,6],
            [ 3,17,18,1],
            [ 2, 5, 7,1]]
-puts "A"; a.pretty_print("%2d")
+a.pretty_print(" %2d", "A")
 l, u, p = a.lu_decomposition
-puts "U"; u.pretty_print("%8.5f")
-puts "L"; l.pretty_print("%8.5f")
-puts "P"; p.pretty_print("%d")
+l.pretty_print(" %8.5f", "L")
+u.pretty_print(" %8.5f", "U")
+p.pretty_print(" %d",    "P")
diff --git a/Task/LU-decomposition/Ruby/lu-decomposition-2.rb b/Task/LU-decomposition/Ruby/lu-decomposition-2.rb
new file mode 100644
index 0000000000..c5d1f32b54
--- /dev/null
+++ b/Task/LU-decomposition/Ruby/lu-decomposition-2.rb
@@ -0,0 +1,4 @@
+l, u, p = a.lup_decomposition
+l.pretty_print(" %8.5f", "L")
+u.pretty_print(" %8.5f", "U")
+p.pretty_print(" %d",    "P")
diff --git a/Task/LZW-compression/00DESCRIPTION b/Task/LZW-compression/00DESCRIPTION
index 041b1fdecb..0fbca44f90 100644
--- a/Task/LZW-compression/00DESCRIPTION
+++ b/Task/LZW-compression/00DESCRIPTION
@@ -1,3 +1,3 @@
 The Lempel-Ziv-Welch (LZW) algorithm provides lossless data compression.
 You can read a complete description of it in the [[wp:Lempel-Ziv-Welch|Wikipedia article]] on the subject.
-It was patented, but it fell in the public domain in 2004.
+It was patented, but it entered the public domain in 2004.
diff --git a/Task/LZW-compression/C/lzw-compression.c b/Task/LZW-compression/C/lzw-compression.c
index 1f49d0d846..51b8043273 100644
--- a/Task/LZW-compression/C/lzw-compression.c
+++ b/Task/LZW-compression/C/lzw-compression.c
@@ -74,7 +74,7 @@ byte* lzw_encode(byte *in, int max_bits)
 	ushort code, c, nc, next_code = M_NEW;
 	lzw_enc_t *d = _new(lzw_enc_t, 512);
 
-	if (max_bits > 16) max_bits = 16;
+	if (max_bits > 15) max_bits = 15;
 	if (max_bits < 9 ) max_bits = 12;
 
 	byte *out = _new(ushort, 4);
diff --git a/Task/LZW-compression/CoffeeScript/lzw-compression.coffee b/Task/LZW-compression/CoffeeScript/lzw-compression.coffee
new file mode 100644
index 0000000000..f22c0be7e6
--- /dev/null
+++ b/Task/LZW-compression/CoffeeScript/lzw-compression.coffee
@@ -0,0 +1,36 @@
+lzw = (s) ->
+  dct = {} # map substrings to codes between 256 and 4096
+  stream = [] # array of compression results
+
+  # initialize basic ASCII characters
+  for code_num in [0..255]
+    c = String.fromCharCode(code_num)
+    dct[c] = code_num
+  code_num = 256
+
+  i = 0
+  while i < s.length
+    # Find word and new_word
+    #   word = longest substr already encountered, or next character
+    #   new_word = word plus next character, a new substr to encode
+    word = ''
+    j = i
+    while j < s.length
+      new_word = word + s[j]
+      break if !dct[new_word]
+      word = new_word
+      j += 1
+
+    # stream out the code for the substring
+    stream.push dct[word]
+
+    # build up our encoding dictionary
+    if code_num < 4096
+      dct[new_word] = code_num
+      code_num += 1
+
+    # advance thru the string
+    i += word.length
+  stream
+
+console.log lzw "TOBEORNOTTOBEORTOBEORNOT"
diff --git a/Task/LZW-compression/D/lzw-compression-2.d b/Task/LZW-compression/D/lzw-compression-2.d
index 150baa9485..eaa5a6968a 100644
--- a/Task/LZW-compression/D/lzw-compression-2.d
+++ b/Task/LZW-compression/D/lzw-compression-2.d
@@ -14,7 +14,7 @@ struct LZW {
             bytes[i] = i;
     }
 
-    static Tcomp[] compress(immutable scope T[] original) pure nothrow
+    static Tcomp[] compress(immutable scope T[] original) pure nothrow @safe
     out(result) {
         if (!original.empty)
             assert(result[0] < initDictSize);
@@ -28,7 +28,7 @@ struct LZW {
         // Here built-in slices give lower efficiency.
         struct Slice {
             size_t start, end;
-            @property opSlice() const pure nothrow {
+            @property opSlice() const pure nothrow @safe @nogc {
                 return original[start .. end];
             }
             alias opSlice this;
@@ -53,7 +53,7 @@ struct LZW {
         return result;
     }
 
-    static Ta decompress(in Tcomp[] compressed) pure
+    static Ta decompress(in Tcomp[] compressed) pure @safe
     in {
         if (!compressed.empty)
             assert(compressed[0] < initDictSize, "Bad compressed");
@@ -91,6 +91,5 @@ void main() {
     immutable txt = "TOBEORNOTTOBEORTOBEORNOT";
     immutable compressed = LZW.compress(txt.representation);
     compressed.writeln;
-    //LZW.decompress(compressed).unrepresentation.writeln;
-    writeln(cast(string)LZW.decompress(compressed));
+    LZW.decompress(compressed).assumeUTF.writeln;
 }
diff --git a/Task/LZW-compression/D/lzw-compression-3.d b/Task/LZW-compression/D/lzw-compression-3.d
new file mode 100644
index 0000000000..4550d0e13c
--- /dev/null
+++ b/Task/LZW-compression/D/lzw-compression-3.d
@@ -0,0 +1,222 @@
+enum Marker: ushort {
+    CLR = 256, // Clear table marker.
+    EOD = 257, // End-of-data marker.
+    NEW = 258  // New code index.
+}
+
+
+ubyte[] lzwEncode(scope const(ubyte)[] inp, in uint maxBits) pure nothrow
+in {
+    assert(maxBits >= 9 && maxBits <= 16);
+} body {
+    // Encode dictionary array. For encoding, entry at
+    // code index is a list of indices that follow current one,
+    // i.e. if code 97 is 'a', code 387 is 'ab', and code 1022 is 'abc',
+    // then dict[97].next['b'] = 387, dict[387].next['c'] = 1022, etc.
+    alias LZWenc = ushort[256];
+
+    auto len = inp.length;
+    uint bits = 9;
+    auto d = new LZWenc[512];
+
+    auto result = new ubyte[16];
+    size_t outLen = 0;
+    size_t oBits = 0;
+    uint tmp = 0;
+
+    void writeBits(in ushort x) nothrow {
+        tmp = (tmp << bits) | x;
+        oBits += bits;
+        if (result.length / 2 <= outLen)
+            result.length *= 2;
+        while (oBits >= 8) {
+            oBits -= 8;
+            assert(tmp >> oBits <= ubyte.max);
+            result[outLen] = cast(ubyte)(tmp >> oBits);
+            outLen++;
+            tmp &= (1 << oBits) - 1;
+        }
+    }
+
+    // writeBits(Marker.CLR);
+    ushort nextCode = Marker.NEW;
+    uint nextShift = 512;
+    ushort code = inp[0];
+    inp = inp[1 .. $]; // popFront.
+    while (--len) {
+        ushort c = inp[0];
+        inp = inp[1 .. $]; // popFront.
+        ushort nc = d[code][c];
+        if (nc) {
+            code = nc;
+        } else {
+            writeBits(code);
+            nc = d[code][c] = nextCode;
+            nextCode++;
+            code = c;
+        }
+
+        // Next new code would be too long for current table.
+        if (nextCode == nextShift) {
+            // Either reset table back to 9 bits.
+            bits++;
+            if (bits > maxBits) {
+                // Table clear marker must occur before bit reset.
+                writeBits(Marker.CLR);
+
+                bits = 9;
+                nextShift = 512;
+                nextCode = Marker.NEW;
+                d[] = LZWenc.init;
+            } else { // Or extend table.
+                nextShift *= 2;
+                d.length = nextShift;
+            }
+        }
+    }
+
+    writeBits(code);
+    writeBits(Marker.EOD);
+    if (tmp) {
+        assert(tmp <= ushort.max);
+        writeBits(cast(ushort)tmp);
+    }
+
+    return result[0 .. outLen];
+}
+
+
+ubyte[] lzwDecode(scope const(ubyte)[] inp) pure {
+    // For decoding, dictionary contains index of whatever prefix
+    // index plus trailing ubyte.  i.e. like previous example,
+    //     dict[1022] = { c: 'c', prev: 387 },
+    //     dict[387]  = { c: 'b', prev: 97 },
+    //     dict[97]   = { c: 'a', prev: 0 }
+    // the "back" element is used for temporarily chaining indices
+    // when resolving a code to bytes.
+    static struct LZWdec {
+        ushort prev, back;
+        ubyte c;
+    }
+
+    auto result = new ubyte[4];
+    uint outLen = 0;
+
+    void writeOut(in ubyte c) nothrow {
+        while (outLen >= result.length)
+            result.length *= 2;
+        result[outLen] = c;
+        outLen++;
+    }
+
+    auto d = new LZWdec[512];
+    ushort code = 0;
+    uint bits = 9;
+    uint len = 0;
+    uint nBits = 0;
+    uint tmp = 0;
+
+    void getCode() nothrow {
+        while (nBits < bits) {
+            if (len > 0) {
+                len--;
+                tmp = (tmp << 8) | inp[0];
+                inp = inp[1 .. $]; // popFront.
+                nBits += 8;
+            } else {
+                tmp = tmp << (bits - nBits);
+                nBits = bits;
+            }
+        }
+
+        nBits -= bits;
+        assert(tmp >> nBits <= ushort.max);
+        code = cast(ushort)(tmp >> nBits);
+        tmp &= (1 << nBits) - 1;
+    }
+
+    uint nextShift = 512;
+    ushort nextCode = Marker.NEW;
+
+    void clearTable() nothrow {
+        d[] = LZWdec.init;
+        foreach (immutable ubyte j; 0 .. 256)
+            d[j].c = j;
+        nextCode = Marker.NEW;
+        nextShift = 512;
+        bits = 9;
+    }
+
+    clearTable(); // In case encoded bits didn't start with Marker.CLR.
+    for (len = inp.length; len;) {
+        getCode();
+        if (code == Marker.EOD)
+            break;
+        if (code == Marker.CLR) {
+            clearTable();
+            continue;
+        }
+
+        if (code >= nextCode)
+            throw new Error("Bad sequence.");
+
+        auto c = code;
+        d[nextCode].prev = c;
+        while (c > 255) {
+            immutable t = d[c].prev;
+            d[t].back = c;
+            c = t;
+        }
+
+        assert(c <= ubyte.max);
+        d[nextCode - 1].c = cast(ubyte)c;
+
+        while (d[c].back) {
+            writeOut(d[c].c);
+            immutable t = d[c].back;
+            d[c].back = 0;
+            c = t;
+        }
+        writeOut(d[c].c);
+
+        nextCode++;
+        if (nextCode >= nextShift) {
+            bits++;
+            if (bits > 16) {
+                // If input was correct, we'd have hit Marker.CLR before this.
+                throw new Error("Too many bits.");
+            }
+            nextShift *= 2;
+            d.length = nextShift;
+        }
+    }
+
+    // Might be OK, so throw just an exception.
+    if (code != Marker.EOD)
+        throw new Exception("Bits did not end in EOD");
+
+    return result[0 .. outLen];
+}
+
+
+void main() {
+    import std.stdio, std.file;
+
+    const inputData = cast(ubyte[])read("unixdict.txt");
+    writeln("Input size:   ", inputData.length);
+
+    immutable encoded = lzwEncode(inputData, 12);
+    writeln("Encoded size: ", encoded.length);
+
+    immutable decoded = lzwDecode(encoded);
+    writeln("Decoded size: ", decoded.length);
+
+    if (inputData.length != decoded.length)
+        return writeln("Error: decoded size differs");
+
+    foreach (immutable i, immutable x; inputData)
+        if (x != decoded[i])
+            return writeln("Bad decode at ", i);
+
+    "Decoded OK.".writeln;
+}
diff --git a/Task/LZW-compression/JavaScript/lzw-compression.js b/Task/LZW-compression/JavaScript/lzw-compression.js
new file mode 100644
index 0000000000..59ff70053b
--- /dev/null
+++ b/Task/LZW-compression/JavaScript/lzw-compression.js
@@ -0,0 +1,81 @@
+//LZW Compression/Decompression for Strings
+var LZW = {
+    compress: function (uncompressed) {
+        "use strict";
+        // Build the dictionary.
+        var i,
+            dictionary = {},
+            c,
+            wc,
+            w = "",
+            result = [],
+            dictSize = 256;
+        for (i = 0; i < 256; i += 1) {
+            dictionary[String.fromCharCode(i)] = i;
+        }
+
+        for (i = 0; i < uncompressed.length; i += 1) {
+            c = uncompressed.charAt(i);
+            wc = w + c;
+            //Do not use dictionary[wc] because javascript arrays
+            //will return values for array['pop'], array['push'] etc
+           // if (dictionary[wc]) {
+            if (dictionary.hasOwnProperty(wc)) {
+                w = wc;
+            } else {
+                result.push(dictionary[w]);
+                // Add wc to the dictionary.
+                dictionary[wc] = dictSize++;
+                w = String(c);
+            }
+        }
+
+        // Output the code for w.
+        if (w !== "") {
+            result.push(dictionary[w]);
+        }
+        return result;
+    },
+
+
+    decompress: function (compressed) {
+        "use strict";
+        // Build the dictionary.
+        var i,
+            dictionary = [],
+            w,
+            result,
+            k,
+            entry = "",
+            dictSize = 256;
+        for (i = 0; i < 256; i += 1) {
+            dictionary[i] = String.fromCharCode(i);
+        }
+
+        w = String.fromCharCode(compressed[0]);
+        result = w;
+        for (i = 1; i < compressed.length; i += 1) {
+            k = compressed[i];
+            if (dictionary[k]) {
+                entry = dictionary[k];
+            } else {
+                if (k === dictSize) {
+                    entry = w + w.charAt(0);
+                } else {
+                    return null;
+                }
+            }
+
+            result += entry;
+
+            // Add w+entry[0] to the dictionary.
+            dictionary[dictSize++] = w + entry.charAt(0);
+
+            w = entry;
+        }
+        return result;
+    }
+}, // For Test Purposes
+    comp = LZW.compress("TOBEORNOTTOBEORTOBEORNOT"),
+    decomp = LZW.decompress(comp);
+document.write(comp + '
' + decomp); diff --git a/Task/LZW-compression/Liberty-BASIC/lzw-compression.liberty b/Task/LZW-compression/Liberty-BASIC/lzw-compression.liberty new file mode 100644 index 0000000000..64ebf8bb6a --- /dev/null +++ b/Task/LZW-compression/Liberty-BASIC/lzw-compression.liberty @@ -0,0 +1,280 @@ + DIM LZW(1, 1) + DIM JDlzw(1) + DIM JDch$(1) + LET maxBits = 20 ' maximum bit width of the dictionary: minimum=12; maximum=21 + LET resetDictionary = 1 ' flag to reset the dictionary when it gets full: 1=TRUE; 0=FALSE + LET printDictionary = 0 ' output encoding and decoding dictionaries to files + LET maxChunkSize = 2 ^ 14 ' maximum size of the data buffer + LET dSize = 2 ^ maxBits ' maximum dictionary size + LET JDext$ = ".lzw" ' file extension used for created archives + FILEDIALOG "Select a file to test LZW...", "*.*", inputName$ + IF inputName$ = "" THEN END + DO ' get fullPath\ and fileName.ext + P = X + X = INSTR(inputName$, "\", (X + 1)) + LOOP UNTIL X = 0 + filePath$ = LEFT$(inputName$, P) + fileName$ = MID$(inputName$, (P + 1)) + DO ' get fileName and .ext + P = X + X = INSTR(fileName$, ".", (X + 1)) + LOOP UNTIL X = 0 + fileExt$ = MID$(fileName$, P) + fileName$ = LEFT$(fileName$, (P - 1)) + + GOSUB [lzwEncode] + GOSUB [lzwDecode] + + END + +'''''''''''''''''''''''''''''''''''''''' +' Start LZW Encoder '''''''''''''''''''' +[lzwEncode] + REDIM LZW(dSize, 4) + LET EMPTY=-1:PREFIX=0:BYTE=1:FIRST=2:LESS=3:MORE=4:bmxCorrect=1 + LET bitsRemain=0:remainIndex=0:tagCount=0:currentBitSize=8:fileTag$="" + FOR dNext = 0 TO 255 ' initialize dictionary for LZW + ' LZW(dNext, PREFIX) = EMPTY ' prefix index of '' + ' LZW(dNext, BYTE) = dNext ' byte value of '' + LZW(dNext, FIRST) = EMPTY ' first index to use as prefix + ' LZW(dNext, LESS) = EMPTY ' lesser index of binary search tree for + ' LZW(dNext, MORE) = EMPTY ' greater index of binary search tree for + NEXT dNext + OPEN inputName$ FOR INPUT AS #lzwIN + IF LOF(#lzwIN) < 2 THEN + CLOSE #lzwIN + END + END IF + OPEN fileName$ + fileExt$ + JDext$ FOR OUTPUT AS #lzwOUT + GOSUB [StartFileChunk] + chnkPoint = 1 + IF maxBits < 12 THEN maxBits = 12 + IF maxBits > 21 THEN maxBits = 21 + settings = maxBits - 12 ' setting for dictionary size; 1st decimal +12 + IF resetDictionary THEN settings = settings + 100 ' setting for dictionary type; 2nd decimal even=static, odd=adaptive + #lzwOUT, CHR$(settings); ' save settings as 1st byte of output + orgIndex = ASC(LEFT$(fileChunk$, 1)) ' read 1st byte into + WHILE fileChunk$ <> "" ' while the buffer is not empty + DO ' begin the main encoder loop + chnkPoint = chnkPoint + 1 + savIndex = FIRST ' initialize the save-to index + prvIndex = orgIndex ' initialize the previous index in search + newByte = ASC(MID$(fileChunk$, chnkPoint, 1)) ' read + dSearch = LZW(orgIndex, FIRST) ' first search index for this in the dictionary + WHILE (dSearch > EMPTY) ' while is present in the dictionary + IF LZW(dSearch, BYTE) = newByte THEN EXIT WHILE ' if is found + IF newByte < LZW(dSearch, BYTE) THEN ' else if new is less than + savIndex = LESS ' follow lesser binary tree + ELSE + savIndex = MORE ' else follow greater binary tree + END IF + prvIndex = dSearch ' set previous + dSearch = LZW(dSearch, savIndex) ' read next search from binary tree + WEND + IF dSearch = EMPTY THEN ' if was not found in the dictionary + GOSUB [WriteIndex] ' write to the output + IF dNext < dSize THEN ' save into the dictionary + LZW(prvIndex, savIndex) = dNext + LZW(dNext, PREFIX) = orgIndex + LZW(dNext, BYTE) = newByte + LZW(dNext, FIRST) = EMPTY + LZW(dNext, LESS) = EMPTY + LZW(dNext, MORE) = EMPTY + IF dNext = (2 ^ currentBitSize) THEN currentBitSize = currentBitSize + 1 + dNext = dNext + 1 + ELSE ' else reset the dictionary... or maybe not + IF resetDictionary THEN + GOSUB [PrintEncode] + REDIM LZW(dSize, 4) + FOR dNext = 0 TO 255 + LZW(dNext, FIRST) = EMPTY + NEXT dNext + currentBitSize = 8 + bmxCorrect = 0 + END IF + END IF + orgIndex = newByte ' set = + ELSE ' if was found in the dictionary, + orgIndex = dSearch ' then set = + END IF + LOOP WHILE chnkPoint < chunk ' loop until the chunk has been processed + GOSUB [GetFileChunk] ' refill the buffer + WEND ' loop until the buffer is empty + GOSUB [WriteIndex] + IF bitsRemain > 0 THEN #lzwOUT, CHR$(remainIndex); + CLOSE #lzwOUT + CLOSE #lzwIN + IF bmxCorrect THEN ' correct the settings, if needed + IF (currentBitSize < maxBits) OR resetDictionary THEN + IF currentBitSize < 12 THEN currentBitSize = 12 + OPEN fileName$ + fileExt$ + JDext$ FOR BINARY AS #lzwOUT + #lzwOUT, CHR$(currentBitSize - 12); + CLOSE #lzwOUT + END IF + END IF + GOSUB [PrintEncode] + REDIM LZW(1, 1) + RETURN + +[WriteIndex] + X = orgIndex ' add remaining bits to input + IF bitsRemain > 0 THEN X = remainIndex + (X * (2 ^ bitsRemain)) + bitsRemain = bitsRemain + currentBitSize ' add current bit size to output stack + WHILE bitsRemain > 7 ' if 8 or more bits are to be written + #lzwOUT, CHR$(X MOD 256); ' attatch lower 8 bits to output string + X = INT(X / 256) ' shift input value down by 2^8 + bitsRemain = bitsRemain - 8 ' adjust counters + WEND + remainIndex = X ' retain trailing bits for next write + RETURN + +' End LZW Encoder '''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''' + +[StartFileChunk] + sizeOfFile = LOF(#lzwIN) ' set EOF marker + bytesRemaining = sizeOfFile ' set EOF counter + chunk = maxChunkSize ' set max buffer size +[GetFileChunk] + fileChunk$ = "" + IF bytesRemaining < 1 THEN RETURN + IF chunk > bytesRemaining THEN chunk = bytesRemaining + bytesRemaining = bytesRemaining - chunk + fileChunk$ = INPUT$(#lzwIN, chunk) + chnkPoint = 0 + RETURN + +'''''''''''''''''''''''''''''''''''''''' +' Start LZW Decoder '''''''''''''''''''' +[lzwDecode] + LET EMPTY=-1:bitsRemain=0:tagCount=0:fileTag$="" + OPEN fileName$ + fileExt$ + JDext$ FOR INPUT AS #lzwIN + OPEN fileName$ + ".Copy" + fileExt$ FOR OUTPUT AS #lzwOUT + GOSUB [StartFileChunk] + chnkPoint = 2 + settings = ASC(fileChunk$) + maxBits = VAL(RIGHT$(STR$(settings), 1)) + 12 + dSize = 2 ^ maxBits + IF settings > 99 THEN resetDictionary = 1 + GOSUB [ResetLZW] + oldIndex = orgIndex + WHILE fileChunk$ <> "" + ' decode current index and write to file + GOSUB [GetIndex] + IF JDch$(orgIndex) = "" THEN + tmpIndex = oldIndex + tmp$ = JDch$(tmpIndex) + WHILE JDlzw(tmpIndex) > EMPTY + tmpIndex = JDlzw(tmpIndex) + tmp$ = JDch$(tmpIndex) + tmp$ + WEND + tmp$ = tmp$ + LEFT$(tmp$, 1) + ELSE + tmpIndex = orgIndex + tmp$ = JDch$(tmpIndex) + WHILE JDlzw(tmpIndex) > EMPTY + tmpIndex = JDlzw(tmpIndex) + tmp$ = JDch$(tmpIndex) + tmp$ + WEND + END IF + #lzwOUT, tmp$; + ' add next dictionary entry or reset dictionary + IF dNext < dSize THEN + JDlzw(dNext) = oldIndex + JDch$(dNext) = LEFT$(tmp$, 1) + dNext = dNext + 1 + IF dNext = (2 ^ currentBitSize) THEN + IF maxBits > currentBitSize THEN + currentBitSize = currentBitSize + 1 + ELSE + IF resetDictionary THEN + GOSUB [PrintDecode] + GOSUB [ResetLZW] + END IF + END IF + END IF + END IF + oldIndex = orgIndex + WEND + CLOSE #lzwOUT + CLOSE #lzwIN + GOSUB [PrintDecode] + REDIM JDlzw(1) + REDIM JDch$(1) + RETURN + +[GetIndex] + byteCount = 0:orgIndex = 0 + bitsToGrab = currentBitSize - bitsRemain + IF bitsRemain > 0 THEN + orgIndex = lastByte + byteCount = 1 + END IF + WHILE bitsToGrab > 0 + lastByte = ASC(MID$(fileChunk$, chnkPoint, 1)) + orgIndex = orgIndex + (lastByte * (2 ^ (byteCount * 8))) + IF chnkPoint = chunk THEN GOSUB [GetFileChunk] + chnkPoint = chnkPoint + 1 + byteCount = byteCount + 1 + bitsToGrab = bitsToGrab - 8 + WEND + IF bitsRemain > 0 THEN orgIndex = orgIndex / (2 ^ (8 - bitsRemain)) + orgIndex = orgIndex AND ((2 ^ currentBitSize) - 1) + bitsRemain = bitsToGrab * (-1) + RETURN + +[ResetLZW] + REDIM JDlzw(dSize) + REDIM JDch$(dSize) + FOR dNext = 0 TO 255 + JDlzw(dNext) = EMPTY ' Prefix index + JDch$(dNext) = CHR$(dNext) ' New byte value + NEXT dNext + currentBitSize = 8 + GOSUB [GetIndex] + #lzwOUT, JDch$(orgIndex); + currentBitSize = 9 + RETURN + +' End LZW Decoder '''''''''''''''''''''' +'''''''''''''''''''''''''''''''''''''''' + +'''''''''''''''''''''''''''''''''''''''' +[PrintEncode] + IF printDictionary < 1 THEN RETURN + OPEN "Encode_" + fileTag$ + fileName$ + ".txt" FOR OUTPUT AS #dictOUT + FOR X = 0 TO 255 + LZW(X, PREFIX) = EMPTY + LZW(X, BYTE) = X + NEXT X + FOR X = dNext TO 0 STEP -1 + tmpIndex = X + tmp$ = CHR$(LZW(tmpIndex, BYTE)) + WHILE LZW(tmpIndex, PREFIX) > EMPTY + tmpIndex = LZW(tmpIndex, PREFIX) + tmp$ = CHR$(LZW(tmpIndex, BYTE)) + tmp$ + WEND + #dictOUT, X; ":"; tmp$ + NEXT X + CLOSE #dictOUT + tagCount = tagCount + 1 + fileTag$ = STR$(tagCount) + "_" + RETURN + +[PrintDecode] + IF printDictionary < 1 THEN RETURN + OPEN "Decode_" + fileTag$ + fileName$ + ".txt" FOR OUTPUT AS #dictOUT + FOR X = dNext TO 0 STEP -1 + tmpIndex = X + tmp$ = JDch$(tmpIndex) + WHILE JDlzw(tmpIndex) > EMPTY + tmpIndex = JDlzw(tmpIndex) + tmp$ = JDch$(tmpIndex) + tmp$ + WEND + #dictOUT, X; ":"; tmp$ + NEXT X + CLOSE #dictOUT + tagCount = tagCount + 1 + fileTag$ = STR$(tagCount) + "_" + RETURN +'''''''''''''''''''''''''''''''''''''''' diff --git a/Task/LZW-compression/PHP/lzw-compression.php b/Task/LZW-compression/PHP/lzw-compression.php index 78abea989d..5a528cbe2b 100644 --- a/Task/LZW-compression/PHP/lzw-compression.php +++ b/Task/LZW-compression/PHP/lzw-compression.php @@ -11,7 +11,8 @@ class LZW } for ($i = 0; $i < strlen($unc); $i++) { $c = $unc[$i]; - if (property_exists($dictionary, $w.$c)) { + $wc = $w.$c; + if (array_key_exists($w.$c, $dictionary)) { $w = $w.$c; } else { array_push($result,$dictionary[$w]); @@ -22,7 +23,6 @@ class LZW if ($w !== "") { array_push($result,$dictionary[$w]); } - array_shift($result); return implode(",",$result); } diff --git a/Task/LZW-compression/Python/lzw-compression.py b/Task/LZW-compression/Python/lzw-compression.py index 6885c5d1a2..3f88eb04dd 100644 --- a/Task/LZW-compression/Python/lzw-compression.py +++ b/Task/LZW-compression/Python/lzw-compression.py @@ -27,13 +27,18 @@ def compress(uncompressed): def decompress(compressed): """Decompress a list of output ks to a string.""" + from cStringIO import StringIO # Build the dictionary. dict_size = 256 dictionary = dict((chr(i), chr(i)) for i in xrange(dict_size)) # in Python 3: dictionary = {chr(i): chr(i) for i in range(dict_size)} - w = result = compressed.pop(0) + # use StringIO, otherwise this becomes O(N^2) + # due to string concatenation in a loop + result = StringIO() + w = compressed.pop(0) + result.write(w) for k in compressed: if k in dictionary: entry = dictionary[k] @@ -41,14 +46,14 @@ def decompress(compressed): entry = w + w[0] else: raise ValueError('Bad compressed k: %s' % k) - result += entry + result.write(entry) # Add w+entry[0] to the dictionary. dictionary[dict_size] = w + entry[0] dict_size += 1 w = entry - return result + return result.getvalue() # How to use: diff --git a/Task/LZW-compression/REXX/lzw-compression.rexx b/Task/LZW-compression/REXX/lzw-compression.rexx new file mode 100644 index 0000000000..09790ba09e --- /dev/null +++ b/Task/LZW-compression/REXX/lzw-compression.rexx @@ -0,0 +1,76 @@ +/* REXX --------------------------------------------------------------- +* 20.07.2014 Wakter Pachl translated from Java +* 21.07.2014 WP allow for blanks in the string +*--------------------------------------------------------------------*/ +Parse Arg str +default="TOBEORNOTTOBEORTOBEORNOT" +If str='' Then + str=default +/* str=space(str,0) */ +Say 'str='str +compressed = compress(str) +Say compressed +If str=default Then Do + cx='[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]' + If cx==compressed Then Say 'compression ok' + End +decompressed = decompress(compressed) +Say 'dec='decompressed +If decompressed=str Then Say 'decompression ok' +Exit + +compress: Procedure +Parse Arg uncompressed +dict.='' +Do i=0 To 255 + z=d2c(i) + d.i=z + dict.z=i + End +dict_size=256 +res='[' +w='' +Do i=1 To length(uncompressed) + c=substr(uncompressed,i,1) + wc=w||c + If dict.wc<>'' Then + w=wc + Else Do + res=res||dict.w', ' + dict.wc=dict_size + dict_size+=1 + w=c + End + End +If w<>'' Then + res=res||dict.w', ' +Return left(res,length(res)-2)']' + +decompress: Procedure +Parse Arg compressed +compressed=space(translate(compressed,'','[],')) +d.='' +Do i=0 To 255 + z=d2c(i) + d.i=z + End +dict_size=256 +Parse Var compressed w compressed +res=d.w +w=d.w +Do i=1 To words(compressed) + k=word(compressed,i) + Select + When d.k<>'' | d.k=='20'x then /* allow for blank */ + entry=d.k + When k=dict_size Then + entry=w||substr(w,1,1) + Otherwise + Say "Bad compressed k: " k + End + res=res||entry + d.dict_size=w||substr(entry,1,1) + dict_size+=1 + w=entry + End +Return res diff --git a/Task/LZW-compression/Scala/lzw-compression.scala b/Task/LZW-compression/Scala/lzw-compression.scala index 4ebfd7648f..34c52bf4d3 100644 --- a/Task/LZW-compression/Scala/lzw-compression.scala +++ b/Task/LZW-compression/Scala/lzw-compression.scala @@ -1,4 +1,3 @@ - // for now, only compress def compress(tc:String) = { //initial dictionary val startDict = (1 to 255).map(a=>(""+a.toChar,a)).toMap @@ -14,5 +13,33 @@ def compress(tc:String) = { if (remain.isEmpty) result.reverse else (fullDict(remain) :: result).reverse } +def decompress(ns: List[Int]): String = { + val startDict = (1 to 255).map(a=>(a,""+a.toChar)).toMap + val (_, result, _) = + ns.foldLeft[(Map[Int, String], List[String], Option[(Int, String)])]((startDict, Nil, None)) { + case ((dict, result, conjecture), n) => { + dict.get(n) match { + case Some(output) => { + val (newDict, newCode) = conjecture match { + case Some((code, prefix)) => ((dict + (code -> (prefix + output.head))), code + 1) + case None => (dict, dict.size + 1) + } + (newDict, output :: result, Some(newCode -> output)) + } + case None => { + // conjecture being None would be an encoding error + val (code, prefix) = conjecture.get + val output = prefix + prefix.head + (dict + (code -> output), output :: result, Some(code + 1 -> output)) + } + } + } + } + result.reverse.mkString("") +} // test -compress("TOBEORNOTTOBEORTOBEORNOT") +val text = "TOBEORNOTTOBEORTOBEORNOT" +val compressed = compress(text) +println(compressed) +val result = decompress(compressed) +println(result) diff --git a/Task/Langtons-ant/00DESCRIPTION b/Task/Langtons-ant/00DESCRIPTION index bc52bda04f..2cb9fdb9b1 100644 --- a/Task/Langtons-ant/00DESCRIPTION +++ b/Task/Langtons-ant/00DESCRIPTION @@ -1,10 +1,17 @@ -[[wp:Langton's ant|Langton's ant]] models an ant sitting on a plane of cells, all of which are white initially, facing in one of four directions. Each cell can either be black or white. The ant moves according to the color of the cell it is currently sitting in, with the following rules: +[[wp:Langton's ant|Langton's ant]] is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, facing in one of four directions. +Each cell can either be black or white. +The ant moves according to the color of the cell it is currently sitting in, with the following rules: # If the cell is black, it changes to white and the ant turns left; # If the cell is white, it changes to black and the ant turns right; # The Ant then moves forward to the next cell, and repeat from step 1. -This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 pixels wide. Conceptually the ant can then travel to infinitely far away. +This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 pixels wide. +Conceptually the ant can then travel infinitely far away. -For this task, start the ant near the center of a 100 by 100 field of cells, which is about big enough to contain the initial chaotic part of the movement. Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind. +For this task, start the ant near the center of a 100 by 100 field of cells, which is about big enough to contain the initial chaotic part of the movement. +Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind. -The problem has received some analysis, for more details, please take a look at the Wikipedia article. +The problem has received some analysis; for more details, please take a look at the Wikipedia article. + +;See also +* [[Conway's Game of Life]] diff --git a/Task/Langtons-ant/AWK/langtons-ant.awk b/Task/Langtons-ant/AWK/langtons-ant.awk new file mode 100644 index 0000000000..36020a883c --- /dev/null +++ b/Task/Langtons-ant/AWK/langtons-ant.awk @@ -0,0 +1,93 @@ +# usage: awk -v debug=0 -f langton.awk + +# Simulates the cellular automaton "Langton's ant", +# see http://en.wikipedia.org/wiki/Langton%27s_ant + +function turnRight() { + dir++ + if( dir>4 ) { dir=1 } +} +function turnLeft() { + dir-- + if( dir<1 ) { dir=4 } +} +function move() { + if (dir==1) { y--; z="^" } + if (dir==3) { y++; z="v" } + + if (dir==2) { x++; z=">" } + if (dir==4) { x--; z="<" } +} + +function ant() { + if( debug ) AntStat() ## + + if( grid[x,y]==0 ) { turnLeft() } else { turnRight() } + if( grid[x,y]==0 ) { color=1 } else { color=0 } + + if( debug ) print( "# action", color, dir, z ) ## + + grid[x,y] = color + move() +} + +### + +function AntStat() { + printf( "Move# %d : Ant @ x=%d y=%d dir=%d %s color=%d\n", + moveNr, x,y, dir,z, grid[x,y] ) +} +function dumpGrid() { + AntStat() + + printf( "Grid:" ) + for(xx=1; xx<=limit/10; xx++) { + printf( "....+....%s", xx ) + } + printf "\n" + + cSum=0 + for(yy=1; yy <= limit; yy++) { + printf( "%4d:",yy ) + for(xx=1; xx <= limit; xx++) { + c = grid[xx,yy] + if( c ) cSum++ + c1++ + c2+=grid[xx,yy] + if( (xx==x)&&(yy==y) ) { c=z } # Ant + printf( c ) + } + printf( "\n" ) + } + printf( "Cells: %d 'black' cells: %d Moves: %d\n\n", limit*limit, cSum, moveNr ) +} + +BEGIN { + print( "Langton's ant\n" ) + + limit = 72 + for(x=1; x <= limit; x++) { + for(y=1; y <= limit; y++) { + grid[x,y] = 0 + } + } + + moveNr = 0 + x = 36 + y = 28 + dir = 1 # 1=up/north 2=right/east 3=down/south 4=left/west + z = "!" + + while( moveNr < 11200 ) { + moveNr++ + ant() + if(x<0 || x>limit) break + if(y<0 || y>limit) break + + # Snapshots: + if (moveNr==163 || moveNr==1297 || moveNr==10095 ) dumpGrid() + if (y<=5 ) break + } + dumpGrid() +} +END { print("END.") } diff --git a/Task/Langtons-ant/AutoHotkey/langtons-ant.ahk b/Task/Langtons-ant/AutoHotkey/langtons-ant.ahk index e86c638022..d64f686425 100644 --- a/Task/Langtons-ant/AutoHotkey/langtons-ant.ahk +++ b/Task/Langtons-ant/AutoHotkey/langtons-ant.ahk @@ -1,20 +1,56 @@ -SetBatchLines -1 -n := 0, x := 50, y := 50, d := 1 ; starting positions and orientation - -While x > 0 and x < 100 and y > 0 and y < 100 ; In this loop the ant moves - d := d + !!(a%x%_%y%) - !(a%x%_%y%) - ,d := d=5 ? 1 : d=0 ? 4 : d - ,a%x%_%y% := !a%x%_%y% - ,x := x + (d=3) - (d=1) - ,y := y + (d=4) - (d=2) - -Loop 99 ; in this loop the ant's movements are compiled into a string -{ - y := A_Index - Loop 99 - x := A_Index - ,o .= a%x%_%y% ? "#" : "." - - o .= "`r`n" +#NoEnv +SetBatchLines, -1 +; Directions +Directions := {0: "North", 1: "East", 2: "South", 3: "West"} +; Initialize the plane (set all cells to white) +White := 0xFFFFFF +Plane := [] +PW := PH := 100 +loop, % PH { + I := A_Index + loop, % PW + Plane[I, A_Index] := White } -clipboard := o ; set the string to the clipboard +; Let it run +DI := D := 0 ; initial direction +X := Y := 50 ; initial coordinates +while (X > 0) && (X <= PW) && (Y > 0) && (Y <= PH) { + D := (D + ((Plane[X, Y] ^= White) ? 1 : 3)) & 3 + if (D & 1) + X += -(D = 3) + (D = 1) + else + Y += -(D = 0) + (D = 2) +} +; Show the result +HBM := CreateDIB(Plane, PW, PH, 400, 400, 0) +Gui, Margin, 0, 0 +Gui, Add, Text, x0 y0 w20 h440 Center 0x200, W +Gui, Add, Text, x20 y0 w400 h20 Center 0x200, N +Gui, Add, Picture, x20 y20 w400 h400 0x4E hwndHPIC ; SS_REALSIZECONTROL = 0x40 | SS_BITMAP = 0xE +DllCall("User32.dll\SendMessage", "Ptr", HPIC, "UInt", 0x172, "Ptr", 0, "Ptr", HBM) ; STM_SETIMAGE = 0x172 +Gui, Add, Text, xp+5 yp h20 0x200 BackgroundTrans, % "Initial direction: " . Directions[DI] +Gui, Add, Text, x20 y420 w400 h20 Center 0x200, S +Gui, Add, Text, x420 y0 w20 h440 Center 0x200, E +Gui, Show, , Langton's ant (%PW%x%PH%) +Return + +GuiClose: +ExitApp + +CreateDIB(PixelArray, PAW, PAH, BMW := 0, BMH := 0, Gradient := 1) { ; SKAN, 01-Apr-2014 / array version by just me + SLL := (PAW * 3) + (PAW & 1) + VarSetCapacity(BMBITS, SLL * PAH, 0) + P := &BMBITS + loop, % PAH { + R := A_Index + loop, % PAW + P := Numput(PixelArray[R, A_Index], P + 0, "UInt") - 1 + P += (PAW & 1) + } + HBM := DllCall("Gdi32.dll\CreateBitmap", "Int", PAW, "Int", PAH, "UInt", 1, "UInt", 24, "Ptr", 0, "UPtr") + HBM := DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", 0, "Int", 0, "UInt", 0x2008, "UPtr") + DllCall( "Gdi32.dll\SetBitmapBits", "Ptr", HBM, "UInt", SLL * PAH, "Ptr", &BMBITS) + if (!Gradient) + HBM := DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", 0, "Int", 0, "Int", 8, "UPtr") + return DllCall("User32.dll\CopyImage", "Ptr", HBM, "UInt", 0, "Int", BMW, "Int", BMH, "UInt", 0x200C, "UPtr") +} ; http://ahkscript.org/boards/viewtopic.php?f=6&t=3203 diff --git a/Task/Langtons-ant/D/langtons-ant-1.d b/Task/Langtons-ant/D/langtons-ant-1.d index 61472875b3..464cf87f68 100644 --- a/Task/Langtons-ant/D/langtons-ant-1.d +++ b/Task/Langtons-ant/D/langtons-ant-1.d @@ -1,25 +1,26 @@ -import std.stdio, std.traits; +void main() @safe { + import std.stdio, std.traits; -void main() { - enum width = 75, height = 52; - enum maxSteps = 12_000; - enum Direction { up, right, down, left } - enum Color : char { white = '.', black = '#' } - uint x = width / 2, y = height / 2; - auto M = new Color[][](height, width); - auto dir = Direction.up; + enum width = 75, height = 52; + enum maxSteps = 12_000; + enum Direction { up, right, down, left } + enum Color : char { white = '.', black = '#' } + uint x = width / 2, y = height / 2; + Color[width][height] M; + auto dir = Direction.up; - for (int i = 0; i < maxSteps && x < width && y < height; i++) { - immutable turn = M[y][x] == Color.black; - dir = [EnumMembers!Direction][(dir + (turn ? 1 : -1)) & 3]; - M[y][x] = (M[y][x] == Color.black) ? Color.white : Color.black; - final switch(dir) with (Direction) { - case up: y--; break; - case right: x--; break; - case down: y++; break; - case left: x++; break; - } - } + with (Color) + for (int i = 0; i < maxSteps && x < width && y < height; i++) { + immutable turn = M[y][x] == black; + dir = [EnumMembers!Direction][(dir + (turn ? 1 : -1)) & 3]; + M[y][x] = (M[y][x] == black) ? white : black; + final switch(dir) with (Direction) { + case up: y--; break; + case right: x--; break; + case down: y++; break; + case left: x++; break; + } + } - writefln("%-(%s\n%)", cast(char[][])M); + writefln("%(%-(%c%)\n%)", M); } diff --git a/Task/Langtons-ant/Fortran/langtons-ant.f b/Task/Langtons-ant/Fortran/langtons-ant.f new file mode 100644 index 0000000000..ae7b442824 --- /dev/null +++ b/Task/Langtons-ant/Fortran/langtons-ant.f @@ -0,0 +1,35 @@ +program langtons_ant + implicit none + + integer, parameter :: dp = selected_real_kind(15,300) + real(kind=dp), parameter :: pi = 3.1415926535897932_dp + + integer, parameter :: grid_size = 100 + integer, dimension(:,:), allocatable :: grid + integer, dimension(3) :: ant = (/ grid_size/2, grid_size/2, 0 /) + integer :: i + + allocate(grid(1:grid_size, 1:grid_size)) + grid = 1 !Grid initially white + + do + grid(ant(1) , ant(2)) = -grid(ant(1) , ant(2)) ! Flip the color of the current square + ant(3) = modulo(ant(3) + grid(ant(1),ant(2)),4) ! Rotate the ant depending on the current square + ant(1) = ant(1) + nint( sin(ant(3) * pi / 2.0_dp) ) ! Move the ant in x + ant(2) = ant(2) + nint( cos(ant(3) * pi / 2.0_dp) ) ! Move the ant in y + + !exit if the ant is outside the grid + if (((ant(1) < 1) .or. (ant(1) > grid_size)) .or. ((ant(2) < 1) .or. (ant(2) > grid_size))) exit + + end do + + !Print out the final grid + open(unit=21, file="ant.dat") + do i = 1, grid_size + write(21,*) int(grid(:,i) + 1 / 2.0_dp) + end do + close(21) + + deallocate(grid) + +end program langtons_ant diff --git a/Task/Langtons-ant/Logo/langtons-ant.logo b/Task/Langtons-ant/Logo/langtons-ant.logo new file mode 100644 index 0000000000..9a1533646d --- /dev/null +++ b/Task/Langtons-ant/Logo/langtons-ant.logo @@ -0,0 +1,51 @@ +make "size 100 +make "white 1 +make "black 2 +make "sum sum :white :black +make "chars [. #] +make "origin quotient :size 2 +make "grid mdarray (list :size :size) +make "directions [ [1 0] [0 1] [-1 0] [0 -1] ] + +repeat size [ + local "y + make "y repcount + repeat size [ + mdsetitem (list repcount :y) :grid :white + ] +] +make "x quotient :size 2 +make "y quotient :size 2 +make "direction sum 1 random count :directions + +while [(and (:x > 0) (:x <= :size) (:y > 0) (:y <= :size))] [ + local "color + make "color mditem (list :x :y) :grid + local "delta + ifelse [equal? :color :white] [ + make "delta 1 + ] [ + make "delta -1 + ] + make "direction sum 1 (modulo (:direction + :delta - 1) count :directions) + make "dir (item :direction :directions) + mdsetitem (list :x :y) :grid (sum :sum minus :color) + make "x sum :x first :dir + make "y sum :y last :dir +] + +repeat size [ + local "y + local "blank + make "y repcount + make "blank "true + repeat size [if ( (mditem (list repcount :y) :grid) = :black ) [make "blank "false]] + + if [not :blank] [ + repeat size [ + type item (mditem (list repcount :y) :grid) :chars + ] + print [] + ] +] +bye diff --git a/Task/Langtons-ant/Lua/langtons-ant.lua b/Task/Langtons-ant/Lua/langtons-ant.lua new file mode 100644 index 0000000000..f7c761abcf --- /dev/null +++ b/Task/Langtons-ant/Lua/langtons-ant.lua @@ -0,0 +1,107 @@ +local socket = require 'socket' -- needed for socket.sleep +local curses = require 'curses' -- used for graphics + +local naptime = 0.02 -- seconds +local world_x, world_y = 100, 100 + +local world = (function (x, y) + local wrl = {} + for i = 1, y do + wrl[i] = {} + for j = 1, x do + wrl[i][j] = 0 + end + end + return wrl +end)(world_x, world_y) + +-- directions: 0 up, clockwise +local ant = { + x = math.floor(world_x / 2), + y = math.floor(world_y / 2), + dir = 0, + step = function(self) + if self.dir == 0 then self.y = self.y - 1 + elseif self.dir == 1 then self.x = self.x + 1 + elseif self.dir == 2 then self.y = self.y + 1 + else self.x = self.x - 1 + end + end +} + +world.step = function (self, ant) + if self[ant.y][ant.x] == 0 then -- white + -- change cell color + self[ant.y][ant.x] = 1 + -- change dir + ant.dir = (ant.dir + 1) % 4 + ant:step() + -- boundary conditions + if ant.x < 1 then ant.x = world_x + elseif ant.x > world_x then ant.x = 1 + end + if ant.y < 1 then ant.y = world_y + elseif ant.y > world_y then ant.y = 1 + end + else + -- change cell color + self[ant.y][ant.x] = 0 + -- change dir + ant.dir = (ant.dir - 1) % 4 + ant:step() + -- boundary conditions + if ant.x < 1 then ant.x = world_x + elseif ant.x > world_x then ant.x = 1 + end + if ant.y < 1 then ant.y = world_y + elseif ant.y > world_y then ant.y = 1 + end + end +end + +world.draw = function (self, ant) + for i = 1, #self do + for j = 1, #self[i] do + if i == ant.y and j == ant.x then + win:attron(curses.color_pair(3)) + win:mvaddch(i,j,"A") + --win:attroff(curses.color_pair(3)) + elseif self[i][j] == 0 then + win:attron(curses.color_pair(1)) + win:mvaddch(i,j," ") + --win:attroff(curses.color_pair(1)) + elseif self[i][j] == 1 then + win:attron(curses.color_pair(2)) + win:mvaddch(i,j," ") + --win:attroff(curses.color_pair(2)) + else error("self[" .. i .. "][" .. j .. "] is " .. self[i][j] .. "!") + end + end + end +end + +local it = 1 +curses.initscr() +curses.start_color() +curses.echo(false) +curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_WHITE) +curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_BLACK) +curses.init_pair(3, curses.COLOR_RED, curses.COLOR_WHITE) +curses.init_pair(4, curses.COLOR_WHITE, curses.COLOR_BLACK) +win = curses.newwin(world_y + 1, world_x, 0, 0) +win:clear() +repeat + world:draw(ant) + win:move(world_y, 0) + win:clrtoeol() + win:attron(curses.color_pair(4)) + win:addstr("Iteration: " .. it .. ", nap = " .. naptime*1000 .. "ms") + win:refresh() + world:step(ant) + it = it + 1 + --local c = stdscr:getch() + --if c == '+' then naptime = naptime - (naptime / 10) + --elseif c == '-' then naptime = naptime + (naptime / 10) + --end + socket.sleep(naptime) +until false diff --git a/Task/Langtons-ant/Python/langtons-ant.py b/Task/Langtons-ant/Python/langtons-ant.py index add8bfe042..ba61a0a23d 100644 --- a/Task/Langtons-ant/Python/langtons-ant.py +++ b/Task/Langtons-ant/Python/langtons-ant.py @@ -5,7 +5,7 @@ nsteps = 12000 class Dir: up, right, down, left = range(4) class Turn: left, right = False, True class Color: white, black = '.', '#' -M = [[Color.white] * width for _ in xrange(height)] +M = [[Color.white] * width for _ in range(height)] x = width // 2 y = height // 2 @@ -25,4 +25,4 @@ while i < nsteps and 0 <= x < width and 0 <= y < height: else: assert False i += 1 -print "\n".join("".join(row) for row in M) +print ("\n".join("".join(row) for row in M)) diff --git a/Task/Langtons-ant/REXX/langtons-ant.rexx b/Task/Langtons-ant/REXX/langtons-ant.rexx index 7bf3f8cf79..604e94f3b4 100644 --- a/Task/Langtons-ant/REXX/langtons-ant.rexx +++ b/Task/Langtons-ant/REXX/langtons-ant.rexx @@ -1,41 +1,37 @@ -/*REXX program implements Langton's ant and displays the path it walked.*/ -parse arg dir . /*allow specification: ant facing*/ - /*binary colors: 0=white, 1=black*/ +/*REXX program implements Langton's ant walk and displays the ant's path*/ +parse arg dir char . /*allow specification: ant facing*/ +if char=='' then char='#' /*binary colors: 0≡white, 1≡black*/ @.=0 /*define stem array (all white).*/ -lb=1 ; rb=100 /* left boundry, right boundry.*/ -bb=1 ; tb=100 /*bottom " top " */ -x=(rb-lb)%2 ; y=(tb-bb)%2 /*approximate center (walk start)*/ +Lb=1 ; Rb=100 /* left boundry, right boundry.*/ +Bb=1 ; Tb=100 /*bottom " top " */ +x=(Rb-Lb)%2 ; y=(Tb-Bb)%2 /*approximate center (walk start)*/ if dir=='' then dir=random(1,4) /*ant is facing random direction,*/ - /*1=north 2=east 3=south 4=west*/ +$.=1; $.0=4; $.2=2; $.3=3; $.4=4 /*1≡north 2≡east 3≡south 4≡west*/ /*───────────────────────────────────────────ant walks hither & thither.*/ - do steps=1 until xrb | ytb /*walk until out-of-bounds*/ - black=@.x.y /*get color code of ant's cell. */ - @.x.y=\@.x.y /*"flip" the color of the cell. */ - if black then dir=dir-1 /*if cell was black, turn left. */ - else dir=dir+1 /* " " " white, " right. */ - if dir==0 then dir=4 /*ant should be facing "west". */ - if dir==5 then dir=1 /* " " " " "north". */ - select /*ant walks direction it's facing*/ - when dir==1 then y=y+1 /*walking north? Then go "up". */ - when dir==2 then x=x+1 /* " east? " " "right"*/ - when dir==3 then y=y-1 /* " south? " " "down".*/ - when dir==4 then x=x-1 /* " west? " " "left".*/ - end /*select*/ - end /*steps*/ + do steps=1 until xRb | yTb /*walk until out─of─bounds*/ + black=@.x.y; @.x.y= \ @.x.y /*ant's cell color code; flip it.*/ + if black then dir=dir-1 /*if cell was black, turn left.*/ + else dir=dir+1 /* " " " white, turn right.*/ + dir=$.dir /*possibly adjust for under/over.*/ + select /*ant walks direction it's facing*/ + when dir==1 then y= y + 1 /*walking north? Then go "up". */ + when dir==2 then x= x + 1 /* " east? " " "right"*/ + when dir==3 then y= y - 1 /* " south? " " "down".*/ + when dir==4 then x= x - 1 /* " west? " " "left".*/ + end /*select*/ + end /*steps*/ /*───────────────────────────────────────────the ant is finished walking*/ -say center(" Langton's ant walked" steps 'steps. ',79,"─"); say - /*Display Langton's ant's trail. */ - do minx =lb to rb /*find leftmost non-blank column.*/ - do y=bb to tb /*search row by row for it. */ - if @.minx.y then leave minx /*found one, now quit searching. */ - end /*y*/ - end /*minx*/ /*above code crops left of array.*/ +say center(" Langton's ant walked" steps 'steps. ', 79, "─"); say + /* [↓] show Langton's ant's trail*/ + do minx =Lb to Rb /*find leftmost non─blank column.*/ + do y=Bb to Tb /*search row by row for the min. */ + if @.minx.y then leave minx /*found one, now quit searching. */ + end /*y*/ + end /*minx*/ /*above code crops left of array.*/ - do y=tb to bb by -1; _='' /*display a plane (row) of cells.*/ - do x=minx to rb /*process a "row" of cells. */ - _=_ || @.x.y /*build a cell row for display. */ - end /*x*/ - _=translate(_,'#',10) /*color the cells: black | white.*/ - if _\='' then say strip(_,'T') /*say line, strip trailing blanks*/ - end /*y*/ - /*stick a fork in it, we're done.*/ + do y=Tb to Bb by -1; _= /*display a plane (row) of cells.*/ + do x=minx to Rb; _=_ || @.x.y /*build a cell row for display. */ + end /*x*/ + _=strip(translate(_,char,10), 'T') /*color the cells: black | white.*/ + if _\=='' then say _ /*say line, strip trailing blanks*/ + end /*y*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Langtons-ant/Ruby/langtons-ant.rb b/Task/Langtons-ant/Ruby/langtons-ant-1.rb similarity index 100% rename from Task/Langtons-ant/Ruby/langtons-ant.rb rename to Task/Langtons-ant/Ruby/langtons-ant-1.rb diff --git a/Task/Langtons-ant/Ruby/langtons-ant-2.rb b/Task/Langtons-ant/Ruby/langtons-ant-2.rb new file mode 100644 index 0000000000..1f690d0719 --- /dev/null +++ b/Task/Langtons-ant/Ruby/langtons-ant-2.rb @@ -0,0 +1,27 @@ +class Ant + MOVE = [[1,0], [0,1], [-1,0], [0,-1]] # [0]:east, [1]:south, [2]:west, [3]:north + + def initialize(size_x, size_y, pos_x=size_x/2, pos_y=size_y/2) + @plane = Array.new(size_y) {Array.new(size_x, true)} # true -> white, false -> black + @sx, @sy = size_x, size_y + @px, @py = pos_x, pos_y # start position + @direction = 0 # south + @moves = 0 + move while (0 <= @px and @px < @sx) and (0 <= @py and @py < @sy) + end + + def move + @moves += 1 + @direction = (@plane[@py][@px] ? @direction+1 : @direction-1) % 4 + @plane[@py][@px] = !@plane[@py][@px] + @px += MOVE[@direction][0] + @py += MOVE[@direction][1] + end + + def to_s + ["out of bounds after #{@moves} moves: (#@px, #@py)"] + + (0...@sy).map {|y| (0...@sx).map {|x| @plane[y][x] ? "." : "#"}.join} + end +end + +puts Ant.new(100, 100).to_s diff --git a/Task/Langtons-ant/Rust/langtons-ant.rust b/Task/Langtons-ant/Rust/langtons-ant.rust new file mode 100644 index 0000000000..a8af4354e5 --- /dev/null +++ b/Task/Langtons-ant/Rust/langtons-ant.rust @@ -0,0 +1,76 @@ +struct Ant { + x: uint, + y: uint, + dir: Direction +} + +impl Ant { + fn move(&mut self, vec: &mut Vec>) { + + let pointer = vec.get_mut(self.y).get_mut(self.x); + //change direction + match *pointer { + 0 => self.dir = self.dir.right(), + 1 => self.dir = self.dir.left(), + _ => fail!("Unexpected colour in grid") + } + //flip colour + //if it's 1 it's black + //if it's 0 it's white + *pointer ^= 1; + + //move direction + match self.dir { + North => self.y -= 1, + South => self.y += 1, + East => self.x += 1, + West => self.x -= 1, + } + + } +} + +enum Direction { + North, + East, + South, + West +} + +impl Direction { + fn right(self) -> Direction { + match self { + North => East, + East => South, + South => West, + West => North, + } + } + + fn left(self) -> Direction { + //3 rights equal a left + self.right().right().right() + } +} + +fn main(){ + //create a 100x100 grid using vectors + let mut grid: Vec> = Vec::from_elem(100, Vec::from_elem(100, 0u8)); + let mut ant = Ant { + x: 50, y: 50, dir: North + }; + + while ant.x < 100 && ant.y < 100 { + ant.move(&mut grid); + } + for each in grid.iter() { + //construct string + //using iterator methods to quickly convert the vector + //to a string + let string = each.iter() + .map(|&x| String::from_byte(x+32)) + .fold(String::new(), |x, y| x+y) + .replace("!", "#"); + println!("{}", string); + } +} diff --git a/Task/Langtons-ant/Seed7/langtons-ant.seed7 b/Task/Langtons-ant/Seed7/langtons-ant.seed7 new file mode 100644 index 0000000000..e4d5b885b0 --- /dev/null +++ b/Task/Langtons-ant/Seed7/langtons-ant.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + +const type: direction is new enum UP, RIGHT, DOWN, LEFT end enum; + +const proc: main is func + local + const integer: width is 75; + const integer: height is 52; + var array array boolean: m is height times width times FALSE; + var direction: dir is UP; + var integer: x is width div 2; + var integer: y is height div 2; + begin + while x in {1 .. width} and y in {1 .. height} do + dir := direction conv ((ord(dir) + 2 * ord(m[y][x]) - 1) mod 4); + m[y][x] := not m[y][x]; + case dir of + when {UP}: decr(y); + when {RIGHT}: decr(x); + when {DOWN}: incr(y); + when {LEFT}: incr(x); + end case; + end while; + for key x range m do + for y range 1 to width do + write(".#"[succ(ord(m[x][y]))]); + end for; + writeln; + end for; + end func; diff --git a/Task/Largest-int-from-concatenated-ints/D/largest-int-from-concatenated-ints.d b/Task/Largest-int-from-concatenated-ints/D/largest-int-from-concatenated-ints.d index 88cbfd0f45..dfd4e43c37 100644 --- a/Task/Largest-int-from-concatenated-ints/D/largest-int-from-concatenated-ints.d +++ b/Task/Largest-int-from-concatenated-ints/D/largest-int-from-concatenated-ints.d @@ -1,17 +1,17 @@ import std.stdio, std.algorithm, std.conv, std.array, permutations2; -auto maxCat1(in int[] arr) { +auto maxCat1(in int[] arr) pure @safe { return arr.to!(string[]).permutations.map!join.reduce!max; } -auto maxCat2(in int[] arr) { +auto maxCat2(in int[] arr) pure nothrow @safe { return arr.to!(string[]).sort!q{b ~ a < a ~ b}.join; } -auto maxCat3(in int[] arr) { - immutable maxl = arr.reduce!max.text.length; +auto maxCat3(in int[] arr) /*pure nothrow @safe*/ { + immutable maxL = arr.reduce!max.text.length; return arr.to!(string[]) - .schwartzSort!(s => s.replicate(maxl/s.length + 1), "a > b") + .schwartzSort!(s => s.replicate(maxL/s.length + 1), "a > b") .join; } diff --git a/Task/Largest-int-from-concatenated-ints/Lua/largest-int-from-concatenated-ints.lua b/Task/Largest-int-from-concatenated-ints/Lua/largest-int-from-concatenated-ints.lua new file mode 100644 index 0000000000..cee3b524e6 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Lua/largest-int-from-concatenated-ints.lua @@ -0,0 +1,10 @@ +function icsort(numbers) + table.sort(numbers,function(x,y) return (x..y) > (y..x) end) + return numbers +end + +for _,numbers in pairs({{1, 34, 3, 98, 9, 76, 45, 4}, {54, 546, 548, 60}}) do + print(('Numbers: {%s}\n Largest integer: %s'):format( + table.concat(numbers,","),table.concat(icsort(numbers)) + )) +end diff --git a/Task/Largest-int-from-concatenated-ints/Mathematica/largest-int-from-concatenated-ints.math b/Task/Largest-int-from-concatenated-ints/Mathematica/largest-int-from-concatenated-ints.math new file mode 100644 index 0000000000..656461199e --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Mathematica/largest-int-from-concatenated-ints.math @@ -0,0 +1,7 @@ +makeLargestInt[list_] := Module[{sortedlist}, + sortedlist = Sort[list, Order[ToString[#1] <> ToString[#2], ToString[#2] <> ToString[#1]] < 0 &]; + Map[ToString, sortedlist] // StringJoin // FromDigits + ] +(* testing with two examples *) +makeLargestInt[{1, 34, 3, 98, 9, 76, 45, 4}] +makeLargestInt[{54, 546, 548, 60}] diff --git a/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-1.pascal b/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-1.pascal new file mode 100644 index 0000000000..5943d1d8da --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-1.pascal @@ -0,0 +1,139 @@ +const + base = 10; + MaxDigitCnt = 11; + source1 : array[0..7] of integer = (1, 34, 3, 98, 9, 76, 45, 4); + source2 : array[0..3] of integer = (54,546,548,60); + source3 : array[0..3] of integer = (60, 54,545454546,0); + +type + tdata = record + datOrg, + datMod : LongWord; + datStrOrg : string[MaxDigitCnt]; + end; + tArrData = array of tData; + +procedure DigitCount(var n: tdata); +begin + with n do + //InttoStr is very fast + str(datOrg,datStrOrg); + +end; + +procedure InsertData(var n: tdata;data:LongWord); +begin + n.datOrg := data; + DigitCount(n); +end; + +function FindMaxLen(const ArrData:tArrData): LongWord; +var + cnt : longInt; + res,t : LongWord; +begin + res := 0;// 1 is minimum + for cnt := High(ArrData) downto Low(ArrData) do + begin + t := length(ArrData[cnt].datStrOrg); + IF res < t then + res := t; + end; + FindMaxLen := res; +end; + +procedure ExtendCount(var ArrData:tArrData;newLen: integer); +var + cnt, + i,k : integer; +begin + For cnt := High(ArrData) downto Low(ArrData) do + with ArrData[cnt] do + begin + datMod := datOrg; + i := newlen-length(datStrOrg); + k := 1; + while i > 0 do + begin + datMod := datMod *Base+Ord(datStrOrg[k])-Ord('0'); + inc(k); + IF k >length(datStrOrg) then + k := 1; + dec(i); + end; + end; +end; + +procedure SortArrData(var ArrData:tArrData); +var + i, + j,idx : integer; + tmpData : tData; +begin + For i := High(ArrData) downto Low(ArrData)+1 do + begin + idx := i; + j := i-1; + For j := j downto Low(ArrData) do + IF ArrData[idx].datMod < ArrData[j].datMod then + idx := j; + IF idx <> i then + begin + tmpData := ArrData[idx]; + ArrData[idx]:= ArrData[i]; + ArrData[i] := tmpData; + end; + end; +end; + +procedure ArrDataOutput(const ArrData:tArrData); +var + i,l : integer; + s : string; +begin +{ the easy way + For i := High(ArrData) downto Low(ArrData) do + write(ArrData[i].datStrOrg); + writeln; + *} + l := 0; + For i := High(ArrData) downto Low(ArrData) do + inc(l,length(ArrData[i].datStrOrg)); + setlength(s,l); + l:= 1; + For i := High(ArrData) downto Low(ArrData) do + with ArrData[i] do + begin + move(datStrOrg[1],s[l],length(datStrOrg)); + inc(l,length(datStrOrg)); + end; + writeln(s); +end; + +procedure HighestInt(var ArrData:tArrData); +begin + ExtendCount(ArrData,FindMaxLen(ArrData)); + SortArrData(ArrData); + ArrDataOutput(ArrData); +end; + +var + i : integer; + tmpData : tArrData; +begin + // Source1 + setlength(tmpData,length(source1)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source1[i]); + HighestInt(tmpData); + // Source2 + setlength(tmpData,length(source2)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source2[i]); + HighestInt(tmpData); + // Source3 + setlength(tmpData,length(source3)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source3[i]); + HighestInt(tmpData); +end. diff --git a/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-2.pascal b/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-2.pascal new file mode 100644 index 0000000000..eb4b9846c8 --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Pascal/largest-int-from-concatenated-ints-2.pascal @@ -0,0 +1,126 @@ +const + base = 10; + MaxDigitCnt = 11; + source1 : array[0..7] of LongInt = (10 , 34, 3, 98, 9, 76, 45, 4); + source2 : array[0..3] of LongInt = (54,546,548,60); + source3 : array[0..3] of LongInt = (0,2121212122,21,60); + +type + tdata = record + datMod : double; + datOrg : LongInt; +//InttoStr is very fast and the string is always needed + datStrOrg : string[MaxDigitCnt]; + end; + tArrData = array of tData; + +procedure InsertData(var n: tdata;data:LongWord); +begin + with n do + begin + datOrg := data; + str(datOrg,datStrOrg); + end; +end; + +function FindMaxLen(const ArrData:tArrData): LongWord; +var + cnt : longInt; + res,t : LongWord; +begin + res := 0;// 1 is minimum + for cnt := High(ArrData) downto Low(ArrData) do + begin + t := length(ArrData[cnt].datStrOrg); + IF res < t then + res := t; + end; + FindMaxLen := res; +end; + +procedure ExtendData(var ArrData:tArrData;newLen: integer); +var + cnt, + i : integer; +begin + For cnt := High(ArrData) downto Low(ArrData) do + with ArrData[cnt] do + begin + //generating 10^length(datStrOrg) + datMod := 1; + i := length(datStrOrg); + // i always >= 1 + repeat + datMod := base*datMod; + dec(i); + until i <= 0; +// 1/(datMod-1.0) = 1/(9...9) + datMod := datOrg/(datMod-1.0)+datOrg; + i := newlen-length(datStrOrg); + For i := i downto 1 do + datMod := datMod*Base; + end; +end; + +procedure SortArrData(var ArrData:tArrData); +//selection sort +var + i, + j,idx : integer; + tmpData : tData; +begin + For i := High(ArrData) downto Low(ArrData)+1 do + begin + idx := i; + j := i-1; + //select max + For j := j downto Low(ArrData) do + IF ArrData[idx].datMod < ArrData[j].datMod then + idx := j; + //finally swap + IF idx <> i then + begin + tmpData := ArrData[idx]; + ArrData[idx]:= ArrData[i]; + ArrData[i] := tmpData; + end; + end; +end; + +procedure ArrDataOutput(const ArrData:tArrData); +var + i : integer; +begin +{ the easy way} + For i := High(ArrData) downto Low(ArrData) do + write(ArrData[i].datStrOrg); + writeln; +end; + +procedure HighestInt(var ArrData:tArrData); +begin + ExtendData(ArrData,FindMaxLen(ArrData)); + SortArrData(ArrData); + ArrDataOutput(ArrData); +end; + +var + i : integer; + tmpData : tArrData; +begin + // Source1 + setlength(tmpData,length(source1)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source1[i]); + HighestInt(tmpData); + // Source2 + setlength(tmpData,length(source2)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source2[i]); + HighestInt(tmpData); + // Source3 + setlength(tmpData,length(source3)); + For i := low(tmpData) to high(tmpData) do + InsertData(tmpData[i],source3[i]); + HighestInt(tmpData); +end. 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 4769ffea14..6e9ec4f58f 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 @@ -1,24 +1,31 @@ /*REXX pgm constructs largest integer from a list using concatenation.*/ @. = /*used to signify end-of-lists. */ -@.1 = '{1, 34, 3, 98, 9, 76, 45, 4}' -@.2 = '{54, 546, 548, 60}' - /* [↓] process all the lists. */ - do j=1 while @.j\==''; $= /*keep truckin' until exausted. */ - z=space(translate(@.j, , '])},{([')) /*perform some scrubbing on list.*/ +@.1 = '{1, 34, 3, 98, 9, 76, 45, 4}' /*the first list of integers. */ +@.2 = '{54, 546, 548, 60}' /* " second " " " */ +@.3 = '{ 4, 45, 54, 5}' /* " third " " " */ + /* [↓] process all the lists. */ + do j=1 while @.j\==''; $= /*keep truckin' until exhausted. */ + z=space(translate(@.j, , '])},{([')) /*perform scrubbing on the list. */ + _=length(space(z,0)) + 1 /*determine the largest possible#*/ + if _>digits() then numeric digits _ /*ensure 'nuff digits for the #. */ + /* [↓] examine each num in list.*/ + do while z\==''; index=1 /*keep examining list until done.*/ + big=isOK(word(z,1)) /*assume first number is biggest.*/ - 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=isOK(word(z,k)) /*get an integer.*/ + x1=left(x,1); L=max(length(big), length(x)) /*get max length.*/ + if left(x, L, x1) <<= left(big, L, left(big,1)) then iterate + big=x; index=k /*we found a new biggie (& index)*/ + end /*k*/ /* [↑] find max concatenated int*/ - 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=space(delword(z, index, 1)) /*remove the "maximum" from list.*/ + $=$ || big /*append the "maximum" number. */ + end /*while z ···*/ /* [↑] process all nums in list.*/ - z=space(delword(z, index, 1)) /*remove the "maximum" from list*/ - $=$ || big /*append the "maximum" number. */ - end /*while z¬==''*/ + say right($,digits()) ' max for: ' @.j /*show max integer & list.*/ + end /*j*/ /* [↑] process each list of nums*/ - say right($,30) ' max for: ' @.j /*show the "max" integer and list*/ - end /*j*/ - /*stick a fork in it, we're done.*/ +exit /*stick a fork in it, we're done.*/ +/*───────────────────────────────────ISOK subroutine────────────────────*/ +isOK: parse arg ?; if datatype(?,'W') then return abs(?)/1 /*normalize*/ +say; say '***error!*** number ' ? "isn't an integer."; say; exit 13 diff --git a/Task/Largest-int-from-concatenated-ints/Scala/largest-int-from-concatenated-ints.scala b/Task/Largest-int-from-concatenated-ints/Scala/largest-int-from-concatenated-ints.scala index 4ed031544e..5011677a75 100644 --- a/Task/Largest-int-from-concatenated-ints/Scala/largest-int-from-concatenated-ints.scala +++ b/Task/Largest-int-from-concatenated-ints/Scala/largest-int-from-concatenated-ints.scala @@ -1,4 +1,7 @@ object LIFCI extends App { - List(List(1, 34, 3, 98, 9, 76, 45, 4), List(54, 546, 548, 60)).map{l=>l.permutations.toList - .map{l=>(l.map{_.toString}:\"")(_+_).toLong}.sorted.last}.foreach{println} + + def lifci(list: List[Long]) = list.permutations.map(_.mkString).max + + println(lifci(List(1, 34, 3, 98, 9, 76, 45, 4))) + println(lifci(List(54, 546, 548, 60))) } diff --git a/Task/Largest-int-from-concatenated-ints/Scheme/largest-int-from-concatenated-ints.ss b/Task/Largest-int-from-concatenated-ints/Scheme/largest-int-from-concatenated-ints.ss new file mode 100644 index 0000000000..964a3d02ed --- /dev/null +++ b/Task/Largest-int-from-concatenated-ints/Scheme/largest-int-from-concatenated-ints.ss @@ -0,0 +1,6 @@ +(define (cat . nums) (apply string-append (map number->string nums))) + +(define (my-compare a b) (string>? (cat a b) (cat b a))) + +(map (lambda (xs) (string->number (apply cat (sort xs my-compare)))) + '((1 34 3 98 9 76 45 4) (54 546 548 60))) diff --git a/Task/Last-Friday-of-each-month/00DESCRIPTION b/Task/Last-Friday-of-each-month/00DESCRIPTION index 35dbeaf063..2d440ae9c3 100644 --- a/Task/Last-Friday-of-each-month/00DESCRIPTION +++ b/Task/Last-Friday-of-each-month/00DESCRIPTION @@ -1,4 +1,6 @@ -Write a program or a script that returns the last Fridays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc.). +Write a program or a script that returns the last Fridays of each month of a given year. + +The year may be given through any simple input method in your language (command line, std in, etc.). Example of an expected output: diff --git a/Task/Last-Friday-of-each-month/00META.yaml b/Task/Last-Friday-of-each-month/00META.yaml new file mode 100644 index 0000000000..e71737a981 --- /dev/null +++ b/Task/Last-Friday-of-each-month/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Date and time diff --git a/Task/Last-Friday-of-each-month/Clojure/last-friday-of-each-month.clj b/Task/Last-Friday-of-each-month/Clojure/last-friday-of-each-month.clj new file mode 100644 index 0000000000..77d6693bce --- /dev/null +++ b/Task/Last-Friday-of-each-month/Clojure/last-friday-of-each-month.clj @@ -0,0 +1,11 @@ +(use '[clj-time.core :only [last-day-of-the-month day-of-week minus days]] + '[clj-time.format :only [unparse formatters]]) + +(defn last-fridays [year] + (let [last-days (map #(last-day-of-the-month year %) (range 1 13 1)) + dow (map day-of-week last-days) + relation (zipmap last-days dow)] + (map #(minus (key %) (days (mod (+ (val %) 2) 7))) relation))) + +(defn last-fridays-formatted [year] + (sort (map #(unparse (formatters :year-month-day) %) (last-fridays year)))) diff --git a/Task/Last-Friday-of-each-month/Common-Lisp/last-friday-of-each-month.lisp b/Task/Last-Friday-of-each-month/Common-Lisp/last-friday-of-each-month.lisp new file mode 100644 index 0000000000..bf61cba48b --- /dev/null +++ b/Task/Last-Friday-of-each-month/Common-Lisp/last-friday-of-each-month.lisp @@ -0,0 +1,14 @@ +(defun friday-before (year month day) + (let* + ((timestamp (encode-universal-time 0 0 12 day month year)) + (weekday (nth 6 (multiple-value-list (decode-universal-time timestamp)))) + (fri (- timestamp (* (+ (mod (+ weekday 2) 7) 1) 86400)))) + (multiple-value-bind (_ _ _ d m y) (decode-universal-time fri) + (list y m d)))) + +(defun last-fridays (year) + (append (loop for month from 2 to 12 collecting (friday-before year month 1)) + (list (friday-before (1+ year) 1 1)))) + +(let* ((year (read-from-string (car *args*)))) + (format t "~{~{~a-~2,'0d-~2,'0d~}~%~}" (last-fridays year))) diff --git a/Task/Last-Friday-of-each-month/Go/last-friday-of-each-month.go b/Task/Last-Friday-of-each-month/Go/last-friday-of-each-month.go index 3ba6c7e87c..573253a574 100644 --- a/Task/Last-Friday-of-each-month/Go/last-friday-of-each-month.go +++ b/Task/Last-Friday-of-each-month/Go/last-friday-of-each-month.go @@ -1,22 +1,22 @@ package main import ( - "fmt" - "os" - "strconv" - "time" + "fmt" + "os" + "strconv" + "time" ) func main() { - y := time.Now().Year() - if len(os.Args) == 2 { - if i, err := strconv.Atoi(os.Args[1]); err == nil { - y = i - } - } - for m := time.January; m <= time.December; m++ { - d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour) - d = d.Add(-time.Duration((d.Weekday() + 2) % 7) * 24 * time.Hour) - fmt.Println(d.Format("2006-01-02")) - } + y := time.Now().Year() + if len(os.Args) == 2 { + if i, err := strconv.Atoi(os.Args[1]); err == nil { + y = i + } + } + for m := time.January; m <= time.December; m++ { + d := time.Date(y, m+1, 1, 0, 0, 0, 0, time.UTC).Add(-24 * time.Hour) + d = d.Add(-time.Duration((d.Weekday()+7-time.Friday)%7) * 24 * time.Hour) + fmt.Println(d.Format("2006-01-02")) + } } diff --git a/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs b/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs new file mode 100644 index 0000000000..fa92c41cae --- /dev/null +++ b/Task/Last-Friday-of-each-month/Haskell/last-friday-of-each-month.hs @@ -0,0 +1,26 @@ +module Rosettatask + where +import Data.Time.Calendar +import Data.Time.Calendar.WeekDate + +findFriday :: Day -> Day +findFriday date = head $ filter isFriday $ map toDate [0, -1 .. -7] + where + toDate :: Integer -> Day + toDate ago = addDays ago date + isFriday :: Day -> Bool + isFriday theDate = d == 5 + where + (_ , _ , d ) = toWeekDate theDate + +fridayDates :: Integer -> [String] +fridayDates year = map ( showGregorian . findFriday ) lastDaysInMonth + where + lastDaysInMonth = map findLastDay [1 .. 12] + findLastDay month = fromGregorian year month ( gregorianMonthLength + year month ) + +main = do + putStrLn "Please enter a year!" + year <- getLine + mapM_ putStrLn $ fridayDates ( read year ) diff --git a/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-1.rebol b/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-1.rebol new file mode 100644 index 0000000000..0b9c12afe9 --- /dev/null +++ b/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-1.rebol @@ -0,0 +1,22 @@ +leap-year?: function [year] [to-logic attempt [to-date reduce [29 2 year]]] + +days-in-feb: function [year] [either leap-year? year [29] [28]] + +days-in-month: function [month year] [ + do pick [31 (days-in-feb year) 31 30 31 30 31 31 30 31 30 31] month +] + +last-day-of-month: function [month year] [ + to-date reduce [year month days-in-month month year] +] + +last-weekday-of-month: function [weekday month year] [ + d: last-day-of-month month year + while [d/weekday != weekday] [d/day: d/day - 1] + d +] + +last-friday-of-month: function [month year] [last-weekday-of-month 5 month year] + +year: to-integer input +repeat month 12 [print last-friday-of-month month year] diff --git a/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-2.rebol b/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-2.rebol new file mode 100644 index 0000000000..459507cdd9 --- /dev/null +++ b/Task/Last-Friday-of-each-month/REBOL/last-friday-of-each-month-2.rebol @@ -0,0 +1,12 @@ +last-fridays-of-year: function [year] [ + collect [ + repeat month 12 [ + d: to-date reduce [1 month year] + d/month: d/month + 1 ; start of next month + until [d/day: d/day - 1 d/weekday = 5] ; go backwards until find a Friday + keep d + ] + ] +] + +foreach friday last-fridays-of-year to-integer input [print friday] diff --git a/Task/Last-Friday-of-each-month/Racket/last-friday-of-each-month.rkt b/Task/Last-Friday-of-each-month/Racket/last-friday-of-each-month.rkt new file mode 100644 index 0000000000..1534aab91d --- /dev/null +++ b/Task/Last-Friday-of-each-month/Racket/last-friday-of-each-month.rkt @@ -0,0 +1,41 @@ +#lang racket +(require srfi/19 math) + +(define (days-in-month m y) + (define lengths #(0 31 #f 31 30 31 30 31 31 30 31 30 31)) + (define d (vector-ref lengths m)) + (or d (days-in-feb y))) + +(define (leap-year? y) + (and (divides? 4 y) + (or (not (divides? 100 y)) + (divides? 400 y)))) + +(define (days-in-feb y) + (if (leap-year? y) 29 28)) + +(define (last-day-in-month m y) + (make-date 0 0 0 0 (days-in-month m y) m y 0)) + +(define (week-day date) + (define days #(sun mon tue wed thu fri sat)) + (vector-ref days (date-week-day date))) + +(define (last-fridays y) + (for/list ([m (in-range 1 13)]) + (prev-friday (last-day-in-month m y)))) + +(define 24hours (make-time time-duration 0 (* 24 60 60))) + +(define (prev-day d) + (time-utc->date + (subtract-duration + (date->time-utc d) 24hours))) + +(define (prev-friday d) + (if (eq? (week-day d) 'fri) + d + (prev-friday (prev-day d)))) + +(for ([d (last-fridays 2012)]) + (displayln (~a (date->string d "~a ~d ~b ~Y")))) diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d index 638de2daa2..479a12d3f7 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-1.d @@ -1,18 +1,23 @@ import std.stdio, std.algorithm, std.string; -void search(string[] items, in int len, ref string[] longest) pure { +void trySwap(string[] items, ref string item, in size_t len, ref string[] longest) +pure nothrow @safe { + swap(items[len], item); + search(items, len + 1, longest); + swap(items[len], item); +} + +void search(string[] items, in size_t len, ref string[] longest) +pure nothrow @safe { if (len > longest.length) longest = items[0 .. len].dup; immutable lastChar = items[len - 1][$ - 1]; foreach (ref item; items[len .. $]) - if (item[0] == lastChar) { - swap(items[len], item); - search(items, len + 1, longest); - swap(items[len], item); - } + if (item[0] == lastChar) + trySwap(items, item, len, longest); } -void main() { +void main() @safe { auto pokemon = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor @@ -25,11 +30,8 @@ tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask".split; string[] solution; - foreach (ref name; pokemon) { - swap(pokemon[0], name); - search(pokemon, 1, solution); - swap(pokemon[0], name); - } + foreach (ref name; pokemon) + trySwap(pokemon, name, 0, solution); writefln("%-(%s\n%)", solution); } diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d index a497f6ba3f..942bd9003b 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-4.d @@ -1,14 +1,14 @@ import std.stdio, std.algorithm, std.string, std.range, std.typecons; Tuple!(uint, string[]) findLongestChain(in string[] words) -pure /*nothrow*/ { +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) /*nothrow*/ { + ref string[] longestPath) nothrow { currentPath[currentPathLen] = currWord; currentPathLen++; @@ -16,7 +16,7 @@ pure /*nothrow*/ { nSolutions++; } else if (currentPathLen > longestPath.length) { nSolutions = 1; - longestPath = currentPath[0 .. currentPathLen].dup;//Throw. + longestPath = currentPath[0 .. currentPathLen].dup; } // Recursive search. @@ -31,12 +31,16 @@ pure /*nothrow*/ { } } - auto heads = words.map!q{ a[0] }; - //immutable {minHead, maxHead} = heads.reduce!(min, max); - immutable minHead = heads.reduce!min; - immutable maxHead = heads.reduce!max; + if (words.empty) + typeof(return)(0, null); + immutable heads = words.map!q{ a[0] }.array; + immutable size_t minHead = reduce!min(heads[0], + heads[1.. $].representation); + immutable size_t maxHead = reduce!max(heads[0], + heads[1.. $].representation); + auto sequences = new Pair[][](maxHead - minHead + 1, 0); - foreach (word; words) + foreach (const word; words) sequences[word[0] - minHead] ~= Pair(word, true); auto currentPath = new string[words.length]; @@ -54,6 +58,7 @@ pure /*nothrow*/ { return typeof(return)(nSolutions, longestPath); } + void main() { auto pokemon = "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino diff --git a/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d b/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d index 39a48f1ba0..a08ff71ad1 100644 --- a/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d +++ b/Task/Last-letter-first-letter/D/last-letter-first-letter-5.d @@ -1,32 +1,31 @@ import std.stdio, std.algorithm, std.array, std.typecons, std.container, std.range; -string[] findChain(in string[] seq) /*pure nothrow*/ { +auto findChain(in string[] seq) pure nothrow /*@safe*/ { const adj = seq - .map!(item => tuple(item, - seq - .filter!(x => x[0] == item[$-1]) - .array)) + .map!(item => tuple(item, seq + .filter!(x => x[0] == item[$ - 1]) + .array)) .assocArray; - string[] res; + SList!string res; - foreach (immutable item; adj.byKey) { // Not nothrow. - void inner(in string item, SList!string lst) nothrow { - lst.insertFront(item); - if (lst[].walkLength > res.length) - res = lst.array; - foreach (immutable x; adj[item]) + foreach (immutable item; adj.byKey) { + void inner(in string it, SList!string lst) nothrow { + lst.insertFront(it); + if (lst[].walkLength > res[].walkLength) + res = lst; + foreach (immutable x; adj[it]) if (!lst[].canFind(x)) inner(x, lst); } + inner(item, SList!string()); } - res.reverse(); - return res; + return res.array.retro; } -void main() { +void main() /*@safe*/ { "audino bagon baltoy banette bidoof braviary bronzor carracosta charmeleon cresselia croagunk darmanitan deino emboar emolga exeggcute gabite girafarig gulpin haxorus heatmor diff --git a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx index 546b704bba..36abde7f8a 100644 --- a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx +++ b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-1.rexx @@ -6,16 +6,16 @@ 'remoraid rufflet sableye scolipede scrafty seaking sealeo silcoon simisear snivy snorlax spoink', 'starly tirtouga trapinch treecko tyrogue vigoroth vulpix wailord wartortle whismur wingull yamask' #=words(@) -parse arg limit .; if limit\=='' then #=limit /*allow a scan limit.*/ +parse arg limit .; if limit\=='' then #=limit /*allow a scan limit.*/ @.=; $$$= /*nullify array, and longest path*/ - do i=1 for # /*build a stemmed array from list*/ + do i=1 for # /*build a stemmed array from list*/ @.i=word(@,i) end /*i*/ soFar=0 /*the initial maximum path length*/ - do j=1 for # - parse value @.1 @.j with @.j @.1 + do j=1 for # + parse value @.1 @.j with @.j @.1 call scanner $$$,2 - parse value @.1 @.j with @.j @.1 + parse value @.1 @.j with @.j @.1 end /*j*/ L=words($$$) say 'Of' # "words," MP 'path's(MP) "have the maximum path length of" L'.' @@ -23,7 +23,7 @@ say; say 'One example path of that length is:' do m=1 for L; say left('',39) word($$$,m); end /*m*/ 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) +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*──────────────────────────────────SCANNER subroutine (recursive)──────*/ scanner: procedure expose @. MP # soFar $$$; parse arg $$$,!; _=!-1 lastChar=right(@._,1) /*last char of penultimate word. */ @@ -31,17 +31,17 @@ lastChar=right(@._,1) /*last char of penultimate word. */ do i=! to # /*scan for the longest word path.*/ if left(@.i,1)==lastChar then /*is the first-char = last-char? */ do - if !==soFar then MP=MP+1 /*bump the maximum paths counter.*/ - else if !>soFar then do; $$$=@.1 /*rebuild it*/ - do n=2 to !-1 - $$$=$$$ @.n - end /*n*/ - $$$=$$$ @.i /*add last. */ - MP=1; soFar=! /*new path. */ - end - parse value @.! @.i with @.i @.! - call scanner $$$,!+1 /*recursive scan for longest path*/ - parse value @.! @.i with @.i @.! + if !==soFar then MP=MP+1 /*bump the maximum paths counter.*/ + else if !>soFar then do; $$$=@.1 /*rebuild.*/ + do n=2 to !-1 + $$$=$$$ @.n + end /*n*/ + $$$=$$$ @.i /*add last*/ + MP=1; soFar=! /*new path*/ + end + parse value @.! @.i with @.i @.! + call scanner $$$, !+1 /*recursive scan for longest path*/ + parse value @.! @.i with @.i @.! end end /*i*/ return /*exhausted this particular scan.*/ diff --git a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx index 7411f71a43..5789144035 100644 --- a/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx +++ b/Task/Last-letter-first-letter/REXX/last-letter-first-letter-2.rexx @@ -8,60 +8,61 @@ #=words(@) parse arg limit .; if limit\=='' then #=limit /*allow a scan limit.*/ @.=; $$$=; ig=0 /*nullify array and longest path.*/ -call build@. - do v=# by -1 for # /*scrub list for unusuable words.*/ - F= left(@.v,1) /*first letter of the word. */ - L=right(@.v,1) /* last " " " " */ - if !.1.F>1 | !.9.L>1 then iterate /*is a dead word?*/ - @=delword(@,v,1) /*delete from @. */ - say 'ignorning dead word:' @.v; ig=ig+1 - end /*v*/ +call build@. /*build a stemmed array from list*/ + do v=# by -1 for # /*scrub list for unusuable words.*/ + F= left(@.v,1) /*first letter of the word. */ + L=right(@.v,1) /* last " " " " */ + if !.1.F>1 | !.9.L>1 then iterate /*is a dead word?*/ + @=delword(@,v,1) /*delete from @. */ + say 'ignorning dead word:' @.v; ig=ig+1 + end /*v*/ + if ig\==0 then do call build@. say; say 'ignoring' ig "dead word"s(ig)'.'; say end soFar=0 /*the initial maximum path length*/ - do j=1 for # - parse value @.1 @.j with @.j @.1 - call scanner $$$,2 - parse value @.1 @.j with @.j @.1 - end /*j*/ + do j=1 for # + parse value @.1 @.j with @.j @.1 + call scanner $$$,2 + parse value @.1 @.j with @.j @.1 + end /*j*/ g=words($$$) -say 'Of' # "words," MP 'path's(MP) "have the maximum path length of" g'.' -say; say 'One example path of that length is:' - - do m=1 for g /*display a list of words. */ +say 'Of' # "words," MP 'path's(MP) "have the maximum path length of" g'.' +say; say 'One example path of that length is:' + do m=1 for g /*display a list of words to term*/ say left('',39) word($$$,m) end /*m*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BUILD suroutine─────────────────────*/ -build@.: !.=0; do i=1 for # /*build a stemmed array from list*/ +build@.: !.=0; do i=1 for # /*build a stemmed array from list*/ @.i=word(@,i) F= left(@.i,1); !.1.F=!.1.F+1 /*count 1st chars*/ L=right(@.i,1); !.9.L=!.9.L+1 /*count last chars*/ end /*i*/ return /*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*──────────────────────────────────SCANNER subroutine (recursive)──────*/ scanner: procedure expose @. MP # !. soFar $$$; parse arg $$$,!; _=!-1 lastChar=right(@._,1) /*last char of penultimate word. */ -if !.1.lastchar==0 then return /*is this a dead-end word ? */ +if !.1.lastchar==0 then return /*is this a dead-end word? */ do i=! to # /*scan for the longest word path.*/ if left(@.i,1)==lastChar then /*is the first-char = last-char? */ do if !==soFar then MP=MP+1 /*bump the maximum paths counter.*/ - else if !>soFar then do; $$$=@.1 /*rebuild it*/ - do n=2 to !-1 - $$$=$$$ @.n - end /*n*/ - $$$=$$$ @.i /*add last. */ - MP=1; soFar=! /*new path. */ - end - parse value @.! @.i with @.i @.! + else if !>soFar then do; $$$=@.1 /*rebuild it*/ + do n=2 to !-1 + $$$=$$$ @.n + end /*n*/ + $$$=$$$ @.i /*add last. */ + MP=1; soFar=! /*new path. */ + end + parse value @.! @.i with @.i @.! call scanner $$$,!+1 /*recursive scan for longest path*/ - parse value @.! @.i with @.i @.! + parse value @.! @.i with @.i @.! end end /*i*/ + return /*exhausted this particular scan.*/ diff --git a/Task/Last-letter-first-letter/Scala/last-letter-first-letter-1.scala b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-1.scala new file mode 100644 index 0000000000..9152236017 --- /dev/null +++ b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-1.scala @@ -0,0 +1,21 @@ +object LastLetterFirstLetterNaive extends App { + def solve(names: Set[String]) = { + def extend(solutions: List[List[String]]): List[List[String]] = { + val more = solutions.flatMap{solution => + val lastLetter = solution.head takeRight 1 + (names -- solution).filter(_.take(1) equalsIgnoreCase lastLetter).map(_ :: solution) + } + if (more.isEmpty) solutions else extend(more) + } + + extend(names.toList.map(List(_))).map(_.reverse) + } + + val names70 = Set("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") + + val solutions = solve(names70) + println(s"Maximum path length: ${solutions.head.length}") + println(s"Paths of that length: ${solutions.size}") + println("Example path of that length:") + println(solutions.head.sliding(7,7).map(_.mkString(" ")).map(" "+_).mkString("\n")) +} diff --git a/Task/Last-letter-first-letter/Scala/last-letter-first-letter-2.scala b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-2.scala new file mode 100644 index 0000000000..26cb9777f4 --- /dev/null +++ b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-2.scala @@ -0,0 +1,26 @@ +object LastLetterFirstLetterLookup extends App { + def solve(names: Set[String]) = { + val transitions = { + val startsWith = names.groupBy(_.take(1).toLowerCase).withDefaultValue(Set.empty) + names.map{name => name -> startsWith(name.takeRight(1).toLowerCase)}.toMap + } + + def extend(solutions: List[List[String]]): List[List[String]] = + solutions.flatMap{solution => + (transitions(solution.head) -- solution).map(_ :: solution) + } match { + case Nil => solutions + case more => extend(more) + } + + extend(names.toList.map(List(_))).map(_.reverse) + } + + val names70 = Set("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") + + val solutions = solve(names70) + println(s"Maximum path length: ${solutions.head.length}") + println(s"Paths of that length: ${solutions.size}") + println("Example path of that length:") + println(solutions.head.sliding(7,7).map(_.mkString(" ")).map(" "+_).mkString("\n")) +} diff --git a/Task/Last-letter-first-letter/Scala/last-letter-first-letter-3.scala b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-3.scala new file mode 100644 index 0000000000..53c625442a --- /dev/null +++ b/Task/Last-letter-first-letter/Scala/last-letter-first-letter-3.scala @@ -0,0 +1,27 @@ +object LastLetterFirstLetterLookupParallel extends App { + def solve(names: Set[String]) = { + val transitions = { + val startsWith = names.groupBy(_.take(1).toLowerCase).withDefaultValue(Set.empty) + names.map{name => name -> startsWith(name.takeRight(1).toLowerCase)}.toMap + } + + import scala.collection.parallel.immutable.ParSeq + def extend(solutions: ParSeq[List[String]]): ParSeq[List[String]] = + solutions.flatMap{solution => + (transitions(solution.head) -- solution).map(_ :: solution) + } match { + case seq if seq.isEmpty => solutions + case more => extend(more) + } + + extend(names.toList.map(List(_)).par).map(_.reverse) + } + + val names70 = Set("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") + + val solutions = solve(names70) + println(s"Maximum path length: ${solutions.head.length}") + println(s"Paths of that length: ${solutions.size}") + println("Example path of that length:") + println(solutions.head.sliding(7,7).map(_.mkString(" ")).map(" "+_).mkString("\n")) +} diff --git a/Task/Leap-year/Ada/leap-year.ada b/Task/Leap-year/Ada/leap-year.ada index 6d9e9e4805..8669c84a08 100644 --- a/Task/Leap-year/Ada/leap-year.ada +++ b/Task/Leap-year/Ada/leap-year.ada @@ -10,12 +10,26 @@ begin end Is_Leap_Year; --- Should be faster without conditional and only one remainder (the other two are really binary and) +-- An enhanced, more efficient version: +-- This version only does the 2 bit comparison (rem 4) if false. +-- It then checks rem 16 (a 4 bit comparison), and only if those are not +-- conclusive, calls rem 100, which is the most expensive operation. +-- I failed to be convinced of the accuracy of the algorithm at first, +-- so I rephrased it below. +-- FYI: 400 is evenly divisible by 16 whereas 100,200 and 300 are not. Ergo, the +-- set of integers evenly divisible by 16 and 100 are all evenly divisible by 400. +-- 1. If a year is not divisible by 4 => not a leap year. Skip other checks. +-- 2. If a year is evenly divisible by 16, it is either evenly divisible by 400 or +-- not evenly divisible by 100 => leap year. Skip further checks. +-- 3. If a year evenly divisible by 100 => not a leap year. +-- 4. Otherwise a leap year. + function Is_Leap_Year (Year : Integer) return Boolean is begin - return (Year rem 4 = 0) and ((Year rem 100 /= 0) or (Year rem 16 = 0)); + return (Year rem 4 = 0) and then ((Year rem 16 = 0) or else (Year rem 100 /= 0)); end Is_Leap_Year; + -- To improve speed a bit more, use with pragma Inline (Is_Leap_Year); diff --git a/Task/Leap-year/C++/leap-year.cpp b/Task/Leap-year/C++/leap-year.cpp new file mode 100644 index 0000000000..db46e39651 --- /dev/null +++ b/Task/Leap-year/C++/leap-year.cpp @@ -0,0 +1,11 @@ +#include + +bool is_leap_year(int year) { + return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); +} + +int main() { + for (auto year : {1900, 1994, 1996, 1997, 2000}) { + std::cout << year << (is_leap_year(year) ? " is" : " is not") << " a leap year.\n"; + } +} diff --git a/Task/Leap-year/C/leap-year.c b/Task/Leap-year/C/leap-year.c index 757fb5ece8..d0376e3be6 100644 --- a/Task/Leap-year/C/leap-year.c +++ b/Task/Leap-year/C/leap-year.c @@ -1,16 +1,15 @@ #include -#include -bool is_leap_year(int year) +int is_leap_year(int year) { - return !(year % 4) && year % 100 || !(year % 400); + return (!(year % 4) && year % 100 || !(year % 400)) ? 1 : 0; } int main() { - int test_case[] = {1900, 1994, 1996, 1997, 2000}, key, end; + int test_case[] = {1900, 1994, 1996, 1997, 2000}, key, end, year; for (key = 0, end = sizeof(test_case)/sizeof(test_case[0]); key < end; ++key) { - int year = test_case[key]; - printf("%d is %sa leap year.\n", year, is_leap_year(year) ? "" : "not "); + year = test_case[key]; + printf("%d is %sa leap year.\n", year, (is_leap_year(year) == 1 ? "" : "not ")); } } diff --git a/Task/Leap-year/D/leap-year.d b/Task/Leap-year/D/leap-year-1.d similarity index 100% rename from Task/Leap-year/D/leap-year.d rename to Task/Leap-year/D/leap-year-1.d diff --git a/Task/Leap-year/D/leap-year-2.d b/Task/Leap-year/D/leap-year-2.d new file mode 100644 index 0000000000..0be04321d8 --- /dev/null +++ b/Task/Leap-year/D/leap-year-2.d @@ -0,0 +1,8 @@ +import std.datetime; + +void main() { + assert(yearIsLeapYear(1724)); + assert(!yearIsLeapYear(1973)); + assert(!Date(1900, 1, 1).isLeapYear); + assert(DateTime(2000, 1, 1).isLeapYear); +} diff --git a/Task/Leap-year/Excel/leap-year.excel b/Task/Leap-year/Excel/leap-year.excel new file mode 100644 index 0000000000..40c3e681a4 --- /dev/null +++ b/Task/Leap-year/Excel/leap-year.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/Haskell/leap-year-4.hs b/Task/Leap-year/Haskell/leap-year-4.hs index 9ce2b9ef29..9a3c317543 100644 --- a/Task/Leap-year/Haskell/leap-year-4.hs +++ b/Task/Leap-year/Haskell/leap-year-4.hs @@ -11,4 +11,4 @@ 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 + ,TestCase $ assertEqual "1900 is not a leap year" False $ isLeapYear 1900] diff --git a/Task/Leap-year/Java/leap-year.java b/Task/Leap-year/Java/leap-year.java index 211aae7bbb..d08b2926e0 100644 --- a/Task/Leap-year/Java/leap-year.java +++ b/Task/Leap-year/Java/leap-year.java @@ -1,16 +1,17 @@ import java.util.GregorianCalendar; import java.text.MessageFormat; -public class Leapyear { - public static void main(String[] argv) { +public class Leapyear{ + public static void main(String[] argv){ int[] yrs = {1800,1900,1994,1998,1999,2000,2001,2004,2100}; GregorianCalendar cal = new GregorianCalendar(); - for (int year : yrs) { - System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.", year, cal.isLeapYear(year), is_leapyear(year))); + for(int year : yrs){ + System.err.println(MessageFormat.format("The year {0,number,#} is leaper: {1} / {2}.", + year, cal.isLeapYear(year), isLeapYear(year))); } } - public static boolean is_leapyear(int year) { + public static boolean isLeapYear(int year){ return (year % 100 == 0) ? (year % 400 == 0) : (year % 4 == 0); } } diff --git a/Task/Leap-year/PHP/leap-year-1.php b/Task/Leap-year/PHP/leap-year-1.php index 88b358d51e..4eb8a4fd44 100644 --- a/Task/Leap-year/PHP/leap-year-1.php +++ b/Task/Leap-year/PHP/leap-year-1.php @@ -1,7 +1,7 @@ m = m.abs(); n = n.abs(); n == 0 ? m : m%n == 0 ? n : gcd(n, m % n) } + +def lcd = { m, n -> Math.abs(m * n) / gcd(m, n) } + +[[m: 12, n: 18, l: 36], + [m: -6, n: 14, l: 42], + [m: 35, n: 0, l: 0]].each { t -> + println "LCD of $t.m, $t.n is $t.l" + assert lcd(t.m, t.n) == t.l +} diff --git a/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx b/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx new file mode 100644 index 0000000000..506f07a181 --- /dev/null +++ b/Task/Least-common-multiple/REXX/least-common-multiple-1.rexx @@ -0,0 +1,24 @@ +/*REXX pgm finds LCM (Least Common Multiple) of any number of integers.*/ +numeric digits 10000 /*can handle 10,000 digit numbers*/ +say 'the LCM of 19 & 0 is: ' lcm(19 0) +say 'the LCM of 0 & 85 is: ' lcm( 0 85) +say 'the LCM of 14 & -6 is: ' lcm(14, -6) +say 'the LCM of 18 & 12 is: ' lcm(18 12) +say 'the LCM of 18 & 12 & -5 is: ' lcm(18 12, -5) +say 'the LCM of 18 & 12 & -5 & 97 is: ' lcm(18, 12, -5, 97) +say 'the LCM of 2**19-1 & 2**521-1 is: ' lcm(2**19-1 2**521-1) + /* [↑] 7th, 13th Mersenne primes*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────LCM subroutine──────────────────────*/ +lcm: procedure; parse arg $,_; $=$ _; do i=3 to arg(); $=$ arg(i); end +parse var $ x $ /*obtain the first value in args.*/ +x=abs(x) /*use the absolute value of X. */ + do while $\=='' /*process the remainder of args. */ + parse var $ ! $; !=abs(!) /*pick off the next arg (ABS val)*/ + if !==0 then return 0 /*if zero, then LCM is also zero.*/ + d=x*! /*calculate part of the LCM here */ + do until !==0; parse value x//! ! with ! x + end /*until*/ /* [↑] this is a short&fast GCD.*/ + x=d%x /*divide the pre─calculated value*/ + end /*while*/ /* [↑] process subsequent args. */ +return x /*return with the LCM of the args*/ diff --git a/Task/Least-common-multiple/REXX/least-common-multiple-2.rexx b/Task/Least-common-multiple/REXX/least-common-multiple-2.rexx new file mode 100644 index 0000000000..3a52c629ec --- /dev/null +++ b/Task/Least-common-multiple/REXX/least-common-multiple-2.rexx @@ -0,0 +1,21 @@ +lcm2: procedure +x=abs(arg(1)) +do k=2 to arg() While x<>0 + y=abs(arg(k)) + x=x*y/gcd2(x,y) + end +return x + +gcd2: procedure +x=abs(arg(1)) +do j=2 to arg() + y=abs(arg(j)) + If y<>0 Then Do + do until z==0 + z=x//y + x=y + y=z + end + end + end +return x diff --git a/Task/Least-common-multiple/REXX/least-common-multiple-3.rexx b/Task/Least-common-multiple/REXX/least-common-multiple-3.rexx new file mode 100644 index 0000000000..35434a0ae4 --- /dev/null +++ b/Task/Least-common-multiple/REXX/least-common-multiple-3.rexx @@ -0,0 +1,72 @@ +Parse Version v +Say 'Version='v +Call time 'R' +Do a=0 To 100 + Do b=0 To 100 + Do c=0 To 100 + x1.a.b.c=lcm1(a,b,c) + End + End + End +Say 'version 1' time('E') +Call time 'R' +Do a=0 To 100 + Do b=0 To 100 + Do c=0 To 100 + x2.a.b.c=lcm2(a,b,c) + End + End + End +Say 'version 2' time('E') +cnt.=0 +Do a=0 To 100 + Do b=0 To 100 + Do c=0 To 100 + If x1.a.b.c=x2.a.b.c then cnt.0ok=cnt.0ok+1 + End + End + End +Say cnt.0ok 'comparisons ok' +Exit +/*----------------------------------LCM subroutine----------------------*/ +lcm1: procedure; d=strip(arg(1) arg(2)); do i=3 to arg(); d=d arg(i); end +parse var d x d /*obtain the first value in args.*/ +x=abs(x) /*use the absolute value of X. */ + do while d\=='' /*process the rest of the args. */ + parse var d ! d; !=abs(!) /*pick off the next arg (ABS val)*/ + if !==0 then return 0 /*if zero, then LCM is also zero.*/ + x=x*!/gcd1(x,!) /*have GCD do the heavy lifting.*/ + end /*while*/ +return x /*return with LCM of arguments.*/ +/*----------------------------------GCD subroutine----------------------*/ +gcd1: procedure; d=strip(arg(1) arg(2)); do j=3 to arg(); d=d arg(j); end +parse var d x d /*obtain the first value in args.*/ +x=abs(x) /*use the absolute value of X. */ + do while d\=='' /*process the rest of the args. */ + parse var d y d; y=abs(y) /*pick off the next arg (ABS val)*/ + if y==0 then iterate /*if zero, then ignore the value.*/ + do until y==0; parse value x//y y with y x; end + end /*while*/ +return x /*return with GCD of arguments.*/ + +lcm2: procedure +x=abs(arg(1)) +do k=2 to arg() While x<>0 + y=abs(arg(k)) + x=x*y/gcd2(x,y) + end +return x + +gcd2: procedure +x=abs(arg(1)) +do j=2 to arg() + y=abs(arg(j)) + If y<>0 Then Do + do until z==0 + z=x//y + x=y + y=z + end + end + end +return x diff --git a/Task/Least-common-multiple/REXX/least-common-multiple.rexx b/Task/Least-common-multiple/REXX/least-common-multiple.rexx deleted file mode 100644 index 0f82114b82..0000000000 --- a/Task/Least-common-multiple/REXX/least-common-multiple.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*REXX pgm finds LCM (Least Common Multiple) of a number of integers.*/ -numeric digits 9000 /*handle nine-thousand digit nums*/ - -say 'the LCM of 19 & 0 is:' lcm(19 0) -say 'the LCM of 0 & 85 is:' lcm( 0 85) -say 'the LCM of 14 & -6 is:' lcm(14,-6) -say 'the LCM of 18 & 12 is:' lcm(18 12) -say 'the LCM of 18 & 12 & -5 is:' lcm(18 12,-5) -say 'the LCM of 18 & 12 & -5 & 97 is:' lcm(18,12,-5,97) -say 'the LCM of 2**19-1 & 2**521-1 is:' lcm(2**19-1 2**521-1) - /*──(above)── the 7th and 13th Mersenne primes.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LCM subroutine──────────────────────*/ -lcm: procedure; $=; do j=1 for arg(); $=$ arg(j); end -x=abs(word($,1)) /* [↑] build a list of arguments.*/ - do k=2 to words($); !=abs(word($,k)); if !=0 then return 0 - x=x*! / gcd(x,!) /*have GCD do the heavy lifting.*/ - end /*k*/ -return x /*return with the money. */ -/*──────────────────────────────────GCD subroutine──────────────────────*/ -gcd: procedure; $=; do j=1 for arg(); $=$ arg(j); end -parse var $ x z .; if x=0 then x=z /* [↑] build a list of arguments.*/ -x=abs(x) - do k=2 to words($); y=abs(word($,k)); if y=0 then iterate - do until _==0; _=x//y; x=y; y=_; end /*until*/ - end /*k*/ -return x /*return with the money. */ diff --git a/Task/Least-common-multiple/Smalltalk/least-common-multiple.st b/Task/Least-common-multiple/Smalltalk/least-common-multiple.st new file mode 100644 index 0000000000..c91f4522d6 --- /dev/null +++ b/Task/Least-common-multiple/Smalltalk/least-common-multiple.st @@ -0,0 +1 @@ +12 lcm: 18 diff --git a/Task/Letter-frequency/00DESCRIPTION b/Task/Letter-frequency/00DESCRIPTION index 4d8c255d81..354b775026 100644 --- a/Task/Letter-frequency/00DESCRIPTION +++ b/Task/Letter-frequency/00DESCRIPTION @@ -1,3 +1,4 @@ Open a text file and count the occurrences of each letter. -Some of these programs count all characters (including punctuation), but some only count letters A to Z. +Some of these programs count all characters (including punctuation), +but some only count letters A to Z. diff --git a/Task/Letter-frequency/00META.yaml b/Task/Letter-frequency/00META.yaml new file mode 100644 index 0000000000..f55f85b554 --- /dev/null +++ b/Task/Letter-frequency/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Randomness +note: Probability_and_statistics diff --git a/Task/Letter-frequency/AWK/letter-frequency.awk b/Task/Letter-frequency/AWK/letter-frequency.awk index 5f1dd624f9..b3a8427627 100644 --- a/Task/Letter-frequency/AWK/letter-frequency.awk +++ b/Task/Letter-frequency/AWK/letter-frequency.awk @@ -1,4 +1,5 @@ -BEGIN { FS="" } -{for(i=1;i<=NF;i++) m[$i]++}END{for(i in m)printf("%9d %-14s\n",m[i],i)} +# usage: awk -f letters.awk HolyBible.txt -usage: awk -f letters.awk HolyBible.txt +BEGIN { FS="" } + { for(i=1;i<=NF;i++) m[$i]++} +END { for(i in m) printf("%9d %-14s\n", m[i],i) } diff --git a/Task/Letter-frequency/D/letter-frequency.d b/Task/Letter-frequency/D/letter-frequency.d index be675e6230..dbc585c223 100644 --- a/Task/Letter-frequency/D/letter-frequency.d +++ b/Task/Letter-frequency/D/letter-frequency.d @@ -1,6 +1,6 @@ -import std.stdio, std.ascii, std.algorithm, std.range, std.typetuple; - void main() { + import std.stdio, std.ascii, std.algorithm, std.range; + uint[26] frequency; foreach (const buffer; "unixdict.txt".File.byChunk(2 ^^ 15)) diff --git a/Task/Letter-frequency/Eiffel/letter-frequency.e b/Task/Letter-frequency/Eiffel/letter-frequency.e new file mode 100644 index 0000000000..564b648906 --- /dev/null +++ b/Task/Letter-frequency/Eiffel/letter-frequency.e @@ -0,0 +1,41 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + -- Read from the file and print frequencies. + local + file: PLAIN_TEXT_FILE + do + create file.make_open_read("input.txt") + file.read_stream(file.count) + file.close + across get_frequencies(file.last_string) as f loop + print(f.key.out + ": " + f.item.out + "%N") + end + end + +feature -- Access + + get_frequencies (s: STRING): HASH_TABLE[INTEGER, CHARACTER] + -- Hash table of counts for alphabetic characters in `s'. + local + char: CHARACTER + do + create Result.make(0) + across s.area as st loop + char := st.item + if char.is_alpha then + if Result.has(char) then + Result.force(Result.at(char) + 1, char) + else + Result.put (1, char) + end + end + end + end +end diff --git a/Task/Letter-frequency/Euphoria/letter-frequency.euphoria b/Task/Letter-frequency/Euphoria/letter-frequency.euphoria new file mode 100644 index 0000000000..fa30d84d70 --- /dev/null +++ b/Task/Letter-frequency/Euphoria/letter-frequency.euphoria @@ -0,0 +1,24 @@ +-- LetterFrequency.ex +-- Count frequency of each letter in own source code. + +include std/console.e +include std/io.e +include std/text.e + +sequence letters = repeat(0,26) + +sequence content = read_file("LetterFrequency.ex") + +content = lower(content) + +for i = 1 to length(content) do + if content[i] > 96 and content[i] < 123 then + letters[content[i]-96] += 1 + end if +end for + +for i = 1 to 26 do + printf(1,"%s: %d\n",{i+96,letters[i]}) +end for + +if getc(0) then end if diff --git a/Task/Letter-frequency/J/letter-frequency-1.j b/Task/Letter-frequency/J/letter-frequency-1.j index 07a9af6177..3cffdf6e27 100644 --- a/Task/Letter-frequency/J/letter-frequency-1.j +++ b/Task/Letter-frequency/J/letter-frequency-1.j @@ -1,5 +1,4 @@ -require 'files' NB. define fread ltrfreq=: 3 : 0 - letters=. u: (u:inv'A') + i.26 NB. upper case letters - <: #/.~ (toupper fread y) (,~ -. -.) letters + letters=. u: 65 + i.26 NB. upper case letters + <: #/.~ letters (, -. -.~) toupper fread y ) diff --git a/Task/Letter-frequency/Julia/letter-frequency.julia b/Task/Letter-frequency/Julia/letter-frequency.julia new file mode 100644 index 0000000000..67b2afa4ff --- /dev/null +++ b/Task/Letter-frequency/Julia/letter-frequency.julia @@ -0,0 +1,5 @@ +function freq(file) + h = Dict{Char, Integer}() + for x in open(readchomp,file) h[x] = get(h,x,0)+1 end + sort(collect(h)) +end diff --git a/Task/Letter-frequency/K/letter-frequency-3.k b/Task/Letter-frequency/K/letter-frequency-3.k index 12f582dd32..451d01d3b0 100644 --- a/Task/Letter-frequency/K/letter-frequency-3.k +++ b/Task/Letter-frequency/K/letter-frequency-3.k @@ -1,10 +1 @@ -(("H";1) - ("e";1) - ("l";3) - ("o";2) - (",";1) - (" ";1) - ("w";1) - ("r";1) - ("d";1) - ("!";1)) + c@>c[;1] diff --git a/Task/Letter-frequency/Python/letter-frequency-2.py b/Task/Letter-frequency/Python/letter-frequency-2.py index 0eaffd8ecd..f6e1902213 100644 --- a/Task/Letter-frequency/Python/letter-frequency-2.py +++ b/Task/Letter-frequency/Python/letter-frequency-2.py @@ -1,5 +1,5 @@ import string -if hasattr(string, ''ascii_lowercase''): +if hasattr(string, 'ascii_lowercase'): letters = string.ascii_lowercase # Python 2.2 and later else: letters = string.lowercase # Earlier versions @@ -7,14 +7,14 @@ offset = ord('a') def countletters(file_handle): """Traverse a file and compute the number of occurences of each letter - """return results as a simple 26 element list of integers. + return results as a simple 26 element list of integers.""" results = [0] * len(letters) for line in file_handle: for char in line: char = char.lower() if char in letters: - results[offset - ord(char)] += 1 - # Ordinal of 'a' minus ordinal of any lowercase ASCII letter -> 0..25 + results[ord(char) - offset] += 1 + # Ordinal minus ordinal of 'a' of any lowercase ASCII letter -> 0..25 return results if __name__ == "__main__": diff --git a/Task/Letter-frequency/Rust/letter-frequency.rust b/Task/Letter-frequency/Rust/letter-frequency.rust new file mode 100644 index 0000000000..55cf1f4062 --- /dev/null +++ b/Task/Letter-frequency/Rust/letter-frequency.rust @@ -0,0 +1,21 @@ +extern crate collections; + +use std::io::fs::File; +use std::io::BufferedReader; +use std::os; + +fn main() { + let filename = match os::args().len() { + 1 => fail!("You must enter a filename to read line by line"), + _ => os::args()[1] + }; + + let file = File::open(&Path::new(filename)); + let mut reader = BufferedReader::new(file); + + let s = input.chars().fold(&mut collections::HashMap::new(), |m, x| { + let r = *m.find(&x).unwrap_or(&0u); m.insert(x, 1 + r); m + }).clone(); + + println!("{}", s); +} diff --git a/Task/Letter-frequency/Scheme/letter-frequency-1.ss b/Task/Letter-frequency/Scheme/letter-frequency-1.ss new file mode 100644 index 0000000000..2c3876c018 --- /dev/null +++ b/Task/Letter-frequency/Scheme/letter-frequency-1.ss @@ -0,0 +1,21 @@ +(use-modules (ice-9 format)) + +(define (char-freq port table) + (if + (eof-object? (peek-char port)) + table + (char-freq port (add-char (read-char port) table)))) + +(define (add-char char table) + (cond + ((null? table) (list (list char 1))) + ((eq? (caar table) char) (cons (list char (+ (cadar table) 1)) (cdr table))) + (#t (cons (car table) (add-char char (cdr table)))))) + +(define (format-table table) + (for-each (lambda (t) (format #t "~10s~10d~%" (car t) (cadr t))) table)) + +(define (print-freq filename) + (format-table (char-freq (open-input-file filename) '()))) + +(print-freq "letter-frequency.scm") diff --git a/Task/Letter-frequency/Scheme/letter-frequency-2.ss b/Task/Letter-frequency/Scheme/letter-frequency-2.ss new file mode 100644 index 0000000000..206188c9b5 --- /dev/null +++ b/Task/Letter-frequency/Scheme/letter-frequency-2.ss @@ -0,0 +1,8 @@ +(with-input-from-string "foobar" + (lambda () + (port-fold (lambda (x s) + (alist-update x + (add1 (alist-ref x s eq? 0)) + s)) + '() + read-char))) diff --git a/Task/Letter-frequency/Scheme/letter-frequency.ss b/Task/Letter-frequency/Scheme/letter-frequency.ss deleted file mode 100644 index 90ecaa9320..0000000000 --- a/Task/Letter-frequency/Scheme/letter-frequency.ss +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/local/bin/gosh - -(use srfi-1) ;; iota - -(define *freqs* (make-vector 256 0)) - -(define (main args) - (with-input-from-file "../word-list.txt" count-char-freqs) - (show-char-freqs #\a #\z)) - -(define (count-char-freqs) - (let* ((ln (read-line)) - (at-eof (eof-object? ln))) - (if (not at-eof) - (let ((string-chars (string->list ln))) - (for-each count-char-freq string-chars) - (count-char-freqs))))) - -(define (count-char-freq ch) - (if (char-alphabetic? ch) - (let* ((char-num (char->integer (char-downcase ch))) - (frq (vector-ref *freqs* char-num))) - (vector-set! *freqs* char-num (+ 1 frq))))) - -(define (show-char-freqs first-letter last-letter) - (format #t "Letter Frequency~%") - (let* ((first-num (char->integer first-letter)) - (last-num (char->integer last-letter)) - (num-count (+ 1 (- last-num first-num))) - (nums-list (iota num-count first-num))) - (for-each show-char-freq nums-list))) - -(define (show-char-freq let-num) - (let ((ch (integer->char let-num)) - (frq (vector-ref *freqs* let-num))) - (format #t "~6a ~8a~%" ch frq))) diff --git a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime index b75e4f5e17..e67bedbb82 100644 --- a/Task/Levenshtein-distance/Aime/levenshtein-distance.aime +++ b/Task/Levenshtein-distance/Aime/levenshtein-distance.aime @@ -9,7 +9,7 @@ dist(text s, integer i, integer ls, text t, integer j, integer lt, list d) x = lt - j; } elif (j == lt) { x = ls - i; - } elif (character(s, i) == character(t, j)) { + } elif (s[i] == t[j]) { x = dist(s, i + 1, ls, t, j + 1, lt, d); } else { x = dist(s, i + 1, ls, t, j + 1, lt, d); diff --git a/Task/Levenshtein-distance/C/levenshtein-distance-1.c b/Task/Levenshtein-distance/C/levenshtein-distance-1.c index 42c63b87e8..b32ee3ee97 100644 --- a/Task/Levenshtein-distance/C/levenshtein-distance-1.c +++ b/Task/Levenshtein-distance/C/levenshtein-distance-1.c @@ -38,7 +38,7 @@ int main() { const char *s1 = "rosettacode"; const char *s2 = "raisethysword"; - printf("distance betweeh `%s' and `%s': %d\n", s1, s2, + printf("distance between `%s' and `%s': %d\n", s1, s2, levenshtein(s1, strlen(s1), s2, strlen(s2))); return 0; diff --git a/Task/Levenshtein-distance/C/levenshtein-distance-2.c b/Task/Levenshtein-distance/C/levenshtein-distance-2.c index 00b62b4ce8..20fb105289 100644 --- a/Task/Levenshtein-distance/C/levenshtein-distance-2.c +++ b/Task/Levenshtein-distance/C/levenshtein-distance-2.c @@ -37,7 +37,7 @@ int main(void) { const char *s1 = "rosettacode"; const char *s2 = "raisethysword"; - printf("distance betweeh `%s' and `%s': %d\n", s1, s2, + printf("distance between `%s' and `%s': %d\n", s1, s2, levenshtein(s1, s2)); return 0; diff --git a/Task/Levenshtein-distance/Clojure/levenshtein-distance.clj b/Task/Levenshtein-distance/Clojure/levenshtein-distance-1.clj similarity index 100% rename from Task/Levenshtein-distance/Clojure/levenshtein-distance.clj rename to Task/Levenshtein-distance/Clojure/levenshtein-distance-1.clj diff --git a/Task/Levenshtein-distance/Clojure/levenshtein-distance-2.clj b/Task/Levenshtein-distance/Clojure/levenshtein-distance-2.clj new file mode 100644 index 0000000000..fd621cea8a --- /dev/null +++ b/Task/Levenshtein-distance/Clojure/levenshtein-distance-2.clj @@ -0,0 +1,21 @@ +(defn levenshtein [w1 w2] + (letfn [(cell-value [same-char? prev-row cur-row col-idx] + (min (inc (nth prev-row col-idx)) + (inc (last cur-row)) + (+ (nth prev-row (dec col-idx)) (if same-char? + 0 + 1))))] + (loop [row-idx 1 + max-rows (inc (count w2)) + prev-row (range (inc (count w1)))] + (if (= row-idx max-rows) + (last prev-row) + (let [ch2 (nth w2 (dec row-idx)) + next-prev-row (reduce (fn [cur-row i] + (let [same-char? (= (nth w1 (dec i)) ch2)] + (conj cur-row (cell-value same-char? + prev-row + cur-row + i)))) + [row-idx] (range 1 (count prev-row)))] + (recur (inc row-idx) max-rows next-prev-row)))))) diff --git a/Task/Levenshtein-distance/D/levenshtein-distance-1.d b/Task/Levenshtein-distance/D/levenshtein-distance-1.d index c27eef5fc4..40c4de7f1e 100644 --- a/Task/Levenshtein-distance/D/levenshtein-distance-1.d +++ b/Task/Levenshtein-distance/D/levenshtein-distance-1.d @@ -1,5 +1,5 @@ -import std.stdio, std.algorithm; - void main() { - writeln(levenshteinDistance("kitten", "sitting")); + import std.stdio, std.algorithm; + + levenshteinDistance("kitten", "sitting").writeln; } diff --git a/Task/Levenshtein-distance/D/levenshtein-distance-2.d b/Task/Levenshtein-distance/D/levenshtein-distance-2.d index 313d6357ec..f543b70626 100644 --- a/Task/Levenshtein-distance/D/levenshtein-distance-2.d +++ b/Task/Levenshtein-distance/D/levenshtein-distance-2.d @@ -3,9 +3,9 @@ import std.stdio, std.algorithm; int distance(in string s1, in string s2) pure nothrow { auto costs = new int[s2.length + 1]; - foreach (i; 0 .. s1.length + 1) { + foreach (immutable i; 0 .. s1.length + 1) { int lastValue = i; - foreach (j; 0 .. s2.length + 1) { + foreach (immutable j; 0 .. s2.length + 1) { if (i == 0) costs[j] = j; else { @@ -27,6 +27,6 @@ int distance(in string s1, in string s2) pure nothrow { } void main() { - foreach(p; [["kitten", "sitting"], ["rosettacode", "raisethysword"]]) + foreach (p; [["kitten", "sitting"], ["rosettacode", "raisethysword"]]) writefln("distance(%s, %s): %d", p[0], p[1], distance(p[0], p[1])); } diff --git a/Task/Levenshtein-distance/D/levenshtein-distance-3.d b/Task/Levenshtein-distance/D/levenshtein-distance-3.d index 8975afd381..4ca3bda585 100644 --- a/Task/Levenshtein-distance/D/levenshtein-distance-3.d +++ b/Task/Levenshtein-distance/D/levenshtein-distance-3.d @@ -1,48 +1,15 @@ -import std.stdio, std.algorithm, std.range; +import std.stdio, std.array, std.algorithm, std.functional; -int lDistR(T)(in T[] a, in T[] b) /*pure nothrow*/ { - if (a.length == 0) - return b.length; - if (b.length == 0) - return a.length; - if (a.length == b.length) { - auto r = iota(a.length); - auto u = r.until!(i => a[i] != b[i])(); - if (equal(r, u)) // u is a short-circuit test until any - // mismatch - return 0; // u is equivalent to r, means no - // mismatch found - } - - const(T)[][] candidate; - immutable alen = a.length; - immutable blen = b.length; - // mutate _a_ by 1 edit to create members of candidate - - // delete an _a_ element - if (alen > blen) - foreach (i; 0 .. alen) - candidate ~= a[0 .. i] ~ a[i+1 .. $]; - // insert matching _b_ element to _a_ - if (alen < blen) { - foreach (i; 0 .. alen+1) // from left - candidate ~= a[0 .. i] ~ b[i] ~ a[i .. $]; - foreach (i; 0 .. alen+1) // from right - candidate ~= a[0 .. $-i] ~ b[$ - i - 1] ~ a[$-i .. $]; - } - // subsistute matching _a_ element with _b_'s - if (alen == blen) - foreach (i; 0 .. alen) - if (a[i] != b[i]) - candidate ~= a[0..i] ~ b[i] ~ a[i+1 .. $]; - - // exclusive cases, so only 1 edit is make to create each - // new candidate - - // minimum distance on this run - return candidate.map!(e => lDistR(e, b) + 1)().reduce!min(); +uint lDist(T)(in const(T)[] s, in const(T)[] t) nothrow { + alias mlDist = memoize!lDist; + if (s.empty || t.empty) return max(t.length, s.length); + if (s[0] == t[0]) return mlDist(s[1 .. $], t[1 .. $]); + return min(mlDist(s, t[1 .. $]), + mlDist(s[1 .. $], t), + mlDist(s[1 .. $], t[1 .. $])) + 1; } void main() { - writeln(lDistR("kitten", "sitting")); + lDist("kitten", "sitting").writeln; + lDist("rosettacode", "raisethysword").writeln; } diff --git a/Task/Levenshtein-distance/Julia/levenshtein-distance.julia b/Task/Levenshtein-distance/Julia/levenshtein-distance.julia new file mode 100644 index 0000000000..8bbcc4c005 --- /dev/null +++ b/Task/Levenshtein-distance/Julia/levenshtein-distance.julia @@ -0,0 +1,20 @@ +function leven(s, t) + + length(s) == 0 && return length(t); + length(t) == 0 && return length(s); + + s1 = s[2:end]; + t1 = t[2:end]; + + return (s[1] == t[1] + ? leven(s1, t1) + : 1 + min( + leven(s1, t1), + leven(s, t1), + leven(s1, t) + ) + ); +end + +println(leven("kitten", "sitting")); # => 3 +println(leven("rosettacode","raisethysword")); # => 8 diff --git a/Task/Levenshtein-distance/Lua/levenshtein-distance.lua b/Task/Levenshtein-distance/Lua/levenshtein-distance.lua index fac3b1b0d8..db202a89cb 100644 --- a/Task/Levenshtein-distance/Lua/levenshtein-distance.lua +++ b/Task/Levenshtein-distance/Lua/levenshtein-distance.lua @@ -1,19 +1,20 @@ -function Levenshtein_Distance( s1, s2 ) - if s1:len() == 0 then return s2:len() end - if s2:len() == 0 then return s1:len() end +function leven(s,t) + if s == '' then return t:len() end + if t == '' then return s:len() end - if s1:sub( -1, -1 ) == s2:sub( -1, -1 ) then - return Levenshtein_Distance( s1:sub( 1, -2 ), s2:sub( 1, -2 ) ) - end + local s1 = s:sub(2, -1) + local t1 = t:sub(2, -1) - local a = Levenshtein_Distance( s1:sub( 1, -2 ), s2:sub( 1, -2 ) ) - local b = Levenshtein_Distance( s1:sub( 1, -1 ), s2:sub( 1, -2 ) ) - local c = Levenshtein_Distance( s1:sub( 1, -2 ), s2:sub( 1, -1 ) ) + if s:sub(0, 1) == t:sub(0, 1) then + return leven(s1, t1) + end - if a > b then return b + 1 end - if a > c then return c + 1 end - return a + 1 + return 1 + math.min( + leven(s1, t1), + leven(s, t1), + leven(s1, t ) + ) end -print( Levenshtein_Distance( "kitten", "sitting" ) ) -print( Levenshtein_Distance( "rosettacode", "raisethysword" ) ) +print(leven("kitten", "sitting")) +print(leven("rosettacode", "raisethysword")) diff --git a/Task/Levenshtein-distance/Objeck/levenshtein-distance.objeck b/Task/Levenshtein-distance/Objeck/levenshtein-distance.objeck new file mode 100644 index 0000000000..4151572e62 --- /dev/null +++ b/Task/Levenshtein-distance/Objeck/levenshtein-distance.objeck @@ -0,0 +1,34 @@ +class Levenshtein { + function : Main(args : String[]) ~ Nil { + if(args->Size() = 2) { + s := args[0]; t := args[1]; d := Distance(s,t); + "{$s} -> {$t} = {$d}"->PrintLine(); + }; + } + + function : native : Distance(s : String,t : String) ~ Int { + d := Int->New[s->Size() + 1, t->Size() + 1]; + for(i := 0; i <= s->Size(); i += 1;) { + d[i,0] := i; + }; + + for(j := 0; j <= t->Size(); j += 1;) { + d[0,j] := j; + }; + + for(j := 1; j <= t->Size(); j += 1;) { + for(i := 1; i <= s->Size(); i += 1;) { + if(s->Get(i - 1) = t->Get(j - 1)) { + d[i,j] := d[i - 1, j - 1]; + } + else { + d[i,j] := (d[i - 1, j] + 1) + ->Min(d[i, j - 1] + 1) + ->Min(d[i - 1, j - 1] + 1); + }; + }; + }; + + return d[s->Size(), t->Size()]; + } +} diff --git a/Task/Levenshtein-distance/PL-I/levenshtein-distance-1.pli b/Task/Levenshtein-distance/PL-I/levenshtein-distance-1.pli new file mode 100644 index 0000000000..5c33ead483 --- /dev/null +++ b/Task/Levenshtein-distance/PL-I/levenshtein-distance-1.pli @@ -0,0 +1,56 @@ +*process source xref attributes or(!); + lsht: Proc Options(main); + Call test('kitten' ,'sitting'); + Call test('rosettacode' ,'raisethysword'); + Call test('Sunday' ,'Saturday'); + Call test('Vladimir_Levenshtein[1965]', + 'Vladimir_Levenshtein[1965]'); + Call test('this_algorithm_is_similar_to', + 'Damerau-Levenshtein_distance'); + Call test('','abc'); + + test: Proc(s,t); + Dcl (s,t) Char(*) Var; + Put Edit(' 1st string = >'!!s!!'<')(Skip,a); + Put Edit(' 2nd string = >'!!t!!'<')(Skip,a); + Put Edit('Levenshtein distance =',LevenshteinDistance(s,t)) + (Skip,a,f(3)); + Put Edit('')(Skip,a); + End; + + LevenshteinDistance: Proc(s,t) Returns(Bin Fixed(31)); + Dcl (s,t) Char(*) Var; + Dcl (sl,tl) Bin Fixed(31); + Dcl ld Bin Fixed(31); + /* for all i and j, d[i,j] will hold the Levenshtein distance between + * the first i characters of s and the first j characters of t; + * note that d has (m+1)*(n+1) values */ + sl=length(s); + tl=length(t); + Begin; + Dcl d(0:sl,0:tl) Bin Fixed(31); + Dcl (i,j,ii,jj) Bin Fixed(31); + d=0; + Do i=1 To sl; /* source prefixes can be transformed into */ + d(i,0)=i; /* empty string by dropping all characters */ + End; + Do j=1 To tl; /* target prefixes can be reached from */ + d(0,j)=j; /* empty source prefix by inserting every character*/ + End; + Do j=1 To tl; + jj=j-1; + Do i=1 To sl; + ii=i-1; + If substr(s,i,1)=substr(t,j,1) Then + d(i,j)=d(ii,jj); /* no operation required */ + Else + d(i,j)=1+min(d(ii,j), /* a deletion */ + d(i,jj), /* an insertion */ + d(ii,jj)); /* a substitution */ + End; + End; + ld=d(sl,tl); + End; + Return(ld); + End; + End; diff --git a/Task/Levenshtein-distance/PL-I/levenshtein-distance-2.pli b/Task/Levenshtein-distance/PL-I/levenshtein-distance-2.pli new file mode 100644 index 0000000000..a9ef5ae336 --- /dev/null +++ b/Task/Levenshtein-distance/PL-I/levenshtein-distance-2.pli @@ -0,0 +1,45 @@ +*process source attributes xref or(!); + ld3: Proc Options(main); + Dcl ld(0:30,0:30) Bin Fixed(31); + call test('kitten' ,'sitting'); + call test('rosettacode' ,'raisethysword'); + call test('Sunday' ,'Saturday'); + call test('Vladimir_Levenshtein[1965]', + 'Vladimir_Levenshtein[1965]'); + call test('this_algorithm_is_similar_to', + 'Damerau-Levenshtein_distance'); + call test('','abc'); + + test: Proc(s,t); + Dcl (s,t) Char(*); + ld=-1; + Put Edit(' 1st string = >'!!s!!'<')(Skip,a); + Put Edit(' 2nd string = >'!!t!!'<')(Skip,a); + Put Edit('Levenshtein distance =', + LevenshteinDistance(s,length(s),t,length(t))) + (Skip,a,f(3)); + Put Edit('')(Skip,a); + End; + + LevenshteinDistance: Proc(s,sl,t,tl) Recursive Returns(Bin Fixed(31)); + Dcl (s,t) Char(*); + Dcl (sl,tl) Bin Fixed(31); + Dcl cost Bin Fixed(31); + If ld(sl,tl)^=-1 Then + Return(ld(sl,tl)); + Select; + When(sl=0) ld(sl,tl)=tl; + When(tl=0) ld(sl,tl)=sl; + Otherwise Do; + /* test if last characters of the strings match */ + cost=(substr(s,sl,1)^=substr(t,tl,1)); + /* return minimum of delete char from s, delete char from t, + and delete char from both */ + ld(sl,tl)=min(LevenshteinDistance(s,sl-1,t,tl )+1, + LevenshteinDistance(s,sl ,t,tl-1)+1, + LevenshteinDistance(s,sl-1,t,tl-1)+cost)); + End; + End; + Return(ld(sl,tl)); + End; + End; diff --git a/Task/Levenshtein-distance/Pascal/levenshtein-distance.pascal b/Task/Levenshtein-distance/Pascal/levenshtein-distance.pascal index 840da846d3..fecee18664 100644 --- a/Task/Levenshtein-distance/Pascal/levenshtein-distance.pascal +++ b/Task/Levenshtein-distance/Pascal/levenshtein-distance.pascal @@ -10,11 +10,11 @@ function LevenshteinDistance(s, t: string): longint; begin n := length(t); m := length(s); - setlength(d, n+1, m+1); + setlength(d, m+1, n+1); - for i := 0 to n do + for i := 0 to m do d[i,0] := i; - for j := 0 to m do + for j := 0 to n do d[0,j] := j; for j := 1 to n do for i := 1 to m do diff --git a/Task/Levenshtein-distance/REXX/levenshtein-distance.rexx b/Task/Levenshtein-distance/REXX/levenshtein-distance-1.rexx similarity index 100% rename from Task/Levenshtein-distance/REXX/levenshtein-distance.rexx rename to Task/Levenshtein-distance/REXX/levenshtein-distance-1.rexx diff --git a/Task/Levenshtein-distance/REXX/levenshtein-distance-2.rexx b/Task/Levenshtein-distance/REXX/levenshtein-distance-2.rexx new file mode 100644 index 0000000000..7bda1daf91 --- /dev/null +++ b/Task/Levenshtein-distance/REXX/levenshtein-distance-2.rexx @@ -0,0 +1,30 @@ +Levenshtein: Procedure +Parse Arg s,t +/* for all i and j, d[i,j] will hold the Levenshtein distance between */ +/* the first i characters of s and the first j characters of t; */ +/* note that d has (m+1)*(n+1) values */ + m=length(s) + n=length(t) + d.=0 + Do i=1 To m /* source prefixes can be transformed into empty string by */ + d.i.0=i /* dropping all characters */ + End + Do j=1 To n /* target prefixes can be reached from empty source prefix */ + d.0.j=j /* by inserting every character */ + End + Do j=1 To n + jj=j-1 + Do i=1 To m + ii=i-1 + If substr(s,i,1)=substr(t,j,1) Then + d.i.j=d.ii.jj /* no operation required */ + else + d.i.j=min(d.ii.j+1,, /* a deletion */ + d.i.jj+1,, /* an insertion */ + d.ii.jj+1) /* a substitution */ + End + End + Say ' 1st string = ' s + Say ' 2nd string = ' t + say 'Levenshtein distance = ' d.m.n; say '' + Return d.m.n diff --git a/Task/Levenshtein-distance/REXX/levenshtein-distance-3.rexx b/Task/Levenshtein-distance/REXX/levenshtein-distance-3.rexx new file mode 100644 index 0000000000..45d78f747f --- /dev/null +++ b/Task/Levenshtein-distance/REXX/levenshtein-distance-3.rexx @@ -0,0 +1,22 @@ +LevenshteinDistance: Procedure +Parse Arg s,t +If s==t Then Return 0; +sl=length(s) +tl=length(t) +If sl=0 Then Return tl +If tl=0 Then Return sl +Do i=0 To tl + v0.i=i + End +Do i=0 To sl-1 + v1.0=i+1 + Do j=0 To tl-1 + jj=j+1 + cost=substr(s,i+1,1)<>substr(t,j+1,1) + v1.jj=min(v1.j+1,v0.jj+1,v0.j+cost) + End + Do j=0 to tl-1 + v0.j=v1.j + End + End +return v1.tl diff --git a/Task/Levenshtein-distance/REXX/levenshtein-distance-4.rexx b/Task/Levenshtein-distance/REXX/levenshtein-distance-4.rexx new file mode 100644 index 0000000000..a9878af6eb --- /dev/null +++ b/Task/Levenshtein-distance/REXX/levenshtein-distance-4.rexx @@ -0,0 +1,38 @@ +call test 'kitten' ,'sitting' +call test 'rosettacode' ,'raisethysword' +call test 'Sunday' ,'Saturday' +call test 'Vladimir_Levenshtein[1965]',, + 'Vladimir_Levenshtein[1965]' +call test 'this_algorithm_is_similar_to',, + 'Damerau-Levenshtein_distance' +call test '','abc' +Exit + +test: Procedure + Parse Arg s,t + ld.='' + Say ' 1st string = >'s'<' + Say ' 2nd string = >'t'<' + Say 'Levenshtein distance =' LevenshteinDistance(s,length(s),t,length(t)) + Say '' + Return + +LevenshteinDistance: Procedure Expose ld. +-- sl and tl are the number of characters in string s and t respectively + Parse Arg s,sl,t,tl + If ld.sl.tl<>'' Then + Return ld.sl.tl + Select + When sl=0 Then ld.sl.tl=tl + When tl=0 Then ld.sl.tl=sl + Otherwise Do + /* test if last characters of the strings match */ + cost=substr(s,sl,1)<>substr(t,tl,1) + /* return minimum of delete char from s, delete char from t, + and delete char from both */ + ld.sl.tl=min(LevenshteinDistance(s,sl-1,t,tl )+1,, + LevenshteinDistance(s,sl ,t,tl-1)+1,, + LevenshteinDistance(s,sl-1,t,tl-1)+cost) + End + End + Return ld.sl.tl diff --git a/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb b/Task/Levenshtein-distance/Ruby/levenshtein-distance-1.rb similarity index 96% rename from Task/Levenshtein-distance/Ruby/levenshtein-distance.rb rename to Task/Levenshtein-distance/Ruby/levenshtein-distance-1.rb index b86917fdbf..17725fe28a 100644 --- a/Task/Levenshtein-distance/Ruby/levenshtein-distance.rb +++ b/Task/Levenshtein-distance/Ruby/levenshtein-distance-1.rb @@ -19,3 +19,5 @@ module Levenshtein end end + +Levenshtein.test diff --git a/Task/Levenshtein-distance/Ruby/levenshtein-distance-2.rb b/Task/Levenshtein-distance/Ruby/levenshtein-distance-2.rb new file mode 100644 index 0000000000..6e0713ad3f --- /dev/null +++ b/Task/Levenshtein-distance/Ruby/levenshtein-distance-2.rb @@ -0,0 +1,34 @@ +def levenshtein_distance(str1, str2) + n = str1.length + m = str2.length + max = n/2 + + return m if 0 == n + return n if 0 == m + return n if (n - m).abs > max + + d = (0..m).to_a + x = nil + + str1.each_char.with_index do |char1,i| + e = i+1 + + str2.each_char.with_index do |char2,j| + cost = (char1 == char2) ? 0 : 1 + x = [ d[j+1] + 1, # insertion + e + 1, # deletion + d[j] + cost # substitution + ].min + d[j] = e + e = x + end + + d[m] = x + end + + x +end + +%w{kitten sitting saturday sunday rosettacode raisethysword}.each_slice(2) do |a, b| + puts "distance(#{a}, #{b}) = #{levenshtein_distance(a, b)}" +end diff --git a/Task/Levenshtein-distance/Scheme/levenshtein-distance.ss b/Task/Levenshtein-distance/Scheme/levenshtein-distance.ss index 9ba9e4940d..aec6668bcb 100644 --- a/Task/Levenshtein-distance/Scheme/levenshtein-distance.ss +++ b/Task/Levenshtein-distance/Scheme/levenshtein-distance.ss @@ -1,32 +1,13 @@ -#!/usr/local/bin/gosh - -(define (main args) - (let* ((a "kitten") - (b "sitting") - (d (levenshteinDistance a b))) - (format #t "Distance between ~a and ~a is ~a.~%" a b d))) - - -;; Number of edits needed to turn s1 into s2. -(define (levenshteinDistance s1 s2) - (let* ((s1Len (string-length s1)) - (s2Len (string-length s2))) - (cond - ; If either empty, distance is length of the other. (insert all) - ((= 0 s1Len) s2Len) - ((= 0 s2Len) s1Len) - (else - (let* ((s1Chars (string->list s1)) - (s2Chars (string->list s2)) - (s1First (car s1Chars)) - (s2First (car s2Chars)) - (s1Rest (list->string (cdr s1Chars))) - (s2Rest (list->string (cdr s2Chars)))) - (cond - ; If first chars equal, then use distance between the tails. - ((equal? s1First s2First) - (levenshteinDistance s1Rest s2Rest)) - ; Distance is minimum of sub-strings. - (else (+ 1 (min (levenshteinDistance s1Rest s2) - (levenshteinDistance s1 s2Rest) - (levenshteinDistance s1Rest s2Rest)))))))))) +(define (levenshtein s t) + (define (%levenshtein s sl t tl) + (cond ((zero? sl) tl) + ((zero? tl) sl) + (else + (min (+ (%levenshtein (cdr s) (- sl 1) t tl) 1) + (+ (%levenshtein s sl (cdr t) (- tl 1)) 1) + (+ (%levenshtein (cdr s) (- sl 1) (cdr t) (- tl 1)) + (if (char=? (car s) (car t)) 0 1)))))) + (%levenshtein (string->list s) + (string-length s) + (string->list t) + (string-length t))) diff --git a/Task/Linear-congruential-generator/D/linear-congruential-generator.d b/Task/Linear-congruential-generator/D/linear-congruential-generator.d index 9d4260e79e..5ddaacd2d3 100644 --- a/Task/Linear-congruential-generator/D/linear-congruential-generator.d +++ b/Task/Linear-congruential-generator/D/linear-congruential-generator.d @@ -1,28 +1,28 @@ -import std.stdio; - struct LinearCongruentialGenerator { enum uint RAND_MAX = (1U << 31) - 1; uint seed = 0; - uint randBSD() pure nothrow { + uint randBSD() pure nothrow @nogc { seed = (seed * 1_103_515_245 + 12_345) & RAND_MAX; return seed; } - uint randMS() pure nothrow { + uint randMS() pure nothrow @nogc { seed = (seed * 214_013 + 2_531_011) & RAND_MAX; return seed >> 16; } } void main() { + import std.stdio; + LinearCongruentialGenerator rnd; - foreach (i; 0 .. 10) - writeln(rnd.randBSD()); - writeln(); + foreach (immutable i; 0 .. 10) + writeln(rnd.randBSD); + writeln; rnd.seed = 0; - foreach (i; 0 .. 10) - writeln(rnd.randMS()); + foreach (immutable i; 0 .. 10) + writeln(rnd.randMS); } diff --git a/Task/Linear-congruential-generator/Perl-6/linear-congruential-generator.pl6 b/Task/Linear-congruential-generator/Perl-6/linear-congruential-generator.pl6 index e5b14ba495..1c94b9d4ed 100644 --- a/Task/Linear-congruential-generator/Perl-6/linear-congruential-generator.pl6 +++ b/Task/Linear-congruential-generator/Perl-6/linear-congruential-generator.pl6 @@ -1,9 +1,15 @@ -my $mod = 2**31; -sub bsd ($seed) { ( 1103515245 * $seed + 12345 ) % $mod }; -sub ms ($seed) { ( 214013 * $seed + 2531011 ) % $mod }; +constant modulus = 2**31; +sub bsd { + $^seed, ( 1103515245 * * + 12345 ) % modulus ... * +} +sub ms { + map * +> 16, ( + $^seed, ( 214013 * * + 2531011 ) % modulus ... * + ) +} -say 'BSD LCG first 10 values:'; -.say for ( 0.&bsd, -> $seed { $seed.&bsd } ... * )[^10]; +say 'BSD LCG first 10 values (fist one is the seed):'; +.say for bsd(0)[^10]; -say "\nMS LCG first 10 values:"; -($_ +> 16).say for ( 0.&ms, -> $seed { $seed.&ms } ... * )[^10]; +say "\nMS LCG first 10 values (fist one is the seed):"; +.say for ms(0)[^10]; diff --git a/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx b/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx index 628a0e0c5b..ac9137be4f 100644 --- a/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx +++ b/Task/Linear-congruential-generator/REXX/linear-congruential-generator.rexx @@ -2,13 +2,16 @@ /* random number generators. BSD= 0──►(2**31)-1, MS= 0──►(2**16)-1 */ numeric digits 20 /*enough digits for the multiply.*/ - do seed=0 to 1; bsd=seed; ms=seed; say center('seed='seed,79,'─') - do j=1 for 20; jjj=right(j,3) - bsd = (1103515245 * bsd + 12345) // 2**31 - ms = ( 214013 * ms + 2531011) // 2**31 - say 'state' jjj " BSD" right(bsd, 11) left('',18), - "MS" right( ms, 11) left('',5), - "rand" right(ms%2**16, 6) + do seed=0 to 1 /*perform for seed=0 & seed=1. */ + bsd=seed; ms=seed; /*assign SEED to 2 REXX variables*/ + say center('seed='seed,79,'─') /*display the seed in a title/sep*/ + + do j=1 for 20 + jjj=right(j,3) /*obtain the right-most 3 digits.*/ + bsd = (1103515245 * bsd + 12345) // 2**31 + ms = ( 214013 * ms + 2531011) // 2**31 + say 'state' jjj ' BSD' right(bsd,11) left('',18), + 'MS' right( ms,11) left('',5), + 'rand' right(ms%2**16,6) end /*j*/ - end /*seed*/ - /*stick a fork in it, we're done.*/ + end /*seed*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Linear-congruential-generator/UNIX-Shell/linear-congruential-generator.sh b/Task/Linear-congruential-generator/UNIX-Shell/linear-congruential-generator.sh new file mode 100644 index 0000000000..ec6a76e466 --- /dev/null +++ b/Task/Linear-congruential-generator/UNIX-Shell/linear-congruential-generator.sh @@ -0,0 +1,25 @@ +#! /bin/bash + +function BSD() { + SEED=$(((1103515245 * $SEED + 12345) % 2**31)) + echo " $SEED" +} + +function MS() { + SEED=$(((214013 * $SEED + 2531011) % 2**31)) + echo " $(($SEED / 2**16))" +} + +function output() { + SEED=0 + echo "$1" + + for i in {1..10}; do + eval "$1" + done + + echo "" +} + +output BSD +output MS diff --git a/Task/List-comprehensions/Prolog/list-comprehensions.pro b/Task/List-comprehensions/Prolog/list-comprehensions.pro index d3f3f0d707..545e03a1ae 100644 --- a/Task/List-comprehensions/Prolog/list-comprehensions.pro +++ b/Task/List-comprehensions/Prolog/list-comprehensions.pro @@ -3,6 +3,10 @@ :- op(450, xfx, ..). :- op(1100, yfx, &). +% use for explicit list usage +my_bind(V, [H|_]) :- V = H. +my_bind(V, [_|T]) :- my_bind(V, T). + % we need to define the intervals of numbers Vs <- M..N :- integer(M), @@ -10,6 +14,11 @@ Vs <- M..N :- M =< N, between(M, N, Vs). +% for explicit list comprehension like Vs <- [1,2,3] +Vs <- Xs :- + is_list(Xs), + my_bind(Vs, Xs). + % finally we define list comprehension % prototype is Vs <- {Var, Dec, Pred} where % Var is the list of variables to output @@ -17,3 +26,7 @@ Vs <- M..N :- % Pred is the list of predicates Vs <- {Var & Dec & Pred} :- findall(Var, maplist(call, [Dec, Pred]), Vs). + +% for list comprehension without Pred +Vs <- {Var & Dec} :- + findall(Var, maplist(call, [Dec]), Vs). diff --git a/Task/List-comprehensions/REXX/list-comprehensions-1.rexx b/Task/List-comprehensions/REXX/list-comprehensions-1.rexx new file mode 100644 index 0000000000..ac0daba129 --- /dev/null +++ b/Task/List-comprehensions/REXX/list-comprehensions-1.rexx @@ -0,0 +1,21 @@ +/*REXX program lists Pythagorean triples up to a specified number. */ +parse arg n . /*get the optional argument. */ +if n=='' then n=100 /*Not specified? Then assume 100*/ +$= /*assign a null to triples list. */ + do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2,*/ + do b=a+1 to n-1; aabb=aa+b*b /* ··· but not by much.*/ + do c=b+1 to n + if aabb==c*c then $=$ '('a"," || b','c")" + end /*c*/ + end /*b*/ + end /*a*/ + +if 'f5'x==5 then do; sup2='b2'x; le='8c'x; end /*EBCDIC?*/ + else do; sup2='fd'x; le='f3'x; end /* ASCII?*/ +say 'Pythagorean triples (a'sup2 "+ b"sup2 '= c'sup2", c "le n'):' +w=words($) /*number of members in the list. */ +say; do j=1 for w /*display the members of the list*/ + say word($,j) /*display a member of the list*/ + end /*j*/ /* [↑] list members vertically.*/ + +say; say w 'members listed.' /*stick a fork in it, we're done.*/ diff --git a/Task/List-comprehensions/REXX/list-comprehensions-2.rexx b/Task/List-comprehensions/REXX/list-comprehensions-2.rexx new file mode 100644 index 0000000000..2c97a5797d --- /dev/null +++ b/Task/List-comprehensions/REXX/list-comprehensions-2.rexx @@ -0,0 +1,17 @@ +/*REXX program lists Pythagorean triples up to a specified number. */ +parse arg n . /*get the optional argument. */ +if n=='' then n=100 /*Not specified? Then assume 100*/ +$= /*assign a null to triples list. */ + do a=1 for n-2; aa=a*a /*Note: A*A is faster than A**2,*/ + do b=a+1 to n-1; aabb=aa+b*b /* ··· but not by much.*/ + do c=b+1 to n + if aabb==c*c then $=$ '('a"," || b','c")" + end /*c*/ + end /*b*/ + end /*a*/ +if 'f5'x==5 then do; sup2='b2'x; le='8c'x; end /*EBCDIC?*/ + else do; sup2='fd'x; le='f3'x; end /* ASCII?*/ +say 'Pythagorean triples (a'sup2 "+ b"sup2 '= c'sup2", c "le n'):' +say; say strip($) /*show the Pythagorean triples. */ +say; say words($) 'members listed.' /*triples listed in order of 1st#*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/List-comprehensions/REXX/list-comprehensions.rexx b/Task/List-comprehensions/REXX/list-comprehensions.rexx deleted file mode 100644 index be607c5be8..0000000000 --- a/Task/List-comprehensions/REXX/list-comprehensions.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX program to list Pythagorean triples up to a specified number. */ -parse arg n . /*get the argument (possibly). */ -if n=='' then n=100 /*Not specified? Then assume 100*/ -call gen_triples n /*generate Pythagorean triples. */ -call showhdr /*show a nice header. */ -call showlist triples /*show the Pythagorean triples. */ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────GEN_TRIPLES subroutine──────────────*/ -gen_triples: parse arg lim /*generate Pythorgorean triples. */ -triples= - - do a=1 for lim-2; aa=a*a /*a*a is faster than a**2 */ - do b=a+1 to lim-1; aabb=aa+b*b - do c=b+1 to lim - if aabb==c*c then triples=triples '['a"-" || b'-'c"]" - end /*c*/ - end /*b*/ - end /*a*/ - -triples=strip(triples) -return -/*──────────────────────────────────SHOWHDR subroutine──────────────────*/ -showHdr: say -if 'f0'x==0 then do; super2='b2'x; le='8c'x; end /*EBCDIC: super2, LE */ - else do; super2='fd'x; le='f3'x; end /* ASCII: " " */ -note='(a'super2 "+ b"super2 '= c'super2", c "le n')' /*prettify equat.*/ -say 'Pythagorean triples' note":" -return -/*──────────────────────────────────SHOWLIST subroutine─────────────────*/ -showlist: procedure; parse arg L /*get the list (L). */ -w=words(L) /*number of members in the list. */ -say; do j=1 for w /*display the members of the list*/ - say word(L,j) - end /*j*/ -say; say w 'members listed.' -return diff --git a/Task/Literals-Floating-point/Eiffel/literals-floating-point.e b/Task/Literals-Floating-point/Eiffel/literals-floating-point.e new file mode 100644 index 0000000000..a19c66015d --- /dev/null +++ b/Task/Literals-Floating-point/Eiffel/literals-floating-point.e @@ -0,0 +1,5 @@ +1. +1.23 +1e-5 +.5 +1.23E4 diff --git a/Task/Literals-Floating-point/Euphoria/literals-floating-point.euphoria b/Task/Literals-Floating-point/Euphoria/literals-floating-point.euphoria new file mode 100644 index 0000000000..a5d33eabd6 --- /dev/null +++ b/Task/Literals-Floating-point/Euphoria/literals-floating-point.euphoria @@ -0,0 +1,3 @@ +printf(1,"Exponential:\t%e, %e, %e, %e\n",{-10.1246,10.2356,16.123456789,64.12}) +printf(1,"Floating Point\t%03.3f, %04.3f, %+3.3f, %3.3f\n",{-10.1246,10.2356,16.123456789,64.12}) +printf(1,"Floating Point or Exponential: %g, %g, %g, %g\n",{10,16.123456789,64,123456789.123}) diff --git a/Task/Literals-Integer/00META.yaml b/Task/Literals-Integer/00META.yaml index 659c8686af..3548159ac8 100644 --- a/Task/Literals-Integer/00META.yaml +++ b/Task/Literals-Integer/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Basic language learning diff --git a/Task/Literals-Integer/Eiffel/literals-integer-1.e b/Task/Literals-Integer/Eiffel/literals-integer-1.e new file mode 100644 index 0000000000..19f675a42f --- /dev/null +++ b/Task/Literals-Integer/Eiffel/literals-integer-1.e @@ -0,0 +1,5 @@ +123 -- decimal +-1_2_3 -- decimal +0x7b -- hexadecimal +0c173 -- octal +0b111_1011 -- binary diff --git a/Task/Literals-Integer/Eiffel/literals-integer-2.e b/Task/Literals-Integer/Eiffel/literals-integer-2.e new file mode 100644 index 0000000000..e567be14c6 --- /dev/null +++ b/Task/Literals-Integer/Eiffel/literals-integer-2.e @@ -0,0 +1,2 @@ +{NATURAL_8} 255 +{INTEGER_64} 2_147_483_648 diff --git a/Task/Literals-Integer/Euphoria/literals-integer.euphoria b/Task/Literals-Integer/Euphoria/literals-integer.euphoria new file mode 100644 index 0000000000..238d62b7fc --- /dev/null +++ b/Task/Literals-Integer/Euphoria/literals-integer.euphoria @@ -0,0 +1,6 @@ +printf(1,"Decimal:\t%d, %d, %d, %d\n",{-10,10,16,64}) +printf(1,"Hex:\t%x, %x, %x, %x\n",{-10,10,16,64}) +printf(1,"Octal:\t%o, %o, %o, %o\n",{-10,10,16,64}) +printf(1,"Exponential:\t%e, %e, %e, %e\n",{-10,10,16,64.12}) +printf(1,"Floating Point\t%3.3f, %3.3f, %+3.3f\n",{-10,10.2,16.25,64.12625}) +printf(1,"Floating Point or Exponential: %g, %g, %g, %g\n",{10,16,64,123456789.123}) diff --git a/Task/Literals-Integer/Julia/literals-integer.julia b/Task/Literals-Integer/Julia/literals-integer.julia new file mode 100644 index 0000000000..389c05ee24 --- /dev/null +++ b/Task/Literals-Integer/Julia/literals-integer.julia @@ -0,0 +1,2 @@ +julia> 0b1011010111 == 0o1327 == 0x2d7 == 727 +true diff --git a/Task/Literals-Integer/Mercury/literals-integer.mercury b/Task/Literals-Integer/Mercury/literals-integer.mercury new file mode 100644 index 0000000000..a7d08bf047 --- /dev/null +++ b/Task/Literals-Integer/Mercury/literals-integer.mercury @@ -0,0 +1,4 @@ +Bin = 0b010101, +Octal = 0o666, +Hex = 0x1fa, +CharCode = 0'a. diff --git a/Task/Literals-String/00DESCRIPTION b/Task/Literals-String/00DESCRIPTION index fb6beedb3d..e191b92f11 100644 --- a/Task/Literals-String/00DESCRIPTION +++ b/Task/Literals-String/00DESCRIPTION @@ -1,3 +1,5 @@ -Show literal specification of characters and strings. If supported, show how verbatim strings (quotes where escape sequences are quoted literally) and here-strings work. Also, discuss which quotes expand variables. +Show literal specification of characters and strings. +If supported, show how verbatim strings (quotes where escape sequences are quoted literally) and here-strings work. +Also, discuss which quotes expand variables. * Related tasks: [[Special characters]], [[Here document]] diff --git a/Task/Literals-String/00META.yaml b/Task/Literals-String/00META.yaml index 659c8686af..0581230ff5 100644 --- a/Task/Literals-String/00META.yaml +++ b/Task/Literals-String/00META.yaml @@ -1,2 +1,5 @@ --- +category: +- String manipulation +- Syntax elements note: Basic language learning diff --git a/Task/Literals-String/Emacs-Lisp/literals-string-1.l b/Task/Literals-String/Emacs-Lisp/literals-string-1.l new file mode 100644 index 0000000000..86d452d95b --- /dev/null +++ b/Task/Literals-String/Emacs-Lisp/literals-string-1.l @@ -0,0 +1 @@ +"This is a string." diff --git a/Task/Literals-String/Emacs-Lisp/literals-string-2.l b/Task/Literals-String/Emacs-Lisp/literals-string-2.l new file mode 100644 index 0000000000..71aa260500 --- /dev/null +++ b/Task/Literals-String/Emacs-Lisp/literals-string-2.l @@ -0,0 +1,2 @@ +?z => 122 +?\n => 10 diff --git a/Task/Literals-String/Go/literals-string-1.go b/Task/Literals-String/Go/literals-string-1.go index 2b192559cb..ce99408cad 100644 --- a/Task/Literals-String/Go/literals-string-1.go +++ b/Task/Literals-String/Go/literals-string-1.go @@ -1 +1,6 @@ ch := 'z' +ch = 122 // or 0x7a or 0172 or any other integer literal +ch = '\x7a' // \x{2*hex} +ch = '\u007a' // \u{4*hex} +ch = '\U0000007a' // \U{8*hex} +ch = '\172' // \{3*octal} diff --git a/Task/Literals-String/Go/literals-string-2.go b/Task/Literals-String/Go/literals-string-2.go index 5d94bdc6c7..d11ebed956 100644 --- a/Task/Literals-String/Go/literals-string-2.go +++ b/Task/Literals-String/Go/literals-string-2.go @@ -1,6 +1,14 @@ -ch := 'z' // by default, ch takes type int32 -var r rune = 'z' // reflect.TypeOf(r) still returns int32 -var b byte = 'z' // reflect.TypeOf(b) returns uint8 +ch := 'z' // ch is type rune (an int32 type) +var r rune = 'z' // r is type rune +var b byte = 'z' // b is type byte (an uint8 type) b2 := byte('z') // equivalent to b -const c byte = 'z' // c is now a "typed constant" +const z = 'z' // z is untyped, it may be freely assigned or used in any integer expression +b = z +r = z +ch2 := z // equivalent to ch (type rune) +var i int = z +const c byte = 'z' // c is a typed constant +b = c +r = rune(c) +i = int(c) b3 := c // equivalent to b diff --git a/Task/Literals-String/Go/literals-string-3.go b/Task/Literals-String/Go/literals-string-3.go index 6f2b67bd93..4dc4d3a9f8 100644 --- a/Task/Literals-String/Go/literals-string-3.go +++ b/Task/Literals-String/Go/literals-string-3.go @@ -1 +1,3 @@ str := "z" +str = "\u007a" +str = "two\nlines" diff --git a/Task/Literals-String/Go/literals-string-6.go b/Task/Literals-String/Go/literals-string-6.go index 6f9a70b82d..5c5f5216a8 100644 --- a/Task/Literals-String/Go/literals-string-6.go +++ b/Task/Literals-String/Go/literals-string-6.go @@ -1,2 +1,2 @@ `abc -def` == "abc\ndef" +def` == "abc\ndef", // never "abc\r\ndef" even if the source file contains CR+LF line endings diff --git a/Task/Literals-String/REXX/literals-string-3.rexx b/Task/Literals-String/REXX/literals-string-3.rexx index 645bcaf90b..7c19a751d4 100644 --- a/Task/Literals-String/REXX/literals-string-3.rexx +++ b/Task/Literals-String/REXX/literals-string-3.rexx @@ -1,16 +1,7 @@ -It's also possible to express characters in hexadecimal notation in a string: lf = '0A'x cr = '0D'x -mmm='01 02 03 34 ee'x -ppp='dead beaf 11112222 33334444 55556666 77778888 00009999 c0ffee'X +mmm = '01 02 03 34 ee'x +ppp = 'dead beaf 11112222 33334444 55556666 77778888 00009999 c0ffee'X -lang='52455858'x /*which is "REXX" on ASCII-computers.*/ - -Binary strings are also possible: - -jjj='01011011'B -jjj='01011011'b -jjj="0101 1011"b -jjj='0101 1011 1111'b -longjjj='11110000 10100001 10110010 11100011 11100100'B +lang = '52455858'x /*which is "REXX" on ASCII-computers.*/ diff --git a/Task/Literals-String/REXX/literals-string-4.rexx b/Task/Literals-String/REXX/literals-string-4.rexx new file mode 100644 index 0000000000..31bb9b6d30 --- /dev/null +++ b/Task/Literals-String/REXX/literals-string-4.rexx @@ -0,0 +1,5 @@ +jjj = '01011011'B +jjj = '01011011'b +jjj = "0101 1011"b +jjj = '0101 1011 1111'b +longjjj = '11110000 10100001 10110010 11100011 11100100'B diff --git a/Task/Logical-operations/00DESCRIPTION b/Task/Logical-operations/00DESCRIPTION index d26c2bc215..a7d54c6e0c 100644 --- a/Task/Logical-operations/00DESCRIPTION +++ b/Task/Logical-operations/00DESCRIPTION @@ -1,3 +1,5 @@ -{{basic data operation}}Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments. If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose. + {{basic data operation}} [[Category:Simple]] +Write a function that takes two logical (boolean) values, and outputs the result of "and" and "or" on both arguments as well as "not" on the first arguments. +If the programming language doesn't provide a separate type for logical values, use the type most commonly used for that purpose. If the language supports additional logical operations on booleans such as XOR, list them as well. diff --git a/Task/Logical-operations/Excel/logical-operations-1.excel b/Task/Logical-operations/Excel/logical-operations-1.excel new file mode 100644 index 0000000000..ed75a27149 --- /dev/null +++ b/Task/Logical-operations/Excel/logical-operations-1.excel @@ -0,0 +1 @@ +=CONCATENATE($A1, " AND ", $B1, " is ", AND($A1,$B1)) diff --git a/Task/Logical-operations/Excel/logical-operations-2.excel b/Task/Logical-operations/Excel/logical-operations-2.excel new file mode 100644 index 0000000000..9efcf244f7 --- /dev/null +++ b/Task/Logical-operations/Excel/logical-operations-2.excel @@ -0,0 +1 @@ +=CONCATENATE($A1, " OR ", $B1, " is ", OR($A1,$B1)) diff --git a/Task/Logical-operations/Excel/logical-operations-3.excel b/Task/Logical-operations/Excel/logical-operations-3.excel new file mode 100644 index 0000000000..1107b6838e --- /dev/null +++ b/Task/Logical-operations/Excel/logical-operations-3.excel @@ -0,0 +1 @@ +=CONCATENATE(" NOT ", $A1, " is ", NOT($A1)) diff --git a/Task/Logical-operations/OOC/logical-operations.ooc b/Task/Logical-operations/OOC/logical-operations.ooc new file mode 100644 index 0000000000..7d73a2d306 --- /dev/null +++ b/Task/Logical-operations/OOC/logical-operations.ooc @@ -0,0 +1,14 @@ +logic: func (a: Bool, b: Bool) { + println() + "A=#{a}, B=#{b}:" println() + "AND: #{a && b}" println() + "OR: #{a || b}" println() + "NOT A: #{!a}" println() +} + +main: func { + logic(true, false) + logic(true, true) + logic(false, false) + logic(false, true) +} diff --git a/Task/Logical-operations/Perl-6/logical-operations.pl6 b/Task/Logical-operations/Perl-6/logical-operations.pl6 new file mode 100644 index 0000000000..462a98b1c7 --- /dev/null +++ b/Task/Logical-operations/Perl-6/logical-operations.pl6 @@ -0,0 +1,29 @@ +sub logic($a,$b) { + say "$a && $b is ", $a && $b; # short-circuiting + say "$a || $b is ", $a || $b; # short-circuiting + say "$a ^^ $b is ", $a ^^ $b; + say "!$a is ", !$a; + + say "$a ?& $b is ", $a ?& $b; # non-short-circuiting + say "$a ?| $b is ", $a ?| $b; # non-short-circuiting + say "$a ?^ $b is ", $a ?^ $b; # non-short-circuiting + + say "$a +& $b is ", $a +& $b; # numeric bitwise + say "$a +| $b is ", $a +| $b; # numeric bitwise + say "$a +^ $b is ", $a +^ $b; # numeric bitwise + + say "$a ~& $b is ", $a ~& $b; # buffer bitwise + say "$a ~| $b is ", $a ~| $b; # buffer bitwise + say "$a ~^ $b is ", $a ~| $b; # buffer bitwise + + say "$a & $b is ", $a & $b; # junctional/autothreading + say "$a | $b is ", $a | $b; # junctional/autothreading + say "$a ^ $b is ", $a ^ $b; # junctional/autothreading + + say "$a and $b is ", ($a and $b); # loose short-circuiting + say "$a or $b is ", ($a or $b); # loose short-circuiting + say "$a xor $b is ", ($a xor $b); + say "not $a is ", (not $a); +} + +logic(3,10); diff --git a/Task/Logical-operations/Rascal/logical-operations.rascal b/Task/Logical-operations/Rascal/logical-operations.rascal new file mode 100644 index 0000000000..ceb4b1044d --- /dev/null +++ b/Task/Logical-operations/Rascal/logical-operations.rascal @@ -0,0 +1,9 @@ +import IO; + +public void logic(bool a, bool b){ + println("a and b, is "); + println("a or b, is "); + println("a equivalent to b, is b>"); + println("a implies b, is b>"); + println("not a", "); +} diff --git a/Task/Logical-operations/Ruby/logical-operations.rb b/Task/Logical-operations/Ruby/logical-operations.rb index 1c7ef69415..d72727eab4 100644 --- a/Task/Logical-operations/Ruby/logical-operations.rb +++ b/Task/Logical-operations/Ruby/logical-operations.rb @@ -1,5 +1,6 @@ def logic(a, b) - print 'a and b: ', a && b, "\n" - print 'a or b: ' , a || b, "\n" - print 'not a: ' , !a , "\n" + print 'a and b: ', a && b, "\n" + print 'a or b: ' , a || b, "\n" + print 'not a: ' , !a , "\n" + print 'a xor b: ' , a ^ b, "\n" end diff --git a/Task/Logical-operations/Slate/logical-operations.slate b/Task/Logical-operations/Slate/logical-operations.slate new file mode 100644 index 0000000000..469d35b416 --- /dev/null +++ b/Task/Logical-operations/Slate/logical-operations.slate @@ -0,0 +1,9 @@ +{#/\. #\/. #not} do: [ |:func| + func arity = 1 ifTrue: [inform: 'True ' ; (func as: String) ; ' = ' ; (func sendTo: {True}) printString. + inform: 'False ' ; (func as: String) ; ' = ' ; (func sendTo: {False}) printString.]. + + func arity = 2 + ifTrue: [{{True. True}. {True. False}. {False. True}. {False. False}} do: + [ |:each| inform: each first printString ; (func as: String) ; each second printString ; ' = ' ; (func sendTo: each) printString]] + +]. diff --git a/Task/Long-multiplication/D/long-multiplication-2.d b/Task/Long-multiplication/D/long-multiplication-2.d index 733d7ac09a..6c3fc38825 100644 --- a/Task/Long-multiplication/D/long-multiplication-2.d +++ b/Task/Long-multiplication/D/long-multiplication-2.d @@ -1,11 +1,11 @@ -import std.stdio, std.algorithm, std.range, std.ascii; +import std.stdio, std.algorithm, std.range, std.ascii, std.string; -auto longMult(in string x1, in string x2) pure /*nothrow*/ { - auto digits1 = x1.retro.map!q{a - '0'}; - immutable digits2 = x2.retro.map!q{a - '0'}.array; +auto longMult(in string x1, in string x2) pure nothrow @safe { + auto digits1 = x1.representation.retro.map!q{a - '0'}; + immutable digits2 = x2.representation.retro.map!q{a - '0'}.array; uint[] res; - foreach (immutable i, immutable d1; uint.max.iota.zip(digits1)) { + foreach (immutable i, immutable d1; digits1.enumerate) { foreach (immutable j, immutable d2; digits2) { immutable k = i + j; if (res.length <= k) diff --git a/Task/Long-multiplication/PicoLisp/long-multiplication.l b/Task/Long-multiplication/PicoLisp/long-multiplication.l index 18146c4233..e67625fa9c 100644 --- a/Task/Long-multiplication/PicoLisp/long-multiplication.l +++ b/Task/Long-multiplication/PicoLisp/long-multiplication.l @@ -1,2 +1,5 @@ -: (* (** 2 64) (** 2 64)) --> 340282366920938463463374607431768211456 +(de multi (A B) + (setq A (format A) B (reverse (chop B))) + (let Result 0 + (for (I . X) B + (setq Result (+ Result (* (format X) A (** 10 (dec I)))))) ) ) diff --git a/Task/Long-multiplication/Scheme/long-multiplication.ss b/Task/Long-multiplication/Scheme/long-multiplication.ss index 1fc943a0cd..993ac0b18e 100644 --- a/Task/Long-multiplication/Scheme/long-multiplication.ss +++ b/Task/Long-multiplication/Scheme/long-multiplication.ss @@ -1 +1,8 @@ -(* (expt 2 64) (expt 2 64)) +(define one (lambda (f) (lambda (x) (f x)))) +(define (add a b) (lambda (f) (lambda (x) ((a f) ((b f) x))))) +(define (mult a b) (lambda (f) (lambda (x) ((a (b f)) x)))) +(define (expo a b) (lambda (f) (lambda (x) (((b a) f) x)))) +(define two (add one one)) +(define six (add two (add two two))) +(define sixty-four (expo two six)) +(display (mult (expo two sixty-four) (expo two sixty-four))) diff --git a/Task/Longest-common-subsequence/APL/longest-common-subsequence.apl b/Task/Longest-common-subsequence/APL/longest-common-subsequence.apl new file mode 100644 index 0000000000..f0262b691f --- /dev/null +++ b/Task/Longest-common-subsequence/APL/longest-common-subsequence.apl @@ -0,0 +1,21 @@ +lcs←{ + ⎕IO←0 + betterof←{⊃(/1 ¯1↓[1]¨⊂⍵} ⍝ rising rows + hmrr←{∨/(rr ⍵)∧∧/⍵=⌈\⍵} ⍝ has monotonically rising rows + rnbc←{{⍵/⍳⍴⍵}¨↓[0]×⍵} ⍝ row numbers by column + valid←hmrr∘cmbn∘rnbc ⍝ any valid solutions? + a w←( +#include +#include // for shared_ptr<> +#include +#include +#include +#include // for lower_bound() + +using namespace std; + +class LCS { +protected: + // This linked list class is used to trace the LCS candidates + class Pair { + public: + uint32_t index1; + uint32_t index2; + shared_ptr next; + + Pair(uint32_t index1, uint32_t index2, shared_ptr next = nullptr) + : index1(index1), index2(index2), next(next) { + } + + static shared_ptr Reverse(const shared_ptr pairs) { + shared_ptr head = nullptr; + for (auto next = pairs; next != nullptr; next = next->next) + head = make_shared(next->index1, next->index2, head); + return head; + } + }; + + typedef deque> PAIRS; + typedef deque THRESHOLD; + typedef deque INDEXES; + typedef map CHAR2INDEXES; + typedef deque MATCHES; + + // return the LCS as a linked list of matched index pairs + uint64_t LCS::Pairs(MATCHES& matches, shared_ptr *pairs) { + auto trace = pairs != nullptr; + PAIRS traces; + THRESHOLD threshold; + + // + //[Assert]After each index1 iteration threshold[index3] is the least index2 + // such that the LCS of s1[0:index1] and s2[0:index2] has length index3 + 1 + // + uint32_t index1 = 0; + for (const auto& it1 : matches) { + if (!it1->empty()) { + auto dq2 = *it1; + auto limit = threshold.end(); + for (auto it2 = dq2.begin(); it2 != dq2.end(); it2++) + { + // Each of the index1, index2 pairs considered here correspond to a match + auto index2 = *it2; + // + // Note: The index2 values are monotonically decreasing, which allows the + // thresholds to be updated in place. Montonicity allows a binary search, + // implemented here by std::lower_bound() + // + limit = lower_bound(threshold.begin(), limit, index2); + auto index3 = distance(threshold.begin(), limit); + + // + // Look ahead to the next index2 value to optimize space used in the Hunt + // and Szymanski algorithm. If the next index2 is also an improvement on + // the value currently held in threshold[index3], a new Pair will only be + // superseded on the next index2 iteration. + // + // Depending on match redundancy, the number of Pair constructions may be + // divided by factors ranging from 2 up to 10 or more. + // + auto skip = it2 + 1 != dq2.end() && + (limit == threshold.begin() || *(limit - 1) < *(it2 + 1)); + + if (skip) continue; + + if (limit == threshold.end()) { + // insert case + threshold.push_back(index2); + if (trace) { + auto prefix = index3 > 0 ? traces[index3 - 1] : nullptr; + auto last = make_shared(index1, index2, prefix); + traces.push_back(last); + } + } + else if (index2 < *limit) { + // replacement case + *limit = index2; + if (trace) { + auto prefix = index3 > 0 ? traces[index3 - 1] : nullptr; + auto last = make_shared(index1, index2, prefix); + traces[index3] = last; + } + } + } // next index2 + } + + index1++; + } // next index1 + + if (trace) { + auto last = traces.size() > 0 ? traces.back() : nullptr; + // Reverse longest back-trace + *pairs = Pair::Reverse(last); + } + + auto length = threshold.size(); + return length; + } + + // + // Match() avoids incurring m*n comparisons by using the associative memory + // implemented by CHAR2INDEXES to achieve O(m+n) performance, where m and n + // are the input lengths. + // + // The symbol space is sparse in the case of records; so, the lookup time is + // at most O(log(m+n)). The lookup time can be assumed constant in the case + // of characters. + // + void Match(CHAR2INDEXES& indexes, MATCHES& matches, + const string& s1, const string& s2) { + uint32_t index = 0; + for (const auto& it : s2) + indexes[it].push_front(index++); + + for (const auto& it : s1) { + auto& dq2 = indexes[it]; + matches.push_back(&dq2); + } + } + + string Select(shared_ptr pairs, uint64_t length, + bool right, const string& s1, const string& s2) { + string buffer; + buffer.reserve(length); + for (auto next = pairs; next != nullptr; next = next->next) { + auto c = right ? s2[next->index2] : s1[next->index1]; + buffer.push_back(c); + } + return buffer; + } + +public: + string Correspondence(const string& s1, const string& s2) { + CHAR2INDEXES indexes; + MATCHES matches; // holds references into indexes + Match(indexes, matches, s1, s2); + shared_ptr pairs; // obtain the LCS as index pairs + auto length = Pairs(matches, &pairs); + return Select(pairs, length, false, s1, s2); + } +}; diff --git a/Task/Longest-common-subsequence/C++/longest-common-subsequence-2.cpp b/Task/Longest-common-subsequence/C++/longest-common-subsequence-2.cpp new file mode 100644 index 0000000000..4874fdc883 --- /dev/null +++ b/Task/Longest-common-subsequence/C++/longest-common-subsequence-2.cpp @@ -0,0 +1,3 @@ + LCS lcs; + auto s = lcs.Correspondence(s1, s2); + cout << s << endl; diff --git a/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-4.lisp b/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-4.lisp new file mode 100644 index 0000000000..f7aed47b27 --- /dev/null +++ b/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-4.lisp @@ -0,0 +1,14 @@ +(defmacro mem-defun (name args body) + (let ((hash-name (gensym))) + `(let ((,hash-name (make-hash-table :test 'equal))) + (defun ,name ,args + (or (gethash (list ,@args) ,hash-name) + (setf (gethash (list ,@args) ,hash-name) + ,body)))))) + +(mem-defun lcs (xs ys) + (labels ((longer (a b) (if (> (length a) (length b)) a b))) + (cond ((or (null xs) (null ys)) nil) + ((equal (car xs) (car ys)) (cons (car xs) (lcs (cdr xs) (cdr ys)))) + (t (longer (lcs (cdr xs) ys) + (lcs xs (cdr ys))))))) diff --git a/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-5.lisp b/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-5.lisp new file mode 100644 index 0000000000..69ae9e2050 --- /dev/null +++ b/Task/Longest-common-subsequence/Common-Lisp/longest-common-subsequence-5.lisp @@ -0,0 +1,3 @@ +(coerce (lcs (coerce "thisisatest" 'list) (coerce "testing123testing" 'list)) 'string)))) + +"tsitest" diff --git a/Task/Longest-common-subsequence/D/longest-common-subsequence-1.d b/Task/Longest-common-subsequence/D/longest-common-subsequence-1.d index fb3bb2a091..084d48b8db 100644 --- a/Task/Longest-common-subsequence/D/longest-common-subsequence-1.d +++ b/Task/Longest-common-subsequence/D/longest-common-subsequence-1.d @@ -1,6 +1,6 @@ import std.stdio, std.array; -T[] lcs(T)(in T[] a, in T[] b) pure nothrow { +T[] lcs(T)(in T[] a, in T[] b) pure nothrow @safe { if (a.empty || b.empty) return null; if (a[0] == b[0]) return a[0] ~ lcs(a[1 .. $], b[1 .. $]); 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 248c3bb517..b4bd24bb3e 100644 --- a/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d +++ b/Task/Longest-common-subsequence/D/longest-common-subsequence-3.d @@ -1,7 +1,6 @@ -import std.stdio, std.algorithm, std.range, std.array, std.string, - std.typecons; +import std.stdio, std.algorithm, std.range, std.array, std.string, std.typecons; -uint[] lensLCS(R)(R xs, R ys) pure nothrow { +uint[] lensLCS(R)(R xs, R ys) pure nothrow @safe { auto prev = new typeof(return)(1 + ys.length); auto curr = new typeof(return)(1 + ys.length); @@ -9,9 +8,7 @@ uint[] lensLCS(R)(R xs, R ys) pure nothrow { swap(curr, prev); size_t i = 0; foreach (immutable y; ys) { - curr[i + 1] = (x == y) - ? prev[i] + 1 - : max(curr[i], prev[i + 1]); + curr[i + 1] = (x == y) ? prev[i] + 1 : max(curr[i], prev[i + 1]); i++; } } @@ -20,7 +17,7 @@ uint[] lensLCS(R)(R xs, R ys) pure nothrow { } void calculateLCS(T)(in T[] xs, in T[] ys, bool[] xs_in_lcs, - in size_t idx=0) pure nothrow { + in size_t idx=0) pure nothrow @safe { immutable nx = xs.length; immutable ny = ys.length; @@ -36,33 +33,27 @@ void calculateLCS(T)(in T[] xs, in T[] ys, bool[] xs_in_lcs, const xe = xs[mid .. $]; immutable ll_b = lensLCS(xb, ys); - // retro is slow with dmd. - const ll_e = lensLCS(xe.retro, ys.retro); + const ll_e = lensLCS(xe.retro, ys.retro); // retro is slow with dmd. //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]; + .minPos!((i, j) => tuple(ll_b[i] + ll_e[ny - i]) > + tuple(ll_b[j] + ll_e[ny - j]))[0]; calculateLCS(xb, ys[0 .. k], xs_in_lcs, idx); calculateLCS(xe, ys[k .. $], xs_in_lcs, idx + mid); } } -const(T)[] lcs(T)(in T[] xs, in T[] ys) pure /*nothrow*/ { +const(T)[] lcs(T)(in T[] xs, in T[] ys) pure /*nothrow*/ @safe { auto xs_in_lcs = new bool[xs.length]; calculateLCS(xs, ys, xs_in_lcs); - - return zip(xs, xs_in_lcs) // Not nothrow. - .filter!q{ a[1] } - .map!q{ a[0] } - .array; + return zip(xs, xs_in_lcs).filter!q{ a[1] }.map!q{ a[0] }.array; // Not nothrow. } -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); +string lcsString(in string s1, in string s2) pure /*nothrow*/ @safe { + return lcs(s1.representation, s2.representation).assumeUTF; } void main() { diff --git a/Task/Longest-common-subsequence/Erlang/longest-common-subsequence-3.erl b/Task/Longest-common-subsequence/Erlang/longest-common-subsequence-3.erl new file mode 100644 index 0000000000..7d0259a594 --- /dev/null +++ b/Task/Longest-common-subsequence/Erlang/longest-common-subsequence-3.erl @@ -0,0 +1,23 @@ +lcs(Xs0, Ys0) -> + CacheKey = {lcs_cache, Xs0, Ys0}, + case get(CacheKey) + of undefined -> + Result = + case {Xs0, Ys0} + of {[], _} -> [] + ; {_, []} -> [] + ; {[Same | Xs], [Same | Ys]} -> + [Same | lcs(Xs, Ys)] + ; {[_ | XsRest]=XsAll, [_ | YsRest]=YsAll} -> + A = lcs(XsRest, YsAll), + B = lcs(XsAll , YsRest), + case length(A) > length(B) + of true -> A + ; false -> B + end + end, + undefined = put(CacheKey, Result), + Result + ; Result -> + Result + end. diff --git a/Task/Longest-common-subsequence/Go/longest-common-subsequence-2.go b/Task/Longest-common-subsequence/Go/longest-common-subsequence-2.go index 56e0c4484a..aad0a15e4e 100644 --- a/Task/Longest-common-subsequence/Go/longest-common-subsequence-2.go +++ b/Task/Longest-common-subsequence/Go/longest-common-subsequence-2.go @@ -1,41 +1,42 @@ func lcs(a, b string) string { - aLen := len(a) - bLen := len(b) - lengths := make([][]int, aLen+1) - for i := 0; i <= aLen; i++ { - lengths[i] = make([]int, bLen+1) - } - // row 0 and column 0 are initialized to 0 already + arunes := []rune(a) + brunes := []rune(b) + aLen := len(arunes) + bLen := len(brunes) + lengths := make([][]int, aLen+1) + for i := 0; i <= aLen; i++ { + lengths[i] = make([]int, bLen+1) + } + // row 0 and column 0 are initialized to 0 already - for i := 0; i < aLen; i++ { - for j := 0; j < bLen; j++ { - if a[i] == b[j] { - lengths[i+1][j+1] = lengths[i][j]+1 - } else if lengths[i+1][j] > lengths[i][j+1] { - lengths[i+1][j+1] = lengths[i+1][j] - } else { - lengths[i+1][j+1] = lengths[i][j+1] - } - } - } + for i := 0; i < aLen; i++ { + for j := 0; j < bLen; j++ { + if arunes[i] == brunes[j] { + lengths[i+1][j+1] = lengths[i][j] + 1 + } else if lengths[i+1][j] > lengths[i][j+1] { + lengths[i+1][j+1] = lengths[i+1][j] + } else { + lengths[i+1][j+1] = lengths[i][j+1] + } + } + } - // read the substring out from the matrix - s := make([]byte, 0, lengths[aLen][bLen]) - for x, y := aLen, bLen; x != 0 && y != 0; { - if lengths[x][y] == lengths[x-1][y] { - x-- - } else if lengths[x][y] == lengths[x][y-1] { - y-- - } else { - s = append(s, a[x-1]) - x-- - y-- - } - } - // reverse string - r := make([]byte, len(s)) - for i := 0; i < len(s); i++ { - r[i] = s[len(s)-1-i] - } - return string(r) + // read the substring out from the matrix + s := make([]rune, 0, lengths[aLen][bLen]) + for x, y := aLen, bLen; x != 0 && y != 0; { + if lengths[x][y] == lengths[x-1][y] { + x-- + } else if lengths[x][y] == lengths[x][y-1] { + y-- + } else { + s = append(s, arunes[x-1]) + x-- + y-- + } + } + // reverse string + for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { + s[i], s[j] = s[j], s[i] + } + return string(s) } diff --git a/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-2.ocaml b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-2.ocaml index c460773e7f..200adb1f69 100644 --- a/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-2.ocaml +++ b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-2.ocaml @@ -1,15 +1,20 @@ -let lcs xs' ys' = - let xs = Array.of_list xs' - and ys = Array.of_list ys' in - let n = Array.length xs - and m = Array.length ys in - let a = Array.make_matrix (n+1) (m+1) [] in - for i = n-1 downto 0 do - for j = m-1 downto 0 do - a.(i).(j) <- if xs.(i) = ys.(j) then - xs.(i) :: a.(i+1).(j+1) - else - longest a.(i).(j+1) a.(i+1).(j) - done - done; - a.(0).(0) +let lcs xs ys = + let cache = Hashtbl.create 16 in + let rec lcs xs ys = + try Hashtbl.find cache (xs, ys) with + | Not_found -> + let result = + match xs, ys with + | [], _ -> [] + | _, [] -> [] + | x :: xs, y :: ys when x = y -> + x :: lcs xs ys + | _ :: xs_rest, _ :: ys_rest -> + let a = lcs xs_rest ys in + let b = lcs xs ys_rest in + if (List.length a) > (List.length b) then a else b + in + Hashtbl.add cache (xs, ys) result; + result + in + lcs xs ys diff --git a/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-3.ocaml b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-3.ocaml index dff5cd0b68..c460773e7f 100644 --- a/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-3.ocaml +++ b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-3.ocaml @@ -1,10 +1,15 @@ -let list_of_string str = - let result = ref [] in - String.iter (fun x -> result := x :: !result) - str; - List.rev !result - -let string_of_list lst = - let result = String.create (List.length lst) in - ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); - result +let lcs xs' ys' = + let xs = Array.of_list xs' + and ys = Array.of_list ys' in + let n = Array.length xs + and m = Array.length ys in + let a = Array.make_matrix (n+1) (m+1) [] in + for i = n-1 downto 0 do + for j = m-1 downto 0 do + a.(i).(j) <- if xs.(i) = ys.(j) then + xs.(i) :: a.(i+1).(j+1) + else + longest a.(i).(j+1) a.(i+1).(j) + done + done; + a.(0).(0) diff --git a/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-4.ocaml b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-4.ocaml new file mode 100644 index 0000000000..dff5cd0b68 --- /dev/null +++ b/Task/Longest-common-subsequence/OCaml/longest-common-subsequence-4.ocaml @@ -0,0 +1,10 @@ +let list_of_string str = + let result = ref [] in + String.iter (fun x -> result := x :: !result) + str; + List.rev !result + +let string_of_list lst = + let result = String.create (List.length lst) in + ignore (List.fold_left (fun i x -> result.[i] <- x; i+1) 0 lst); + result diff --git a/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-1.rb b/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-1.rb index 162f6c0677..04d70b757c 100644 --- a/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-1.rb +++ b/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-1.rb @@ -3,12 +3,12 @@ irb(main):001:0> lcs('thisisatest', 'testing123testing') => "tsitest" =end def lcs(xstr, ystr) - return "" if xstr.empty? || ystr.empty? + return "" if xstr.empty? || ystr.empty? - x, xs, y, ys = xstr[0..0], xstr[1..-1], ystr[0..0], ystr[1..-1] - if x == y - x + lcs(xs, ys) - else - [lcs(xstr, ys), lcs(xs, ystr)].max_by {|x| x.size} - end + x, xs, y, ys = xstr[0..0], xstr[1..-1], ystr[0..0], ystr[1..-1] + if x == y + x + lcs(xs, ys) + else + [lcs(xstr, ys), lcs(xs, ystr)].max_by {|x| x.size} + end end diff --git a/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-2.rb b/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-2.rb index 25b87f316c..a33af54952 100644 --- a/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-2.rb +++ b/Task/Longest-common-subsequence/Ruby/longest-common-subsequence-2.rb @@ -1,11 +1,22 @@ -class LcsWalker +class LCS SELF, LEFT, UP, DIAG = [0,0], [0,-1], [-1,0], [-1,-1] - def initialize(matrix); @m, @i, @j = matrix, 0, 0; end - def valid?(i=@i, j=@j); i >= 0 && j >= 0; end - def match(c, d); @m[@i][@j] = compute_entry(c, d); end - def pos(i, j); @i, @j = i, j; end - def lookup(x, y); [@i+x, @j+y]; end + def initialize(a, b) + @m = Array.new(a.length) { Array.new(b.length) } + a.each_char.with_index do |x, i| + b.each_char.with_index do |y, j| + match(x, y, i, j) + end + end + end + + def match(c, d, i, j) + @i, @j = i, j + @m[i][j] = compute_entry(c, d) + end + + def lookup(x, y) [@i+x, @j+y] end + def valid?(i=@i, j=@j) i >= 0 && j >= 0 end def peek(x, y) i, j = lookup(x, y) @@ -17,10 +28,20 @@ class LcsWalker end def backtrack - Enumerator.new { |y| y << @i+1 if backstep while valid? } + @i, @j = @m.length-1, @m[0].length-1 + y = [] + y << @i+1 if backstep? while valid? + y.reverse end - def backstep + def backtrack2 + @i, @j = @m.length-1, @m[0].length-1 + y = [] + y << @j+1 if backstep? while valid? + [backtrack, y.reverse] + end + + def backstep? backstep = compute_backstep @i, @j = lookup(*backstep) backstep == DIAG @@ -34,3 +55,13 @@ class LcsWalker end end end + +def lcs(a, b) + walker = LCS.new(a, b) + walker.backtrack.map{|i| a[i]}.join +end + +if $0 == __FILE__ + puts lcs('thisisatest', 'testing123testing') + puts lcs("rosettacode", "raisethysword") +end diff --git a/Task/Longest-common-subsequence/Scala/longest-common-subsequence.scala b/Task/Longest-common-subsequence/Scala/longest-common-subsequence.scala index 199c643d49..01de964635 100644 --- a/Task/Longest-common-subsequence/Scala/longest-common-subsequence.scala +++ b/Task/Longest-common-subsequence/Scala/longest-common-subsequence.scala @@ -65,5 +65,4 @@ object LCS extends App { println{val t = elapsed(s = lcsd(p._1,p._2)) "lcsd(\""+p._1+"\",\""+p._2+"\") = \""+s+"\" ("+t+" sec)"} } - } diff --git a/Task/Longest-string-challenge/Ada/longest-string-challenge-1.ada b/Task/Longest-string-challenge/Ada/longest-string-challenge-1.ada index 260fb0093a..771acc6279 100644 --- a/Task/Longest-string-challenge/Ada/longest-string-challenge-1.ada +++ b/Task/Longest-string-challenge/Ada/longest-string-challenge-1.ada @@ -6,20 +6,28 @@ procedure Longest_String_Challenge is Separator: constant Character := Ada.Characters.Latin_1.NUL; procedure Funny_Stuff(B, L: in out Unbounded_String; N: Unbounded_String) is + -- B holds a list of all longest strings, separated by Separator + -- L holds longest string so far + -- N is the next string to be considered Nat: Natural; begin Nat := Length(N) - Length(L); + -- (1) this raises exception if L longer then N declare Pos: Positive; begin - Pos := Nat; + Pos := Nat; -- (2) this raises exception if L at least as long as N + -- at this point, we know N is longer then L B := N; L := N; exception - when Constraint_Error => B := B & Separator & N; + when Constraint_Error -- come from (2) + -- at this point, we know L and N are of the same length + => B := B & Separator & N; -- add N to the set of solutions end; exception - when Constraint_Error => null; + when Constraint_Error => null; -- come from (1) + -- at this point, we know L is longer then N end Funny_Stuff; Buffer: Unbounded_String := +""; @@ -29,10 +37,11 @@ procedure Longest_String_Challenge is begin while True loop Next := + Ada.Text_IO.Get_Line; + -- (3) raises exception when trying to read beyond the end of file Funny_Stuff(Buffer, Longest, Next); end loop; exception - when others => + when others => -- come from (3) for I in To_String(Buffer)'Range loop if To_String(Buffer)(I) = Separator then Ada.Text_IO.New_Line; diff --git a/Task/Longest-string-challenge/Ada/longest-string-challenge-2.ada b/Task/Longest-string-challenge/Ada/longest-string-challenge-2.ada index 24346d31ff..4f30307282 100644 --- a/Task/Longest-string-challenge/Ada/longest-string-challenge-2.ada +++ b/Task/Longest-string-challenge/Ada/longest-string-challenge-2.ada @@ -11,21 +11,26 @@ procedure Longest_String_Challenge is S, T: String) is C: Character; begin - if S = T then - B := B & Separator & N; - else - C:= T(T'First); -- raises Constraint_Error if T is empty - begin - C := S(S'First); -- same if S is empty - Funny_Stuff(B,L,N,S(S'First+1 .. S'Last), T(T'First+1..T'Last)); -- - exception - when Constraint_Error => - B := N; - L := N; - end; - end if; + C:= T(T'First); -- (1) raises Constraint_Error if T is empty + begin + C := S(S'First); -- (2) raises Constraint_Error if S is empty + -- at this point, we know that neither S nor T are empty + Funny_Stuff(B,L,N,S(S'First+1 .. S'Last), T(T'First+1..T'Last)); + exception + when Constraint_Error => -- come from (2), S is empty, T is not empty! + B := N; + L := N; + end; exception - when Constraint_Error => null; + when Constraint_Error => -- come from (1), T is empty + begin + C := S(S'First); -- (3) raises Constraint_Error if S is empty + -- at this point, we know that T is empty and S isn't + null; + exception + when Constraint_Error => -- come from (3); both S and T are empty + B := B & Separator & N; + end; end Funny_Stuff; Buffer: Unbounded_String := +""; @@ -35,10 +40,11 @@ procedure Longest_String_Challenge is begin while True loop Next := + Ada.Text_IO.Get_Line; + -- (4) raises exception when trying to read beyond end of file Funny_Stuff(Buffer, Longest, Next, -Longest, -Next); end loop; exception - when others => + when others => -- come from (4) for I in To_String(Buffer)'Range loop if To_String(Buffer)(I) = Separator then Ada.Text_IO.New_Line; diff --git a/Task/Longest-string-challenge/Java/longest-string-challenge.java b/Task/Longest-string-challenge/Java/longest-string-challenge.java new file mode 100644 index 0000000000..b9209dc99c --- /dev/null +++ b/Task/Longest-string-challenge/Java/longest-string-challenge.java @@ -0,0 +1,28 @@ +import java.io.File; +import java.util.Scanner; + +public class LongestStringChallenge { + + public static void main(String[] args) throws Exception { + String lines = "", longest = ""; + try (Scanner sc = new Scanner(new File("lines.txt"))) { + while(sc.hasNext()) { + String line = sc.nextLine(); + if (longer(longest, line)) + lines = longest = line; + else if (!longer(line, longest)) + lines = lines.concat("\n").concat(line); + } + } + System.out.println(lines); + } + + static boolean longer(String a, String b) { + try { + String dummy = a.substring(b.length()); + } catch (StringIndexOutOfBoundsException e) { + return true; + } + return false; + } +} diff --git a/Task/Longest-string-challenge/Lua/longest-string-challenge-1.lua b/Task/Longest-string-challenge/Lua/longest-string-challenge-1.lua new file mode 100644 index 0000000000..94508b55a4 --- /dev/null +++ b/Task/Longest-string-challenge/Lua/longest-string-challenge-1.lua @@ -0,0 +1,26 @@ +function longer(s1, s2) + while true do + s1 = s1:sub(1, -2) + s2 = s2:sub(1, -2) + if s1:find('^$') and not s2:find('^$') then + return false + elseif s2:find('^$') then + return true + end + end +end + +local output = '' +local longest = '' + +for line in io.lines() do + local islonger = longer(line, longest) + if islonger and longer(longest, line) then + output = output .. line .. '\n' + elseif islonger then + longest = line + output = line .. '\n' + end +end + +print(output) diff --git a/Task/Longest-string-challenge/Lua/longest-string-challenge-2.lua b/Task/Longest-string-challenge/Lua/longest-string-challenge-2.lua new file mode 100644 index 0000000000..e3685cfa83 --- /dev/null +++ b/Task/Longest-string-challenge/Lua/longest-string-challenge-2.lua @@ -0,0 +1,7 @@ +function longer(s1, s2) + if s1:sub(#s2):find('^$') then + return false + else + return true + end +end diff --git a/Task/Longest-string-challenge/Ruby/longest-string-challenge.rb b/Task/Longest-string-challenge/Ruby/longest-string-challenge-1.rb similarity index 100% rename from Task/Longest-string-challenge/Ruby/longest-string-challenge.rb rename to Task/Longest-string-challenge/Ruby/longest-string-challenge-1.rb diff --git a/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb b/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb new file mode 100644 index 0000000000..096445ed4d --- /dev/null +++ b/Task/Longest-string-challenge/Ruby/longest-string-challenge-2.rb @@ -0,0 +1 @@ +puts open("test.txt").each_line.group_by(&:size).max.last diff --git a/Task/Longest-string-challenge/Scala/longest-string-challenge.scala b/Task/Longest-string-challenge/Scala/longest-string-challenge.scala new file mode 100644 index 0000000000..a5cc31c2a4 --- /dev/null +++ b/Task/Longest-string-challenge/Scala/longest-string-challenge.scala @@ -0,0 +1,2 @@ +val longest = scala.io.Source.fromFile(args.head).getLines.toIterable.groupBy(_.length).max._2 +println(longest mkString "\n") diff --git a/Task/Look-and-say-sequence/00DESCRIPTION b/Task/Look-and-say-sequence/00DESCRIPTION index df134fb4b6..1c13de8581 100644 --- a/Task/Look-and-say-sequence/00DESCRIPTION +++ b/Task/Look-and-say-sequence/00DESCRIPTION @@ -1,11 +1,11 @@ +The [[wp:Look and say sequence|Look and say sequence]] is a recursively defined sequence of numbers studied most notably by [[wp:John Horton Conway|John Conway]]. + '''Sequence Definition''' * Take a decimal number * ''Look'' at the number, visually grouping consecutive runs of the same digit. * ''Say'' the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped. :This becomes the next number of the sequence. -The [[wp:Look_and_say_sequence|sequence]] is from [[wp:John Horton Conway|John Conway]], of [[Conway's Game of Life]] fame. - '''An example:''' * Starting with the number 1, you have ''one'' 1 which produces 11. * Starting with 11, you have ''two'' 1's i.e. 21 @@ -16,6 +16,7 @@ The [[wp:Look_and_say_sequence|sequence]] is from [[wp:John Horton Conway|John C :Write a program to generate successive members of the look-and-say sequence. '''See also''' +* [https://www.youtube.com/watch?v=ea7lJkEhytA Look-and-Say Numbers (feat John Conway)], A Numberphile Video. * This task is related to, and an application of, the [[Run-length encoding]] task. * Sequence [https://oeis.org/A005150 A005150] on The On-Line Encyclopedia of Integer Sequences. diff --git a/Task/Look-and-say-sequence/Bracmat/look-and-say-sequence.bracmat b/Task/Look-and-say-sequence/Bracmat/look-and-say-sequence.bracmat new file mode 100644 index 0000000000..ccf275b6e4 --- /dev/null +++ b/Task/Look-and-say-sequence/Bracmat/look-and-say-sequence.bracmat @@ -0,0 +1,23 @@ +( 1:?number +& 0:?lines +& whl + ' ( 1+!lines:~>10:?lines + & :?say { This will accumulate all that has to be said after one iteration. } + & 0:?begin + & ( @( !number { Pattern matching. The '@' indicates we're looking in a string rather than a tree structure. } + : ? + ( [!begin + %@?digit + ? + [?end + ( (|(%@:~!digit) ?) { The %@ guarantees we're testing one character - not less (%) and not more (@). The ? takes the rest. } + & !say !end+-1*!begin !digit:?say + & !end:?begin { When backtracking, 'begin' advances to the begin of the next sequence, or to the end of the string. } + ) + & ~ { fail! This forces backtracking. Backtracking stops when all begin positions have been tried. } + ) + ) + | out$(str$!say:?number) { After backtracking, output string and set number to string for next iteration. } + ) + ) +); diff --git a/Task/Look-and-say-sequence/D/look-and-say-sequence-5.d b/Task/Look-and-say-sequence/D/look-and-say-sequence-5.d new file mode 100644 index 0000000000..5e196caf92 --- /dev/null +++ b/Task/Look-and-say-sequence/D/look-and-say-sequence-5.d @@ -0,0 +1,137 @@ +import core.stdc.stdio, std.conv; + +// On Windows this uses the printf from the Microsoft C runtime, +// that doesn't handle real type and some of the C99 format +// specifiers, but it's faster for bulk printing. +version (LDC) version (Windows) +extern(C) nothrow @nogc int printf(const char*, ...); + +// http://www.njohnston.ca/2010/10/a-derivation-of-conways-degree-71-look-and-say-polynomial/ +struct Sequence { + string seq; + uint[6] next; +} + +immutable Sequence[93] sequences = [ + {"", []}, + {"1112", [63]}, + {"1112133", [64, 62]}, + {"111213322112", [65]}, + {"111213322113", [66]}, + {"1113", [68]}, + {"11131", [69]}, + {"111311222112", [84, 55]}, + {"111312", [70]}, + {"11131221", [71]}, + {"1113122112", [76]}, + {"1113122113", [77]}, + {"11131221131112", [82]}, + {"111312211312", [78]}, + {"11131221131211", [79]}, + {"111312211312113211", [80]}, + {"111312211312113221133211322112211213322112", [81, 29, 91]}, + {"111312211312113221133211322112211213322113", [81, 29, 90]}, + {"11131221131211322113322112", [81, 30]}, + {"11131221133112", [75, 29, 92]}, + {"1113122113322113111221131221", [75, 32]}, + {"11131221222112", [72]}, + {"111312212221121123222112", [73]}, + {"111312212221121123222113", [74]}, + {"11132", [83]}, + {"1113222", [86]}, + {"1113222112", [87]}, + {"1113222113", [88]}, + {"11133112", [89, 92]}, + {"12", [1]}, + {"123222112", [3]}, + {"123222113", [4]}, + {"12322211331222113112211", [2, 61, 29, 85]}, + {"13", [5]}, + {"131112", [28]}, + {"13112221133211322112211213322112", [24, 33, 61, 29, 91]}, + {"13112221133211322112211213322113", [24, 33, 61, 29, 90]}, + {"13122112", [7]}, + {"132", [8]}, + {"13211", [9]}, + {"132112", [10]}, + {"1321122112", [21]}, + {"132112211213322112", [22]}, + {"132112211213322113", [23]}, + {"132113", [11]}, + {"1321131112", [19]}, + {"13211312", [12]}, + {"1321132", [13]}, + {"13211321", [14]}, + {"132113212221", [15]}, + {"13211321222113222112", [18]}, + {"1321132122211322212221121123222112", [16]}, + {"1321132122211322212221121123222113", [17]}, + {"13211322211312113211", [20]}, + {"1321133112", [6, 61, 29, 92]}, + {"1322112", [26]}, + {"1322113", [27]}, + {"13221133112", [25, 29, 92]}, + {"1322113312211", [25, 29, 67]}, + {"132211331222113112211", [25, 29, 85]}, + {"13221133122211332", [25, 29, 68, 61, 29, 89]}, + {"22", [61]}, + {"3", [33]}, + {"3112", [40]}, + {"3112112", [41]}, + {"31121123222112", [42]}, + {"31121123222113", [43]}, + {"3112221", [38, 39]}, + {"3113", [44]}, + {"311311", [48]}, + {"31131112", [54]}, + {"3113112211", [49]}, + {"3113112211322112", [50]}, + {"3113112211322112211213322112", [51]}, + {"3113112211322112211213322113", [52]}, + {"311311222", [47, 38]}, + {"311311222112", [47, 55]}, + {"311311222113", [47, 56]}, + {"3113112221131112", [47, 57]}, + {"311311222113111221", [47, 58]}, + {"311311222113111221131221", [47, 59]}, + {"31131122211311122113222", [47, 60]}, + {"3113112221133112", [47, 33, 61, 29, 92]}, + {"311312", [45]}, + {"31132", [46]}, + {"311322113212221", [53]}, + {"311332", [38, 29, 89]}, + {"3113322112", [38, 30]}, + {"3113322113", [38, 31]}, + {"312", [34]}, + {"312211322212221121123222113", [36]}, + {"312211322212221121123222112", [35]}, + {"32112", [37]} +]; + +void evolve(in uint seq, in uint n) nothrow @nogc { + if (n <= 0) { + printf(sequences[seq].seq.ptr); + } else { + foreach (immutable next; sequences[seq].next) { + if (next == 0) + break; + evolve(next, n - 1); + } + } +} + +void main(in string[] args) { + immutable uint n = (args.length != 2) ? 10 : args[1].to!uint; + + immutable base = 8; + immutable string[base] results = ["", "1", "11", "21", "1211", + "111221", "312211", "13112221"]; + if (n < base) { + printf("%s\n", results[n].ptr); + return; + } + + evolve(24, n - base); + evolve(39, n - base); + '\n'.putchar; +} diff --git a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir index f0b55835ba..06780a0934 100644 --- a/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir +++ b/Task/Look-and-say-sequence/Elixir/look-and-say-sequence.elixir @@ -1,10 +1,10 @@ defmodule LookAndSay do def next(n) do - Enum.chunks_by(to_char_list(n), &(&1)) + Enum.chunk_by(to_char_list(n), &(&1)) |> Enum.map(fn cl=[h|_] -> Enum.concat(to_char_list(length cl), [h]) end) |> Enum.concat - |> list_to_integer + |> List.to_integer end def sequence_from(n) do @@ -14,7 +14,6 @@ defmodule LookAndSay do def main([start_str|_]) do {start_val,_} = Integer.parse(start_str) :io.format("~w~n", [LookAndSay.sequence_from(start_val) |> Enum.take 9] ) - exit 0 end def main([]) do diff --git a/Task/Look-and-say-sequence/JavaScript/look-and-say-sequence.js b/Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-1.js similarity index 100% rename from Task/Look-and-say-sequence/JavaScript/look-and-say-sequence.js rename to Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-1.js diff --git a/Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-2.js b/Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-2.js new file mode 100644 index 0000000000..8ec96bac40 --- /dev/null +++ b/Task/Look-and-say-sequence/JavaScript/look-and-say-sequence-2.js @@ -0,0 +1,26 @@ +function lookSay(digits) { + var result = '', + chars = (digits + ' ').split(''), + lastChar = chars[0], + times = 0; + + chars.forEach(function(nextChar) { + if (nextChar === lastChar) { + times++; + } + else { + result += (times + '') + lastChar; + lastChar = nextChar; + times = 1; + } + }); + + return result; +} + +(function output(seed, iterations) { + for (var i = 0; i < iterations; i++) { + console.log(seed); + seed = lookSay(seed); + } +})("1", 10); diff --git a/Task/Look-and-say-sequence/PHP/look-and-say-sequence.php b/Task/Look-and-say-sequence/PHP/look-and-say-sequence.php index 774514f651..7591f6a988 100644 --- a/Task/Look-and-say-sequence/PHP/look-and-say-sequence.php +++ b/Task/Look-and-say-sequence/PHP/look-and-say-sequence.php @@ -1,11 +1,19 @@ "; + $num = lookAndSay($num); } + ?> diff --git a/Task/Look-and-say-sequence/Pascal/look-and-say-sequence.pascal b/Task/Look-and-say-sequence/Pascal/look-and-say-sequence-1.pascal similarity index 100% rename from Task/Look-and-say-sequence/Pascal/look-and-say-sequence.pascal rename to Task/Look-and-say-sequence/Pascal/look-and-say-sequence-1.pascal diff --git a/Task/Look-and-say-sequence/Pascal/look-and-say-sequence-2.pascal b/Task/Look-and-say-sequence/Pascal/look-and-say-sequence-2.pascal new file mode 100644 index 0000000000..cce76bba47 --- /dev/null +++ b/Task/Look-and-say-sequence/Pascal/look-and-say-sequence-2.pascal @@ -0,0 +1,78 @@ +program LookAndSayDemo(input, output); +{$IFDEF FPC} + {$Mode Delphi} // using result + {$optimization ON} +// i3-4330 3.5 Ghz +// {$CodeAlign proc=16,loop=8} //2,6 secs + {$CodeAlign proc=16,loop=1} //1,6 secs so much faster ??? +{$ENDIF} + +uses + SysUtils; +const + cntChar : array[1..9] of char = + ('1','2','3','4','5','6','7','8','9'); + +function LookAndSay2 (const s: string): string; +//using pChar for result +var + source, + destin : pChar; + len, + idxFrom, + idxTo : integer; + cnt: integer; + + item: char; +begin + idxFrom := length(s); + source := @s[1]; + + //adjust length of result + len := round(length(s)* 1.306+10); + setlength(result,len); + destin := @result[1]; + dec(destin); + + idxto := 1; + item := source^; + inc(source); + cnt := 1; + for idxFrom := idxFrom downto 2 do + begin + if item <> source^ then + begin + destin[idxTo] := cntChar[cnt]; + destin[idxTo+1]:= item; + item := source^; + cnt := 1; + inc(idxto,2); + end + else + inc(cnt); + inc(source); + end; + destin[idxTo] := cntChar[cnt]; + destin[idxTo+1]:= item; + setlength(result,idxto+1); +end; + +var + number: string; + l1,l2, + i : integer; +begin + number := '1'; + writeln(number); + writeln(1:4,length(number):16,1/1:10:6); + + For i := 2 to 70 do + begin + l1 := length(number); + number := LookAndSay2(number); + l2 := length(number); + IF i <10 then + writeln(number); + writeln(i:4,length(number):16,l2/l1:10:6); + end; +end. diff --git a/Task/Look-and-say-sequence/Scala/look-and-say-sequence.scala b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala similarity index 100% rename from Task/Look-and-say-sequence/Scala/look-and-say-sequence.scala rename to Task/Look-and-say-sequence/Scala/look-and-say-sequence-1.scala diff --git a/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala new file mode 100644 index 0000000000..9d76326c80 --- /dev/null +++ b/Task/Look-and-say-sequence/Scala/look-and-say-sequence-2.scala @@ -0,0 +1,17 @@ +object Main extends App { + + def lookAndSay(previous: List[BigInt]): Stream[List[BigInt]] = { + + def next(num: List[BigInt]): List[BigInt] = num match { + case Nil => Nil + case head :: Nil => 1 :: head :: Nil + case head :: tail => + val size = (num takeWhile (_ == head)).size + List(BigInt(size), head) ::: next(num.drop(size)) + } + val x = next(previous) + x #:: lookAndSay(x) + } + + (lookAndSay(1 :: Nil) take 10).foreach(s => println(s.mkString(""))) +} diff --git a/Task/Look-and-say-sequence/UNIX-Shell/look-and-say-sequence.sh b/Task/Look-and-say-sequence/UNIX-Shell/look-and-say-sequence.sh new file mode 100644 index 0000000000..89b957b4d5 --- /dev/null +++ b/Task/Look-and-say-sequence/UNIX-Shell/look-and-say-sequence.sh @@ -0,0 +1,17 @@ +lookandsay() { + local num=$1 char seq i + for ((i=0; i<=${#num}; i++)); do + char=${num:i:1} + if [[ $char == ${seq:0:1} ]]; then + seq+=$char + else + [[ -n $seq ]] && printf "%d%s" ${#seq} ${seq:0:1} + seq=$char + fi + done +} + +for ((num=1, i=1; i<=10; i++)); do + echo $num + num=$( lookandsay $num ) +done diff --git a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION index b2989799e8..e3804f41b8 100644 --- a/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION +++ b/Task/Loop-over-multiple-arrays-simultaneously/00DESCRIPTION @@ -1,4 +1,5 @@ -Loop over multiple arrays (or lists or tuples or whatever they're called in your language) and print the ''i''th element of each. Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. +Loop over multiple arrays (or lists or tuples or whatever they're called in your language) and print the ''i''th element of each. +Use your language's "for each" loop if it has one, otherwise iterate through the collection in order with some other loop. For this example, loop over the arrays (a,b,c), (A,B,C) and (1,2,3) to produce the output
aA1
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/C/loop-over-multiple-arrays-simultaneously.c b/Task/Loop-over-multiple-arrays-simultaneously/C/loop-over-multiple-arrays-simultaneously.c
new file mode 100644
index 0000000000..c35bbe319e
--- /dev/null
+++ b/Task/Loop-over-multiple-arrays-simultaneously/C/loop-over-multiple-arrays-simultaneously.c
@@ -0,0 +1,11 @@
+#include 
+
+char a1[] = {'a','b','c'};
+char a2[] = {'A','B','C'};
+int a3[] = {1,2,3};
+
+int main(void) {
+    for (int i = 0; i < 3; i++) {
+        printf("%c%c%i\n", a1[i], a2[i], a3[i]);
+    }
+}
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Go/loop-over-multiple-arrays-simultaneously.go b/Task/Loop-over-multiple-arrays-simultaneously/Go/loop-over-multiple-arrays-simultaneously.go
index 541c7001e8..f9ba0a406e 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/Go/loop-over-multiple-arrays-simultaneously.go
+++ b/Task/Loop-over-multiple-arrays-simultaneously/Go/loop-over-multiple-arrays-simultaneously.go
@@ -2,12 +2,12 @@ package main
 
 import "fmt"
 
-var a1 = []int{'a','b','c'}
-var a2 = []int{'A','B','C'}
-var a3 = []int{1,2,3}
+var a1 = []string{"a", "b", "c"}
+var a2 = []byte{'A', 'B', 'C'}
+var a3 = []int{1, 2, 3}
 
 func main() {
-    for i := range a1 {
-        fmt.Printf("%c%c%d\n", a1[i], a2[i], a3[i])
-    }
+	for i := range a1 {
+		fmt.Printf("%v%c%v\n", a1[i], a2[i], a3[i])
+	}
 }
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-1.j b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-1.j
index 66b903da02..8c6fe24a76 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-1.j
+++ b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-1.j
@@ -1 +1,4 @@
-,.&:(":"0@>)/ 'abc' ; 'ABC' ; 1 2 3
+   ,.&:(":"0@>)/ 'abc' ; 'ABC' ; 1 2 3
+aA1
+bB2
+cC3
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-2.j b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-2.j
index 8ceb1b05db..4ce4a419a7 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-2.j
+++ b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-2.j
@@ -1 +1,4 @@
-,.&:>/ 'abc' ; 'ABC' ; '123'
+   ,.&:>/ 'abc' ; 'ABC' ; '123'
+aA1
+bB2
+cC3
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-3.j b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-3.j
index f014767922..6e9fc4ba84 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-3.j
+++ b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-3.j
@@ -1 +1,4 @@
-|: 'abc', 'ABC' ,:;":&> 1 2 3
+   |: 'abc', 'ABC' ,:;":&> 1 2 3
+aA1
+bB2
+cC3
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-4.j b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-4.j
index 121a05dcd3..2d4e847926 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-4.j
+++ b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-4.j
@@ -1 +1,4 @@
-|: 'abc', 'ABC',: '123'
+   |: 'abc', 'ABC',: '123'
+aA1
+bB2
+cC3
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-5.j b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-5.j
index b3ebdd926e..574d858308 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-5.j
+++ b/Task/Loop-over-multiple-arrays-simultaneously/J/loop-over-multiple-arrays-simultaneously-5.j
@@ -1 +1,8 @@
-|:>]&.>L:_1 'abc';'ABC';<1 2 3
+   |:>]&.>L:_1 'abc';'ABC';<1 2 3
+┌─┬─┬─┐
+│a│A│1│
+├─┼─┼─┤
+│b│B│2│
+├─┼─┼─┤
+│c│C│3│
+└─┴─┴─┘
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Java/loop-over-multiple-arrays-simultaneously.java b/Task/Loop-over-multiple-arrays-simultaneously/Java/loop-over-multiple-arrays-simultaneously.java
index 6935753c15..7363a09ced 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/Java/loop-over-multiple-arrays-simultaneously.java
+++ b/Task/Loop-over-multiple-arrays-simultaneously/Java/loop-over-multiple-arrays-simultaneously.java
@@ -1,6 +1,6 @@
 String[] a = {"a","b","c"};
 String[] b = {"A","B","C"};
 int[] c = {1,2,3};
-for (int i = 0;i < a.length;i++) {
-    System.out.println(a[i] + b[i] + c[i] + "\n");
+for(int i = 0;i < a.length;i++){
+    System.out.println(a[i] + b[i] + c[i]);
 }
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-2.k b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-2.k
index e22bded786..362ca7ffcf 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-2.k
+++ b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-2.k
@@ -1,3 +1 @@
-("aA1"
- "bB2"
- "cC3")
+      &/#:'x
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-3.k b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-3.k
index 362ca7ffcf..0c69e13006 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-3.k
+++ b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-3.k
@@ -1 +1 @@
-      &/#:'x
+   {+x[;!(&/#:'x)]}("abc";"ABC";"1234")
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-4.k b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-4.k
index 0c69e13006..f1d80888e5 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-4.k
+++ b/Task/Loop-over-multiple-arrays-simultaneously/K/loop-over-multiple-arrays-simultaneously-4.k
@@ -1 +1 @@
-   {+x[;!(&/#:'x)]}("abc";"ABC";"1234")
+   {a:,/'($:'x);+a[;!(&/#:'a)]}("abc";"ABC";1 2 3 4)
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp b/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp
new file mode 100644
index 0000000000..6141dfeba6
--- /dev/null
+++ b/Task/Loop-over-multiple-arrays-simultaneously/NewLISP/loop-over-multiple-arrays-simultaneously.newlisp
@@ -0,0 +1 @@
+(map println '(a b c) '(A B C) '(1 2 3))
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Oberon-2/loop-over-multiple-arrays-simultaneously.oberon-2 b/Task/Loop-over-multiple-arrays-simultaneously/Oberon-2/loop-over-multiple-arrays-simultaneously.oberon-2
new file mode 100644
index 0000000000..6b47dd16f2
--- /dev/null
+++ b/Task/Loop-over-multiple-arrays-simultaneously/Oberon-2/loop-over-multiple-arrays-simultaneously.oberon-2
@@ -0,0 +1,24 @@
+MODULE LoopMArrays;
+IMPORT
+	Out;
+VAR
+	x,y: ARRAY 3 OF CHAR;
+	z: ARRAY 3 OF INTEGER;
+
+PROCEDURE DoLoop;
+VAR
+	i: INTEGER;
+BEGIN
+	i := 0;
+	WHILE i < LEN(x) DO
+		Out.Char(x[i]);Out.Char(y[i]);Out.LongInt(z[i],0);Out.Ln;
+		INC(i)
+	END
+END DoLoop;
+
+BEGIN
+	x[0] := 'a';y[0] := 'A';z[0] := 1;
+	x[1] := 'b';y[1] := 'B';z[1] := 2;
+	x[2] := 'c';y[2] := 'C';z[2] := 3;
+	DoLoop
+END LoopMArrays.
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx
index a3f05df28c..9674dbd5cb 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx
+++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-1.rexx
@@ -1,11 +1,9 @@
 /*REXX program shows how to  simultaneously  loop over  multiple arrays.*/
-
 x. = ' ';      x.1 =  "a";      x.2 = 'b';      x.3 = "c"
 y. = ' ';      y.1 =  "A";      y.2 = 'B';      y.3 = "C"
 z. = ' ';      z.1 =  "1";      z.2 = '2';      z.3 = "3"
 
            do j=1  until output=''
-           output=x.j || y.j || z.j
+           output = x.j || y.j || z.j
            say output
-           end    /*j*/
-                                       /*stick a fork in it, we're done.*/
+           end    /*j*/                /*stick a fork in it, we're done.*/
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx
index 6da64e8bc6..110d9b9473 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx
+++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-2.rexx
@@ -1,11 +1,9 @@
 /*REXX program shows how to  simultaneously  loop over  multiple arrays.*/
-
 x.=' ';      x.1="a";      x.2='b';      x.3="c";      x.4='d'
 y.=' ';      y.1="A";      y.2='B';      y.3="C";
 z.=' ';      z.1= 1 ;      z.2= 2 ;      z.3= 3 ;      z.4= 4;      z.5= 5
 
        do j=1  until output=''
-       output= x.j || y.j || z.j
+       output=x.j || y.j || z.j
        say output
-       end   /*j*/
-                                       /*stick a fork in it, we're done.*/
+       end   /*j*/                     /*stick a fork in it, we're done.*/
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx
new file mode 100644
index 0000000000..67dd5db656
--- /dev/null
+++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-3.rexx
@@ -0,0 +1,8 @@
+/*REXX program shows how to  simultaneously  loop over  multiple  lists.*/
+x = 'a b c d'
+y = 'A B C'
+z =  1 2 3 4
+               do j=1  until  output=''
+               output = word(x,j) || word(y,j) || word(z,j)
+               say output
+               end    /*j*/            /*stick a fork in it, we're done.*/
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx
new file mode 100644
index 0000000000..d5f2e69be4
--- /dev/null
+++ b/Task/Loop-over-multiple-arrays-simultaneously/REXX/loop-over-multiple-arrays-simultaneously-4.rexx
@@ -0,0 +1,7 @@
+/*REXX program shows how to  simultaneously  loop over  multiple  lists.*/
+x = 'a b c d'
+y = 'A B C'
+z =  1 2 3 4 ..LAST
+                     do j=1  for max(words(x), words(y), words(z))
+                     say word(x,j) || word(y,j) || word(z,j)
+                     end    /*j*/      /*stick a fork in it, we're done.*/
diff --git a/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-2.rb b/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-2.rb
index 9c074c7bd7..59f41fc135 100644
--- a/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-2.rb
+++ b/Task/Loop-over-multiple-arrays-simultaneously/Ruby/loop-over-multiple-arrays-simultaneously-2.rb
@@ -1 +1 @@
-['a','b','c'].zip(['A','B','C'], [1,2,3]) {|a| puts a.join('')}
+['a','b','c'].zip(['A','B','C'], [1,2,3]) {|a| puts a.join}
diff --git a/Task/Loops-Break/00DESCRIPTION b/Task/Loops-Break/00DESCRIPTION
index 5500dcb6c1..596fe3785e 100644
--- a/Task/Loops-Break/00DESCRIPTION
+++ b/Task/Loops-Break/00DESCRIPTION
@@ -1 +1,4 @@
- Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive). If a number is 10, stop the loop after printing it, and do not generate any further numbers.  Otherwise, generate and print a second random number before restarting the loop.  If the number 10 is never generated as the first number in a loop, loop forever.
+Show a loop which prints random numbers (each number newly generated each loop) from 0 to 19 (inclusive).
+If a number is 10, stop the loop after printing it, and do not generate any further numbers.
+Otherwise, generate and print a second random number before restarting the loop.
+If the number 10 is never generated as the first number in a loop, loop forever.
diff --git a/Task/Loops-Break/00META.yaml b/Task/Loops-Break/00META.yaml
index 782552d0b1..ccaf323e0b 100644
--- a/Task/Loops-Break/00META.yaml
+++ b/Task/Loops-Break/00META.yaml
@@ -1,4 +1,5 @@
 ---
 category:
 - Loop modifiers
+- Simple
 note: Iteration
diff --git a/Task/Loops-Break/Batch-File/loops-break.bat b/Task/Loops-Break/Batch-File/loops-break.bat
index a5de397c7f..6fec9a6883 100644
--- a/Task/Loops-Break/Batch-File/loops-break.bat
+++ b/Task/Loops-Break/Batch-File/loops-break.bat
@@ -3,4 +3,6 @@
   set /a N=%RANDOM% %% 20
   echo %N%
   if %N%==10 exit /b
+  set /a N=%RANDOM% %% 20
+  echo %N%
 goto loop
diff --git a/Task/Loops-Break/ColdFusion/loops-break.cfm b/Task/Loops-Break/ColdFusion/loops-break.cfm
new file mode 100644
index 0000000000..80f4442d51
--- /dev/null
+++ b/Task/Loops-Break/ColdFusion/loops-break.cfm
@@ -0,0 +1,8 @@
+
+
+  
+  #randNum#
+  
+  #RandRange(0, 19)#
+  
+
diff --git a/Task/Loops-Break/MAXScript/loops-break.max b/Task/Loops-Break/MAXScript/loops-break.max new file mode 100644 index 0000000000..80ec7bc280 --- /dev/null +++ b/Task/Loops-Break/MAXScript/loops-break.max @@ -0,0 +1,8 @@ +while true do +( + a = random 0 19 + format ("A: % \n") a + if a == 10 do exit + b = random 0 19 + format ("B: % \n") b +) diff --git a/Task/Loops-Break/NewLISP/loops-break.newlisp b/Task/Loops-Break/NewLISP/loops-break.newlisp new file mode 100644 index 0000000000..0ad2ac2ca3 --- /dev/null +++ b/Task/Loops-Break/NewLISP/loops-break.newlisp @@ -0,0 +1,2 @@ +(until (= 10 (println (rand 20))) + (println (rand 20))) diff --git a/Task/Loops-Break/Oberon-2/loops-break.oberon-2 b/Task/Loops-Break/Oberon-2/loops-break.oberon-2 new file mode 100644 index 0000000000..d9a53173be --- /dev/null +++ b/Task/Loops-Break/Oberon-2/loops-break.oberon-2 @@ -0,0 +1,21 @@ +MODULE LoopBreak; +IMPORT + RandomNumbers, + Out; + +PROCEDURE Do(); +VAR + rn: LONGINT; +BEGIN + LOOP + rn := RandomNumbers.RND(20); + Out.LongInt(rn,0);Out.Ln; + IF rn = 10 THEN EXIT END; + rn := RandomNumbers.RND(20); + Out.LongInt(rn,0);Out.Ln + END +END Do; + +BEGIN + Do +END LoopBreak. diff --git a/Task/Loops-Break/PL-I/loops-break.pli b/Task/Loops-Break/PL-I/loops-break.pli index d68738878e..37d5bb6d0d 100644 --- a/Task/Loops-Break/PL-I/loops-break.pli +++ b/Task/Loops-Break/PL-I/loops-break.pli @@ -1,7 +1,7 @@ do forever; - k = random()*19; + k = trunc(random()*20); put (k); if k = 10 then leave; - k = random()*19; + k = trunc(random()*20); put skip list (k); end; diff --git a/Task/Loops-Break/Ruby/loops-break-1.rb b/Task/Loops-Break/Ruby/loops-break-1.rb new file mode 100644 index 0000000000..b3307b25f0 --- /dev/null +++ b/Task/Loops-Break/Ruby/loops-break-1.rb @@ -0,0 +1,10 @@ +loop do + a = rand(20) + print a + if a == 10 + puts + break + end + b = rand(20) + puts "\t#{b}" +end diff --git a/Task/Loops-Break/Ruby/loops-break-2.rb b/Task/Loops-Break/Ruby/loops-break-2.rb new file mode 100644 index 0000000000..349d5f7550 --- /dev/null +++ b/Task/Loops-Break/Ruby/loops-break-2.rb @@ -0,0 +1,5 @@ +loop do + print a = rand(20) + puts or break if a == 10 + puts "\t#{rand(20)}" +end diff --git a/Task/Loops-Break/Ruby/loops-break.rb b/Task/Loops-Break/Ruby/loops-break.rb deleted file mode 100644 index 123d3f9f81..0000000000 --- a/Task/Loops-Break/Ruby/loops-break.rb +++ /dev/null @@ -1,9 +0,0 @@ -loop do - a = rand(20) - puts a - if a == 10 - break - end - b = rand(20) - puts b -end diff --git a/Task/Loops-Break/TorqueScript/loops-break.torque b/Task/Loops-Break/TorqueScript/loops-break.torque index e1b99eb69f..ea527ec424 100644 --- a/Task/Loops-Break/TorqueScript/loops-break.torque +++ b/Task/Loops-Break/TorqueScript/loops-break.torque @@ -1,6 +1,6 @@ for(%a = 0; %a > -1; %a++) { - %number = getRand(0, 19); + %number = getRandom(0, 19); if(%number == 10) break; } diff --git a/Task/Loops-Continue/00DESCRIPTION b/Task/Loops-Continue/00DESCRIPTION index be47817622..212ffa5efc 100644 --- a/Task/Loops-Continue/00DESCRIPTION +++ b/Task/Loops-Continue/00DESCRIPTION @@ -1,5 +1,8 @@ +{{omit from|GUISS}} +{{omit from|M4}} Show the following output using one loop. 1, 2, 3, 4, 5 6, 7, 8, 9, 10 -Try to achieve the result by forcing the next iteration within the loop upon a specific condition, if your language allows it. +Try to achieve the result by forcing the next iteration within the loop +upon a specific condition, if your language allows it. diff --git a/Task/Loops-Continue/00META.yaml b/Task/Loops-Continue/00META.yaml index 05fe73c7e1..782552d0b1 100644 --- a/Task/Loops-Continue/00META.yaml +++ b/Task/Loops-Continue/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Loop modifiers note: Iteration diff --git a/Task/Loops-Continue/Ada/loops-continue.ada b/Task/Loops-Continue/Ada/loops-continue.ada index 07b18a7fed..2e676ec1d1 100644 --- a/Task/Loops-Continue/Ada/loops-continue.ada +++ b/Task/Loops-Continue/Ada/loops-continue.ada @@ -1,13 +1,17 @@ -with Ada.Text_Io; use Ada.Text_Io; +with Ada.Text_IO; +use Ada.Text_IO; procedure Loop_Continue is begin - for I in 1..10 loop - Put(Integer'Image(I)); - if I mod 5 = 0 then - New_Line; - else - Put(","); - end if; - end loop; + for I in 1..10 loop + Put (Integer'Image(I)); + if I = 5 or I = 10 then + New_Line; + goto Continue; + end if; + Put (","); + -- label must be followed by a statement. + <> + null; + end loop; end Loop_Continue; diff --git a/Task/Loops-Continue/Applesoft-BASIC/loops-continue.applesoft b/Task/Loops-Continue/Applesoft-BASIC/loops-continue.applesoft new file mode 100644 index 0000000000..9b4ef10c0f --- /dev/null +++ b/Task/Loops-Continue/Applesoft-BASIC/loops-continue.applesoft @@ -0,0 +1,5 @@ + 10 FOR I = 1 TO 10 + 20 PRINT I; + 30 IF I - INT (I / 5) * 5 = 0 THEN PRINT : GOTO 50"CONTINUE + 40 PRINT ", "; + 50 NEXT diff --git a/Task/Loops-Continue/Clojure/loops-continue-1.clj b/Task/Loops-Continue/Clojure/loops-continue-1.clj new file mode 100644 index 0000000000..0037521231 --- /dev/null +++ b/Task/Loops-Continue/Clojure/loops-continue-1.clj @@ -0,0 +1,5 @@ +(doseq [n (range 1 11)] + (print n) + (if (zero? (rem n 5)) + (println) + (print ", "))) diff --git a/Task/Loops-Continue/Clojure/loops-continue-2.clj b/Task/Loops-Continue/Clojure/loops-continue-2.clj new file mode 100644 index 0000000000..8c63ce8d87 --- /dev/null +++ b/Task/Loops-Continue/Clojure/loops-continue-2.clj @@ -0,0 +1,7 @@ +(loop [xs (range 1 11)] + (when-let [x (first xs)] + (print x) + (if (zero? (rem x 5)) + (println) + (print ", ")) + (recur (rest xs)))) diff --git a/Task/Loops-Continue/Clojure/loops-continue.clj b/Task/Loops-Continue/Clojure/loops-continue.clj deleted file mode 100644 index 7996593d32..0000000000 --- a/Task/Loops-Continue/Clojure/loops-continue.clj +++ /dev/null @@ -1,5 +0,0 @@ -(doseq - [n (range 1 11)] - (do - (print n) - (if (= (rem n 5) 0) (print "\n") (print ", ")))) diff --git a/Task/Loops-Continue/NewLISP/loops-continue.newlisp b/Task/Loops-Continue/NewLISP/loops-continue.newlisp new file mode 100644 index 0000000000..50fc534e90 --- /dev/null +++ b/Task/Loops-Continue/NewLISP/loops-continue.newlisp @@ -0,0 +1,5 @@ +(for (i 1 10) + (print i) + (if (= 0 (% i 5)) + (println) + (print ", "))) diff --git a/Task/Loops-Continue/Ruby/loops-continue-3.rb b/Task/Loops-Continue/Ruby/loops-continue-3.rb index 4a37d96c32..56ef36d454 100644 --- a/Task/Loops-Continue/Ruby/loops-continue-3.rb +++ b/Task/Loops-Continue/Ruby/loops-continue-3.rb @@ -1 +1 @@ -1.upto(10) {|i| print "%d%s" % [i, i%5==0 ? "\n" : ", "]} +(1..10).each_slice(5){|ar| puts ar.join(", ")} diff --git a/Task/Loops-Do-while/00DESCRIPTION b/Task/Loops-Do-while/00DESCRIPTION index 392b3111a1..2bdec501ef 100644 --- a/Task/Loops-Do-while/00DESCRIPTION +++ b/Task/Loops-Do-while/00DESCRIPTION @@ -1 +1,3 @@ -Start with a value at 0. Loop while value mod 6 is not equal to 0. Each time through the loop, add 1 to the value then print it. The loop must execute at least once. +Start with a value at 0. Loop while value mod 6 is not equal to 0. +Each time through the loop, add 1 to the value then print it. +The loop must execute at least once. diff --git a/Task/Loops-Do-while/00META.yaml b/Task/Loops-Do-while/00META.yaml index a6bdfa14ab..e69ff9609f 100644 --- a/Task/Loops-Do-while/00META.yaml +++ b/Task/Loops-Do-while/00META.yaml @@ -1,4 +1,5 @@ --- category: - Conditional loops +- Simple note: Iteration diff --git a/Task/Loops-Do-while/360-Assembly/loops-do-while.360 b/Task/Loops-Do-while/360-Assembly/loops-do-while.360 new file mode 100644 index 0000000000..ce1e1dbd08 --- /dev/null +++ b/Task/Loops-Do-while/360-Assembly/loops-do-while.360 @@ -0,0 +1,26 @@ +DOWHILE CSECT , -This program's control section + BAKR 14,0 -Caller's registers to linkage stack + LR 12,15 -load entry point address into Reg 12 + USING DOWHILE,12 -tell assembler we use Reg 12 as base + XR 9,9 -clear Reg 9 - divident value + LA 6,6 -load divisor value 6 in Reg 6 + LA 8,WTOLEN -address of WTO area in Reg 8 +LOOP DS 0H + LA 9,1(,9) -add 1 to divident Reg 9 + ST 9,FW2 -store it + LM 4,5,FDOUBLE -load into even/odd register pair + STH 9,WTOTXT -store divident in text area + MVI WTOTXT,X'F0' -first of two bytes zero + OI WTOTXT+1,X'F0' -make second byte printable + WTO TEXT=(8) -print it (Write To Operator macro) + DR 4,6 -divide Reg pair 4,5 by Reg 6 + LTR 5,5 -test quotient (remainder in Reg 4) + BNZ RETURN -if one: 6 iterations, exit loop. + B LOOP -if zero: loop again. +RETURN PR , -return to caller. +FDOUBLE DC 0FD + DC F'0' +FW2 DC F'0' +WTOLEN DC H'2' -fixed WTO length of two +WTOTXT DC CL2' ' + END DOWHILE diff --git a/Task/Loops-Do-while/Emacs-Lisp/loops-do-while.l b/Task/Loops-Do-while/Emacs-Lisp/loops-do-while.l new file mode 100644 index 0000000000..72bffc9d94 --- /dev/null +++ b/Task/Loops-Do-while/Emacs-Lisp/loops-do-while.l @@ -0,0 +1,5 @@ +(let ((val 0)) + (while (progn + (setq val (1+ val)) + (message "%d" val) + (/= 0 (mod val 6))))) diff --git a/Task/Loops-Do-while/Euphoria/loops-do-while.euphoria b/Task/Loops-Do-while/Euphoria/loops-do-while.euphoria new file mode 100644 index 0000000000..f63ba0166d --- /dev/null +++ b/Task/Loops-Do-while/Euphoria/loops-do-while.euphoria @@ -0,0 +1,12 @@ +include std/console.e +include std/math.e + +atom x = 0 + +loop do + x += 1 + ?x + until(mod(x,6)) = 0 +end loop + +if getc(0) then end if diff --git a/Task/Loops-Do-while/NewLISP/loops-do-while.newlisp b/Task/Loops-Do-while/NewLISP/loops-do-while.newlisp new file mode 100644 index 0000000000..4b16fcb15e --- /dev/null +++ b/Task/Loops-Do-while/NewLISP/loops-do-while.newlisp @@ -0,0 +1,3 @@ +(let ((i 0)) + (do-until (= 0 (% i 6)) + (println (++ i)))) diff --git a/Task/Loops-Do-while/Oberon-2/loops-do-while.oberon-2 b/Task/Loops-Do-while/Oberon-2/loops-do-while.oberon-2 new file mode 100644 index 0000000000..798a9ec71e --- /dev/null +++ b/Task/Loops-Do-while/Oberon-2/loops-do-while.oberon-2 @@ -0,0 +1,18 @@ +MODULE LoopDoWhile; +IMPORT + Out; + +PROCEDURE Do(); +VAR + i: INTEGER; +BEGIN + i := 0; + REPEAT + Out.LongInt(i,0);Out.Ln; + INC(i) + UNTIL (i MOD 6 = 0); +END Do; + +BEGIN + Do +END LoopDoWhile. diff --git a/Task/Loops-Do-while/OpenEdge-Progress/loops-do-while.openedge b/Task/Loops-Do-while/OpenEdge-Progress/loops-do-while.openedge new file mode 100644 index 0000000000..a075961864 --- /dev/null +++ b/Task/Loops-Do-while/OpenEdge-Progress/loops-do-while.openedge @@ -0,0 +1,6 @@ +DEFINE VARIABLE ii AS INTEGER. + +DO WHILE ii MODULO 6 <> 0 OR ii = 0: + ii = ii + 1. + MESSAGE ii VIEW-AS ALERT-BOX. +END. diff --git a/Task/Loops-Do-while/PARI-GP/loops-do-while.pari b/Task/Loops-Do-while/PARI-GP/loops-do-while-1.pari similarity index 56% rename from Task/Loops-Do-while/PARI-GP/loops-do-while.pari rename to Task/Loops-Do-while/PARI-GP/loops-do-while-1.pari index f73701a9e4..01ce41ff40 100644 --- a/Task/Loops-Do-while/PARI-GP/loops-do-while.pari +++ b/Task/Loops-Do-while/PARI-GP/loops-do-while-1.pari @@ -1,5 +1,5 @@ x = 0; while(1, print(x++); - if(val % 6 == 0, break) + if(x % 6 == 0, break) ) diff --git a/Task/Loops-Do-while/PARI-GP/loops-do-while-2.pari b/Task/Loops-Do-while/PARI-GP/loops-do-while-2.pari new file mode 100644 index 0000000000..b654f8eb63 --- /dev/null +++ b/Task/Loops-Do-while/PARI-GP/loops-do-while-2.pari @@ -0,0 +1,2 @@ +x = 0; +while (print(x++) || x % 6, ) diff --git a/Task/Loops-Do-while/Suneido/loops-do-while.suneido b/Task/Loops-Do-while/Suneido/loops-do-while.suneido new file mode 100644 index 0000000000..ba49d4c1f1 --- /dev/null +++ b/Task/Loops-Do-while/Suneido/loops-do-while.suneido @@ -0,0 +1,5 @@ +val = 0 +do + { + Print(++val) + } while (val % 6 isnt 0) diff --git a/Task/Loops-Downward-for/00META.yaml b/Task/Loops-Downward-for/00META.yaml index 05fe73c7e1..3ae6306db2 100644 --- a/Task/Loops-Downward-for/00META.yaml +++ b/Task/Loops-Downward-for/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Iteration diff --git a/Task/Loops-Downward-for/NewLISP/loops-downward-for.newlisp b/Task/Loops-Downward-for/NewLISP/loops-downward-for.newlisp new file mode 100644 index 0000000000..1fb38afa5f --- /dev/null +++ b/Task/Loops-Downward-for/NewLISP/loops-downward-for.newlisp @@ -0,0 +1,2 @@ +(for (i 10 0) + (println i)) diff --git a/Task/Loops-For-with-a-specified-step/00DESCRIPTION b/Task/Loops-For-with-a-specified-step/00DESCRIPTION index 426ca5bd39..f28f44c47c 100644 --- a/Task/Loops-For-with-a-specified-step/00DESCRIPTION +++ b/Task/Loops-For-with-a-specified-step/00DESCRIPTION @@ -1 +1 @@ -Demonstrate a for loop where the step value is greater than one. +Demonstrate a for-loop where the step-value is greater than one. diff --git a/Task/Loops-For-with-a-specified-step/00META.yaml b/Task/Loops-For-with-a-specified-step/00META.yaml index 05fe73c7e1..3ae6306db2 100644 --- a/Task/Loops-For-with-a-specified-step/00META.yaml +++ b/Task/Loops-For-with-a-specified-step/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Iteration diff --git a/Task/Loops-For-with-a-specified-step/AWK/loops-for-with-a-specified-step.awk b/Task/Loops-For-with-a-specified-step/AWK/loops-for-with-a-specified-step.awk index 50653b990c..a1b74b9aed 100644 --- a/Task/Loops-For-with-a-specified-step/AWK/loops-for-with-a-specified-step.awk +++ b/Task/Loops-For-with-a-specified-step/AWK/loops-for-with-a-specified-step.awk @@ -1,6 +1,6 @@ BEGIN { - for (l= 2; l <= 8; l = l + 2) { - print l + for (i= 2; i <= 8; i = i + 2) { + print i } - print "Ain't never to late!" + print "Ain't never too late!" } diff --git a/Task/Loops-For-with-a-specified-step/ColdFusion/loops-for-with-a-specified-step.cfm b/Task/Loops-For-with-a-specified-step/ColdFusion/loops-for-with-a-specified-step.cfm new file mode 100644 index 0000000000..8596e76973 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/ColdFusion/loops-for-with-a-specified-step.cfm @@ -0,0 +1,3 @@ + + #i# + diff --git a/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-4.j b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-4.j new file mode 100644 index 0000000000..e78f819994 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-4.j @@ -0,0 +1 @@ + thru=: <./ + i.@(+*)@-~ diff --git a/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-5.j b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-5.j new file mode 100644 index 0000000000..ab0e80c479 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-5.j @@ -0,0 +1,6 @@ + (#~ 0 = 2&|) 1 thru 20 +2 4 6 8 10 12 14 16 18 20 + (#~ 0 = 3&|) 1 thru 20 +3 6 9 12 15 18 + (#~ 1 = 3&|) 1 thru 20 +1 4 7 10 13 16 19 diff --git a/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-6.j b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-6.j new file mode 100644 index 0000000000..4c7a47b113 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/J/loops-for-with-a-specified-step-6.j @@ -0,0 +1,2 @@ + (#~ 1&p:) 1 thru 20 +2 3 5 7 11 13 17 19 diff --git a/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-1.max b/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-1.max new file mode 100644 index 0000000000..4f1b00c64f --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-1.max @@ -0,0 +1 @@ +for i = 0 to 10 by 2 do format "%\n" i diff --git a/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-2.max b/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-2.max new file mode 100644 index 0000000000..c6e5c08f8e --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/MAXScript/loops-for-with-a-specified-step-2.max @@ -0,0 +1,7 @@ +0 +2 +4 +6 +8 +10 +OK diff --git a/Task/Loops-For-with-a-specified-step/NewLISP/loops-for-with-a-specified-step.newlisp b/Task/Loops-For-with-a-specified-step/NewLISP/loops-for-with-a-specified-step.newlisp new file mode 100644 index 0000000000..c12e01fe82 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/NewLISP/loops-for-with-a-specified-step.newlisp @@ -0,0 +1,2 @@ +(for (i 0 10 2) + (println i)) diff --git a/Task/Loops-For-with-a-specified-step/Oberon-2/loops-for-with-a-specified-step.oberon-2 b/Task/Loops-For-with-a-specified-step/Oberon-2/loops-for-with-a-specified-step.oberon-2 new file mode 100644 index 0000000000..2962568d67 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Oberon-2/loops-for-with-a-specified-step.oberon-2 @@ -0,0 +1,14 @@ +MODULE LoopForStep; +IMPORT + Out; +VAR + i: INTEGER; + +BEGIN + FOR i := 0 TO 10 BY 3 DO + Out.LongInt(i,0);Out.Ln + END; + FOR i := 10 TO 0 BY -3 DO + Out.LongInt(i,0);Out.Ln + END +END LoopForStep. diff --git a/Task/Loops-For-with-a-specified-step/TorqueScript/loops-for-with-a-specified-step.torque b/Task/Loops-For-with-a-specified-step/TorqueScript/loops-for-with-a-specified-step.torque new file mode 100644 index 0000000000..f499fc98f5 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/TorqueScript/loops-for-with-a-specified-step.torque @@ -0,0 +1,4 @@ +for(%i = 0; %i < 201; %i += 2) +{ + echo(%i); +} diff --git a/Task/Loops-For-with-a-specified-step/Vim-Script/loops-for-with-a-specified-step.vim b/Task/Loops-For-with-a-specified-step/Vim-Script/loops-for-with-a-specified-step.vim new file mode 100644 index 0000000000..febb955ee5 --- /dev/null +++ b/Task/Loops-For-with-a-specified-step/Vim-Script/loops-for-with-a-specified-step.vim @@ -0,0 +1,3 @@ +for i in range(2, 10, 2) + echo i +endfor diff --git a/Task/Loops-For/00DESCRIPTION b/Task/Loops-For/00DESCRIPTION index 2a5e4500fd..9dcb6e1a1d 100644 --- a/Task/Loops-For/00DESCRIPTION +++ b/Task/Loops-For/00DESCRIPTION @@ -1,3 +1,4 @@ +{{omit from|GUISS}} “For” loops are used to make some block of code be iterated a number of times, setting a variable or parameter to a monotonically increasing integer value for each execution of the block of code. Common extensions of this allow other counting patterns or iterating over abstract structures other than the integers. For this task, show how two loops may be nested within each other, with the number of iterations performed by the inner for loop being controlled by the outer for loop. Specifically print out the following pattern by using one for loop nested in another: diff --git a/Task/Loops-For/00META.yaml b/Task/Loops-For/00META.yaml index 05fe73c7e1..3ae6306db2 100644 --- a/Task/Loops-For/00META.yaml +++ b/Task/Loops-For/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Iteration diff --git a/Task/Loops-For/ALGOL-60/loops-for.alg b/Task/Loops-For/ALGOL-60/loops-for.alg new file mode 100644 index 0000000000..d56a4051db --- /dev/null +++ b/Task/Loops-For/ALGOL-60/loops-for.alg @@ -0,0 +1,4 @@ +FOR i:=1 UNTIL 5 DO + FOR j:=1 UNTIL i DO + OUTTEXT("*"); + OUTLINE diff --git a/Task/Loops-For/AppleScript/loops-for.applescript b/Task/Loops-For/AppleScript/loops-for.applescript new file mode 100644 index 0000000000..58b1f9833d --- /dev/null +++ b/Task/Loops-For/AppleScript/loops-for.applescript @@ -0,0 +1,8 @@ +set x to return +repeat with i from 1 to 5 + repeat with j from 1 to i + set x to x & "*" + end repeat + set x to x & return +end repeat +return x diff --git a/Task/Loops-For/BASIC/loops-for-11.basic b/Task/Loops-For/BASIC/loops-for-11.basic index 611a057478..92571e13cc 100644 --- a/Task/Loops-For/BASIC/loops-for-11.basic +++ b/Task/Loops-For/BASIC/loops-for-11.basic @@ -1,7 +1,7 @@ -Local i,j -ClrIO -For i, 1, 5 - For j, 1, i - Output i*8, j*6, "*" - EndFor -EndFor +Public OutConsole As Scripting.TextStream +For i = 0 To 4 + For j = 0 To i + OutConsole.Write "*" + Next j + OutConsole.WriteLine +Next i diff --git a/Task/Loops-For/BASIC/loops-for-12.basic b/Task/Loops-For/BASIC/loops-for-12.basic index 6cc6794172..a38aab1aa9 100644 --- a/Task/Loops-For/BASIC/loops-for-12.basic +++ b/Task/Loops-For/BASIC/loops-for-12.basic @@ -1,15 +1,6 @@ -'This Prints to the Debug-Window! -Dim i As Integer -Dim ii As Integer -Dim x As Integer -Dim out As String - -output = "" - -For i = 1 To 5 - For ii = 1 To i - out = out + "*" - Next ii - Debug.Print (out) - out = "" -Next i +For x As Integer = 0 To 4 + For y As Integer = 0 To x + Console.Write("*") + Next + Console.WriteLine() +Next diff --git a/Task/Loops-For/BASIC/loops-for-13.basic b/Task/Loops-For/BASIC/loops-for-13.basic index a38aab1aa9..f47f2192b5 100644 --- a/Task/Loops-For/BASIC/loops-for-13.basic +++ b/Task/Loops-For/BASIC/loops-for-13.basic @@ -1,6 +1,6 @@ -For x As Integer = 0 To 4 - For y As Integer = 0 To x - Console.Write("*") - Next - Console.WriteLine() -Next +10 FOR i = 1 TO 5 +20 FOR j = 1 TO i +30 PRINT "*"; +40 NEXT j +50 PRINT +60 NEXT i diff --git a/Task/Loops-For/Babel/loops-for.pb b/Task/Loops-For/Babel/loops-for.pb index 3d3a162720..d3a0c6c052 100644 --- a/Task/Loops-For/Babel/loops-for.pb +++ b/Task/Loops-For/Babel/loops-for.pb @@ -1,11 +1,11 @@ -star_triangle: { <- { { "*" << } iter times "\n" << } -> times } -main: { 10 star_triangle } -* -** -*** -**** -***** -****** -******* -******** -********* +((main { 10 star_triangle ! }) + +(star_triangle { + dup + <- + { dup { "*" << } <-> + iter - 1 + + times + "\n" << } + -> + times })) diff --git a/Task/Loops-For/Oberon-2/loops-for.oberon-2 b/Task/Loops-For/Oberon-2/loops-for.oberon-2 new file mode 100644 index 0000000000..2aa12ff988 --- /dev/null +++ b/Task/Loops-For/Oberon-2/loops-for.oberon-2 @@ -0,0 +1,14 @@ +MODULE LoopFor; +IMPORT + Out; +VAR + i, j: INTEGER; + +BEGIN + FOR i := 1 TO 5 DO + FOR j := 1 TO i DO + Out.Char('*'); + END; + Out.Ln + END +END LoopFor. diff --git a/Task/Loops-For/PL-I/loops-for-1.pli b/Task/Loops-For/PL-I/loops-for-1.pli new file mode 100644 index 0000000000..195212878d --- /dev/null +++ b/Task/Loops-For/PL-I/loops-for-1.pli @@ -0,0 +1,6 @@ +do i = 1 to 5; + do j = 1 to i; + put edit ('*') (a); + end; + put skip; +end; diff --git a/Task/Loops-For/PL-I/loops-for.pli b/Task/Loops-For/PL-I/loops-for-2.pli similarity index 100% rename from Task/Loops-For/PL-I/loops-for.pli rename to Task/Loops-For/PL-I/loops-for-2.pli diff --git a/Task/Loops-For/PL-I/loops-for-3.pli b/Task/Loops-For/PL-I/loops-for-3.pli new file mode 100644 index 0000000000..a6bd2184e1 --- /dev/null +++ b/Task/Loops-For/PL-I/loops-for-3.pli @@ -0,0 +1 @@ +put edit ((('*' do j = 1 to i)do i=1 to 5))(a); /* no new line */ diff --git a/Task/Loops-For/Ruby/loops-for-1.rb b/Task/Loops-For/Ruby/loops-for-1.rb index 011755c189..31fc3ec7ef 100644 --- a/Task/Loops-For/Ruby/loops-for-1.rb +++ b/Task/Loops-For/Ruby/loops-for-1.rb @@ -1,6 +1,6 @@ for i in 1..5 - for j in 1..i - print "*" - end - puts + for j in 1..i + print "*" + end + puts end diff --git a/Task/Loops-For/Ruby/loops-for-2.rb b/Task/Loops-For/Ruby/loops-for-2.rb index 63f55eaa20..5b766fe627 100644 --- a/Task/Loops-For/Ruby/loops-for-2.rb +++ b/Task/Loops-For/Ruby/loops-for-2.rb @@ -1,6 +1,6 @@ -1.upto(5) do |i| - 1.upto(i) do |j| - print "*" - end - puts +(1..5).each do |i| + (1..i).each do |j| + print "*" + end + puts end diff --git a/Task/Loops-For/Ruby/loops-for-3.rb b/Task/Loops-For/Ruby/loops-for-3.rb index 09964bf5dd..bbba277f12 100644 --- a/Task/Loops-For/Ruby/loops-for-3.rb +++ b/Task/Loops-For/Ruby/loops-for-3.rb @@ -1,7 +1,6 @@ -5.times do |i| - # i goes from 0 to 4 - (i+1).times do - print "*" - end - puts +1.upto(5) do |i| + 1.upto(i) do |j| + print "*" + end + puts end diff --git a/Task/Loops-For/Ruby/loops-for-4.rb b/Task/Loops-For/Ruby/loops-for-4.rb index 3985f46a8d..19b0797af0 100644 --- a/Task/Loops-For/Ruby/loops-for-4.rb +++ b/Task/Loops-For/Ruby/loops-for-4.rb @@ -1,10 +1,7 @@ -i = 1 -loop do - j = 1 - loop do - print "*" - break if (j += 1) > i - end - puts - break if (i += 1) > 5 +5.times do |i| + # i goes from 0 to 4 + (i+1).times do + print "*" + end + puts end diff --git a/Task/Loops-For/Ruby/loops-for-5.rb b/Task/Loops-For/Ruby/loops-for-5.rb index 621a0d6eb0..5116059089 100644 --- a/Task/Loops-For/Ruby/loops-for-5.rb +++ b/Task/Loops-For/Ruby/loops-for-5.rb @@ -1 +1,10 @@ -puts (1..5).map { |i| "*" * i } +i = 1 +loop do + j = 1 + loop do + print "*" + break if (j += 1) > i + end + puts + break if (i += 1) > 5 +end diff --git a/Task/Loops-For/Ruby/loops-for-6.rb b/Task/Loops-For/Ruby/loops-for-6.rb new file mode 100644 index 0000000000..621a0d6eb0 --- /dev/null +++ b/Task/Loops-For/Ruby/loops-for-6.rb @@ -0,0 +1 @@ +puts (1..5).map { |i| "*" * i } diff --git a/Task/Loops-For/Simula/loops-for.simula b/Task/Loops-For/Simula/loops-for.simula new file mode 100644 index 0000000000..83d9b7a8b6 --- /dev/null +++ b/Task/Loops-For/Simula/loops-for.simula @@ -0,0 +1,4 @@ +FOR I:=1 UNTIL 5 DO + FOR J:=1 UNTIL I DO + OUTTEXT("*"); + OUTLINE diff --git a/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 b/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 index f813f771ed..b99df15c50 100644 --- a/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 +++ b/Task/Loops-For/TI-83-BASIC/loops-for.ti-83 @@ -1,7 +1,6 @@ -PROGRAM:FORLOOPS -:ClrHome -:For(I,1,5) -:For(J,1,I) -:Output(I,J,"*") -:End -:End +ClrHome +For(I,1,5) +For(J,1,I) +Output(I,J,"*") +End +End diff --git a/Task/Loops-Foreach/AWK/loops-foreach-2.awk b/Task/Loops-Foreach/AWK/loops-foreach-2.awk index 4f1768ca52..593bc1a69a 100644 --- a/Task/Loops-Foreach/AWK/loops-foreach-2.awk +++ b/Task/Loops-Foreach/AWK/loops-foreach-2.awk @@ -1,3 +1,6 @@ -for(i=1; i <= length(strs); i++) { - print strs[i] +BEGIN { + n = split("Mary had a little lamb", strs, " ") + for(i=1; i <= n; i++) { + print strs[i] + } } diff --git a/Task/Loops-Foreach/C++/loops-foreach-2.cpp b/Task/Loops-Foreach/C++/loops-foreach-2.cpp index 6528be668c..b32ea17181 100644 --- a/Task/Loops-Foreach/C++/loops-foreach-2.cpp +++ b/Task/Loops-Foreach/C++/loops-foreach-2.cpp @@ -1,2 +1,2 @@ std::copy(container.begin(), container.end(), - std::output_iterator(std::cout, "\n")); + std::ostream_iterator(std::cout, "\n")); diff --git a/Task/Loops-Foreach/C++/loops-foreach-4.cpp b/Task/Loops-Foreach/C++/loops-foreach-4.cpp index 6010227277..b428011922 100644 --- a/Task/Loops-Foreach/C++/loops-foreach-4.cpp +++ b/Task/Loops-Foreach/C++/loops-foreach-4.cpp @@ -1,5 +1,3 @@ -#include - for (auto element: container) { std::cout << element << "\n"; diff --git a/Task/Loops-Foreach/C++/loops-foreach-5.cpp b/Task/Loops-Foreach/C++/loops-foreach-5.cpp index c05f5e0e5b..e5357a435a 100644 --- a/Task/Loops-Foreach/C++/loops-foreach-5.cpp +++ b/Task/Loops-Foreach/C++/loops-foreach-5.cpp @@ -1,5 +1,3 @@ -#include - for (auto const& element: container) { std::cout << element << "\n"; diff --git a/Task/Loops-Foreach/C++/loops-foreach-6.cpp b/Task/Loops-Foreach/C++/loops-foreach-6.cpp new file mode 100644 index 0000000000..3a7e8bb408 --- /dev/null +++ b/Task/Loops-Foreach/C++/loops-foreach-6.cpp @@ -0,0 +1,4 @@ +for (auto&& element: container) //use a 'universal reference' +{ + element += 42; +} diff --git a/Task/Loops-Foreach/ColdFusion/loops-foreach.cfm b/Task/Loops-Foreach/ColdFusion/loops-foreach.cfm new file mode 100644 index 0000000000..9d23ac48f8 --- /dev/null +++ b/Task/Loops-Foreach/ColdFusion/loops-foreach.cfm @@ -0,0 +1,3 @@ + + #i#! + diff --git a/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-1.l b/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-1.l new file mode 100644 index 0000000000..6c82b50d3f --- /dev/null +++ b/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-1.l @@ -0,0 +1,2 @@ +(dolist (x '(1 2 3 4)) + (message "x=%d" x)) diff --git a/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-2.l b/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-2.l new file mode 100644 index 0000000000..c538b64175 --- /dev/null +++ b/Task/Loops-Foreach/Emacs-Lisp/loops-foreach-2.l @@ -0,0 +1,3 @@ +(mapc (lambda (x) + (message "x=%d" x)) + '(1 2 3 4)) diff --git a/Task/Loops-Foreach/Euphoria/loops-foreach.euphoria b/Task/Loops-Foreach/Euphoria/loops-foreach.euphoria new file mode 100644 index 0000000000..a5022eeae7 --- /dev/null +++ b/Task/Loops-Foreach/Euphoria/loops-foreach.euphoria @@ -0,0 +1,24 @@ +include std/console.e + +sequence s = {-2,-1,0,1,2} --print elements of a numerical list +for i = 1 to length(s) do + ? s[i] +end for + +puts(1,'\n') + +s = {"Name","Date","Field1","Field2"} -- print elements of a list of 'strings' +for i = 1 to length(s) do + printf(1,"%s\n",{s[i]}) +end for + +puts(1,'\n') + +for i = 1 to length(s) do -- print subelements of elements of a list of 'strings' + for j = 1 to length(s[i]) do + printf(1,"%s\n",s[i][j]) + end for + puts(1,'\n') +end for + +if getc(0) then end if diff --git a/Task/Loops-Foreach/MAXScript/loops-foreach.max b/Task/Loops-Foreach/MAXScript/loops-foreach.max index d189b066cf..7ef3ab8552 100644 --- a/Task/Loops-Foreach/MAXScript/loops-foreach.max +++ b/Task/Loops-Foreach/MAXScript/loops-foreach.max @@ -1,4 +1,5 @@ -for i in collect do -( - print i -) +arr = for i in 1 to 50 collect ("Number: " + (random 10 99) as string) +makeuniquearray arr +sort arr + +for i in arr do print i as string diff --git a/Task/Loops-Foreach/NewLISP/loops-foreach.newlisp b/Task/Loops-Foreach/NewLISP/loops-foreach.newlisp new file mode 100644 index 0000000000..574ff362b0 --- /dev/null +++ b/Task/Loops-Foreach/NewLISP/loops-foreach.newlisp @@ -0,0 +1 @@ +(map println '(Apple Banana Coconut)) diff --git a/Task/Loops-Foreach/Prolog/loops-foreach.pro b/Task/Loops-Foreach/Prolog/loops-foreach.pro new file mode 100644 index 0000000000..84ea3d699c --- /dev/null +++ b/Task/Loops-Foreach/Prolog/loops-foreach.pro @@ -0,0 +1,7 @@ +?- foreach(member(X, [red,green,blue,black,white]), writeln(X)). +red +green +blue +black +white +true. diff --git a/Task/Loops-Foreach/Python/loops-foreach-2.py b/Task/Loops-Foreach/Python/loops-foreach-2.py index 078dcb39d0..48485a08e0 100644 --- a/Task/Loops-Foreach/Python/loops-foreach-2.py +++ b/Task/Loops-Foreach/Python/loops-foreach-2.py @@ -5,6 +5,6 @@ for eachline in f: for eachword in eachline.split(): words += 1 for eachchar in eachword: - chracters += 1 + characters += 1 print lines, words, characters diff --git a/Task/Loops-Foreach/Python/loops-foreach-3.py b/Task/Loops-Foreach/Python/loops-foreach-3.py new file mode 100644 index 0000000000..9ed57a11e7 --- /dev/null +++ b/Task/Loops-Foreach/Python/loops-foreach-3.py @@ -0,0 +1,7 @@ +d = {3: "Earth", 1: "Mercury", 4: "Mars", 2: "Venus"} +for k in sorted(d): + print("%i: %s" % (k, d[k])) + +d = {"London": "United Kingdom", "Berlin": "Germany", "Rome": "Italy", "Paris": "France"} +for k in sorted(d): + print("%s: %s" % (k, d[k])) diff --git a/Task/Loops-Foreach/Python/loops-foreach-4.py b/Task/Loops-Foreach/Python/loops-foreach-4.py new file mode 100644 index 0000000000..1f7fb8a09b --- /dev/null +++ b/Task/Loops-Foreach/Python/loops-foreach-4.py @@ -0,0 +1,3 @@ +d = {"fortytwo": 42, 3.14159: "pi", 23: "twentythree", "zero": 0, 13: "thirteen"} +for k in sorted(d): + print("%s: %s" % (k, d[k])) diff --git a/Task/Loops-Foreach/REXX/loops-foreach.rexx b/Task/Loops-Foreach/REXX/loops-foreach.rexx index 94a25ee260..e9b19cd5c8 100644 --- a/Task/Loops-Foreach/REXX/loops-foreach.rexx +++ b/Task/Loops-Foreach/REXX/loops-foreach.rexx @@ -2,4 +2,5 @@ days = 'zuntik montik dinstik mitvokh donershtik fraytik shabes' do j=1 for words(days) /*loop through days of the week. */ say word(days,j) /*display the weekday to screen. */ - end /*j*//*stick a fork in it, we're done.*/ + end /*j*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-Foreach/Vim-Script/loops-foreach.vim b/Task/Loops-Foreach/Vim-Script/loops-foreach.vim new file mode 100644 index 0000000000..4d1a5b5990 --- /dev/null +++ b/Task/Loops-Foreach/Vim-Script/loops-foreach.vim @@ -0,0 +1,3 @@ +for i in ["alpha", "beta", 42, 5.54] + echo i +endfor diff --git a/Task/Loops-Infinite/00META.yaml b/Task/Loops-Infinite/00META.yaml index 05fe73c7e1..3ae6306db2 100644 --- a/Task/Loops-Infinite/00META.yaml +++ b/Task/Loops-Infinite/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Iteration diff --git a/Task/Loops-Infinite/360-Assembly/loops-infinite.360 b/Task/Loops-Infinite/360-Assembly/loops-infinite.360 new file mode 100644 index 0000000000..fa780a9c38 --- /dev/null +++ b/Task/Loops-Infinite/360-Assembly/loops-infinite.360 @@ -0,0 +1,16 @@ +INFINITE CSECT , this PGM control section +INFINITE AMODE 31 addressing mode 31 bit +INFINITE RMODE ANY loader can load either 24 or 31 + BAKR 14,0 stack caller's register contents + LR 12,15 establish base + LA 13,0 no savearea + USING INFINITE,12 base to assembler + LA 10,1 1 in reg 10 + LA 11,2 2 in reg 11 +LOOP EQU * + CR 10,11 1==2? + BE RETURN Yes, exit. + WTO 'SPAM',ROUTCDE=11 print SPAM to syslog + B LOOP No, check again. +RETURN PR , return to caller + END INFINITE diff --git a/Task/Loops-Infinite/BASIC/loops-infinite-4.basic b/Task/Loops-Infinite/BASIC/loops-infinite-4.basic new file mode 100644 index 0000000000..dd81640c5a --- /dev/null +++ b/Task/Loops-Infinite/BASIC/loops-infinite-4.basic @@ -0,0 +1 @@ +FOR I = 0 TO 1 STEP 0 : PRINT "SPAM" : NEXT diff --git a/Task/Loops-Infinite/Fortran/loops-infinite-1.f b/Task/Loops-Infinite/Fortran/loops-infinite-1.f index 92e5b67c63..a928358315 100644 --- a/Task/Loops-Infinite/Fortran/loops-infinite-1.f +++ b/Task/Loops-Infinite/Fortran/loops-infinite-1.f @@ -1,17 +1,3 @@ - PROGRAM INFINITELOOP -C While you can put this label on the WRITE statement, it is good -C form to label CONTINUE statements whenever possible, rather than -C statements that actually contain instructions. This way, you can -C indent inside the "loop" and make it more readable. - 10 CONTINUE - WRITE (*,*) 'SPAM' - GOTO 10 - -C It is also good form to close the "loop" with another label. In -C this case, there is absolutely no reason to do this at all, but, -C if you wanted to break, you would be able to add `GOTO 20` to -C exit the loop. - 20 CONTINUE - - STOP + 10 WRITE(*,*) 'SPAM' + GO TO 10 END diff --git a/Task/Loops-Infinite/Fortran/loops-infinite-2.f b/Task/Loops-Infinite/Fortran/loops-infinite-2.f index 96c4e53536..986b7a5188 100644 --- a/Task/Loops-Infinite/Fortran/loops-infinite-2.f +++ b/Task/Loops-Infinite/Fortran/loops-infinite-2.f @@ -1,3 +1,6 @@ -DO - WRITE(*,*) "SPAM" -END DO +program spam + implicit none + do + write(*,*) 'SPAM' + end do +end program spam diff --git a/Task/Loops-Infinite/Intercal/loops-infinite.ical b/Task/Loops-Infinite/Intercal/loops-infinite.ical new file mode 100644 index 0000000000..7976794b5d --- /dev/null +++ b/Task/Loops-Infinite/Intercal/loops-infinite.ical @@ -0,0 +1,11 @@ + NOTE THIS IS INTERCAL + PLEASE ,1 <- #5 + DO ,1 SUB #1 <- #54 + DO ,1 SUB #2 <- #192 + DO ,1 SUB #3 <- #136 + PLEASE ,1 SUB #4 <- #208 + DO ,1 SUB #5 <- #98 + DO COME FROM (1) + DO READ OUT ,1 +(2) DO ,1 SUB #1 <- #134 +(1) PLEASE ABSTAIN FROM (2) diff --git a/Task/Loops-Infinite/LOLCODE/loops-infinite.lol b/Task/Loops-Infinite/LOLCODE/loops-infinite.lol new file mode 100644 index 0000000000..498328946f --- /dev/null +++ b/Task/Loops-Infinite/LOLCODE/loops-infinite.lol @@ -0,0 +1,6 @@ +HAI + CAN HAS STDIO? + IM IN YR LOOP + VISIBLE "SPAM" + IM OUTTA YR LOOP +KTHXBYE diff --git a/Task/Loops-Infinite/MATLAB/loops-infinite.m b/Task/Loops-Infinite/MATLAB/loops-infinite.m index fbfc9c6411..f8cc6de9ba 100644 --- a/Task/Loops-Infinite/MATLAB/loops-infinite.m +++ b/Task/Loops-Infinite/MATLAB/loops-infinite.m @@ -1 +1,3 @@ - while (1), printf('SPAM\n'); end; +while true + fprintf('SPAM\n') +end diff --git a/Task/Loops-Infinite/NewLISP/loops-infinite.newlisp b/Task/Loops-Infinite/NewLISP/loops-infinite.newlisp new file mode 100644 index 0000000000..34cf0d27fe --- /dev/null +++ b/Task/Loops-Infinite/NewLISP/loops-infinite.newlisp @@ -0,0 +1 @@ +(while (println "SPAM")) diff --git a/Task/Loops-Infinite/Oberon-2/loops-infinite.oberon-2 b/Task/Loops-Infinite/Oberon-2/loops-infinite.oberon-2 new file mode 100644 index 0000000000..3a65455426 --- /dev/null +++ b/Task/Loops-Infinite/Oberon-2/loops-infinite.oberon-2 @@ -0,0 +1,8 @@ +MODULE InfiniteLoop; +IMPORT + Out; +BEGIN + LOOP + Out.String("SPAM");Out.Ln + END +END InfiniteLoop. diff --git a/Task/Loops-Infinite/REXX/loops-infinite-3.rexx b/Task/Loops-Infinite/REXX/loops-infinite-3.rexx index a1967fdef6..a125a4dd19 100644 --- a/Task/Loops-Infinite/REXX/loops-infinite-3.rexx +++ b/Task/Loops-Infinite/REXX/loops-infinite-3.rexx @@ -1,7 +1,6 @@ /*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. */ diff --git a/Task/Loops-Infinite/REXX/loops-infinite-4.rexx b/Task/Loops-Infinite/REXX/loops-infinite-4.rexx new file mode 100644 index 0000000000..bfd23e7c8e --- /dev/null +++ b/Task/Loops-Infinite/REXX/loops-infinite-4.rexx @@ -0,0 +1,7 @@ +/*REXX program displays the word SPAM forever. */ + + do until 0>1 /*too-clever-by-half forever loop*/ + say 'SPAM' + end /*DO until 0>1*/ + /*control will never reach here. */ + /*don't stick a fork in it. */ diff --git a/Task/Loops-Infinite/Rust/loops-infinite.rust b/Task/Loops-Infinite/Rust/loops-infinite.rust new file mode 100644 index 0000000000..08ad7e48f4 --- /dev/null +++ b/Task/Loops-Infinite/Rust/loops-infinite.rust @@ -0,0 +1,5 @@ +fn main() { + loop { + println!("SPAM"); + } +} diff --git a/Task/Loops-N-plus-one-half/00DESCRIPTION b/Task/Loops-N-plus-one-half/00DESCRIPTION index 6e57fd6290..d05bd4e039 100644 --- a/Task/Loops-N-plus-one-half/00DESCRIPTION +++ b/Task/Loops-N-plus-one-half/00DESCRIPTION @@ -1,7 +1,10 @@ -Quite often one needs loops which, in the last iteration, execute only part of the loop body. The goal of this task is to demonstrate the best way to do this. +Quite often one needs loops which, in the last iteration, +execute only part of the loop body. +The goal of this task is to demonstrate the best way to do this. Write a loop which writes the comma-separated list 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 -using separate output statements for the number and the comma from within the body of the loop. +using separate output statements for the number +and the comma from within the body of the loop. See also: [[Loop/Break]] diff --git a/Task/Loops-N-plus-one-half/00META.yaml b/Task/Loops-N-plus-one-half/00META.yaml index 05fe73c7e1..3ae6306db2 100644 --- a/Task/Loops-N-plus-one-half/00META.yaml +++ b/Task/Loops-N-plus-one-half/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Iteration diff --git a/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half.awk b/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-1.awk similarity index 70% rename from Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half.awk rename to Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-1.awk index 5814411e8b..56b2e4d562 100644 --- a/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half.awk +++ b/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-1.awk @@ -1,2 +1 @@ $ awk 'BEGIN{for(i=1;i<=10;i++){printf i;if(i<10)printf ", "};print}' -1, 2, 3, 4, 5, 6, 7, 8, 9, 10 diff --git a/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-2.awk b/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-2.awk new file mode 100644 index 0000000000..af845f0bd2 --- /dev/null +++ b/Task/Loops-N-plus-one-half/AWK/loops-n-plus-one-half-2.awk @@ -0,0 +1,8 @@ +BEGIN { + n=10 + for(i=1;i<=n;i++) { + printf i; + if(i for i to 10 do printf( "%d%s", i, `if`( i = 10, "\n", ", " ) ) end: +1, 2, 3, 4, 5, 6, 7, 8, 9, 10 diff --git a/Task/Loops-N-plus-one-half/NewLISP/loops-n-plus-one-half.newlisp b/Task/Loops-N-plus-one-half/NewLISP/loops-n-plus-one-half.newlisp new file mode 100644 index 0000000000..6b87209d3c --- /dev/null +++ b/Task/Loops-N-plus-one-half/NewLISP/loops-n-plus-one-half.newlisp @@ -0,0 +1,4 @@ +(for (i 0 10) + (print i) + (unless (= i 10) + (print ", "))) diff --git a/Task/Loops-N-plus-one-half/Pascal/loops-n-plus-one-half.pascal b/Task/Loops-N-plus-one-half/Pascal/loops-n-plus-one-half.pascal index b2c06d1a9e..f0c32c95a7 100644 --- a/Task/Loops-N-plus-one-half/Pascal/loops-n-plus-one-half.pascal +++ b/Task/Loops-N-plus-one-half/Pascal/loops-n-plus-one-half.pascal @@ -1,14 +1,20 @@ program numlist(output); +const MAXNUM: integer = 10; var i: integer; begin - for i := 1 to 10 do + { loop 1: w/ if branching } + for i := 1 to MAXNUM do begin write(i); - if i <> 10 then + if i <> MAXNUM then write(', ') end; writeln; + { loop 2: w/o if branching } + for i := 1 to MAXNUM-1 do + write(i, ', '); + writeln(MAXNUM); end. diff --git a/Task/Loops-N-plus-one-half/REXX/loops-n-plus-one-half-3.rexx b/Task/Loops-N-plus-one-half/REXX/loops-n-plus-one-half-3.rexx new file mode 100644 index 0000000000..48453eaed0 --- /dev/null +++ b/Task/Loops-N-plus-one-half/REXX/loops-n-plus-one-half-3.rexx @@ -0,0 +1,7 @@ +list='aa bb cc dd' +sep=', ' +Do i=1 By 1 While list<>'' + If i>1 Then Call charout ,sep + Parse Var list item list + Call charout ,item + End diff --git a/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-1.rb b/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-1.rb new file mode 100644 index 0000000000..5afb640d49 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-1.rb @@ -0,0 +1,6 @@ +(1..10).each do |i| + print i + break if i == 10 + print ", " +end +puts diff --git a/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-2.rb b/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-2.rb new file mode 100644 index 0000000000..9c5ce2b3c8 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half-2.rb @@ -0,0 +1 @@ +puts (1..10).join(", ") diff --git a/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half.rb b/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half.rb deleted file mode 100644 index c08231a9b5..0000000000 --- a/Task/Loops-N-plus-one-half/Ruby/loops-n-plus-one-half.rb +++ /dev/null @@ -1,6 +0,0 @@ -for i in 1..10 do - print i - break if i == 10 - print ", " -end -puts diff --git a/Task/Loops-N-plus-one-half/Scala/loops-n-plus-one-half.scala b/Task/Loops-N-plus-one-half/Scala/loops-n-plus-one-half.scala new file mode 100644 index 0000000000..06ec2b4d5a --- /dev/null +++ b/Task/Loops-N-plus-one-half/Scala/loops-n-plus-one-half.scala @@ -0,0 +1,3 @@ +object LoopAndHalf extends App { + println((1 to 10).mkString(", ")) +} diff --git a/Task/Loops-N-plus-one-half/Vim-Script/loops-n-plus-one-half.vim b/Task/Loops-N-plus-one-half/Vim-Script/loops-n-plus-one-half.vim new file mode 100644 index 0000000000..6ad43fafb4 --- /dev/null +++ b/Task/Loops-N-plus-one-half/Vim-Script/loops-n-plus-one-half.vim @@ -0,0 +1,6 @@ +for i in range(1, 10) + echon i + if (i != 10) + echon ", " + endif +endfor diff --git a/Task/Loops-Nested/00DESCRIPTION b/Task/Loops-Nested/00DESCRIPTION index e48f9fda63..9441448c62 100644 --- a/Task/Loops-Nested/00DESCRIPTION +++ b/Task/Loops-Nested/00DESCRIPTION @@ -1 +1,3 @@ -Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [1,\ldots,20]. The loops iterate rows and columns of the array printing the elements until the value 20 is met. Specifically, this task also shows how to [[Loop/Break|break]] out of nested loops. +Show a nested loop which searches a two-dimensional array filled with random numbers uniformly distributed over [1,\ldots,20]. +The loops iterate rows and columns of the array printing the elements until the value 20 is met. +Specifically, this task also shows how to [[Loop/Break|break]] out of nested loops. diff --git a/Task/Loops-Nested/ColdFusion/loops-nested.cfm b/Task/Loops-Nested/ColdFusion/loops-nested.cfm new file mode 100644 index 0000000000..b0c8fbe6fa --- /dev/null +++ b/Task/Loops-Nested/ColdFusion/loops-nested.cfm @@ -0,0 +1,9 @@ + + + + + #randNum# + + +
+
diff --git a/Task/Loops-Nested/MAXScript/loops-nested-1.max b/Task/Loops-Nested/MAXScript/loops-nested-1.max new file mode 100644 index 0000000000..189e659eac --- /dev/null +++ b/Task/Loops-Nested/MAXScript/loops-nested-1.max @@ -0,0 +1,11 @@ +fn scan_Nested arr = +( + for subArray in arr where classof subArray == Array do + ( + for item in subArray do + ( + print item as string + if item == 20 do return OK + ) + ) +) diff --git a/Task/Loops-Nested/MAXScript/loops-nested-2.max b/Task/Loops-Nested/MAXScript/loops-nested-2.max new file mode 100644 index 0000000000..d2d2120610 --- /dev/null +++ b/Task/Loops-Nested/MAXScript/loops-nested-2.max @@ -0,0 +1,11 @@ +testArray = #(#(1,5,2,19),#(11,20,7,2)) +scan_nested testArray + +#(#(1, 5, 2, 19), #(11, 20, 7, 2)) +1 +5 +2 +19 +11 +20 +OK diff --git a/Task/Loops-Nested/NewLISP/loops-nested.newlisp b/Task/Loops-Nested/NewLISP/loops-nested.newlisp new file mode 100644 index 0000000000..158ac0999d --- /dev/null +++ b/Task/Loops-Nested/NewLISP/loops-nested.newlisp @@ -0,0 +1,11 @@ +(let (a (array 10 10)) + (dotimes (i 10) + (dotimes (j 10) + (setf (a i j) (rand 21)))) + (catch + (dotimes (i 10) + (dotimes (j 10) + (print (a i j)) + (print " ") + (if (= 20 (a i j)) + (throw)))))) diff --git a/Task/Loops-Nested/OoRexx/loops-nested.rexx b/Task/Loops-Nested/OoRexx/loops-nested.rexx new file mode 100644 index 0000000000..0370d6fca9 --- /dev/null +++ b/Task/Loops-Nested/OoRexx/loops-nested.rexx @@ -0,0 +1,14 @@ +numbers = .array~new() +do i = 1 to 10 + do j = 1 to 10 + numbers[i,j] = random(1, 20) + end +end + +do i = 1 to numbers~dimension(1) + do j = 1 to numbers~dimension(2) + say numbers[i,j] + if numbers[i,j] = 20 then + leave i + end +end diff --git a/Task/Loops-Nested/REXX/loops-nested.rexx b/Task/Loops-Nested/REXX/loops-nested.rexx index 8af3ab092e..2ebb3f87c1 100644 --- a/Task/Loops-Nested/REXX/loops-nested.rexx +++ b/Task/Loops-Nested/REXX/loops-nested.rexx @@ -1,18 +1,22 @@ -/*REXX program to loop through a 2-dimensional array to look for a '20'.*/ -rows=60 -cols=10 - do row =1 for rows /*1st dimension ∙∙∙ */ - do col=1 for cols /*2nd dimension ∙∙∙ */ - @.row.col=random(1,20) /*generate some nums.*/ +/*REXX program loops through a 2-dimensional array to look for a '20'. */ +parse arg rows cols targ . /*obtain optional args from C.L. */ +if rows=='' | rows==',' then rows=60 /*Rows not specified? Use default*/ +if cols=='' | cols==',' then cols=10 /*Cols " " " " */ +if targ=='' | targ==',' then targ=20 /*Targ " " " " */ +w=max(length(rows),length(cols),length(targ)) /*for formatting output.*/ +not='not' /* [↓] construct the 2-dim array.*/ + do row=1 for rows /*1st dimension of the array. */ + do col=1 for cols /*2nd " " " " */ + @.row.col=random(1,targ) /*generate some random numbers. */ end /*row*/ end /*col*/ -/*─────────────────────────────────────now, search for the hidden twenty*/ - do r =1 for rows - do c=1 for cols - say left('@.'r"."c,9) '=' right(@.r.c,4) - if @.r.c==20 then leave r - end /*c*/ - end /*r*/ +/*═════════════════════════════════════now, search for the target {20}.*/ + do r=1 for rows + do c=1 for cols + say left('@.'r"."c,3+w+w) '=' right(@.r.c,w) /*display.*/ + if @.r.c==targ then do; not=; leave r; end /*found ? */ + end /*c*/ + end /*r*/ -say right(' Done with Loops/Nested. ',50,'─') +say right(space('Target' not 'found:') targ, 33, '─') /*stick a fork in it, we're done.*/ diff --git a/Task/Loops-Nested/Ruby/loops-nested.rb b/Task/Loops-Nested/Ruby/loops-nested-1.rb similarity index 97% rename from Task/Loops-Nested/Ruby/loops-nested.rb rename to Task/Loops-Nested/Ruby/loops-nested-1.rb index 500e5c4533..8fb13496bd 100644 --- a/Task/Loops-Nested/Ruby/loops-nested.rb +++ b/Task/Loops-Nested/Ruby/loops-nested-1.rb @@ -1,4 +1,3 @@ -srand ary = (1..20).to_a.shuffle.each_slice(4).to_a p ary diff --git a/Task/Loops-Nested/Ruby/loops-nested-2.rb b/Task/Loops-Nested/Ruby/loops-nested-2.rb new file mode 100644 index 0000000000..f62835297d --- /dev/null +++ b/Task/Loops-Nested/Ruby/loops-nested-2.rb @@ -0,0 +1,8 @@ +slices = (1..20).to_a.shuffle.each_slice(4) + +slices.any? do |slice| + slice.any? do |element| + puts element + element == 20 + end +end diff --git a/Task/Loops-While/00DESCRIPTION b/Task/Loops-While/00DESCRIPTION index a06c29e029..f828d8be82 100644 --- a/Task/Loops-While/00DESCRIPTION +++ b/Task/Loops-While/00DESCRIPTION @@ -1 +1,3 @@ -Start an integer value at 1024. Loop while it is greater than 0. Print the value (with a newline) and divide it by two each time through the loop. +{{omit from|GUISS|No loops and we cannot read values}} +Start an integer value at 1024. Loop while it is greater than 0. +Print the value (with a newline) and divide it by two each time through the loop. diff --git a/Task/Loops-While/00META.yaml b/Task/Loops-While/00META.yaml index 05fe73c7e1..e69ff9609f 100644 --- a/Task/Loops-While/00META.yaml +++ b/Task/Loops-While/00META.yaml @@ -1,2 +1,5 @@ --- +category: +- Conditional loops +- Simple note: Iteration diff --git a/Task/Loops-While/360-Assembly/loops-while.360 b/Task/Loops-While/360-Assembly/loops-while.360 new file mode 100644 index 0000000000..e2f83fae8d --- /dev/null +++ b/Task/Loops-While/360-Assembly/loops-while.360 @@ -0,0 +1,27 @@ +WHILE CSECT , This program's control section + BAKR 14,0 Caller's registers to linkage stack + LR 12,15 load entry point address into Reg 12 + LA 13,0 inidicate caller no savearea + USING WHILE,12 tell assembler we use Reg 12 as base + XR 3,3 Register 3 zero. + XR 4,4 clear even divident reg + LA 5,1024 load odd divident reg + LA 9,2 divisor in reg 9 + LA 8,WTOLEN address of WTO area in Reg 8 + MVC WTOTXT,=C'1024' + WTO TEXT=(8) write to operator initial value 1024 +LOOP DS 0H + DR 4,9 divide r4/5 by r9 + CLR 3,4 less than zero? + BL RETURN yes, return + CVD 5,PACKED convert result to (packed) decimal + OI PACKED+7,X'0F' prepare unpack + XC WTOTXT,WTOTXT clear wto text + UNPK WTOTXT,PACKED packed decimal to zoned (printable) + WTO TEXT=(8) and write-to-operator + B LOOP loop. +RETURN PR , return to caller. +WTOLEN DC H'4' fixed WTO length of four +WTOTXT DS CL4 +PACKED DS CL8 + END WHILE diff --git a/Task/Loops-While/ALGOL-60/loops-while.alg b/Task/Loops-While/ALGOL-60/loops-while.alg new file mode 100644 index 0000000000..647ce67aba --- /dev/null +++ b/Task/Loops-While/ALGOL-60/loops-while.alg @@ -0,0 +1,7 @@ +INTEGER I; +I:=1024; +WHILE I>0 DO +BEGIN + OUTINT(I); + I:=I/2 +END diff --git a/Task/Loops-While/Bracmat/loops-while.bracmat b/Task/Loops-While/Bracmat/loops-while.bracmat new file mode 100644 index 0000000000..9c75244e6d --- /dev/null +++ b/Task/Loops-While/Bracmat/loops-while.bracmat @@ -0,0 +1 @@ +1024:?n & whl'(!n:>0 & out$!n & div$(!n.2):?n) diff --git a/Task/Loops-While/Emacs-Lisp/loops-while.l b/Task/Loops-While/Emacs-Lisp/loops-while.l new file mode 100644 index 0000000000..434fd96284 --- /dev/null +++ b/Task/Loops-While/Emacs-Lisp/loops-while.l @@ -0,0 +1,4 @@ +(let ((i 1024)) + (while (> i 0) + (message "%d" i) + (setq i (/ i 2)))) diff --git a/Task/Loops-While/Fortran/loops-while-2.f b/Task/Loops-While/Fortran/loops-while-2.f index 85189c7e3a..0d86ed16dd 100644 --- a/Task/Loops-While/Fortran/loops-while-2.f +++ b/Task/Loops-While/Fortran/loops-while-2.f @@ -13,21 +13,5 @@ C Handle I. C Jump back to before the IF block. GOTO 10 ENDIF - -C This is an alternative while loop with labels on both ends. This -C will use the condition as a break rather than create an entire -C IF block. Which you use is up to you, but be aware that you must -C use this one if you plan on allowing for breaks. - I = 1024 - 20 CONTINUE -C If condition is false, break. - IF (I .LE. 0) GOTO 30 -C Handle I. - WRITE (*,*) I - I = I / 2 -C Jump back to the "loop" beginning. - GOTO 20 - 30 CONTINUE - STOP END diff --git a/Task/Loops-While/Fortran/loops-while-3.f b/Task/Loops-While/Fortran/loops-while-3.f new file mode 100644 index 0000000000..260868c7b5 --- /dev/null +++ b/Task/Loops-While/Fortran/loops-while-3.f @@ -0,0 +1,12 @@ + PROGRAM LOOPWHILE + INTEGER I +C FORTRAN 66 does not have IF block. + I = 1024 + 10 CONTINUE + IF (I .LE. 0) GOTO 20 + WRITE (*,*) I + I = I / 2 + GOTO 10 + 20 CONTINUE + STOP + END diff --git a/Task/Loops-While/NewLISP/loops-while.newlisp b/Task/Loops-While/NewLISP/loops-while.newlisp new file mode 100644 index 0000000000..60fe147103 --- /dev/null +++ b/Task/Loops-While/NewLISP/loops-while.newlisp @@ -0,0 +1,4 @@ +(let (i 1024) + (while (> i 0) + (println i) + (setq i (/ i 2)))) diff --git a/Task/Loops-While/OOC/loops-while.ooc b/Task/Loops-While/OOC/loops-while.ooc new file mode 100644 index 0000000000..85a2b5654b --- /dev/null +++ b/Task/Loops-While/OOC/loops-while.ooc @@ -0,0 +1,7 @@ +main: func { + value := 1024 + while (value > 0) { + value toString() println() + value /= 2 + } +} diff --git a/Task/Loops-While/Prolog/loops-while-1.pro b/Task/Loops-While/Prolog/loops-while-1.pro new file mode 100644 index 0000000000..cc0ad8db85 --- /dev/null +++ b/Task/Loops-While/Prolog/loops-while-1.pro @@ -0,0 +1,5 @@ +while(0) :- !. +while(X) :- + writeln(X), + X1 is X // 2, + while(X1). diff --git a/Task/Loops-While/Prolog/loops-while-2.pro b/Task/Loops-While/Prolog/loops-while-2.pro new file mode 100644 index 0000000000..5639cdef0f --- /dev/null +++ b/Task/Loops-While/Prolog/loops-while-2.pro @@ -0,0 +1 @@ +?- while(1024). diff --git a/Task/Loops-While/Prolog/loops-while.pro b/Task/Loops-While/Prolog/loops-while.pro deleted file mode 100644 index 9cc74c4430..0000000000 --- a/Task/Loops-While/Prolog/loops-while.pro +++ /dev/null @@ -1,2 +0,0 @@ -while(0) :- !. -while(X) :- X>0,write(X), nl, X1 is X // 2, while(X1). diff --git a/Task/Loops-While/Ruby/loops-while-2.rb b/Task/Loops-While/Ruby/loops-while-2.rb index 8af9a4fa49..84ec93dcc9 100644 --- a/Task/Loops-While/Ruby/loops-while-2.rb +++ b/Task/Loops-While/Ruby/loops-while-2.rb @@ -1,2 +1,2 @@ -i = 1024 -puts i or i /= 2 while i > 0 +puts i = 1024 +puts i /= 2 while i > 0 diff --git a/Task/Loops-While/Rust/loops-while.rust b/Task/Loops-While/Rust/loops-while.rust new file mode 100644 index 0000000000..2ba44ee978 --- /dev/null +++ b/Task/Loops-While/Rust/loops-while.rust @@ -0,0 +1,7 @@ +fn main() { + let mut n = 1024i; + while n > 0 { + println!("{}", n); + n /= 2; + } +} diff --git a/Task/Loops-While/TI-83-BASIC/loops-while.ti-83 b/Task/Loops-While/TI-83-BASIC/loops-while.ti-83 new file mode 100644 index 0000000000..bb30ff9fac --- /dev/null +++ b/Task/Loops-While/TI-83-BASIC/loops-while.ti-83 @@ -0,0 +1,5 @@ +1024→I +While I>0 +Disp I +I/2→I +End diff --git a/Task/Loops-While/Vim-Script/loops-while.vim b/Task/Loops-While/Vim-Script/loops-while.vim new file mode 100644 index 0000000000..f0cb323541 --- /dev/null +++ b/Task/Loops-While/Vim-Script/loops-while.vim @@ -0,0 +1,5 @@ +let i = 1024 +while i > 0 + echo i + let i = i / 2 +endwhile diff --git a/Task/Lucas-Lehmer-test/360-Assembly/lucas-lehmer-test.360 b/Task/Lucas-Lehmer-test/360-Assembly/lucas-lehmer-test.360 new file mode 100644 index 0000000000..98f9b730aa --- /dev/null +++ b/Task/Lucas-Lehmer-test/360-Assembly/lucas-lehmer-test.360 @@ -0,0 +1,73 @@ +* Lucas-Lehmer test +LUCASLEH CSECT + USING LUCASLEH,R12 +SAVEARA B STM-SAVEARA(R15) + DC 17F'0' + DC CL8'LUCASLEH' +STM STM R14,R12,12(R13) save calling context + ST R13,4(R15) + ST R15,8(R13) + LR R12,R15 set addessability +* ---- CODE + LA R2,2 R2=2 + LA R11,0 R11:N' + BCTR R11,0 N':=X'FFFFFFFF' + LA R10,1 R10:N N=1 + LA R4,1 R4:IEXP + LA R6,1 step + LH R7,IEXPMAX R7:IEXPMAX limit +LOOPE BXH R4,R6,ENDLOOPE do iexp=2 to iexpmax + SR R3,R3 R3:S S=0 + CR R4,R2 if iexp=2 then S=0 + BE OKS + LA R3,4 else S=4 +OKS EQU * + SLDA R10,1 n=(n+1)*2-1 + LA R5,0 I + LA R8,1 step + LR R9,R4 IEXP + SR R9,R2 IEXP-2 limit +LOOPI BXH R5,R8,ENDLOOPI do i=1 to iexp-2 +* ---- compute s=(s*s-2) MOD n + SR R14,R14 R14=0 + LR R15,R3 R15=S + MR R14,R3 R{14-15}=S*S + SLR R15,R2 R15=R15-2=S*S-2 + BNM *+6 skip next if no borrow + BCTR R14,0 perform borrow + DR R14,R10 R10=N + LR R3,R14 R14=MOD + B LOOPI +ENDLOOPI EQU * + LTR R3,R3 + BNZ NOPRT if s<>0 then no print + CVD R4,P store to packed P + UNPK Z,P Z=P + MVC C,Z C=Z + OI C+L'C-1,X'F0' zap sign + MVC WTOBUF(4),C+12 + MVI WTOBUF,C'M' + WTO MF=(E,WTOMSG) +NOPRT EQU * + B LOOPE +ENDLOOPE EQU * +* ---- END CODE +RETURN EQU * + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +* ---- DATA +IEXPMAX DC H'31' +I DS H +IEXP DS H +S DS F +N DS F +P DS PL8 packed +Z DS ZL16 zoned +C DS CL16 character +WTOMSG DS 0F + DC H'80',XL2'0000' +WTOBUF DC 80C' ' + LTORG + YREGS + END LUCASLEH diff --git a/Task/Lucas-Lehmer-test/C++/lucas-lehmer-test.cpp b/Task/Lucas-Lehmer-test/C++/lucas-lehmer-test.cpp index b6c3b16c07..adb7f220b3 100644 --- a/Task/Lucas-Lehmer-test/C++/lucas-lehmer-test.cpp +++ b/Task/Lucas-Lehmer-test/C++/lucas-lehmer-test.cpp @@ -1,8 +1,22 @@ #include #include -mpz_class pow2(mpz_class exp); -bool is_mersenne_prime(mpz_class p); +static bool is_mersenne_prime(mpz_class p) +{ + if( 2 == p ) + return true; + else + { + mpz_class s(4); + mpz_class div( (mpz_class(1) << p.get_ui()) - 1 ); + for( mpz_class i(3); i <= p; ++i ) + { + s = (s * s - mpz_class(2)) % div ; + } + + return ( s == mpz_class(0) ); + } +} int main() { @@ -21,37 +35,3 @@ int main() } } } - -bool is_mersenne_prime(mpz_class p) -{ - if( 2 == p ) - return true; - else - { - mpz_class div = pow2(p) - mpz_class(1); - mpz_class s(4); - mpz_class s(4); - for( mpz_class i(3); - i <= p; - ++i ) - { - s = (s * s - mpz_class(2)) % div ; - } - - return ( s == mpz_class(0) ); - } -} - -mpz_class pow2(mpz_class exp) -{ - // Unfortunately, GMP doesn't have a left-shift method. - // It also doesn't have a pow() equivalent that takes arbitrary-precision exponents. - // So we have to do it the hard (and presumably slow) way. - mpz_class ret(2); - mpz_class ret(2); - for(mpz_class i(1); i < exp; ++i) - ret *= mpz_class(2); - ret *= mpz_class(2); - //std::cout << "pow2( " << exp << " ) = " << ret << std::endl; - return ret; -} diff --git a/Task/Lucas-Lehmer-test/C/lucas-lehmer-test-1.c b/Task/Lucas-Lehmer-test/C/lucas-lehmer-test-1.c new file mode 100644 index 0000000000..88bb0756bf --- /dev/null +++ b/Task/Lucas-Lehmer-test/C/lucas-lehmer-test-1.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +int lucas_lehmer(unsigned long p) +{ + mpz_t V, mp, t; + unsigned long k, tlim; + int res; + + if (p == 2) return 1; + if (!(p&1)) return 0; + + mpz_init_set_ui(t, p); + if (!mpz_probab_prime_p(t, 25)) /* if p is composite, 2^p-1 is not prime */ + { mpz_clear(t); return 0; } + + if (p < 23) /* trust the PRP test for these values */ + { mpz_clear(t); return (p != 11); } + + mpz_init(mp); + mpz_setbit(mp, p); + mpz_sub_ui(mp, mp, 1); + + /* If p=3 mod 4 and p,2p+1 both prime, then 2p+1 | 2^p-1. Cheap test. */ + if (p > 3 && p % 4 == 3) { + mpz_mul_ui(t, t, 2); + mpz_add_ui(t, t, 1); + if (mpz_probab_prime_p(t,25) && mpz_divisible_p(mp, t)) + { mpz_clear(mp); mpz_clear(t); return 0; } + } + + /* Do a little trial division first. Saves quite a bit of time. */ + tlim = p/2; + if (tlim > (ULONG_MAX/(2*p))) + tlim = ULONG_MAX/(2*p); + for (k = 1; k < tlim; k++) { + unsigned long q = 2*p*k+1; + /* factor must be 1 or 7 mod 8 and a prime */ + if ( (q%8==1 || q%8==7) && + q % 3 && q % 5 && q % 7 && + mpz_divisible_ui_p(mp, q) ) + { mpz_clear(mp); mpz_clear(t); return 0; } + } + + mpz_init_set_ui(V, 4); + for (k = 3; k <= p; k++) { + mpz_mul(V, V, V); + mpz_sub_ui(V, V, 2); + /* mpz_mod(V, V, mp) but more efficiently done given mod 2^p-1 */ + if (mpz_sgn(V) < 0) mpz_add(V, V, mp); + /* while (n > mp) { n = (n >> p) + (n & mp) } if (n==mp) n=0 */ + /* but in this case we can have at most one loop plus a carry */ + mpz_tdiv_r_2exp(t, V, p); + mpz_tdiv_q_2exp(V, V, p); + mpz_add(V, V, t); + while (mpz_cmp(V, mp) >= 0) mpz_sub(V, V, mp); + } + res = !mpz_sgn(V); + mpz_clear(t); mpz_clear(mp); mpz_clear(V); + return res; +} + +int main(int argc, char* argv[]) { + unsigned long i, n = 43112609; + if (argc >= 2) n = strtoul(argv[1], 0, 10); + for (i = 1; i <= n; i++) { + if (lucas_lehmer(i)) { + printf("M%lu ", i); + fflush(stdout); + } + } + printf("\n"); + return 0; +} diff --git a/Task/Lucas-Lehmer-test/C/lucas-lehmer-test.c b/Task/Lucas-Lehmer-test/C/lucas-lehmer-test-2.c similarity index 100% rename from Task/Lucas-Lehmer-test/C/lucas-lehmer-test.c rename to Task/Lucas-Lehmer-test/C/lucas-lehmer-test-2.c diff --git a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d index 4445111744..376710c128 100644 --- a/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d +++ b/Task/Lucas-Lehmer-test/D/lucas-lehmer-test.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.bigint; -bool isPrime(in int p) pure nothrow { +bool isPrime(in uint p) pure nothrow @safe @nogc { if (p < 2 || p % 2 == 0) return p == 2; foreach (immutable i; 3 .. cast(uint)real(p).sqrt + 1) @@ -9,7 +9,7 @@ bool isPrime(in int p) pure nothrow { return true; } -bool isMersennePrime(in int p) pure /*nothrow*/ { +bool isMersennePrime(in uint p) pure nothrow /*@safe*/ { if (!p.isPrime) return false; if (p == 2) diff --git a/Task/Lucas-Lehmer-test/Perl-6/lucas-lehmer-test.pl6 b/Task/Lucas-Lehmer-test/Perl-6/lucas-lehmer-test.pl6 index 7f32290f30..5761667b04 100644 --- a/Task/Lucas-Lehmer-test/Perl-6/lucas-lehmer-test.pl6 +++ b/Task/Lucas-Lehmer-test/Perl-6/lucas-lehmer-test.pl6 @@ -1,12 +1,13 @@ -multi is_prime(2) { True } -multi is_prime(Int $p) { $p %% none(2,3,5,7...^ * > sqrt($p)) } - multi is_mersenne_prime(2) { True } multi is_mersenne_prime(Int $p) { my $m_p = 2 ** $p - 1; my $s = 4; - $s = ($s ** 2 - 2) % $m_p for 3 .. $p; + # Alternate but slightly slower: $s = ($s * $s - 2) % $m_p for 3..$p; + for (3 .. $p) { + $s = $s.expmod(2, $m_p) - 2; + $s += $m_p if $s < 0; + } $s == 0; } -say "M$_" if is_prime($_) and is_mersenne_prime($_) for 2..*; +say "M$_" if is-prime($_) and is_mersenne_prime($_) for 2..*; diff --git a/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-1.pl b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-1.pl new file mode 100644 index 0000000000..42432640f4 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-1.pl @@ -0,0 +1,16 @@ +use Math::GMP qw/:constant/; + +sub is_prime { Math::GMP->new(shift)->probab_prime(12); } + +sub is_mersenne_prime { + my $p = shift; + return 1 if $p == 2; + my $mp = 2 ** $p - 1; + my $s = 4; + $s = ($s * $s - 2) % $mp for 3..$p; + $s == 0; +} + +foreach my $p (2 .. 43_112_609) { + print "M$p\n" if is_prime($p) && is_mersenne_prime($p); +} diff --git a/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-2.pl b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-2.pl new file mode 100644 index 0000000000..c9729a06b6 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-2.pl @@ -0,0 +1,8 @@ +use ntheory qw/:all/; +$|=1; # flush output on every print +my $n = 0; +for (1..47) { + 1 while !is_mersenne_prime(++$n); + print "M$n "; +} +print "\n"; diff --git a/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-3.pl b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-3.pl new file mode 100644 index 0000000000..dfd5e69b2e --- /dev/null +++ b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-3.pl @@ -0,0 +1,7 @@ +use ntheory qw/:all/; +use bigint try=>"GMP,Pari"; +forprimes { + my $p = $_; + my $mp1 = 2**$p; + print "M$p\n" if $p == 2 || 0 == (lucas_sequence($mp1-1, 4, 1, $mp1))[0]; +} 43_112_609; diff --git a/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test.pl b/Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-4.pl similarity index 100% rename from Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test.pl rename to Task/Lucas-Lehmer-test/Perl/lucas-lehmer-test-4.pl diff --git a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx index 34c148310d..00d579512b 100644 --- a/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx +++ b/Task/Lucas-Lehmer-test/REXX/lucas-lehmer-test.rexx @@ -1,63 +1,56 @@ /*REXX program to use Lucas-Lehmer primality test for prime powers of 2.*/ -parse arg limit . /*get the argument (if any). */ -if limit=='' then limit=1000 /*if no argument, assume 1000. */ +parse arg limit . /*get the optional arg from C.L. */ +if limit=='' then limit=1000 /*No argument? Then assume 1000.*/ list= /*placeholder for the results. */ - - do j=1 by 2 to limit /*only process so much... */ - /*there're only so many hours in a day...*/ - power=j - if j==1 then power=2 /*special case for the even prime*/ - if \isprime(power ) then iterate /*if not prime, then ignore it. */ - list=list Lucas_Lehmer2(power) /*add to list (or maybe not). */ + /* [↓] only process up to LIMIT,*/ + do j=1 by 2 to limit /*···only so many hours in a day.*/ + power=j + (j==1) /*POWER ≡ J except for when J=1.*/ + if \isPrime(power) then iterate /*if not prime, then ignore it. */ + list=list Lucas_Lehmer2(power) /*add to list (···or maybe not).*/ end /*j*/ -list=space(list) /*remove extraneous blanks. */ +list=space(list) /*remove all extraneous blanks. */ say; say center('list',60-3,"═") /*show a fancy-dancy header/title*/ say - do k=1 for words(list) /*show entries in list, 1/line. */ - say right(word(list,k),30) /*and right-justify 'em. */ + do k=1 for words(list) /*show entries in list, 1/line. */ + say right(word(list,k),30) /*right-justify 'em to look nice.*/ end /*k*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────LUCAS_LEHMER2 subroutine────────────*/ -Lucas_Lehmer2: procedure; parse arg ? /*Lucas-Lehmer test on 2**? - 1 */ -numeric form /*ensure correct scientific form.*/ - -if ?==2 then s=0 - else s=4 - /* DIGITs of 1 million could be used, but that really */ - /* slows up the whole works. So, we start with the */ - /* default of 9 digits, find the 10's exponent in */ - /* the product (2**?), double it, and then add 6. */ - /* 2 is all that's needed, but 6 is a lot safer. */ - /* The doubling is for the square of S (s*s, below).*/ - -q=2**? /*compute a power of 2, using only 9 decimal digits. */ - -if pos('E',q)\==0 then do /*is it in exponential notation? */ - parse var q 'E' tenpow - numeric digits tenpow*2+6 - end - else numeric digits digits()*2+6 /* 9*2 + 6 */ - -q=2**?-1 /*now, compute the real McCoy. */ - do ?-2 /*apply, rinse, repeat ... */ - s=(s*s-2) // q /*modulus in REXX is: // */ - end - -if s\==0 then return '' /*return nuttin' if not prime. */ -say "Mersenne prime via Lucas Lehmer test:", - right('M'?,10) right("["digits() "digits]",25) -return 'M'? /*return modified (prime) number.*/ /*──────────────────────────────────ISPRIME subroutine──────────────────*/ -isprime: procedure; parse arg x -if x<17 then return wordpos(x,'2 3 5 7 11 13')\==0 /*test special cases*/ +isPrime: procedure; parse arg x /*get # to be tested*/ +if x<17 then return wordpos(x,'2 3 5 7 11 13')\==0 /*test special cases*/ if x//2==0 then return 0 /*is it even? Not prime.*/ if x//3==0 then return 0 /*divisible by three? Not prime.*/ -if right(x,1)==5 then return 0 /*divisible by three? Not prime.*/ +if right(x,1)==5 then return 0 /*right-most dig ≡ 5? Not prime.*/ if x//7==0 then return 0 /*divisible by seven? Not prime.*/ - do j=11 by 6 /*ensures J isn't divisible by 3.*/ - if x// j ==0 then return 0 - if x//(j+2)==0 then return 0 - if j*j>x then return 1 /*past the sqrt of X? It's prime*/ - end /*j*/ + do j=11 by 6 until j*j>x /*ensures J isn't divisible by 3.*/ + if x// j ==0 then return 0 /*is divisible by J ? */ + if x//(j+2)==0 then return 0 /* " " " J+2 ? ___*/ + end /*j*/ /* [↑] perform loop through √ x */ +return 1 /*indicate the number X is prime.*/ +/*──────────────────────────────────LUCAS_LEHMER2 subroutine────────────*/ +Lucas_Lehmer2: procedure; parse arg ? /*Lucas-Lehmer test on 2**? - 1 */ +if form()\=='SCIENTIFIC' then numeric form /*ensure correct # form.*/ +if ?==2 then s=0 /*handle the special even case.*/ + else s=4 +q=2**? /*╔═════════════════════════════════════════════════════════════╗ + ║Compute a power of 2, using only 9 decimal digits. DIGITs ║ + ║of 1 million could be used, but that really gums up the whole║ + ║works. So, we start with the default of 9 digits, find the ║ + ║ten's exponent in the product (2**?), double it, and then add║ + ║6. 2 is all that's needed, but 6 is a lot safer.║ + ║The doubling is for the squaring of S (below, for s*s).║ + ╚═════════════════════════════════════════════════════════════╝*/ +if pos('E',q)\==0 then do /*is # in exponential notation?*/ + parse var q 'E' tenpow + numeric digits tenpow*2 + 6 + end + else numeric digits digits()*2 + 6 /* 9*2 + 6 */ +q=2**?-1 + do ?-2 /*apply, rinse, repeat ··· */ + s=(s*s-2) // q /*remainder in REXX is: // */ + end /* [↑] compute the real McCoy. */ + +if s\==0 then return '' /*return nuttin' if not prime. */ + return 'M'? /*return modified (prime) number.*/ diff --git a/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala b/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala index 3c52db5be9..3dd39a361f 100644 --- a/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala +++ b/Task/Lucas-Lehmer-test/Scala/lucas-lehmer-test.scala @@ -9,7 +9,7 @@ object LLT extends App { def s(mp: BigInt, p: Int): BigInt = { if (p == 1) 4 else ((s(mp, p - 1) pow 2) - 2) % mp } - val upbPrime = 9999 + val upbPrime = 9941 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 }) diff --git a/Task/Lucas-Lehmer-test/Scilab/lucas-lehmer-test.scilab b/Task/Lucas-Lehmer-test/Scilab/lucas-lehmer-test.scilab new file mode 100644 index 0000000000..a9c7d22915 --- /dev/null +++ b/Task/Lucas-Lehmer-test/Scilab/lucas-lehmer-test.scilab @@ -0,0 +1,10 @@ + iexpmax=30 + n=1 + for iexp=2:iexpmax + if iexp==2 then s=0; else s=4; end + n=(n+1)*2-1 + for i=1:iexp-2 + s=modulo((s*s-2),n) + end + if s==0 then printf("M%d ",iexp); end + end diff --git a/Task/Lucas-Lehmer-test/TI-83-BASIC/lucas-lehmer-test.ti-83 b/Task/Lucas-Lehmer-test/TI-83-BASIC/lucas-lehmer-test.ti-83 new file mode 100644 index 0000000000..7806df2595 --- /dev/null +++ b/Task/Lucas-Lehmer-test/TI-83-BASIC/lucas-lehmer-test.ti-83 @@ -0,0 +1,15 @@ +19→M +1→N +For(E,2,M) +If E=2 +Then:0→S +Else:4→S +End +(N+1)*2-1→N +For(I,1,E-2) +Reminder(S*S-2,N)→S +End +If S=0 +Then:Disp E +End +End diff --git a/Task/Lucas-Lehmer-test/VBScript/lucas-lehmer-test.vb b/Task/Lucas-Lehmer-test/VBScript/lucas-lehmer-test.vb new file mode 100644 index 0000000000..9b0ef86c46 --- /dev/null +++ b/Task/Lucas-Lehmer-test/VBScript/lucas-lehmer-test.vb @@ -0,0 +1,18 @@ +iexpmax = 15 +n=1 +out="" +For iexp = 2 To iexpmax + If iexp = 2 Then + s = 0 + Else + s = 4 + End If + n = (n + 1) * 2 - 1 + For i = 1 To iexp - 2 + s = (s * s - 2) Mod n + Next + If s = 0 Then + out=out & "M" & iexp & " " + End If +Next +Wscript.echo out diff --git a/Task/Lucas-Lehmer-test/Visual-Basic-.NET/lucas-lehmer-test.visual b/Task/Lucas-Lehmer-test/Visual-Basic-.NET/lucas-lehmer-test.visual new file mode 100644 index 0000000000..ac77c702ea --- /dev/null +++ b/Task/Lucas-Lehmer-test/Visual-Basic-.NET/lucas-lehmer-test.visual @@ -0,0 +1,23 @@ +Public Class LucasLehmer + Private Sub btnGo_Click(sender As Object, e As EventArgs) Handles btnGo.Click + Const iexpmax = 31 + Dim s, n As Long + Dim i, iexp As Integer + n = 1 + txtOut.Text = "" + For iexp = 2 To iexpmax + If iexp = 2 Then + s = 0 + Else + s = 4 + End If + n = (n + 1) * 2 - 1 + For i = 1 To iexp - 2 + s = (s * s - 2) Mod n + Next i + If s = 0 Then + txtOut.Text = txtOut.Text & "M" & iexp & " " + End If + Next iexp + End Sub +End Class diff --git a/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION b/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION index 48cfaa0f72..03d03ce103 100644 --- a/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION +++ b/Task/Luhn-test-of-credit-card-numbers/00DESCRIPTION @@ -1,3 +1,4 @@ +{{omit from|GUISS}} The [[wp:Luhn algorithm|Luhn test]] is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits. Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test: diff --git a/Task/Luhn-test-of-credit-card-numbers/00META.yaml b/Task/Luhn-test-of-credit-card-numbers/00META.yaml new file mode 100644 index 0000000000..0b9ae97960 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/00META.yaml @@ -0,0 +1,2 @@ +--- +note: Checksums diff --git a/Task/Luhn-test-of-credit-card-numbers/Clojure/luhn-test-of-credit-card-numbers.clj b/Task/Luhn-test-of-credit-card-numbers/Clojure/luhn-test-of-credit-card-numbers.clj index bf765860f2..6fec88bb3a 100644 --- a/Task/Luhn-test-of-credit-card-numbers/Clojure/luhn-test-of-credit-card-numbers.clj +++ b/Task/Luhn-test-of-credit-card-numbers/Clojure/luhn-test-of-credit-card-numbers.clj @@ -1,14 +1,8 @@ -(defn- digits [n] - (map #(Character/digit % 10) (str n))) - -(defn luhn? [n] - (let [sum (reduce + (map - (fn [d idx] - (if (even? idx) - (reduce + (digits (* d 2))) - d)) - (reverse (digits n)) - (iterate inc 1)))] +(defn luhn? [cc] + (let [factors (flatten (repeat [1 2])) + numbers (map #(Character/digit % 10) (seq cc)) + sum (reduce + (map #(int (+ (/ %1 10) (mod %1 10))) + (map * (reverse numbers) factors)))] (zero? (mod sum 10)))) (doseq [n [49927398716 49927398717 1234567812345678 1234567812345670]] diff --git a/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-1.d b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-1.d index d368be9e03..3027378c8b 100644 --- a/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-1.d +++ b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-1.d @@ -1,18 +1,13 @@ -import std.algorithm; +import std.algorithm, std.range, std.string; -bool luhnTest(in string num) @safe pure nothrow { - uint sum; - foreach_reverse (immutable i, immutable n; num) { - immutable uint ord = n - '\u0030'; - sum += ((num.length - i) & 1) ? ord : ord / 5 + (2 * ord) % 10; - } - return sum % 10 == 0; -} +enum luhnTest = (in string n) pure /*nothrow*/ @safe /*@nogc*/ => + retro(n) + .zip(only(1, 2).cycle) + .map!(p => (p[0] - '0') * p[1]) + .map!(d => d / 10 + d % 10) + .sum % 10 == 0; void main() { - immutable data = ["49927398716", - "49927398717", - "1234567812345678", - "1234567812345670"]; - assert(data.map!luhnTest.equal([true, false, false, true])); + assert("49927398716 49927398717 1234567812345678 1234567812345670" + .split.map!luhnTest.equal([true, false, false, true])); } diff --git a/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-2.d b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-2.d index 436552653b..4601f1acb6 100644 --- a/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-2.d +++ b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-2.d @@ -1,59 +1,18 @@ -import std.stdio; +import std.algorithm; -struct Interval(T) { - immutable T a, b; - - this(in T a_, in T b_) pure nothrow { - this.a = a_; - this.b = b_; - } - - bool opBinaryRight(string op="in")(in T x) const pure nothrow { - return x >= a && x <= b; - } - - pure nothrow const invariant() { - assert(a <= b); +bool luhnTest(in string num) @safe pure nothrow @nogc { + uint sum; + foreach_reverse (immutable i, immutable n; num) { + immutable uint ord = n - '\u0030'; + sum += ((num.length - i) & 1) ? ord : ord / 5 + (2 * ord) % 10; } + return sum % 10 == 0; } -Interval!T interval(T)(in T a, in T b) pure nothrow { - return Interval!T(a, b); -} - - -bool luhnTest(in string num) pure nothrow -in { - assert(num.length <= 20); -} body { - int sum = 0; - bool od = true; - bool ok = true; - immutable int numLen = num.length; - - foreach_reverse (immutable p; 0 .. numLen) { - immutable int i = num[p] - '0'; - if (i !in interval(0, 9)) { - ok = false; - break; - } - - immutable int x = ((i * 2) % 10) + (i / 5); - assert((numLen - p) in interval(0, 19)); - assert(sum in interval(0, (numLen - p) * 10)); - assert(i in interval(0, 9)); - assert(x in interval(0, 9)); - sum += od ? i : x; - od = !od; - } - - return ok && (sum % 10) == 0; -} - - void main() { - foreach (immutable n; ["49927398716", "49927398717", - "1234567812345678", "1234567812345670", - "123456781234567D"]) - writefln("%s is %svalid", n, luhnTest(n) ? "" : "not "); + immutable data = ["49927398716", + "49927398717", + "1234567812345678", + "1234567812345670"]; + assert(data.map!luhnTest.equal([true, false, false, true])); } diff --git a/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-3.d b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-3.d new file mode 100644 index 0000000000..d6258c0fdd --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/D/luhn-test-of-credit-card-numbers-3.d @@ -0,0 +1,60 @@ +import std.stdio; + +struct Interval(T) { + immutable T a, b; + + this(in T a_, in T b_) pure nothrow @nogc { + this.a = a_; + this.b = b_; + } + + bool opBinaryRight(string op="in")(in T x) + const pure nothrow @nogc { + return x >= a && x <= b; + } + + pure nothrow @safe @nogc const invariant { + assert(a <= b); + } +} + +Interval!T interval(T)(in T a, in T b) pure nothrow @nogc { + return Interval!T(a, b); +} + + +bool luhnTest(in string num) pure nothrow @nogc +in { + assert(num.length <= 20); +} body { + int sum = 0; + bool od = true; + bool ok = true; + immutable int numLen = num.length; + + foreach_reverse (immutable p; 0 .. numLen) { + immutable int i = num[p] - '0'; + if (i !in interval(0, 9)) { + ok = false; + break; + } + + immutable int x = ((i * 2) % 10) + (i / 5); + assert((numLen - p) in interval(0, 19)); + assert(sum in interval(0, (numLen - p) * 10)); + assert(i in interval(0, 9)); + assert(x in interval(0, 9)); + sum += od ? i : x; + od = !od; + } + + return ok && (sum % 10) == 0; +} + + +void main() { + foreach (immutable n; ["49927398716", "49927398717", + "1234567812345678", "1234567812345670", + "123456781234567D"]) + writefln("%s is %svalid", n, luhnTest(n) ? "" : "not "); +} diff --git a/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-4.k b/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-4.k new file mode 100644 index 0000000000..2326ace34c --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-4.k @@ -0,0 +1,6 @@ +luhn:{[cc] + digits:0$/:|cc / convert chars to digit ints + s:digits*(#cc)#1 2 / evens doubled, odds not + nines:+/s>9 / number of sums greater than 9 + :~((+/s)-(9*nines))!10 / sum minus the nines is mod ten? + } diff --git a/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-5.k b/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-5.k new file mode 100644 index 0000000000..218322a707 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/K/luhn-test-of-credit-card-numbers-5.k @@ -0,0 +1,3 @@ + test:("49927398716";"49927398717";"1234567812345678";"1234567812345670") + luhn'test +1 0 0 1 diff --git a/Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers.math b/Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-1.math similarity index 100% rename from Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers.math rename to Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-1.math diff --git a/Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-2.math b/Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-2.math new file mode 100644 index 0000000000..063151ea37 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Mathematica/luhn-test-of-credit-card-numbers-2.math @@ -0,0 +1,6 @@ +LuhnQ[n_Integer] := + Block[{digits = Reverse@IntegerDigits@n}, + Mod[Total[{digits[[;; ;; 2]], + IntegerDigits[2 #] & /@ digits[[2 ;; ;; 2]]}, -1], 10] == 0] + +LuhnQ /@ {49927398716, 49927398717, 1234567812345678, 1234567812345670} diff --git a/Task/Luhn-test-of-credit-card-numbers/OpenEdge-Progress/luhn-test-of-credit-card-numbers.openedge b/Task/Luhn-test-of-credit-card-numbers/OpenEdge-Progress/luhn-test-of-credit-card-numbers.openedge new file mode 100644 index 0000000000..5ca04c59bb --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/OpenEdge-Progress/luhn-test-of-credit-card-numbers.openedge @@ -0,0 +1,49 @@ +FUNCTION fnLuhnAlgorithm RETURNS LOGICAL + (INPUT pcNumber AS CHARACTER): +/*------------------------------------------------------------------------------ + Purpose: Applies Luhn Algorithm to check a Number + Notes: Returns True/False Validation based on check digit +------------------------------------------------------------------------------*/ + DEFINE VARIABLE cNum AS CHARACTER NO-UNDO. + DEFINE VARIABLE iCheck AS INTEGER NO-UNDO. + DEFINE VARIABLE iLength AS INTEGER NO-UNDO. + DEFINE VARIABLE iLoopCnt AS INTEGER NO-UNDO. + DEFINE VARIABLE iNum AS INTEGER NO-UNDO. + DEFINE VARIABLE iNum1 AS INTEGER NO-UNDO. + DEFINE VARIABLE iNum2 AS INTEGER NO-UNDO. + DEFINE VARIABLE iTestLength AS INTEGER NO-UNDO. + + ASSIGN + iLength = LENGTH(pcNumber) + iTestLength = iLength - 1 + iCheck = 1. /* 1 for the check digit we skip */ + + DO iLoopCnt = iTestLength TO 1 BY -1: + ASSIGN + iNum = INTEGER(SUBSTR(pcNumber,iLoopCnt,1)) + iCheck = iCheck + 1. + + IF iCheck MODULO 2 = 1 THEN + ASSIGN iNum1 = iNum1 + iNum. + ELSE + DO: + ASSIGN iNum2 = iNum * 2. + IF iNum2 < 10 THEN + ASSIGN iNum1 = iNum1 + iNum2. + ELSE + ASSIGN + cNum = STRING(iNum2) + iNum1 = iNum1 + INTEGER(SUBSTR(cNum,1,1)) + INTEGER(SUBSTR(cNum,2,1)). + END. + END. + + ASSIGN + iNum2 = iNum1 * 9 + iNum = iNum2 MODULO 10. + + IF iNum = INTEGER(SUBSTR(pcNumber,iLength,1)) THEN + RETURN TRUE. + ELSE + RETURN FALSE. + +END FUNCTION. /* fnLuhnAlgorithm */ diff --git a/Task/Luhn-test-of-credit-card-numbers/R/luhn-test-of-credit-card-numbers.r b/Task/Luhn-test-of-credit-card-numbers/R/luhn-test-of-credit-card-numbers.r new file mode 100644 index 0000000000..33df3ce4c6 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/R/luhn-test-of-credit-card-numbers.r @@ -0,0 +1,19 @@ +luhnTest <- function(cc){ + # Reverse the digits, convert to numeric vector + cc2 <- as.numeric(unlist(strsplit(as.character(cc), "")))[nchar(cc):1] + + s1 <- 0 + s2 <- 0 + + for (index in 1:length(cc2)){ + if (index %% 2 == 1){ + s1 <- sum(s1, cc2[index]) + } else if (cc2[index] >= 5){ + s2 <- sum(s2, (cc2[index]*2 - 9)) + } else { + s2 <- sum(s2, (cc2[index]*2)) + } + } + + return ((s1 + s2) %% 10 == 0) +} diff --git a/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb b/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb new file mode 100644 index 0000000000..c8d401fc3f --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Ruby/luhn-test-of-credit-card-numbers.rb @@ -0,0 +1,15 @@ +def luhn(code) + s1 = s2 = 0 + code.to_s.reverse.chars.each_slice(2) do |odd, even| + s1 += odd.to_i + + double = even.to_i * 2 + double -= 9 if double >= 10 + s2 += double + end + (s1 + s2) % 10 == 0 +end + +[49927398716, 49927398717, 1234567812345678, 1234567812345670].each do |n| + p [n, luhn(n)] +end diff --git a/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust new file mode 100644 index 0000000000..70a0df843a --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/Rust/luhn-test-of-credit-card-numbers.rust @@ -0,0 +1,48 @@ +fn get_digits(i: &int) -> Vec { + let mut digits = Vec::new(); + let mut n = *i; + while n > 0 { + digits.push(n % 10); + n /= 10; + } + digits.reverse(); + return digits +} + +fn luhn_test(n: &int) -> bool { + let mut digits = get_digits(n); + + let mut i = 0; + let mut sum = 0; + + let is_odd = |x: int| x&1 == 1; + + digits.reverse(); + for n in digits.iter() { + i += 1; + if is_odd(i) { + // add directly to sum + sum += *n; + } else { + // get sum of digits of n*2 + let n_digits = get_digits(&(*n * 2)); + for n_digit in n_digits.iter() { + sum += *n_digit; + } + } + } + + return sum % 10 == 0; +} + +fn main() { + let nos = [49927398716, 49927398717, 1234567812345678, 1234567812345670]; + for n in nos.iter() { + if luhn_test(n) { + println!("{} passes.", n); + continue + } + + println!("{} fails.", n); + } +} diff --git a/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala b/Task/Luhn-test-of-credit-card-numbers/Scala/luhn-test-of-credit-card-numbers-1.scala index 3d371cfa04..8146fc337d 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,9 +1,17 @@ object LuhnTest extends App { + 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 + } + sum % 10 == 0 + } 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 + (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 } // Bonus function Compute check digit and assemble it to a valid number @@ -12,7 +20,6 @@ object LuhnTest extends App { ((10 - luhnChecksum((partialCardNumber.toLong * 10).toString)) % 10).toString } - // Section of test val (validNumbers, invalidNumbers) = (List("49927398716", "1234567812345670"), List("49927398717", "1234567812345678")) diff --git a/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh b/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh new file mode 100644 index 0000000000..231abf0839 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/UNIX-Shell/luhn-test-of-credit-card-numbers.sh @@ -0,0 +1,36 @@ +luhn() { + reverse $1 | { + while read odd; do + (( s1 += odd )) + read even + e=0 + for digit in $(digits $(( 2 * even)) ); do + (( e += digit )) + done + (( s2 += e )) + done + (( (s1+s2) % 10 == 0 )) + } +} + +reverse() { + local i digits=( $(digits $1) ) + for ((i=${#digits[@]}-1; i>=0; i--)); do + echo ${digits[i]} + done +} + +digits() { + local i + for ((i=0; i<${#1}; i++)); do + echo ${1:i:1} + done +} + +for c in 49927398716 49927398717 1234567812345678 1234567812345670; do + if luhn $c; then + echo $c is valid + else + echo $c is invalid + fi +done diff --git a/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb b/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb new file mode 100644 index 0000000000..c89906e644 --- /dev/null +++ b/Task/Luhn-test-of-credit-card-numbers/VBScript/luhn-test-of-credit-card-numbers.vb @@ -0,0 +1,33 @@ +Function Luhn_Test(cc) + cc = RevString(cc) + s1 = 0 + s2 = 0 + For i = 1 To Len(cc) + If i Mod 2 > 0 Then + s1 = s1 + CInt(Mid(cc,i,1)) + Else + tmp = CInt(Mid(cc,i,1))*2 + If tmp < 10 Then + s2 = s2 + tmp + Else + s2 = s2 + CInt(Right(CStr(tmp),1)) + 1 + End If + End If + Next + If Right(CStr(s1 + s2),1) = "0" Then + Luhn_Test = "Valid" + Else + Luhn_Test = "Invalid" + End If +End Function + +Function RevString(s) + For i = Len(s) To 1 Step -1 + RevString = RevString & Mid(s,i,1) + Next +End Function + +WScript.Echo "49927398716 is " & Luhn_Test("49927398716") +WScript.Echo "49927398717 is " & Luhn_Test("49927398717") +WScript.Echo "1234567812345678 is " & Luhn_Test("1234567812345678") +WScript.Echo "1234567812345670 is " & Luhn_Test("1234567812345670") diff --git a/Task/MD4/00DESCRIPTION b/Task/MD4/00DESCRIPTION index 0a6c9a3a51..979d598c03 100644 --- a/Task/MD4/00DESCRIPTION +++ b/Task/MD4/00DESCRIPTION @@ -1,4 +1,6 @@ -Find the MD4 message digest of a string of [[octet]]s. Use the ASCII encoded string “Rosetta Code” (without quotes). You may either call an MD4 library, or implement MD4 in your language. +Find the MD4 message digest of a string of [[octet]]s. +Use the ASCII encoded string “Rosetta Code” (without quotes). +You may either call an MD4 library, or implement MD4 in your language. '''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. diff --git a/Task/MD4/Clojure/md4.clj b/Task/MD4/Clojure/md4.clj new file mode 100644 index 0000000000..1e5c591022 --- /dev/null +++ b/Task/MD4/Clojure/md4.clj @@ -0,0 +1,2 @@ +(use 'pandect.core) +(md4 "Rosetta Code") diff --git a/Task/MD4/D/md4.d b/Task/MD4/D/md4.d new file mode 100644 index 0000000000..9dff96af1d --- /dev/null +++ b/Task/MD4/D/md4.d @@ -0,0 +1,47 @@ +import std.stdio, std.string, std.range; + +ubyte[16] md4(const(ubyte)[] inData) pure nothrow { + enum f = (uint x, uint y, uint z) => (x & y) | (~x & z); + enum g = (uint x, uint y, uint z) => (x & y) | (x & z) | (y & z); + enum h = (uint x, uint y, uint z) => x ^ y ^ z; + enum r = (uint v, uint s) => (v << s) | (v >> (32 - s)); + + immutable bitLen = ulong(inData.length) << 3; + inData ~= 0x80; + while (inData.length % 64 != 56) + inData ~= 0; + const data = cast(uint[])inData ~ [uint(bitLen & uint.max), uint(bitLen >> 32)]; + + uint a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476; + + foreach (const x; data.chunks(16)) { + immutable a2 = a, b2 = b, c2 = c, d2 = d; + foreach (immutable i; [0, 4, 8, 12]) { + a = r(a + f(b, c, d) + x[i+0], 3); + d = r(d + f(a, b, c) + x[i+1], 7); + c = r(c + f(d, a, b) + x[i+2], 11); + b = r(b + f(c, d, a) + x[i+3], 19); + } + foreach (immutable i; [0, 1, 2, 3]) { + a = r(a + g(b, c, d) + x[i+0] + 0x5a827999, 3); + d = r(d + g(a, b, c) + x[i+4] + 0x5a827999, 5); + c = r(c + g(d, a, b) + x[i+8] + 0x5a827999, 9); + b = r(b + g(c, d, a) + x[i+12] + 0x5a827999, 13); + } + foreach (immutable i; [0, 2, 1, 3]) { + a = r(a + h(b, c, d) + x[i+0] + 0x6ed9eba1, 3); + d = r(d + h(a, b, c) + x[i+8] + 0x6ed9eba1, 9); + c = r(c + h(d, a, b) + x[i+4] + 0x6ed9eba1, 11); + b = r(b + h(c, d, a) + x[i+12] + 0x6ed9eba1, 15); + } + a += a2, b += b2, c += c2, d += d2; + } + + //return cast(ubyte[16])[a, b, c, d]; + immutable uint[4] result = [a, b, c, d]; + return cast(ubyte[16])result; +} + +void main() { + writefln("%(%02x%)", "Rosetta Code".representation.md4); +} diff --git a/Task/MD4/Go/md4.go b/Task/MD4/Go/md4.go index b0dd71bd75..dc9bd85600 100644 --- a/Task/MD4/Go/md4.go +++ b/Task/MD4/Go/md4.go @@ -1,7 +1,7 @@ package main import ( - "code.google.com/p/go.crypto/md4" + "golang.org/x/crypto/md4" "fmt" ) diff --git a/Task/MD4/PicoLisp/md4.l b/Task/MD4/PicoLisp/md4.l new file mode 100644 index 0000000000..d3f319a0e8 --- /dev/null +++ b/Task/MD4/PicoLisp/md4.l @@ -0,0 +1,176 @@ +(de *Md4-W . + (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 + 1 9 5 13 3 11 7 15 2 10 6 14 4 12 8 16 .)) +(de *Md4-R1 . (3 7 11 19 .)) +(de *Md4-R2 . (3 5 9 13 .)) +(de *Md4-R3 . (3 9 11 15 .)) + +(de mod32 (N) + (& N `(hex "FFFFFFFF")) ) + +(de not32 (N) + (x| N `(hex "FFFFFFFF")) ) + +(de add32 @ + (mod32 (pass +)) ) + +(de leftRotate (X C) + (| (mod32 (>> (- C) X)) (>> (- 32 C) X)) ) + +(de md4 (Str) + (let Len (length Str) + (setq Str + (conc + (need + (- 8 (* 64 (/ (+ Len 1 8 63) 64))) # Pad to 64-8 bytes + (conc + (mapcar char (chop Str)) # Works only with ASCII characters + (cons `(hex "80")) ) # '1' bit + 0 ) # Pad with '0' + (make + (setq Len (* 8 Len)) + (do 8 + (link (& Len 255)) + (setq Len (>> 8 Len )) ) ) ) ) ) + (let + (H0 `(hex "67452301") + H1 `(hex "EFCDAB89") + H2 `(hex "98BADCFE") + H3 `(hex "10325476") + R2 `(hex "5A827999") + R3 `(hex "6ED9EBA1") ) + (while Str + (let + (A H0 B H1 C H2 D H3 + W (make + (do 16 + (link + (apply | + (mapcar >> (0 -8 -16 -24) (cut 4 'Str)) ) ) ) ) ) + (for I 12 + (cond + ((>= 4 I) + (setq + A (leftRotate + (add32 + A + (| (& B C) (& (not32 B) D)) + (get W (pop '*Md4-W)) ) + (pop '*Md4-R1) ) + D (leftRotate + (add32 + D + (| (& A B) (& (not32 A) C)) + (get W (pop '*Md4-W)) ) + (pop '*Md4-R1) ) + C (leftRotate + (add32 + C + (| (& D A) (& (not32 D) B)) + (get W (pop '*Md4-W)) ) + (pop '*Md4-R1) ) + B (leftRotate + (add32 + B + (| (& C D) (& (not32 C) A)) + (get W (pop '*Md4-W)) ) + (pop '*Md4-R1) ) ) ) + ((>= 8 I) + (setq + A (leftRotate + (add32 + A + (| + (& B (| C D)) + (& C D) ) + (get W (pop '*Md4-W)) + R2 ) + (pop '*Md4-R2) ) + D (leftRotate + (add32 + D + (| + (& A (| B C)) + (& B C) ) + (get W (pop '*Md4-W)) + R2 ) + (pop '*Md4-R2) ) + C (leftRotate + (add32 + C + (| + (& D (| A B)) + (& A B) ) + (get W (pop '*Md4-W)) + R2 ) + (pop '*Md4-R2) ) + B (leftRotate + (add32 + B + (| + (& C (| D A)) + (& D A) ) + (get W (pop '*Md4-W)) + R2 ) + (pop '*Md4-R2) ) ) ) + (T + (setq + A (leftRotate + (add32 + A + (x| B C D) + (get W (pop '*Md4-W)) + R3 ) + (pop '*Md4-R3) ) + D (leftRotate + (add32 + D + (x| A B C) + (get W (pop '*Md4-W)) + R3 ) + (pop '*Md4-R3) ) + C (leftRotate + (add32 + C + (x| D A B) + (get W (pop '*Md4-W)) + R3 ) + (pop '*Md4-R3) ) + B (leftRotate + (add32 + B + (x| C D A) + (get W (pop '*Md4-W)) + R3 ) + (pop '*Md4-R3) ) ) ) ) ) + (setq + H0 (add32 H0 A) + H1 (add32 H1 B) + H2 (add32 H2 C) + H3 (add32 H3 D) ) ) ) + (make + (for N (list H0 H1 H2 H3) + (do 4 + (link (& N 255)) + (setq N (>> 8 N)) ) ) ) ) ) + +(let Str "Rosetta Code" + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (md4 Str) ) ) ) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (native + "libcrypto.so" + "MD4" + '(B . 16) + Str + (length Str) + '(NIL (16)) ) ) ) ) ) + +(bye) diff --git a/Task/MD4/Racket/md4.rkt b/Task/MD4/Racket/md4.rkt new file mode 100644 index 0000000000..acec573ecc --- /dev/null +++ b/Task/MD4/Racket/md4.rkt @@ -0,0 +1,3 @@ +#lang racket +(require (planet soegaard/digest:1:2/digest)) +(md4 #"Rosetta Code") diff --git a/Task/MD4/Ruby/md4-2.rb b/Task/MD4/Ruby/md4-2.rb index 89f6dd745a..802dd63ac6 100644 --- a/Task/MD4/Ruby/md4-2.rb +++ b/Task/MD4/Ruby/md4-2.rb @@ -13,41 +13,22 @@ def md4(string) # initial hash a, b, c, d = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 + bit_len = string.size << 3 + string += "\x80" + while (string.size % 64) != 56 + string += "\0" + end + string = string.force_encoding('ascii-8bit') + [bit_len & mask, bit_len >> 32].pack("V2") + + if string.size % 64 != 0 + fail "failed to pad to correct length" + end + io = StringIO.new(string) block = "" - term = false # appended "\x80" in second-last block? - last = false # last block? - until last - # Read next block of 16 words (64 bytes, 512 bits). - 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("") - ) - # Unpack block into 32-bit words "V". - case len = block.length - when 64 - # Unpack 16 words. - x = block.unpack("V16") - when 56..63 - # Second-last block: append padding, unpack 16 words. - block.concat("\x80"); term = true - block.concat("\0" * (63 - len)) - x = block.unpack("V16") - when 0..55 - # Last block: append padding, unpack 14 words. - block.concat(term ? "\0" : "\x80") - block.concat("\0" * (55 - len)) - x = block.unpack("V14") - - # Append bit length, 2 words. - bit_len = string.length << 3 - x.push(bit_len & mask, bit_len >> 32) - last = true - else - fail "impossible" - end + while io.read(64, block) + x = block.unpack("V16") # Process this block. aa, bb, cc, dd = a, b, c, d diff --git a/Task/MD4/Scala/md4.scala b/Task/MD4/Scala/md4.scala new file mode 100644 index 0000000000..975f8fe06e --- /dev/null +++ b/Task/MD4/Scala/md4.scala @@ -0,0 +1,12 @@ +import org.bouncycastle.crypto.digests.MD4Digest + +object RosettaRIPEMD160 extends App { + val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new MD4Digest()) + messageDigest.update(raw, 0, raw.length) + val out = Array.fill[Byte](messageDigest.getDigestSize())(0) + messageDigest.doFinal(out, 0) + + assert(out.map("%02x".format(_)).mkString == "a52bcfc6a0d0d300cdc5ddbfbefe478b") + import scala.compat.Platform.currentTime + println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") +} diff --git a/Task/MD5-Implementation/D/md5-implementation.d b/Task/MD5-Implementation/D/md5-implementation.d index ce9f8f23f5..4a56a025fa 100644 --- a/Task/MD5-Implementation/D/md5-implementation.d +++ b/Task/MD5-Implementation/D/md5-implementation.d @@ -6,12 +6,13 @@ version (D_InlineAsm_X86) {} else { } // 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 S(in uint n) pure nothrow @safe @nogc { + static immutable aux = [7u, 12, 17, 22, 5, 9, 14, 20, 4, 11, + 16, 23, 6, 10, 15, 21]; + return aux[(n / 16) * 4 + (n % 4)]; } -uint K(in uint n) pure nothrow { +uint K(in uint n) pure nothrow @safe @nogc { uint r = 0; if (n <= 15) r = n; @@ -24,7 +25,7 @@ uint K(in uint n) pure nothrow { return r % 16; } -uint T(in uint n) pure nothrow { +uint T(in uint n) pure nothrow @nogc { return cast(uint)(abs(sin(n + 1.0L)) * (2UL ^^ 32)); } @@ -42,7 +43,7 @@ string SUB(in int n, in string s) pure nothrow { } // FF, GG, HH & II expressions part 1 (F, G, H, I). -string fghi1(in int n) pure nothrow { +string fghi1(in int n) pure nothrow @nogc { switch (n / 16) { case 0: // (bb & cc) | (~bb & dd) @@ -104,14 +105,14 @@ string FGHI(in int n) pure nothrow { }); } -string genExpr(uint n) pure { +string genExpr(uint n) pure nothrow { 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 { +string genTransformCode(int n) pure nothrow { return (n < 63) ? n.genExpr ~ genTransformCode(n + 1) : n.genExpr; } @@ -128,13 +129,12 @@ struct ZMD5 { 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 { + private void transform(ubyte* block) pure nothrow @nogc { uint[16] x = void; version (BigEndian) { - foreach (immutable size_t i; 0 .. 16) - x[i] = littleEndianToNative!uint( - *cast(ubyte[4]*)&block[i * 4]); + foreach (immutable i; 0 .. 16) + x[i] = littleEndianToNative!uint(*cast(ubyte[4]*)&block[i * 4]); } else { (cast(ubyte*)x.ptr)[0 .. 64] = block[0 .. 64]; } @@ -142,7 +142,7 @@ struct ZMD5 { auto pState = state.ptr; auto pBuffer = x.ptr; - asm { + asm pure nothrow @nogc { mov ESI, pState[EBP]; mov EDX, [ESI + 3 * 4]; mov ECX, [ESI + 2 * 4]; @@ -154,9 +154,9 @@ struct ZMD5 { mov EBP, pBuffer[EBP]; } - mixin("asm { " ~ coreZMD5 ~ "}"); + mixin("asm pure nothrow @nogc { " ~ coreZMD5 ~ "}"); - asm { + asm pure nothrow @nogc { pop ESI; pop EBP; add [ESI + 0 * 4], EAX; @@ -167,9 +167,9 @@ struct ZMD5 { x[] = 0; } - void update(in void[] input) pure nothrow { + void update(in void[] input) pure nothrow @nogc { auto inputLen = input.length; - uint index = (cast(uint)count >> 3) & (64 - 1); + uint index = (count >> 3) & 0b11_1111U; count += inputLen * 8; immutable uint partLen = 64 - index; @@ -187,11 +187,11 @@ struct ZMD5 { memcpy(&buffer[index], &input[i], inputLen - i); } - void finish(ref ubyte[16] digest) pure nothrow { - ubyte bits[8] = void; + void finish(ref ubyte[16] digest) pure nothrow @nogc { + ubyte[8] bits = void; bits[0 .. 8] = nativeToLittleEndian(count)[]; - immutable uint index = (cast(uint)count >> 3) & (64 - 1); + immutable uint index = (count >> 3) & 0b11_1111U; immutable uint padLen = (index < 56) ? (56 - index) : (120 - index); update(padding[0 .. padLen]); diff --git a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 index 970f0b8d22..aacdce9c14 100644 --- a/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 +++ b/Task/MD5-Implementation/Perl-6/md5-implementation.pl6 @@ -23,7 +23,7 @@ constant k = ( $_ for ^16), sub little-endian($w, $n, *@v) { (@v X+> ($w X* ^$n)) X% (2 ** $w) } -sub md5-pad(Buf $msg) +sub md5-pad(Blob $msg) { my \bits = 8 * $msg.elems; my @padded = $msg.list, 0x80, 0x00 xx (-(bits div 8 + 1 + 8) % 64); @@ -41,12 +41,12 @@ sub md5-block(@H is rw, @X) @H «⊞=» ($A, $B, $C, $D); } -sub md5(Buf $msg --> Buf) +sub md5(Blob $msg --> Blob) { my @M = md5-pad($msg); my @H = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476; md5-block(@H, @M[$_ .. $_+15]) for 0, 16 ...^ +@M; - Buf.new: little-endian(8, 4, @H); + Blob.new: little-endian(8, 4, @H); } for 'd41d8cd98f00b204e9800998ecf8427e', '', diff --git a/Task/MD5-Implementation/Python/md5-implementation.py b/Task/MD5-Implementation/Python/md5-implementation.py index eaca0811fc..0723fadcd8 100644 --- a/Task/MD5-Implementation/Python/md5-implementation.py +++ b/Task/MD5-Implementation/Python/md5-implementation.py @@ -26,7 +26,7 @@ def left_rotate(x, amount): def md5(message): message = bytearray(message) #copy our input into a mutable buffer - orig_len_in_bits = 8*len(message) + orig_len_in_bits = (8 * len(message)) & 0xffffffffffffffff message.append(0x80) while len(message)%64 != 56: message.append(0) diff --git a/Task/MD5/AutoHotkey/md5-1.ahk b/Task/MD5/AutoHotkey/md5-1.ahk index e643140d9b..a63342a8f8 100644 --- a/Task/MD5/AutoHotkey/md5-1.ahk +++ b/Task/MD5/AutoHotkey/md5-1.ahk @@ -9,4 +9,3 @@ MD5( ByRef V, L=0 ) { N := NumGet( MD5_CTX,87+A_Index,"Char"), MD5 .= SubStr(Hex,N>>4,1) . SubStr(Hex,N&15,1) Return MD5 } -} diff --git a/Task/MD5/C/md5-2.c b/Task/MD5/C/md5-2.c index c6077ae453..d14c9a824d 100644 --- a/Task/MD5/C/md5-2.c +++ b/Task/MD5/C/md5-2.c @@ -117,6 +117,10 @@ unsigned *md5( const char *msg, int mlen) h[p] += abcd[p]; os += 64; } + + if( msg2 ) + free( msg2 ); + return h; } diff --git a/Task/MD5/Maple/md5.maple b/Task/MD5/Maple/md5.maple new file mode 100644 index 0000000000..52527b932c --- /dev/null +++ b/Task/MD5/Maple/md5.maple @@ -0,0 +1,21 @@ +> with( StringTools ): +> Hash( "" ); + "d41d8cd98f00b204e9800998ecf8427e" + +> Hash( "a" ); + "0cc175b9c0f1b6a831c399e269772661" + +> Hash( "abc" ); + "900150983cd24fb0d6963f7d28e17f72" + +> Hash( "message digest" ); + "f96b697d7cb7938d525a2f31aaf161d0" + +> Hash( "abcdefghijklmnopqrstuvwxyz" ); + "c3fcd3d76192e4007dfb496cca67e13b" + +> Hash( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" ); + "d174ab98d277d9f5a5611c2c9f419d9f" + +> Hash( "12345678901234567890123456789012345678901234567890123456789012345678901234567890" ); + "57edf4a22be3c955ac49da2e2107b67a" diff --git a/Task/MD5/NewLISP/md5.newlisp b/Task/MD5/NewLISP/md5.newlisp new file mode 100644 index 0000000000..907eeb71bc --- /dev/null +++ b/Task/MD5/NewLISP/md5.newlisp @@ -0,0 +1,4 @@ +;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html +;; (import native functions from the crypto library, provided by OpenSSL) +(module "crypto.lsp") +(crypto:md5 "The quick brown fox jumped over the lazy dog's back") diff --git a/Task/MD5/REXX/md5.rexx b/Task/MD5/REXX/md5.rexx index c80ea6307c..9a0e926ea0 100644 --- a/Task/MD5/REXX/md5.rexx +++ b/Task/MD5/REXX/md5.rexx @@ -1,124 +1,119 @@ /*REXX program to test the MD5 procedure as per the test suite in the */ -/* IETF RFC (1321) ─── The MD5 Message─Digest Algorithm. April 1992. */ - -/*─────────────────────────────────────Md5 test suite (from above doc). */ -msg.1='' -msg.2='a' -msg.3='abc' -msg.4='message digest' -msg.5='abcdefghijklmnopqrstuvwxyz' -msg.6='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' -msg.7='12345678901234567890123456789012345678901234567890123456789012345678901234567890 -msg.0=7 - do m=1 for msg.0 - say ' in =' msg.m - say 'out =' MD5(msg.m) - say +/*─── IETF RFC (1321) ─── The MD5 Message-Digest Algorithm. April 1992.*/ +msg.1 = /*────────────MD5 test suite [from above doc].*/ +msg.2 = 'a' +msg.3 = 'abc' +msg.4 = 'message digest' +msg.5 = 'abcdefghijklmnopqrstuvwxyz' +msg.6 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' +msg.7 = 12345678901234567890123456789012345678901234567890123456789012345678901234567890 +msg.0 = 7 /* [↑] value doesn't need quotes*/ + do m=1 for msg.0 /*process each of the 7 messages.*/ + say ' in =' msg.m /*display the in message. */ + say 'out =' MD5(msg.m) /* " " out " */ + say /* " a blank like for a sep.*/ end /*m*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────MD5 subroutine──────────────────────*/ MD5: procedure; parse arg !; numeric digits 20 /*insure enough digits.*/ parse value '67452301'x 'efcdab89'x '98badcfe'x '10325476'x with a b c d -#=length(!) -L=#*8 // 512 - select - when L<448 then plus=448-L - when L>448 then plus=960-L - when L=448 then plus=512 - end /*select*/ - -$=!||'80'x||copies('0'x,plus%8-1)reverse(right(d2c(8*#),4,'0'x))||'00000000'x - +#=length(!) /*length of the message*/ +L=#*8 // 512; if L<448 then plus=448-L + if L>448 then plus=960-L + if L=448 then plus=512 + /* [↓] a little of this, ··· */ +$=!'80'x||copies("0"x,plus%8-1)reverse(right(d2c(8*#),4,'0'x))||"00000000"x + /* [↑] ··· and a little of that.*/ do j=0 to length($)%64-1 /*process message (lots of steps)*/ - a_=a; b_=b; c_=c; d_=d - chunk=j*64 - do k=1 for 16 /*process the message in chunks. */ - !.k=reverse(substr($,chunk+1+4*(k-1),4)) + a_=a; b_=b; c_=c; d_=d /*save original values for later.*/ + chunk=j*64 /*calculate size of the chunks. */ + do k=1 for 16 /*process the message in chunks. */ + !.k=reverse(substr($,chunk+1+4*(k-1),4)) /*magic stuff.*/ end /*k*/ - a=.part1(a,b,c,d, 0, 7,3614090360) /* 1*/ - d=.part1(d,a,b,c, 1,12,3905402710) /* 2*/ - c=.part1(c,d,a,b, 2,17, 606105819) /* 3*/ - b=.part1(b,c,d,a, 3,22,3250441966) /* 4*/ - a=.part1(a,b,c,d, 4, 7,4118548399) /* 5*/ - d=.part1(d,a,b,c, 5,12,1200080426) /* 6*/ - c=.part1(c,d,a,b, 6,17,2821735955) /* 7*/ - b=.part1(b,c,d,a, 7,22,4249261313) /* 8*/ - a=.part1(a,b,c,d, 8, 7,1770035416) /* 9*/ - d=.part1(d,a,b,c, 9,12,2336552879) /*10*/ - c=.part1(c,d,a,b,10,17,4294925233) /*11*/ - b=.part1(b,c,d,a,11,22,2304563134) /*12*/ - a=.part1(a,b,c,d,12, 7,1804603682) /*13*/ - d=.part1(d,a,b,c,13,12,4254626195) /*14*/ - c=.part1(c,d,a,b,14,17,2792965006) /*15*/ - b=.part1(b,c,d,a,15,22,1236535329) /*16*/ - a=.part2(a,b,c,d, 1, 5,4129170786) /*17*/ - d=.part2(d,a,b,c, 6, 9,3225465664) /*18*/ - c=.part2(c,d,a,b,11,14, 643717713) /*19*/ - b=.part2(b,c,d,a, 0,20,3921069994) /*20*/ - a=.part2(a,b,c,d, 5, 5,3593408605) /*21*/ - d=.part2(d,a,b,c,10, 9, 38016083) /*22*/ - c=.part2(c,d,a,b,15,14,3634488961) /*23*/ - b=.part2(b,c,d,a, 4,20,3889429448) /*24*/ - a=.part2(a,b,c,d, 9, 5, 568446438) /*25*/ - d=.part2(d,a,b,c,14, 9,3275163606) /*26*/ - c=.part2(c,d,a,b, 3,14,4107603335) /*27*/ - b=.part2(b,c,d,a, 8,20,1163531501) /*28*/ - a=.part2(a,b,c,d,13, 5,2850285829) /*29*/ - d=.part2(d,a,b,c, 2, 9,4243563512) /*30*/ - c=.part2(c,d,a,b, 7,14,1735328473) /*31*/ - b=.part2(b,c,d,a,12,20,2368359562) /*32*/ - a=.part3(a,b,c,d, 5, 4,4294588738) /*33*/ - d=.part3(d,a,b,c, 8,11,2272392833) /*34*/ - c=.part3(c,d,a,b,11,16,1839030562) /*35*/ - b=.part3(b,c,d,a,14,23,4259657740) /*36*/ - a=.part3(a,b,c,d, 1, 4,2763975236) /*37*/ - d=.part3(d,a,b,c, 4,11,1272893353) /*38*/ - c=.part3(c,d,a,b, 7,16,4139469664) /*39*/ - b=.part3(b,c,d,a,10,23,3200236656) /*40*/ - a=.part3(a,b,c,d,13, 4, 681279174) /*41*/ - d=.part3(d,a,b,c, 0,11,3936430074) /*42*/ - c=.part3(c,d,a,b, 3,16,3572445317) /*43*/ - b=.part3(b,c,d,a, 6,23, 76029189) /*44*/ - a=.part3(a,b,c,d, 9, 4,3654602809) /*45*/ - d=.part3(d,a,b,c,12,11,3873151461) /*46*/ - c=.part3(c,d,a,b,15,16, 530742520) /*47*/ - b=.part3(b,c,d,a, 2,23,3299628645) /*48*/ - a=.part4(a,b,c,d, 0, 6,4096336452) /*49*/ - d=.part4(d,a,b,c, 7,10,1126891415) /*50*/ - c=.part4(c,d,a,b,14,15,2878612391) /*51*/ - b=.part4(b,c,d,a, 5,21,4237533241) /*52*/ - a=.part4(a,b,c,d,12, 6,1700485571) /*53*/ - d=.part4(d,a,b,c, 3,10,2399980690) /*54*/ - c=.part4(c,d,a,b,10,15,4293915773) /*55*/ - b=.part4(b,c,d,a, 1,21,2240044497) /*56*/ - a=.part4(a,b,c,d, 8, 6,1873313359) /*57*/ - d=.part4(d,a,b,c,15,10,4264355552) /*58*/ - c=.part4(c,d,a,b, 6,15,2734768916) /*59*/ - b=.part4(b,c,d,a,13,21,1309151649) /*60*/ - a=.part4(a,b,c,d, 4, 6,4149444226) /*61*/ - d=.part4(d,a,b,c,11,10,3174756917) /*62*/ - c=.part4(c,d,a,b, 2,15, 718787259) /*63*/ - b=.part4(b,c,d,a, 9,21,3951481745) /*64*/ - a=.a(a_,a); b=.a(b_,b); c=.a(c_,c); d=.a(d_,d) + a = .part1( a, b, c, d, 0, 7, 3614090360) /*────1───*/ + d = .part1( d, a, b, c, 1, 12, 3905402710) /*────2───*/ + c = .part1( c, d, a, b, 2, 17, 606105819) /*────3───*/ + b = .part1( b, c, d, a, 3, 22, 3250441966) /*────4───*/ + a = .part1( a, b, c, d, 4, 7, 4118548399) /*────5───*/ + d = .part1( d, a, b, c, 5, 12, 1200080426) /*────6───*/ + c = .part1( c, d, a, b, 6, 17, 2821735955) /*────7───*/ + b = .part1( b, c, d, a, 7, 22, 4249261313) /*────8───*/ + a = .part1( a, b, c, d, 8, 7, 1770035416) /*────9───*/ + d = .part1( d, a, b, c, 9, 12, 2336552879) /*───10───*/ + c = .part1( c, d, a, b, 10, 17, 4294925233) /*───11───*/ + b = .part1( b, c, d, a, 11, 22, 2304563134) /*───12───*/ + a = .part1( a, b, c, d, 12, 7, 1804603682) /*───13───*/ + d = .part1( d, a, b, c, 13, 12, 4254626195) /*───14───*/ + c = .part1( c, d, a, b, 14, 17, 2792965006) /*───15───*/ + b = .part1( b, c, d, a, 15, 22, 1236535329) /*───16───*/ + a = .part2( a, b, c, d, 1, 5, 4129170786) /*───17───*/ + d = .part2( d, a, b, c, 6, 9, 3225465664) /*───18───*/ + c = .part2( c, d, a, b, 11, 14, 643717713) /*───19───*/ + b = .part2( b, c, d, a, 0, 20, 3921069994) /*───20───*/ + a = .part2( a, b, c, d, 5, 5, 3593408605) /*───21───*/ + d = .part2( d, a, b, c, 10, 9, 38016083) /*───22───*/ + c = .part2( c, d, a, b, 15, 14, 3634488961) /*───23───*/ + b = .part2( b, c, d, a, 4, 20, 3889429448) /*───24───*/ + a = .part2( a, b, c, d, 9, 5, 568446438) /*───25───*/ + d = .part2( d, a, b, c, 14, 9, 3275163606) /*───26───*/ + c = .part2( c, d, a, b, 3, 14, 4107603335) /*───27───*/ + b = .part2( b, c, d, a, 8, 20, 1163531501) /*───28───*/ + a = .part2( a, b, c, d, 13, 5, 2850285829) /*───29───*/ + d = .part2( d, a, b, c, 2, 9, 4243563512) /*───30───*/ + c = .part2( c, d, a, b, 7, 14, 1735328473) /*───31───*/ + b = .part2( b, c, d, a, 12, 20, 2368359562) /*───32───*/ + a = .part3( a, b, c, d, 5, 4, 4294588738) /*───33───*/ + d = .part3( d, a, b, c, 8, 11, 2272392833) /*───34───*/ + c = .part3( c, d, a, b, 11, 16, 1839030562) /*───35───*/ + b = .part3( b, c, d, a, 14, 23, 4259657740) /*───36───*/ + a = .part3( a, b, c, d, 1, 4, 2763975236) /*───37───*/ + d = .part3( d, a, b, c, 4, 11, 1272893353) /*───38───*/ + c = .part3( c, d, a, b, 7, 16, 4139469664) /*───39───*/ + b = .part3( b, c, d, a, 10, 23, 3200236656) /*───40───*/ + a = .part3( a, b, c, d, 13, 4, 681279174) /*───41───*/ + d = .part3( d, a, b, c, 0, 11, 3936430074) /*───42───*/ + c = .part3( c, d, a, b, 3, 16, 3572445317) /*───43───*/ + b = .part3( b, c, d, a, 6, 23, 76029189) /*───44───*/ + a = .part3( a, b, c, d, 9, 4, 3654602809) /*───45───*/ + d = .part3( d, a, b, c, 12, 11, 3873151461) /*───46───*/ + c = .part3( c, d, a, b, 15, 16, 530742520) /*───47───*/ + b = .part3( b, c, d, a, 2, 23, 3299628645) /*───48───*/ + a = .part4( a, b, c, d, 0, 6, 4096336452) /*───49───*/ + d = .part4( d, a, b, c, 7, 10, 1126891415) /*───50───*/ + c = .part4( c, d, a, b, 14, 15, 2878612391) /*───51───*/ + b = .part4( b, c, d, a, 5, 21, 4237533241) /*───52───*/ + a = .part4( a, b, c, d, 12, 6, 1700485571) /*───53───*/ + d = .part4( d, a, b, c, 3, 10, 2399980690) /*───54───*/ + c = .part4( c, d, a, b, 10, 15, 4293915773) /*───55───*/ + b = .part4( b, c, d, a, 1, 21, 2240044497) /*───56───*/ + a = .part4( a, b, c, d, 8, 6, 1873313359) /*───57───*/ + d = .part4( d, a, b, c, 15, 10, 4264355552) /*───58───*/ + c = .part4( c, d, a, b, 6, 15, 2734768916) /*───59───*/ + b = .part4( b, c, d, a, 13, 21, 1309151649) /*───60───*/ + a = .part4( a, b, c, d, 4, 6, 4149444226) /*───61───*/ + d = .part4( d, a, b, c, 11, 10, 3174756917) /*───62───*/ + c = .part4( c, d, a, b, 2, 15, 718787259) /*───63───*/ + b = .part4( b, c, d, a, 9, 21, 3951481745) /*───64───*/ + a=.a(a_,a); b=.a(b_,b); c=.a(c_,c); d=.a(d_,d) end /*j*/ return c2x(reverse(a))c2x(reverse(b))c2x(reverse(c))c2x(reverse(d)) -/*─────────────────────────────────────subroutines──────────────────────*/ -.part1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 - return .a(.lR(right(d2c(_+c2d(w)+c2d(.f(x,y,z))+c2d(!.n)),4,'0'x),m),x) -.part2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 - return .a(.lR(right(d2c(_+c2d(w)+c2d(.g(x,y,z))+c2d(!.n)),4,'0'x),m),x) -.part3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 - return .a(.lR(right(d2c(_+c2d(w)+c2d(.h(x,y,z))+c2d(!.n)),4,'0'x),m),x) -.part4: procedure expose !.; parse arg w,x,y,z,n,m; n=n+1 - return .a(.lR(right(d2c(c2d(w)+c2d(.i(x,y,z))+c2d(!.n)+arg(7)),4,'0'x),m),x) -.h: procedure; parse arg x,y,z; return bitxor(bitxor(x,y),z) -.i: return bitxor(arg(2),bitor(arg(1),bitxor(arg(3),'ffffffff'x))) -.a: return right(d2c(c2d(arg(1))+c2d(arg(2))),4,'0'x) +/*─────────────────────────────────────subroutines────────────────────────────────*/ +.a: return right(d2c(c2d(arg(1)) + c2d(arg(2))), 4, '0'x) +.h: procedure; parse arg x,y,z; return bitxor(bitxor(x, y), z) +.i: return bitxor(arg(2), bitor(arg(1), bitxor(arg(3), 'ffffffff'x))) .f: procedure; parse arg x,y,z - return bitor(bitand(x,y),bitand(bitxor(x,'ffffffff'x),z)) + return bitor(bitand(x,y), bitand(bitxor(x, 'ffffffff'x), z)) .g: procedure; parse arg x,y,z - return bitor(bitand(x,z),bitand(y,bitxor(z,'ffffffff'x))) -.lR: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/ - ?=x2b(c2x(_)); return x2c(b2x(right(?||left(?,#),length(?)))) + return bitor(bitand(x,z), bitand(y, bitxor(z, 'ffffffff'x))) +.Lr: procedure; parse arg _,#; if #==0 then return _ /*left rotate.*/ + ?=x2b(c2x(_)); return x2c(b2x(right(? || left(?, #), length(?)))) +.part1: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 + return .a(.Lr(right(d2c(_+c2d(w)+c2d(.f(x,y,z))+c2d(!.n)),4,'0'x),m),x) +.part2: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 + return .a(.Lr(right(d2c(_+c2d(w)+c2d(.g(x,y,z))+c2d(!.n)),4,'0'x),m),x) +.part3: procedure expose !.; parse arg w,x,y,z,n,m,_; n=n+1 + return .a(.Lr(right(d2c(_+c2d(w)+c2d(.h(x,y,z))+c2d(!.n)),4,'0'x),m),x) +.part4: procedure expose !.; parse arg w,x,y,z,n,m; n=n+1 + return .a(.Lr(right(d2c(c2d(w)+c2d(.i(x,y,z))+c2d(!.n)+arg(7)),4,'0'x),m),x) diff --git a/Task/MD5/Scala/md5.scala b/Task/MD5/Scala/md5.scala index 9b5b41acbd..29a5fa84ba 100644 --- a/Task/MD5/Scala/md5.scala +++ b/Task/MD5/Scala/md5.scala @@ -1,7 +1,21 @@ -def MD5( s:String ) : String = { - // Besides "MD5", "SHA-256", and other hashes are available - val m = java.security.MessageDigest.getInstance("MD5").digest(s.getBytes("UTF-8")); - m map {c => (c & 0xff) toHexString} mkString -} +object RosettaMD5 extends App { -MD5("The quick brown fox jumped over the lazy dog's back") + def MD5(s: String): String = { + // Besides "MD5", "SHA-256", and other hashes are available + val m = java.security.MessageDigest.getInstance("MD5").digest(s.getBytes("UTF-8")) + m.map("%02x".format(_)).mkString + } + + assert("d41d8cd98f00b204e9800998ecf8427e" == MD5("")) + assert("0cc175b9c0f1b6a831c399e269772661" == MD5("a")) + assert("900150983cd24fb0d6963f7d28e17f72" == MD5("abc")) + assert("f96b697d7cb7938d525a2f31aaf161d0" == MD5("message digest")) + assert("c3fcd3d76192e4007dfb496cca67e13b" == MD5("abcdefghijklmnopqrstuvwxyz")) + assert("e38ca1d920c4b8b8d3946b2c72f01680" == MD5("The quick brown fox jumped over the lazy dog's back")) + assert("d174ab98d277d9f5a5611c2c9f419d9f" == + MD5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")) + assert("57edf4a22be3c955ac49da2e2107b67a" == + MD5("12345678901234567890123456789012345678901234567890123456789012345678901234567890")) + import scala.compat.Platform.currentTime + println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") +} diff --git a/Task/Mad-Libs/00DESCRIPTION b/Task/Mad-Libs/00DESCRIPTION index 57ddca2c49..e09cde5dbf 100644 --- a/Task/Mad-Libs/00DESCRIPTION +++ b/Task/Mad-Libs/00DESCRIPTION @@ -1,6 +1,8 @@ [[wp:Mad Libs|Mad Libs]] is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results. -Write a program to create a Mad Libs like story. The program should read a multiline story from the input. The story will be terminated with a blank line. Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. +Write a program to create a Mad Libs like story. +The program should read a multiline story from the input. The story will be terminated with a blank line. +Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story. The input should be in the form:
diff --git a/Task/Mad-Libs/ALGOL-68/mad-libs.alg b/Task/Mad-Libs/ALGOL-68/mad-libs.alg
new file mode 100644
index 0000000000..4731d9f18e
--- /dev/null
+++ b/Task/Mad-Libs/ALGOL-68/mad-libs.alg
@@ -0,0 +1,128 @@
+# Mad Libs style story generation                                        #
+
+# gets the story template from the file f. The template terminates with  #
+# a blank line                                                           #
+# The user is then promoted for the replacements for the  markers  #
+# and the story is printed with the substitutions made                   #
+PROC story = ( REF FILE f )VOID:
+BEGIN
+
+    # a linked list of strings, used to hold the story template          #
+    MODE STRINGLIST = STRUCT( STRING text, REF STRINGLIST next );
+
+    # a linked list of pairs of strings, used to hold the replacements   #
+    MODE REPLACEMENTLIST = STRUCT( STRING word
+                                 , STRING replacement
+                                 , REF REPLACEMENTLIST next
+                                 );
+
+    # NIL reference for marking the end of a STRINGLIST                  #
+    REF STRINGLIST      nil stringlist      = NIL;
+
+    # NIL reference for marking the end of a REPLACEMENTLIST             #
+    REF REPLACEMENTLIST nil replacementlist = NIL;
+
+
+    # returns "text" with trailing spaces removed                        #
+    OP RTRIM = ( STRING text )STRING:
+    BEGIN
+        INT trim pos := UPB text;
+        FOR text pos FROM UPB text BY -1 TO LWB text WHILE text[ text pos ] = " "
+        DO
+            trim pos := text pos - 1
+        OD;
+
+        text[ LWB text : trim pos ]
+    END; # RTRIM #
+
+    # looks for word in the dictionary. If it is found, replacement is   #
+    # set to its replacement and TRUE is returned. If word not present,  #
+    # FALSE is returned - uses recursion                                 #
+    PROC find replacement = ( STRING word
+                            , REF STRING replacement
+                            , REF REPLACEMENTLIST dictionary
+                            )BOOL:
+        IF   dictionary IS nil replacementlist
+        THEN
+            FALSE
+        ELIF word OF dictionary = word
+        THEN
+            replacement := replacement OF dictionary;
+            TRUE
+        ELSE
+            find replacement( word, replacement, next OF dictionary )
+        FI; # find replacement #
+
+
+    # read the story template                                            #
+
+    # the result has a dummy element so "next OF next" is always valid   #
+    REF STRINGLIST     story := HEAP STRINGLIST := ( "dummy", nil stringlist );
+    REF REF STRINGLIST next  := story;
+
+    # read the story template, terminates with a blank line              #
+
+    WHILE
+        STRING text;
+        get( f, ( text, newline ) );
+        text := RTRIM text;
+        text /= ""
+    DO
+        # add the line to the end of the list #
+        next := ( next OF next ) := HEAP STRINGLIST := ( text, nil stringlist )
+    OD;
+
+    # find the  markers in the story and replace them with the     #
+    # user's chosen text - we ignore the dummy element at the start      #
+
+    REF REPLACEMENTLIST dictionary := nil replacementlist;
+    REF STRINGLIST      line       := story;
+
+    WHILE line := next OF line;
+          line ISNT nil stringlist
+    DO
+        # have a line of text - replace all the  markers in it     #
+        STRING word, replacement;
+        INT start pos, end pos;
+        WHILE char in string( "<", start pos, text OF line )
+          AND char in string( ">", end pos,   text OF line )
+        DO
+            # have a marker, get it from the line                        #
+            word := ( text OF line )[ start pos : end pos ];
+            # get its replacement                                        #
+            IF NOT find replacement( word, replacement, dictionary )
+            THEN
+                # we don't already have a replacement for word           #
+                # get one from the user and add it to the dictionary     #
+                print( ( "What should replace ", word, "? " ) );
+                read( ( replacement, newline ) );
+                dictionary := HEAP REPLACEMENTLIST := ( word, replacement, dictionary )
+            FI;
+            # replace  with the replacement                        #
+            text OF line := ( text OF line )[ : start pos - 1 ]
+                          + replacement
+                          + ( text OF line )[ end pos + 1 : ]
+        OD
+    OD;
+
+    # print the story, ignoring the dummy element at the start           #
+
+    line := story;
+
+    WHILE line := next OF line;
+          line ISNT nil stringlist
+    DO
+        print( ( text OF line, newline ) )
+    OD
+
+END; # story #
+
+main:(
+
+    # we read the template from stand in (the keyboard unless it's been  #
+    # redirected) we could prompt the user for a template file name,     #
+    # open it and read that instead...                                   #
+    print( ( "Please Enter the story template terminated by a blank line", newline ) );
+    story( stand in )
+
+)
diff --git a/Task/Mad-Libs/C-sharp/mad-libs.cs b/Task/Mad-Libs/C-sharp/mad-libs.cs
new file mode 100644
index 0000000000..1054694ac7
--- /dev/null
+++ b/Task/Mad-Libs/C-sharp/mad-libs.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using System.Threading.Tasks;
+namespace madLibs {
+    class Program {
+        static void Main(string[] args) {
+            string name, sex, addThis, thing;
+            bool isMale = false;
+            Console.Write("Enter a name: ");
+            name = Console.ReadLine();
+            while(isMale == false) {
+                Console.Write("Is that a male or female name? [m/f] ");
+                sex = Console.ReadLine().ToLower().ToCharArray()[0].ToString();
+                if(sex == "m") { isMale = true; } else if(sex == "f") { break; }
+            }
+            if (isMale){ addThis = "He "; }else{ addThis = "She "; }
+            Console.Write("Enter a thing: ");
+            thing = Console.ReadLine();
+            Console.WriteLine(Environment.NewLine + String.Format(("{0} went for a walk in the park. " + addThis +
+                "found a {1}. {0} decided to take it home."), name, thing));
+            Console.ReadKey();
+        }
+    }
+}
diff --git a/Task/Mad-Libs/Haskell/mad-libs.hs b/Task/Mad-Libs/Haskell/mad-libs.hs
new file mode 100644
index 0000000000..61e1f34f8d
--- /dev/null
+++ b/Task/Mad-Libs/Haskell/mad-libs.hs
@@ -0,0 +1,49 @@
+import System.IO
+import System.Environment
+import qualified Data.Map as M
+
+getLines :: IO [String]
+getLines = getLines' [] >>= return . reverse
+    where
+      getLines' xs = do
+        line <- getLine
+        case line of
+          [] -> return xs
+          _  -> getLines' $ line:xs
+
+prompt :: String -> IO String
+prompt p = putStr p >> hFlush stdout >> getLine
+
+getKeyword :: String -> Maybe String
+getKeyword ('<':xs) = getKeyword' xs []
+    where
+      getKeyword' []        _   = Nothing
+      getKeyword' (x:'>':_) acc = Just $ '<' : (reverse $ '>':x:acc)
+      getKeyword' (x:xs)    acc = getKeyword' xs $ x:acc
+getKeyword _        = Nothing
+
+parseText :: String -> M.Map String String -> IO String
+parseText []          _        = return []
+parseText line@(l:lx) keywords = do
+  case getKeyword line of
+    Nothing      -> parseText lx keywords >>= return . (l:)
+    Just keyword -> do
+      let rest = drop (length keyword) line
+      case M.lookup keyword keywords of
+        Nothing        -> do
+                         newword <- prompt $ "Enter a word for " ++ keyword ++ ": "
+                         rest'   <- parseText rest $ M.insert keyword newword keywords
+                         return $ newword ++ rest'
+        Just knownword -> do
+                         rest' <- parseText rest keywords
+                         return $ knownword ++ rest'
+
+main :: IO ()
+main = do
+  args    <- getArgs
+  nlines  <- case args of
+               []    -> getLines >>= return . unlines
+               arg:_ -> readFile arg
+  nlines' <- parseText nlines M.empty
+  putStrLn ""
+  putStrLn nlines'
diff --git a/Task/Mad-Libs/Mathematica/mad-libs.math b/Task/Mad-Libs/Mathematica/mad-libs.math
new file mode 100644
index 0000000000..99510db2e4
--- /dev/null
+++ b/Task/Mad-Libs/Mathematica/mad-libs.math
@@ -0,0 +1,14 @@
+filename = InputString["Enter the filename of the story template: "];
+text = Import[filename];
+listofblanks = StringCases[text, RegularExpression["<[^>]+>"]] // Union;
+listofanswers = {};
+Do[
+ answer = InputString["Enter a/an: " <> listofblanks[[i]]];
+ AppendTo[listofanswers, answer];
+ , {i, 1, Length[listofblanks]}
+ ]
+Do[
+ text = StringReplace[text, listofblanks[[i]] -> listofanswers[[i]]]
+ , {i, 1, Length[listofblanks]}
+ ]
+text
diff --git a/Task/Mad-Libs/REBOL/mad-libs.rebol b/Task/Mad-Libs/REBOL/mad-libs.rebol
new file mode 100644
index 0000000000..dfcc93d43a
--- /dev/null
+++ b/Task/Mad-Libs/REBOL/mad-libs.rebol
@@ -0,0 +1,7 @@
+t: { went for a walk in the park.  found a .  decided to take it home.}
+view layout [a: area wrap t  btn "Done" [x: a/text unview]]
+w: copy []
+parse x [any [to "<" copy brackets thru ">" (append w brackets)] to end]
+w: unique w
+foreach i w [replace/all x i ask join i ": "]
+alert x
diff --git a/Task/Mad-Libs/REXX/mad-libs.rexx b/Task/Mad-Libs/REXX/mad-libs.rexx
index a4ba638219..9cb3573d63 100644
--- a/Task/Mad-Libs/REXX/mad-libs.rexx
+++ b/Task/Mad-Libs/REXX/mad-libs.rexx
@@ -1,23 +1,23 @@
-/*REXX program to prompt user for template substitutions within a story.*/
-@.=;   !.=0;   #=0;   @=               /*assign some defaults.          */
+/*REXX program prompts user for a template substitutions within a story.*/
+@.=;   !.=0;   #=0;    @=              /*assign some defaults.          */
 parse arg iFID .                       /*allow use to specify input file*/
-if iFID==''  then iFID="MAD_LIBS.TXT"  /*Not specified? Then use default*/
+if iFID==''  then iFID="MAD_LIBS.TXT"  /*Not specified?   Use a default.*/
 
-   do recs=1  while lines(iFID)\==0    /*read the input file 'til done. */
-   @.recs=linein(iFID);  @=@ @.recs    /*read a record, append it to  @ */
+   do recs=1  while  lines(iFID)\==0   /*read the input file 'til done. */
+   @.recs=linein(iFID);   @=@ @.recs   /*read a record, append it to  @ */
    if @.recs=''  then leave            /*Read a blank line?  We're done.*/
    end  /*recs*/
 
 recs=recs-1                            /*adjust for E─O─F or blank line.*/
 
-     do forever                        /*look for templates in the text.*/
+     do  forever                       /*look for templates in the text.*/
      parse var  @   '<'   ?   '>'   @  /*scan for  <ααα>  stuff in text.*/
      if ?=''   then leave              /*if no   ααα,  then we're done. */
      if !.?    then iterate            /*already asked?   Keep scanning.*/
      !.?=1                             /*mark this   ααα   as  "found". */
-            do forever                 /*prompt user for a replacement. */
+            do  forever                /*prompt user for a replacement. */
             say '─────────── please enter a word or phrase to replace: ' ?
-            parse pull ans;    if ans\=''  then leave
+            parse pull ans;         if ans\=''  then leave
             end   /*forever*/
      #=#+1                             /*bump the template counter.     */
      old.# = '<'?">";    new.# = ans   /*assign "old" name & "new" name.*/
diff --git a/Task/Mad-Libs/Ruby/mad-libs.rb b/Task/Mad-Libs/Ruby/mad-libs.rb
index f4f809adfd..580aac77de 100644
--- a/Task/Mad-Libs/Ruby/mad-libs.rb
+++ b/Task/Mad-Libs/Ruby/mad-libs.rb
@@ -1,13 +1,13 @@
 puts "Enter a story, terminated by an empty line:"
 story = ""
-until (line = STDIN.gets).chomp.empty?
+until (line = gets).chomp.empty?
   story << line
 end
 
 story.scan(/(?<=[<]).+?(?=[>])/).uniq.each do |var|
   print "Enter a value for '#{var}': "
-  story.gsub!(/<#{var}>/, STDIN.gets.chomp)
+  story.gsub!(/<#{var}>/, gets.chomp)
 end
 
-puts ""
+puts
 puts story
diff --git a/Task/Mad-Libs/Scala/mad-libs.scala b/Task/Mad-Libs/Scala/mad-libs.scala
new file mode 100644
index 0000000000..7ea1ce716a
--- /dev/null
+++ b/Task/Mad-Libs/Scala/mad-libs.scala
@@ -0,0 +1,14 @@
+object MadLibs extends App{
+  val input = " went for a walk in the park. \nfound a .  decided to take it home."
+  println(input)
+  println
+
+  val todo = "(<[^>]+>)".r
+  val replacements = todo.findAllIn(input).toSet.map{found: String =>
+    found -> readLine(s"Enter a $found ")
+  }.toMap
+
+  val output = todo.replaceAllIn(input, found => replacements(found.matched))
+  println
+  println(output)
+}
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 7fa07fcdd3..d9011d97ba 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,13 +1,15 @@
+import std.stdio, std.range, std.algorithm;
+
 /// Rotate uint left.
-uint rol(in uint x, in uint nBits) @safe pure nothrow {
+uint rol(in uint x, in uint nBits) @safe pure nothrow @nogc {
     return (x << nBits) | (x >> (32 - nBits));
 }
 
 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)
+private bool _validateSBox(in SBox data) @safe pure nothrow @nogc {
+    foreach (const ref row; data)
         foreach (ub; row)
             if (ub >= 16) // Verify it's a nibble.
                 return false;
@@ -16,13 +18,9 @@ private bool _validateSBox(in SBox data) @safe pure nothrow {
 
 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;
+        return k87.length.iota
+               .map!(i=> (s[0][k][i >> 4] << 4) | s[0][k - 1][i & 0xF])
+               .array;
     }
 
     private uint[2] buffer;
@@ -32,7 +30,7 @@ struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {
                                         k21 = generate!1;
 
     // Endianess problems?
-    private static uint f(in uint x) pure nothrow {
+    private static uint f(in uint x) pure nothrow @nogc @safe {
         immutable uint y = (k87[(x >> 24) & 0xFF] << 24) |
                            (k65[(x >> 16) & 0xFF] << 16) |
                            (k43[(x >>  8) & 0xFF] <<  8) |
@@ -41,15 +39,14 @@ struct GOST(s...) if (s.length == 1 && s[0]._validateSBox) {
     }
 
     // This performs only a step of the encoding.
-    public void mainStep(in uint[2] input, in uint key) pure nothrow {
+    public void mainStep(in uint[2] input, in uint key)
+    pure nothrow @nogc @safe {
         buffer[0] = f(key + input[0]) ^ input[1];
         buffer[1] = input[0];
     }
 }
 
 void main() {
-    import std.stdio;
-
     // S-boxes used by the Central Bank of Russian Federation:
     // http://en.wikipedia.org/wiki/GOST_28147-89
     // (This is a matrix of nibbles).
diff --git a/Task/Main-step-of-GOST-28147-89/Go/main-step-of-gost-28147-89.go b/Task/Main-step-of-GOST-28147-89/Go/main-step-of-gost-28147-89.go
index 871f502728..3ae4db627c 100644
--- a/Task/Main-step-of-GOST-28147-89/Go/main-step-of-gost-28147-89.go
+++ b/Task/Main-step-of-GOST-28147-89/Go/main-step-of-gost-28147-89.go
@@ -45,6 +45,7 @@ var cbrf = sBox{
 
 func u32(b []byte) uint32 {
     return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
+}
 
 func b4(u uint32, b []byte) {
     b[0] = byte(u)
diff --git a/Task/Main-step-of-GOST-28147-89/PicoLisp/main-step-of-gost-28147-89.l b/Task/Main-step-of-GOST-28147-89/PicoLisp/main-step-of-gost-28147-89.l
new file mode 100644
index 0000000000..61b8cf8c38
--- /dev/null
+++ b/Task/Main-step-of-GOST-28147-89/PicoLisp/main-step-of-gost-28147-89.l
@@ -0,0 +1,62 @@
+(setq K1 (13  2  8  4  6 15 11  1 10  9  3 14  5  0 12  7))
+(setq K2 ( 4 11  2 14 15  0  8 13  3 12  9  7  5 10  6  1))
+(setq K3 (12  1 10 15  9  2  6  8  0 13  3  4 14  7  5 11))
+(setq K4 ( 2 12  4  1  7 10 11  6  8  5  3 15 13  0 14  9))
+(setq K5 ( 7 13 14  3  0  6  9 10  1  2  8  5 11 12  4 15))
+(setq K6 (10  0  9 14  6  3 15  5  1 13 12  7 11  4  2  8))
+(setq K7 (15  1  8 14  6 11  3  4  9  7  2 13 12  0  5 10))
+(setq K8 (14  4 13  1  2 15 11  8  3 10  6 12  5  9  0  7))
+
+(setq K21
+   (mapcar
+      '((N)
+         (|
+            (>> -4 (get K2 (inc (>> 4 N))))
+            (get K1 (inc (& N 15))) ) )
+      (range 0 255) ) )
+
+(setq K43
+   (mapcar
+      '((N)
+         (|
+            (>> -4 (get K4 (inc (>> 4 N))))
+            (get K3 (inc (& N 15))) ) )
+      (range 0 255) ) )
+
+(setq K65
+   (mapcar
+      '((N)
+         (|
+            (>> -4 (get K6 (inc (>> 4 N))))
+            (get K5 (inc (& N 15))) ) )
+      (range 0 255) ) )
+
+(setq K87
+   (mapcar
+      '((N)
+         (|
+            (>> -4 (get K8 (inc (>> 4 N))))
+            (get K7 (inc (& N 15))) ) )
+      (range 0 255) ) )
+
+(de leftRotate (X C)
+   (|
+      (& `(hex "FFFFFFFF") (>> (- C) X))
+      (>> (- 32 C) X) ) )
+
+(de f (X)
+   (leftRotate
+      (apply
+         |
+         (mapcar
+            '((Lst N)
+               (>>
+                  N
+                  (get
+                     (val Lst)
+                     (inc (& 255 (>> (abs N) X))) ) ) )
+            '(K87 K65 K43 K21)
+            (-24 -16 -8 0) ) )
+      11 ) )
+
+(bye)
diff --git a/Task/Man-or-boy-test/00DESCRIPTION b/Task/Man-or-boy-test/00DESCRIPTION
index 3d1c40c4ae..9029ac7ca5 100644
--- a/Task/Man-or-boy-test/00DESCRIPTION
+++ b/Task/Man-or-boy-test/00DESCRIPTION
@@ -1,12 +1,9 @@
-{{Template:clarify task}}
-[[Category:Recursion]]
-
 '''Background''': The '''man or boy test''' was proposed by computer scientist [[wp:Donald_Knuth|Donald Knuth]] as a means of evaluating implementations of the [[:Category:ALGOL 60|ALGOL 60]] programming language. The aim of the test was to distinguish compilers that correctly implemented "recursion and non-local references" from those that did not.
 
 
I have written the following simple routine, which may separate the 'man-compilers' from the 'boy-compilers'
Donald Knuth
-'''Task''': Imitate Knuth's example in Algol 60 in another language, as far as possible. +'''Task''': Imitate [[#ALGOL 60 - Knuth's example|Knuth's example in Algol 60]] in another language, as far as possible. '''Details''': Local variables of routines are often kept in [http://c2.com/cgi/wiki?ActivationRecord ''activation records''] (also ''call frames''). In many languages, these records are kept on a [[System stack|call stack]]. In Algol (and e.g. in [[Smalltalk]]), they are allocated on a [[heap]] instead. Hence it is possible to pass references to routines that still can use and update variables from their call environment, even if the routine where those variables are declared already returned. This difference in implementations is sometimes called the [[wp:Funarg_problem|Funarg Problem]]. @@ -18,11 +15,11 @@ in completely different parts of the call tree. Knuth used this to test the correctness of the compiler, but one can of course also use it to test that other languages can emulate the Algol behavior correctly. If the handling of activation records is correct, the computed value will be −67. -'''Performance and Memory''': Man or Boy is intense and can be pushed to challenge any machine. Memory not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. +'''Performance and Memory''': Man or Boy is intense and can be pushed to challenge any machine. Memory (both stack and heap) not CPU time is the constraining resource as the recursion creates a proliferation activation records which will quickly exhaust memory and present itself through a stack error. Each language may have ways of adjusting the amount of memory or increasing the recursion depth. Optionally, show how you would make such adjustments. -The table below shows the result, call depths, and total calls for a range of k: -{| class="wikitable" -! k +The table below shows the result, call depths, and total calls for a range of ''k'': +{| class="wikitable" style="font-size: 85%" +! ''k'' ! 0 ! 1 ! 2 @@ -55,7 +52,7 @@ The table below shows the result, call depths, and total calls for a range of k: ! 29 ! 30 |- -! A +! ''A'' |align="right"| 1 |align="right"| 0 |align="right"| -2 @@ -88,7 +85,7 @@ The table below shows the result, call depths, and total calls for a range of k: |align="right"| -230,560,902 |align="right"| -512,016,658 |- -! A called +! ''A'' called |align="right"| 1 |align="right"| 2 |align="right"| 3 @@ -121,7 +118,7 @@ The table below shows the result, call depths, and total calls for a range of k: |  |  |- -! A depth +! ''A'' depth |align="right"| 1 |align="right"| 2 |align="right"| 3 @@ -154,7 +151,7 @@ The table below shows the result, call depths, and total calls for a range of k: |  |  |- -! B called +! ''B'' called |align="right"| 0 |align="right"| 1 |align="right"| 2 @@ -187,7 +184,7 @@ The table below shows the result, call depths, and total calls for a range of k: |  |  |- -! B depth +! ''B'' depth |align="right"| 0 |align="right"| 1 |align="right"| 2 diff --git a/Task/Man-or-boy-test/00META.yaml b/Task/Man-or-boy-test/00META.yaml index f407ff9d83..0d2b469697 100644 --- a/Task/Man-or-boy-test/00META.yaml +++ b/Task/Man-or-boy-test/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Recursion note: Classic CS problems and programs 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 21ce4a6b40..9d1b3f488e 100644 --- a/Task/Man-or-boy-test/Aime/man-or-boy-test.aime +++ b/Task/Man-or-boy-test/Aime/man-or-boy-test.aime @@ -1,13 +1,13 @@ integer F(list l) { - return l_q_integer(l, 1); + return l[1]; } integer eval(list l) { - return call(l_query(l, 0), l); + return call(l[0], l); } integer A(list); @@ -17,12 +17,11 @@ B(list l) { integer x; - x = l_q_integer(l, 1); + x = l[1]; x -= 1; l_r_integer(l, 1, x); - return A(l_assemble(B, x, l, l_query(l, -5), l_query(l, -4), - l_query(l, -3), l_query(l, -2))); + return A(l_assemble(B, x, l, l[-5], l[-4], l[-3], l[-2])); } integer @@ -31,9 +30,9 @@ A(list l) integer x; if (l_q_integer(l, 1) < 1) { - x = eval(l_q_list(l, -2)) + eval(l_q_list(l, -1)); + x = eval(l[-2]) + eval(l[-1]); } else { - x = B(l); + x = B(l); } return x; diff --git a/Task/Man-or-boy-test/D/man-or-boy-test-2.d b/Task/Man-or-boy-test/D/man-or-boy-test-2.d index 515e4c3cc5..215d5101a9 100644 --- a/Task/Man-or-boy-test/D/man-or-boy-test-2.d +++ b/Task/Man-or-boy-test/D/man-or-boy-test-2.d @@ -1,14 +1,14 @@ -import std.stdio; - -int A(int k, int delegate()[] x ...) { - int b() { +int A(int k, int delegate() nothrow @safe[] x...) nothrow @safe { + int b() nothrow @safe { k--; return A(k, &b, x[0], x[1], x[2], x[3]); } - return (k <= 0) ? x[3]() + x[4]() : b(); + return (k > 0) ? b() : x[3]() + x[4](); } void main() { - writeln(A(10, 1, -1, -1, 1, 0)); + import std.stdio; + + A(10, 1, -1, -1, 1, 0).writeln; } diff --git a/Task/Man-or-boy-test/D/man-or-boy-test-3.d b/Task/Man-or-boy-test/D/man-or-boy-test-3.d index 600e628c70..cbd41b1969 100644 --- a/Task/Man-or-boy-test/D/man-or-boy-test-3.d +++ b/Task/Man-or-boy-test/D/man-or-boy-test-3.d @@ -1,7 +1,5 @@ -import std.stdio; - -int delegate() mb(T)(T mob) { // embeding function - int b() { +auto mb(T)(T mob) nothrow @safe { // Embeding function. + int b() nothrow @safe @nogc { static if (is(T == int)) return mob; else @@ -11,11 +9,11 @@ int delegate() mb(T)(T mob) { // embeding function return &b; } -int A(T)(int k, T x1, T x2, T x3, T x4, T x5) { +int A(T)(int k, T x1, T x2, T x3, T x4, T x5) nothrow @safe { static if (is(T == int)) { return A(k, mb(x1), mb(x2), mb(x3), mb(x4), mb(x5)); } else { - int b() { + int b() nothrow @safe { k--; return A(k, &b, x1, x2, x3, x4); } @@ -24,5 +22,7 @@ int A(T)(int k, T x1, T x2, T x3, T x4, T x5) { } void main() { - writeln(A(10, 1, -1, -1, 1, 0)); + import std.stdio; + + A(10, 1, -1, -1, 1, 0).writeln; } diff --git a/Task/Man-or-boy-test/Dylan/man-or-boy-test.dylan b/Task/Man-or-boy-test/Dylan/man-or-boy-test.dylan new file mode 100644 index 0000000000..33d85a9745 --- /dev/null +++ b/Task/Man-or-boy-test/Dylan/man-or-boy-test.dylan @@ -0,0 +1,27 @@ +define method a + (k :: , x1 :: , x2 :: , x3 :: , + x4 :: , x5 :: ) + => (i :: ) + + local b() => (i :: ) + k := k - 1; + a(k, b, x1, x2, x3, x4) + end; + + if (k <= 0) x4() + x5() else b() end if + +end method a; + +define method man-or-boy + (x :: ) + => (i :: ) + + a(x, method() 1 end, + method() -1 end, + method() -1 end, + method() 1 end, + method() 0 end) + +end method man-or-boy; + +format-out("%d\n", man-or-boy(10)) diff --git a/Task/Man-or-boy-test/Io/man-or-boy-test.io b/Task/Man-or-boy-test/Io/man-or-boy-test.io new file mode 100644 index 0000000000..6a53befcd7 --- /dev/null +++ b/Task/Man-or-boy-test/Io/man-or-boy-test.io @@ -0,0 +1,14 @@ +Range + +a := method(k, xs, + b := block( + k = k -1 + a(k, list(b, xs slice(0,4)) flatten)) + if(k <= 0, + (xs at(3) call) + (xs at(4) call), + b call)) + +f := method(x, block(x)) +1 to(500) foreach(k, + (k .. " ") print + a(k, list(1, -1, -1, 1, 0) map (x, f(x))) println) diff --git a/Task/Man-or-boy-test/Java/man-or-boy-test-1.java b/Task/Man-or-boy-test/Java/man-or-boy-test-1.java new file mode 100644 index 0000000000..d2d4ce234c --- /dev/null +++ b/Task/Man-or-boy-test/Java/man-or-boy-test-1.java @@ -0,0 +1,21 @@ +import java.util.function.DoubleSupplier; + +public class ManOrBoy { + + static double A(int k, DoubleSupplier x1, DoubleSupplier x2, + DoubleSupplier x3, DoubleSupplier x4, DoubleSupplier x5) { + + DoubleSupplier B = new DoubleSupplier() { + int m = k; + public double getAsDouble() { + return A(--m, this, x1, x2, x3, x4); + } + }; + + return k <= 0 ? x4.getAsDouble() + x5.getAsDouble() : B.getAsDouble(); + } + + public static void main(String[] args) { + System.out.println(A(10, () -> 1.0, () -> -1.0, () -> -1.0, () -> 1.0, () -> 0.0)); + } +} diff --git a/Task/Man-or-boy-test/Java/man-or-boy-test.java b/Task/Man-or-boy-test/Java/man-or-boy-test-2.java similarity index 100% rename from Task/Man-or-boy-test/Java/man-or-boy-test.java rename to Task/Man-or-boy-test/Java/man-or-boy-test-2.java diff --git a/Task/Man-or-boy-test/Pascal/man-or-boy-test.pascal b/Task/Man-or-boy-test/Pascal/man-or-boy-test.pascal new file mode 100644 index 0000000000..1b6063c56e --- /dev/null +++ b/Task/Man-or-boy-test/Pascal/man-or-boy-test.pascal @@ -0,0 +1,25 @@ +program manorboy(output); + +function zero: integer; begin zero := 0 end; +function one: integer; begin one := 1 end; +function negone: integer; begin negone := -1 end; + +function A( + k: integer; + function x1: integer; + function x2: integer; + function x3: integer; + function x4: integer; + function x5: integer +): integer; + + function B: integer; + begin k := k - 1; + B := A(k, B, x1, x2, x3, x4) + end; + +begin if k <= 0 then A := x4 + x5 else A := B +end; + +begin writeln(A(10, one, negone, negone, one, zero)) +end. diff --git a/Task/Man-or-boy-test/REXX/man-or-boy-test.rexx b/Task/Man-or-boy-test/REXX/man-or-boy-test.rexx new file mode 100644 index 0000000000..5664c15964 --- /dev/null +++ b/Task/Man-or-boy-test/REXX/man-or-boy-test.rexx @@ -0,0 +1,16 @@ +/*REXX program performs the "man or boy" test as far as possible for N. */ + do n=0 /*increment N from 0 forever.*/ + say 'n='n a(N,x1,x2,x3,x4,x5) /*display the result to the term.*/ + end /*n*/ /* [↑] do until something breaks*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────A subroutine────────────────────────*/ +a: procedure; parse arg k,x1,x2,x3,x4,x5 + if k<=0 then return f(x4)+f(x5) + else return f(b) +/*──────────────────────────────────one─liner subroutines───────────────*/ +b: k=k-1; return a(k,b,x1,x2,x3,x4) +f: interpret 'v=' arg(1)"()"; return v +x1: procedure; return 1 +x2: procedure; return -1 +x3: procedure; return -1 +x4: procedure; return 1 diff --git a/Task/Mandelbrot-set/00DESCRIPTION b/Task/Mandelbrot-set/00DESCRIPTION index 05d31ac7d2..6ff0ec5889 100644 --- a/Task/Mandelbrot-set/00DESCRIPTION +++ b/Task/Mandelbrot-set/00DESCRIPTION @@ -1 +1,3 @@ -Generate and draw the [[wp:Mandelbrot set|Mandelbrot set]]. Note that there are [http://en.wikibooks.org/wiki/Fractals/Iterations_in_the_complex_plane/Mandelbrot_set many algorithms] to draw Mandelbrot set and there are [http://en.wikibooks.org/wiki/Pictures_of_Julia_and_Mandelbrot_sets many functions] which generate it . +Generate and draw the [[wp:Mandelbrot set|Mandelbrot set]]. + +Note that there are [http://en.wikibooks.org/wiki/Fractals/Iterations_in_the_complex_plane/Mandelbrot_set many algorithms] to draw Mandelbrot set and there are [http://en.wikibooks.org/wiki/Pictures_of_Julia_and_Mandelbrot_sets many functions] which generate it . diff --git a/Task/Mandelbrot-set/00META.yaml b/Task/Mandelbrot-set/00META.yaml index 77e833cb39..4233712735 100644 --- a/Task/Mandelbrot-set/00META.yaml +++ b/Task/Mandelbrot-set/00META.yaml @@ -1,4 +1,5 @@ --- category: +- Graphics - Raster graphics operations note: Fractals diff --git a/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js b/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js new file mode 100644 index 0000000000..d1f7faf9b4 --- /dev/null +++ b/Task/Mandelbrot-set/JavaScript/mandelbrot-set.js @@ -0,0 +1,69 @@ +function Mandeliter( cx, cy, maxiter ){ + var + x = 0.0, + y = 0.0, + xx = 0, + yy = 0, + xy = 0; + + var i = maxiter; + while( i-- && xx + yy <= 4 ){ + xy = x * y; + xx = x * x; + yy = y * y; + x = xx - yy + cx; + y = xy + xy + cy; + } + return maxiter - i; +} + +function Mandelbrot( width,height, xmin,xmax, ymin,ymax, iterations ){ + var canvas = document.createElement( 'canvas' ); + canvas.width = width; + canvas.height = height; + + var ctx = canvas.getContext( '2d' ); + var img = ctx.getImageData( 0, 0, width, height ); + var pix = img.data; + for( var ix = 0; ix < width; ++ix ) + for( var iy = 0; iy < height; ++iy ) + { + var x = xmin + (xmax - xmin) * ix / (width - 1); + var y = ymin + (ymax - ymin) * iy / (height - 1); + var i = Mandeliter( x, y, iterations ); + var ppos = 4 * (width * iy + ix); + if( i === iterations ) + { + pix[ppos] = 0; + pix[ppos+1] = 0; + pix[ppos+2] = 0; + } + else + { + var c = 3 * Math.log(i)/Math.log(iterations - 1.0); + if (c < 1) + { + pix[ppos] = 255*c; + pix[ppos+1] = 0; + pix[ppos+2] = 0; + } + else if( c < 2 ) + { + pix[ppos] = 255; + pix[ppos+1] = 255*(c-1); + pix[ppos+2] = 0; + } + else + { + pix[ppos] = 255; + pix[ppos+1] = 255; + pix[ppos+2] = 255*(c-2); + } + } + pix[ ppos+3 ] = 255; + } + ctx.putImageData( img, 0,0 ); + document.body.insertBefore( canvas, document.body.childNodes[0] ); +} + +Mandelbrot( 900,600, -2,1, -1,1, 1000 ); diff --git a/Task/Mandelbrot-set/Pascal/mandelbrot-set.pascal b/Task/Mandelbrot-set/Pascal/mandelbrot-set.pascal new file mode 100644 index 0000000000..a58b8a3b7b --- /dev/null +++ b/Task/Mandelbrot-set/Pascal/mandelbrot-set.pascal @@ -0,0 +1,88 @@ +program mandelbrot; + +const + ixmax = 800; + iymax = 800; + cxmin = -2.5; + cxmax = 1.5; + cymin = -2.0; + cymax = 2.0; + maxcolorcomponentvalue = 255; + maxiteration = 200; + escaperadius = 2; + +type + colortype = record + red : byte; + green : byte; + blue : byte; + end; + +var + ix, iy : integer; + cx, cy : real; + pixelwidth : real = (cxmax - cxmin) / ixmax; + pixelheight : real = (cymax - cymin) / iymax; + filename : string = 'new1.ppm'; + comment : string = '# '; + outfile : textfile; + color : colortype; + zx, zy : real; + zx2, zy2 : real; + iteration : integer; + er2 : real = (escaperadius * escaperadius); + +begin + {$I-} + assign(outfile, filename); + rewrite(outfile); + if ioresult <> 0 then + begin + writeln(stderr, 'unable to open output file: ', filename); + exit; + end; + + writeln(outfile, 'P6'); + writeln(outfile, ' ', comment); + writeln(outfile, ' ', ixmax); + writeln(outfile, ' ', iymax); + writeln(outfile, ' ', maxcolorcomponentvalue); + + for iy := 1 to iymax do + begin + cy := cymin + (iy - 1)*pixelheight; + if abs(cy) < pixelheight / 2 then cy := 0.0; + for ix := 1 to ixmax do + begin + cx := cxmin + (ix - 1)*pixelwidth; + zx := 0.0; + zy := 0.0; + zx2 := zx*zx; + zy2 := zy*zy; + iteration := 0; + while (iteration < maxiteration) and (zx2 + zy2 < er2) do + begin + zy := 2*zx*zy + cy; + zx := zx2 - zy2 + cx; + zx2 := zx*zx; + zy2 := zy*zy; + iteration := iteration + 1; + end; + if iteration = maxiteration then + begin + color.red := 0; + color.green := 0; + color.blue := 0; + end + else + begin + color.red := 255; + color.green := 255; + color.blue := 255; + end; + write(outfile, chr(color.red), chr(color.green), chr(color.blue)); + end; + end; + + close(outfile); +end. diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-1.py b/Task/Mandelbrot-set/Python/mandelbrot-set-1.py index 27387246a8..b780804ffb 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-1.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-1.py @@ -5,11 +5,14 @@ except: pass -def mandelbrot(a): return reduce(lambda z, _: z*z + a, range(50), 0) -def step(start, step, iterations): return (start + (i * step) for i in range(iterations)) +def mandelbrot(a): + return reduce(lambda z, _: z * z + a, range(50), 0) -rows = (('*' if abs(mandelbrot(complex(x, y))) < 2 else ' ' +def step(start, step, iterations): + return (start + (i * step) for i in range(iterations)) + +rows = (("*" if abs(mandelbrot(complex(x, y))) < 2 else " " for x in step(-2.0, .0315, 80)) for y in step(1, -.05, 41)) -print( '\n'.join(''.join(row) for row in rows) ) +print("\n".join("".join(row) for row in rows)) diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-2.py b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py index 2cbddcf2ec..e615a9d35d 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-2.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-2.py @@ -1,6 +1,15 @@ import math -mandelbrot = lambda z , c , n = 40 : float('nan') if abs(z) > 1000 else mandelbrot(z**2+c,c,n-1) if n > 0 else z**2+c -print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0,x+1j*y).real) else " " - for x in [a*0.02 for a in xrange(-80,30)]]) - for y in [a*0.05 for a in xrange(-20,20)]]) + +def mandelbrot(z , c , n=40): + if abs(z) > 1000: + return float("nan") + else: + if n > 0: + return mandelbrot(z ** 2 + c, c, n - 1) + else: + return z ** 2 + c + +print("\n".join(["".join(["#" if not math.isnan(mandelbrot(0, x + 1j * y).real) else " " + for x in [a * 0.02 for a in range(-80, 30)]]) + for y in [a * 0.05 for a in range(-20, 20)]]) ) diff --git a/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx b/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx new file mode 100644 index 0000000000..bb1ea9f7ca --- /dev/null +++ b/Task/Mandelbrot-set/REXX/mandelbrot-set.rexx @@ -0,0 +1,17 @@ +/*REXX program generates and displays a Mandelbrot set as an ASCII image*/ +xsize = 59; minre = -2; maxre = +1; stepx = (maxre-minre)/xsize +ysize = 21; minim = -1; maxim = +1; stepy = (maxim-minim)/ysize + + do y=0 for ysize + im=minim+stepy*y + do x=0 for xsize + re=minre+stepx*x; zr=re; zi=im + do n=0 for 30 + a=zr*zr; b=zi*zi + if a+b>4 then leave + zi=2*zr*zi+im; zr=a-b+re + end /*n*/ + call charout ,d2c(62-n) /*display number as a char──►term*/ + end /*x*/ + say /*force last CHAROUTs to the term*/ + end /*y*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Mandelbrot-set/Scala/mandelbrot-set-1.scala b/Task/Mandelbrot-set/Scala/mandelbrot-set-1.scala index 8403ebd00d..d4d0c8d4e6 100644 --- a/Task/Mandelbrot-set/Scala/mandelbrot-set-1.scala +++ b/Task/Mandelbrot-set/Scala/mandelbrot-set-1.scala @@ -1,4 +1,4 @@ -import rosettacode.ArithmeticComplex._ +import org.rosettacode.ArithmeticComplex._ import java.awt.Color object Mandelbrot diff --git a/Task/Mandelbrot-set/Scala/mandelbrot-set-2.scala b/Task/Mandelbrot-set/Scala/mandelbrot-set-2.scala index ff69e1078c..729cd0bd6e 100644 --- a/Task/Mandelbrot-set/Scala/mandelbrot-set-2.scala +++ b/Task/Mandelbrot-set/Scala/mandelbrot-set-2.scala @@ -1,3 +1,5 @@ +import scala.swing._ +import javax.swing.ImageIcon val imgMandel=Mandelbrot.generate() val mainframe=new MainFrame(){title="Test"; visible=true contents=new Label(){icon=new ImageIcon(imgMandel.image)} diff --git a/Task/Mandelbrot-set/Z80-Assembly/mandelbrot-set.z80 b/Task/Mandelbrot-set/Z80-Assembly/mandelbrot-set.z80 new file mode 100644 index 0000000000..714ee37290 --- /dev/null +++ b/Task/Mandelbrot-set/Z80-Assembly/mandelbrot-set.z80 @@ -0,0 +1,240 @@ +; +; Compute a Mandelbrot set on a simple Z80 computer. +; +; Porting this program to another Z80 platform should be easy and straight- +; forward: The only dependencies on my homebrew machine are the system-calls +; used to print strings and characters. These calls are performed by loading +; IX with the number of the system-call and performing an RST 08. To port this +; program to another operating system just replace these system-calls with +; the appropriate versions. Only three system-calls are used in the following: +; _crlf: Prints a CR/LF, _puts: Prints a 0-terminated string (the adress of +; which is expected in HL), and _putc: Print a single character which is +; expected in A. RST 0 give control back to the monitor. +; +#include "mondef.asm" + + org ram_start + +scale equ 256 ; Do NOT change this - the + ; arithmetic routines rely on + ; this scaling factor! :-) +divergent equ scale * 4 + + ld hl, welcome ; Print a welcome message + ld ix, _puts + rst 08 + +; for (y = ; y <= y_end; y += y_step) +; { +outer_loop ld hl, (y_end) ; Is y <= y_end? + ld de, (y) + and a ; Clear carry + sbc hl, de ; Perform the comparison + jp m, mandel_end ; End of outer loop reached + +; for (x = x_start; x <= x_end; x += x_step) +; { + ld hl, (x_start) ; x = x_start + ld (x), hl +inner_loop ld hl, (x_end) ; Is x <= x_end? + ld de, (x) + and a + sbc hl, de + jp m, inner_loop_end ; End of inner loop reached + +; z_0 = z_1 = 0; + ld hl, 0 + ld (z_0), hl + ld (z_1), hl + +; for (iteration = iteration_max; iteration; iteration--) +; { + ld a, (iteration_max) + ld b, a +iteration_loop push bc ; iteration -> stack +; z2 = (z_0 * z_0 - z_1 * z_1) / SCALE; + ld de, (z_1) ; Compute DE HL = z_1 * z_1 + ld bc, de + call mul_16 + ld (z_0_square_low), hl ; z_0 ** 2 is needed later again + ld (z_0_square_high), de + + ld de, (z_0) ; Compute DE HL = z_0 * z_0 + ld bc, de + call mul_16 + ld (z_1_square_low), hl ; z_1 ** 2 will be also needed + ld (z_1_square_high), de + + and a ; Compute subtraction + ld bc, (z_0_square_low) + sbc hl, bc + ld (scratch_0), hl ; Save lower 16 bit of result + ld hl, de + ld bc, (z_0_square_high) + sbc hl, bc + ld bc, (scratch_0) ; HL BC = z_0 ** 2 - z_1 ** 2 + + ld c, b ; Divide by scale = 256 + ld b, l ; Discard the rest + push bc ; We need BC later + +; z3 = 2 * z0 * z1 / SCALE; + ld hl, (z_0) ; Compute DE HL = 2 * z_0 * z_1 + add hl, hl + ld de, hl + ld bc, (z_1) + call mul_16 + + ld b, e ; Divide by scale (= 256) + ld c, h ; BC contains now z_3 + +; z1 = z3 + y; + ld hl, (y) + add hl, bc + ld (z_1), hl + +; z_0 = z_2 + x; + pop bc ; Here BC is needed again :-) + ld hl, (x) + add hl, bc + ld (z_0), hl + +; if (z0 * z0 / SCALE + z1 * z1 / SCALE > 4 * SCALE) + ld hl, (z_0_square_low) ; Use the squares computed + ld de, (z_1_square_low) ; above + add hl, de + ld bc, hl ; BC contains lower word of sum + + ld hl, (z_0_square_high) + ld de, (z_1_square_high) + adc hl, de + + ld h, l ; HL now contains (z_0 ** 2 + + ld l, b ; z_1 ** 2) / scale + + ld bc, divergent + and a + sbc hl, bc + +; break; + jp c, iteration_dec ; No break + pop bc ; Get latest iteration counter + jr iteration_end ; Exit loop + +; iteration++; +iteration_dec pop bc ; Get iteration counter + djnz iteration_loop ; We might fall through! +; } +iteration_end +; printf("%c", display[iteration % 7]); + ld a, b + and $7 ; lower three bits only (c = 0) + sbc hl, hl + ld l, a + ld de, display ; Get start of character array + add hl, de ; address and load the + ld a, (hl) ; character to be printed + ld ix, _putc ; Print the character + rst 08 + + ld de, (x_step) ; x += x_step + ld hl, (x) + add hl, de + ld (x), hl + + jp inner_loop +; } +; printf("\n"); +inner_loop_end ld ix, _crlf ; Print a CR/LF pair + rst 08 + + ld de, (y_step) ; y += y_step + ld hl, (y) + add hl, de + ld (y), hl ; Store new y-value + + jp outer_loop +; } + +mandel_end ld hl, finished ; Print finished-message + ld ix, _puts + rst 08 + + rst 0 ; Return to the monitor + +welcome defb "Generating a Mandelbrot set" + defb cr, lf, eos +finished defb "Computation finished.", cr, lf, eos + +iteration_max defb 10 ; How many iterations +x defw 0 ; x-coordinate +x_start defw -2 * scale ; Minimum x-coordinate +x_end defw 5 * scale / 10 ; Maximum x-coordinate +x_step defw 4 * scale / 100 ; x-coordinate step-width +y defw -1 * scale ; Minimum y-coordinate +y_end defw 1 * scale ; Maximum y-coordinate +y_step defw 1 * scale / 10 ; y-coordinate step-width +z_0 defw 0 +z_1 defw 0 +scratch_0 defw 0 +z_0_square_high defw 0 +z_0_square_low defw 0 +z_1_square_high defw 0 +z_1_square_low defw 0 +display defb " .-+*=#@" ; 8 characters for the display + +; +; Compute DEHL = BC * DE (signed): This routine is not too clever but it +; works. It is based on a standard 16-by-16 multiplication routine for unsigned +; integers. At the beginning the sign of the result is determined based on the +; signs of the operands which are negated if necessary. Then the unsigned +; multiplication takes place, followed by negating the result if necessary. +; +mul_16 xor a ; Clear carry and A (-> +) + bit 7, b ; Is BC negative? + jr z, bc_positive ; No + sub c ; A is still zero, complement + ld c, a + ld a, 0 + sbc a, b + ld b, a + scf ; Set carry (-> -) +bc_positive bit 7, D ; Is DE negative? + jr z, de_positive ; No + push af ; Remember carry for later! + xor a + sub e + ld e, a + ld a, 0 + sbc a, d + ld d, a + pop af ; Restore carry for complement + ccf ; Complement Carry (-> +/-?) +de_positive push af ; Remember state of carry + and a ; Start multiplication + sbc hl, hl + ld a, 16 ; 16 rounds +mul_16_loop add hl, hl + rl e + rl d + jr nc, mul_16_exit + add hl, bc + jr nc, mul_16_exit + inc de +mul_16_exit dec a + jr nz, mul_16_loop + pop af ; Restore carry from beginning + ret nc ; No sign inversion necessary + xor a ; Complement DE HL + sub l + ld l, a + ld a, 0 + sbc a, h + ld h, a + ld a, 0 + sbc a, e + ld e, a + ld a, 0 + sbc a, d + ld d, a + ret diff --git a/Task/Map-range/ACL2/map-range.acl2 b/Task/Map-range/ACL2/map-range.acl2 index 3b622ec909..996c67542b 100644 --- a/Task/Map-range/ACL2/map-range.acl2 +++ b/Task/Map-range/ACL2/map-range.acl2 @@ -2,3 +2,13 @@ (+ b1 (/ (* (- s a1) (- b2 b1)) (- a2 a1)))) + +(defun map-each (a1 a2 b1 b2 ss) + (if (endp ss) + nil + (cons (mapping a1 a2 b1 b2 (first ss)) + (map-each a1 a2 b1 b2 (rest ss))))) + +(map-each 0 10 -1 0 '(0 1 2 3 4 5 6 7 8 9 10)) + +;; (-1 -9/10 -4/5 -7/10 -3/5 -1/2 -2/5 -3/10 -1/5 -1/10 0) diff --git a/Task/Map-range/D/map-range.d b/Task/Map-range/D/map-range.d index 33e302b53b..184364dd0e 100644 --- a/Task/Map-range/D/map-range.d +++ b/Task/Map-range/D/map-range.d @@ -1,13 +1,13 @@ -import std.stdio; - double mapRange(in double[] a, in double[] b, in double s) -pure nothrow { - return b[0] + ((s - a[0]) * (b[1] - b[0]) / (a[1] - a[0])); +pure nothrow @nogc { + return b[0] + ((s - a[0]) * (b[1] - b[0]) / (a[1] - a[0])); } void main() { - const r1 = [0.0, 10.0]; - const r2 = [-1.0, 0.0]; - foreach (s; 0 .. 11) + import std.stdio; + + immutable r1 = [0.0, 10.0]; + immutable r2 = [-1.0, 0.0]; + foreach (immutable s; 0 .. 11) writefln("%2d maps to %5.2f", s, mapRange(r1, r2, s)); } diff --git a/Task/Map-range/Pascal/map-range.pascal b/Task/Map-range/Pascal/map-range-1.pascal similarity index 100% rename from Task/Map-range/Pascal/map-range.pascal rename to Task/Map-range/Pascal/map-range-1.pascal diff --git a/Task/Map-range/Pascal/map-range-2.pascal b/Task/Map-range/Pascal/map-range-2.pascal new file mode 100644 index 0000000000..ce16131c1b --- /dev/null +++ b/Task/Map-range/Pascal/map-range-2.pascal @@ -0,0 +1,56 @@ +Program Map(output); + +type + real = double; + tRange = Array [0..1] of real; + tMapRec = record + mrFrom, + mrTo : tRange; + mrScale : real + end; + +function InitRange(rfrom,rTo:real):tRange; +begin + InitRange[0] :=rfrom; + InitRange[1] :=rTo; +end; + +function InitMapRec(const fromRange, toRange: tRange):tMapRec; +begin + With InitMapRec do + Begin + mrFrom := fromRange; + mrTo := toRange; + mrScale := (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]); + end; +end; + +function MapRecRange(const value: real;var MR :tMapRec): real; +begin + with MR do + MapRecRange := (value-mrFrom[0]) * mrScale + mrTo[0]; +end; + +function MapRange(const value: real;const fromRange, toRange: tRange): real; +begin + MapRange := (value-fromRange[0]) * (toRange[1]-toRange[0]) / (fromRange[1]-fromRange[0]) + toRange[0]; +end; + +var + value:real; + rFrom,rTo : tRange; + mr : tMapRec; + i: LongInt; + +begin + rFrom:= InitRange( 0, 10); + rTo := InitRange( -1, 0); + mr:= InitMapRec(rFrom,rTo); + + for i := 0 to 10 do + Begin + value := i; + writeln (i:4, ' maps to: ', MapRange(value,rFrom, rTo):10:6, + MapRecRange(value,mr):10:6); + end; +end. diff --git a/Task/Map-range/REXX/map-range-4.rexx b/Task/Map-range/REXX/map-range-4.rexx index 6543c0d9f7..90266d33b7 100644 --- a/Task/Map-range/REXX/map-range-4.rexx +++ b/Task/Map-range/REXX/map-range-4.rexx @@ -4,8 +4,7 @@ do j=0 to 10 say right(j,3) ' maps to ' mapRange(0,10,-1,0,j) end -exit /*stick a fork in it, we're done.*/ - +exit /*──────────────────────────────────MAPRANGE subroutine─────────────────*/ mapRange: return arg(3)+(arg(5)-arg(1))*(arg(4)-arg(3))/(arg(2)-arg(1)) /* Arguments are arg a1,a2,b1,b2,x */ diff --git a/Task/Map-range/Ruby/map-range-1.rb b/Task/Map-range/Ruby/map-range-1.rb new file mode 100644 index 0000000000..2fbf28148e --- /dev/null +++ b/Task/Map-range/Ruby/map-range-1.rb @@ -0,0 +1,6 @@ +def map_range(a, b, s) + af, al, bf, bl = a.first, a.last, b.first, b.last + bf + (s - af)*(bl - bf).quo(al - af) +end + +(0..10).each{|s| puts "%s maps to %g" % [s, map_range(0..10, -1..0, s)]} diff --git a/Task/Map-range/Ruby/map-range-2.rb b/Task/Map-range/Ruby/map-range-2.rb new file mode 100644 index 0000000000..d7e14ac938 --- /dev/null +++ b/Task/Map-range/Ruby/map-range-2.rb @@ -0,0 +1,3 @@ +(0..10).each do |s| + puts "%s maps to %s" % [s, map_range(0..10, -1..0, s)] +end diff --git a/Task/Map-range/Ruby/map-range.rb b/Task/Map-range/Ruby/map-range.rb deleted file mode 100644 index 7389938c4e..0000000000 --- a/Task/Map-range/Ruby/map-range.rb +++ /dev/null @@ -1,9 +0,0 @@ -def map_range(a, b, s) - af, al, bf, bl = a.first, a.last, b.first, b.last - bf + (s - af).*(bl - bf).quo(al - af) -end - -11.times do |s| - s *= 1.0 # force floating point - print s, " maps to ", map_range((0..10), (-1..0), s), "\n" -end diff --git a/Task/Matrix-arithmetic/D/matrix-arithmetic.d b/Task/Matrix-arithmetic/D/matrix-arithmetic.d index 0c72dc70c3..dbbda2ed0e 100644 --- a/Task/Matrix-arithmetic/D/matrix-arithmetic.d +++ b/Task/Matrix-arithmetic/D/matrix-arithmetic.d @@ -1,32 +1,30 @@ import std.algorithm, std.range, std.traits, permutations2, permutations_by_swapping1; -auto prod(Range)(Range r) /*pure*/ nothrow { - return reduce!q{a * b}(cast(ForeachType!Range)1, r); +auto prod(Range)(Range r) nothrow @safe @nogc { + return reduce!q{a * b}(ForeachType!Range(1), r); } -T permanent(T)(in T[][] a) /*pure nothrow*/ +T permanent(T)(in T[][] a) nothrow @safe in { - foreach (const row; a) - assert(row.length == a[0].length); + assert(a.all!(row => row.length == a[0].length)); } body { auto r = a.length.iota; T tot = 0; - foreach (sigma; r.array.permutations) + foreach (const sigma; r.array.permutations) tot += r.map!(i => a[i][sigma[i]]).prod; return tot; } -T determinant(T)(in T[][] a) /*pure nothrow*/ +T determinant(T)(in T[][] a) nothrow in { - foreach (const row; a) - assert(row.length == a[0].length); + assert(a.all!(row => row.length == a[0].length)); } body { immutable n = a.length; auto r = n.iota; T tot = 0; //foreach (sigma, sign; n.spermutations) { - foreach (sigma_sign; n.spermutations) { + foreach (const sigma_sign; n.spermutations) { const sigma = sigma_sign[0]; immutable sign = sigma_sign[1]; tot += sign * r.map!(i => a[i][sigma[i]]).prod; diff --git a/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d b/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d index 28d12beb83..28a906b71f 100644 --- a/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d +++ b/Task/Matrix-exponentiation-operator/D/matrix-exponentiation-operator.d @@ -1,63 +1,57 @@ -import std.stdio, std.string, std.math, std.array; +import std.stdio, std.string, std.math, std.array, std.algorithm; struct SquareMat(T = creal) { public static string fmt = "%8.3f"; private alias TM = T[][]; private TM a; - public this(in size_t side) pure nothrow + public this(in size_t side) pure nothrow @safe in { assert(side > 0); } body { a = new TM(side, side); } - public this(in TM m) pure nothrow + public this(in TM m) pure nothrow @safe in { assert(!m.empty); - foreach (const row; m) - assert(m.length == m[0].length); + assert(m.all!(row => row.length == m.length)); // Is square. } body { + // 2D dup. a.length = m.length; foreach (immutable i, const row; m) - //a[i] = row.dup; // Not nothrow. - a[i] = row ~ []; // Slower. + a[i] = row.dup; } - string toString() const { + string toString() const @safe { return format("<%(%(" ~ fmt ~ ", %)\n %)>", a); } - public static SquareMat identity(in size_t side) pure nothrow { - SquareMat m; - m.a.length = side; - foreach (immutable r, ref row; m.a) { - row.length = side; + public static SquareMat identity(in size_t side) pure nothrow @safe { + auto m = SquareMat(side); + foreach (immutable r, ref row; m.a) foreach (immutable c; 0 .. side) - row[c] = cast(T)(r == c ? 1 : 0); - } + row[c] = (r == c) ? 1+0i : 0+0i; return m; } public SquareMat opBinary(string op:"*")(in SquareMat other) - const pure nothrow in { + const pure nothrow @safe in { assert (a.length == other.a.length); } body { - immutable size_t side = other.a.length; - SquareMat d; - d.a = new TM(side, side); + immutable side = other.a.length; + auto d = SquareMat(side); foreach (immutable r; 0 .. side) foreach (immutable c; 0 .. side) { - d.a[r][c] = cast(T)0; + d.a[r][c] = 0+0i; foreach (immutable k, immutable ark; a[r]) d.a[r][c] += ark * other.a[k][c]; } return d; } - // This is the task part --------------- - public SquareMat opBinary(string op:"^^")(int n) const pure nothrow - in { + public SquareMat opBinary(string op:"^^")(int n) // The task part. + const pure nothrow @safe in { assert(n >= 0, "Negative exponent not implemented."); } body { auto sq = SquareMat(this.a); @@ -71,7 +65,7 @@ struct SquareMat(T = creal) { void main() { alias M = SquareMat!(); - immutable real q = sqrt(0.5); + enum real q = 0.5.sqrt; 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]]); diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-2.d b/Task/Matrix-multiplication/D/matrix-multiplication-2.d index de5a108536..d6ef54908a 100644 --- a/Task/Matrix-multiplication/D/matrix-multiplication-2.d +++ b/Task/Matrix-multiplication/D/matrix-multiplication-2.d @@ -1,6 +1,6 @@ import std.stdio, std.range, std.array, std.numeric, std.algorithm; -T[][] matMul(T)(in T[][] A, in T[][] B) /*pure*/ nothrow { +T[][] matMul(T)(in T[][] A, in T[][] B) pure nothrow /*@safe*/ { 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; } diff --git a/Task/Matrix-multiplication/D/matrix-multiplication-4.d b/Task/Matrix-multiplication/D/matrix-multiplication-4.d index ed0c098146..0f2280bcf5 100644 --- a/Task/Matrix-multiplication/D/matrix-multiplication-4.d +++ b/Task/Matrix-multiplication/D/matrix-multiplication-4.d @@ -5,9 +5,13 @@ alias TMMul_helper(M1, M2) = Unqual!(ForeachType!(ForeachType!M1)) 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 + /*out*/ ref T2[n][k] result) pure nothrow /*@safe*/ @nogc if (is(T2 == Unqual!T)) { - T2[m] aux; + static if (hasIndirections!T) + T2[m] aux; + else + T2[m] aux = void; + foreach (immutable j; 0 .. n) { foreach (immutable i, const ref bi; B) aux[i] = bi[j]; diff --git a/Task/Matrix-multiplication/Fortran/matrix-multiplication.f b/Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f similarity index 100% rename from Task/Matrix-multiplication/Fortran/matrix-multiplication.f rename to Task/Matrix-multiplication/Fortran/matrix-multiplication-1.f diff --git a/Task/Matrix-multiplication/Fortran/matrix-multiplication-2.f b/Task/Matrix-multiplication/Fortran/matrix-multiplication-2.f new file mode 100644 index 0000000000..7e0883a692 --- /dev/null +++ b/Task/Matrix-multiplication/Fortran/matrix-multiplication-2.f @@ -0,0 +1,7 @@ + program mm + real , allocatable :: a(:,:),b(:,:) + integer :: l=5,m=6,n=4 + a = reshape([1:l*m],[l,m]) + b = reshape([1:m*n],[m,n]) + print'(f15.7)',transpose(matmul(a,b)) + end program diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-1.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-1.math index 8d3cfd61df..55ae6c9516 100644 --- a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-1.math +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-1.math @@ -1,7 +1 @@ -M1 = {{1, 2}, - {3, 4}, - {5, 6}, - {7, 8}} -M2 = {{1, 2, 3}, - {4, 5, 6}} -M = M1.M2 +Dot[{{a, b}, {c, d}}, {{w, x}, {y, z}}] diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-2.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-2.math index 88477892ba..5710a67b8a 100644 --- a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-2.math +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-2.math @@ -1 +1 @@ -{{1, 2}, {3, 4}, {5, 6}, {7, 8}}.{{1, 2, 3}, {4, 5, 6}} +{{a w + b y, a x + b z}, {c w + d y, c x + d z}} diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-3.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-3.math index fa324e603c..802a043a72 100644 --- a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-3.math +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-3.math @@ -1 +1 @@ -{{9, 12, 15}, {19, 26, 33}, {29, 40, 51}, {39, 54, 69}} +{{a, b}, {c, d}} . {{w, x}, {y, z}} diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-4.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-4.math index a0811cc75f..be2ae941f9 100644 --- a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-4.math +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-4.math @@ -1,7 +1 @@ -matrixMul[m1_, m2_] := Table[Times @@ {a, b} // Tr, {a, m1}, {b, Transpose@m2}] -matrixMul2[m1_, m2_] :=Table[Sum[Times @@ i, {i, Transpose@{a, b}}], {a, m1}, {b, Transpose@m2}] - -a = {{1, 2}, {3, 4}, {5, 6}, {7, 8}}; -b = {{1, 2, 3}, {4, 5, 6}}; -matrixMul[a, b] -matrixMul2[a, b] +Times[{{a, b}, {c, d}}, {{w, x}, {y, z}}] diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-5.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-5.math new file mode 100644 index 0000000000..ae41b7f2c8 --- /dev/null +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-5.math @@ -0,0 +1 @@ +{{a w, b x}, {c y, d z}} diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-6.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-6.math new file mode 100644 index 0000000000..d3bfd5a221 --- /dev/null +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-6.math @@ -0,0 +1 @@ +{{a, b}, {c, d}}*{{w, x}, {y, z}} diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-7.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-7.math new file mode 100644 index 0000000000..17d319b3ef --- /dev/null +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-7.math @@ -0,0 +1 @@ +{{a, b}, {c, d}} {{w, x}, {y, z}} diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-8.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-8.math new file mode 100644 index 0000000000..4d599ba67f --- /dev/null +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-8.math @@ -0,0 +1 @@ +Dot[{{85, 60, 65}, {54, 99, 33}, {46, 52, 87}}, {{89, 77, 98}, {55, 27, 25}, {80, 68, 85}}] diff --git a/Task/Matrix-multiplication/Mathematica/matrix-multiplication-9.math b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-9.math new file mode 100644 index 0000000000..d151ed5785 --- /dev/null +++ b/Task/Matrix-multiplication/Mathematica/matrix-multiplication-9.math @@ -0,0 +1 @@ +{{16065, 12585, 15355}, {12891, 9075, 10572}, {13914, 10862, 13203}} diff --git a/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx b/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx index 18170a2ce8..1b3e966be9 100644 --- a/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx +++ b/Task/Matrix-multiplication/REXX/matrix-multiplication.rexx @@ -1,37 +1,39 @@ -/*REXX program multiplies two matrixes together, shows matrixes & result*/ -x.= -x.1 = '1 2' -x.2 = '3 4' -x.3 = "5 6" /*either kind of quote works. */ -x.4 = '7 8' - do r=1 while x.r\=='' /*build the "A" matric from X. #s*/ - do c=1 while x.r\==''; parse var x.r a.r.c x.r; end - end -Arows=r-1; Acols=c-1 -y.= -y.1 = 1 2 3 /*if all values are positive, */ -y.2 = 4 5 6 /*can eliminate the quotes. */ - do r=1 while y.r\=='' /*build the "B" matric from Y. #s*/ - do c=1 while y.r\==''; parse var y.r b.r.c y.r; end - end -Brows=r-1; Bcols=c-1 -c.=0; L=0 /*L is max width of an element. */ - do i =1 for Arows /*multiply matrix A & B ──� C */ - do j =1 for Bcols - do k=1 for Acols +/*REXX program multiplies 2 matrixes together, shows matrixes and result*/ +x. = /*the beginnings of the A matrix.*/ +x.1 = 1 2 /*╔═════════════════════════════╗*/ +x.2 = 3 4 /*║As none of the values haven't║*/ +x.3 = 5 6 /*║a sign, quotes aren't needed.║*/ +x.4 = 7 8 /*╚═════════════════════════════╝*/ + do r=1 while x.r\=='' /*build the "A" matric from X. #s*/ + do c=1 while x.r\==''; parse var x.r a.r.c x.r; end + end /*r*/ +Arows=r-1 /*adjust number of rows (DO loop)*/ +Acols=c-1 /* " " " cols " " */ +y. = /*the beginnings of the B matrix.*/ +y.1 = 1 2 3 +y.2 = 4 5 6 + do r=1 while y.r\=='' /*build the "B" matric from Y. #s*/ + do c=1 while y.r\==''; parse var y.r b.r.c y.r; end + end +Brows=r-1 /*adjust number of rows (DO loop)*/ +Bcols=c-1 /* " " " cols " " */ +c.=0; L=0 /*L is max width of an element.*/ + do i =1 for Arows /*multiply matrix A & B ──► C */ + do j =1 for Bcols + do k=1 for Acols c.i.j = c.i.j + a.i.k * b.k.j; L=max(L,length(c.i.j)) end /*k*/ end /*j*/ - end /*i*/ + end /*i*/ -call showMat 'A', Arows, Acols -call showMat 'B', Brows, Bcols -call showMat 'C', Arows, Bcols +call showMatrix 'A', Arows, Acols /*display matrix A ───► terminal.*/ +call showMatrix 'B', Brows, Bcols /* " " B ───► " */ +call showMatrix 'C', Arows, Bcols /* " " C ───► " */ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SHOWMAT subroutine──────────────────*/ -showMat: parse arg mat,rows,cols; say +/*──────────────────────────────────SHOWMATRIX subroutine───────────────*/ +showMatrix: 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); end; say _ - end + end /*r*/ return diff --git a/Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication.ti-83 b/Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-1.ti-83 similarity index 100% rename from Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication.ti-83 rename to Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-1.ti-83 diff --git a/Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-2.ti-83 b/Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-2.ti-83 new file mode 100644 index 0000000000..c99a17ea48 --- /dev/null +++ b/Task/Matrix-multiplication/TI-83-BASIC/matrix-multiplication-2.ti-83 @@ -0,0 +1 @@ +[[1,2][3,4][5,6][7,8]]*[[1,2,3][4,5,6]] diff --git a/Task/Matrix-transposition/Clojure/matrix-transposition.clj b/Task/Matrix-transposition/Clojure/matrix-transposition.clj new file mode 100644 index 0000000000..0859f4342b --- /dev/null +++ b/Task/Matrix-transposition/Clojure/matrix-transposition.clj @@ -0,0 +1,11 @@ +(defmulti matrix-transpose + "Switch rows with columns." + class) + +(defmethod matrix-transpose clojure.lang.PersistentList + [mtx] + (apply map list mtx)) + +(defmethod matrix-transpose clojure.lang.PersistentVector + [mtx] + (vec (apply map vector mtx))) diff --git a/Task/Matrix-transposition/HicEst/matrix-transposition.hicest b/Task/Matrix-transposition/HicEst/matrix-transposition.hicest new file mode 100644 index 0000000000..1e6b41e55a --- /dev/null +++ b/Task/Matrix-transposition/HicEst/matrix-transposition.hicest @@ -0,0 +1,7 @@ +REAL :: mtx(2, 4) + +mtx = 1.1 * $ +WRITE() mtx + +SOLVE(Matrix=mtx, Transpose=mtx) +WRITE() mtx diff --git a/Task/Matrix-transposition/Lua/matrix-transposition-2.lua b/Task/Matrix-transposition/Lua/matrix-transposition-2.lua index d289694f18..71aa277a04 100644 --- a/Task/Matrix-transposition/Lua/matrix-transposition-2.lua +++ b/Task/Matrix-transposition/Lua/matrix-transposition-2.lua @@ -8,10 +8,10 @@ function mapn(f, ...) local c = {} local k = 1 local aarg = {...} - local n = table.getn(aarg) + local n = #aarg while true do local a = map(function(b) return b[k] end, aarg) - if table.getn(a) < n then return c end + if #a < n then return c end c[k] = f(unpack(a)) k = k + 1 end diff --git a/Task/Maze-generation/D/maze-generation.d b/Task/Maze-generation/D/maze-generation.d index cfed6e1d42..842245c214 100644 --- a/Task/Maze-generation/D/maze-generation.d +++ b/Task/Maze-generation/D/maze-generation.d @@ -1,4 +1,4 @@ -void main() { +void main() @safe { import std.stdio, std.algorithm, std.range, std.random; enum uint w = 14, h = 10; @@ -6,9 +6,10 @@ void main() { hor = iota(h + 1).map!(_ => ["+---"].replicate(w)).array, ver = h.iota.map!(_ => ["| "].replicate(w) ~ "|").array; - void walk(in uint x, in uint y) /*nothrow*/ { + void walk(in uint x, in uint y) /*nothrow*/ @safe /*@nogc*/ { vis[y][x] = true; - foreach (p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) { + //foreach (immutable p; [[x-1,y], [x,y+1], [x+1,y], [x,y-1]].randomCover) { + foreach (const p; [[x-1, y], [x, y+1], [x+1, y], [x, y-1]].randomCover) { if (p[0] >= w || p[1] >= h || vis[p[1]][p[0]]) continue; if (p[0] == x) hor[max(y, p[1])][x] = "+ "; if (p[1] == y) ver[y][max(x, p[0])] = " "; @@ -17,5 +18,5 @@ void main() { } walk(uniform(0, w), uniform(0, h)); foreach (const a, const b; hor.zip(ver ~ [])) - join(a ~ ["+\n"] ~ b).writeln; + join(a ~ "+\n" ~ b).writeln; } diff --git a/Task/Maze-generation/Lua/maze-generation-1.lua b/Task/Maze-generation/Lua/maze-generation-1.lua new file mode 100644 index 0000000000..72a3e8b265 --- /dev/null +++ b/Task/Maze-generation/Lua/maze-generation-1.lua @@ -0,0 +1,17 @@ +Stack = {} + +function Stack:Create() + local stack = {} + + function stack:push(item) + self[#self + 1] = item + end + + function stack:pop() + local item = self[#self] + self[#self] = nil + return item + end + + return stack +end diff --git a/Task/Maze-generation/Lua/maze-generation-2.lua b/Task/Maze-generation/Lua/maze-generation-2.lua new file mode 100644 index 0000000000..e0f5d29ee4 --- /dev/null +++ b/Task/Maze-generation/Lua/maze-generation-2.lua @@ -0,0 +1,114 @@ +require "stack" + +Maze = +{ + directions = + { + north = { x = 0, y = -1 }, + east = { x = 1, y = 0 }, + south = { x = 0, y = 1 }, + west = { x = -1, y = 0 } + } +} + +function Maze:Create(width, height, closed) + -- Actual maze setup + local maze = {} + for y = 1, height do + maze[y] = {} + for x = 1, width do + maze[y][x] = { east = self:CreateDoor(closed), south = self:CreateDoor(closed)} + + -- Doors are shared beetween the cells to avoid out of sync conditions and data dublication + if x ~= 1 then maze[y][x].west = maze[y][x - 1].east + else maze[y][x].west = self:CreateDoor(closed) end + + if y ~= 1 then maze[y][x].north = maze[y - 1][x].south + else maze[y][x].north = self:CreateDoor(closed) end + end + end + + function maze:resetDoors(close) + for y = 1, #self do + self[y][#self[1]].east:setOpened(not close) + + for i, cell in ipairs(self[y]) do + cell.north:setOpened(not close) + cell.west:setOpened(not close) + end + end + + for i, cell in ipairs(self[#self]) do + cell.south:setOpened(not close) + end + end + + function maze:resetVisited() + for y = 1, #self do + for x = 1, #self[1] do + self[y][x].visited = nil + end + end + end + + function maze:tostring(wall, passage) + wall = wall or "#" + passage = passage or " " + + local result = "" + + local verticalBorder = "" + for i = 1, #self[1] do + verticalBorder = verticalBorder .. wall .. (self[1][i].north:isClosed() and wall or passage) + end + verticalBorder = verticalBorder .. wall + result = result .. verticalBorder .. "\n" + + for y, row in ipairs(self) do + local line = row[1].west:isClosed() and wall or passage + local underline = wall + for x, cell in ipairs(row) do + line = line .. " " .. (cell.east:isClosed() and wall or passage) + underline = underline .. (cell.south:isClosed() and wall or passage) .. wall + end + result = result .. line .. "\n" .. underline .. "\n" + end + + return result + end + + return maze +end + + +-- This function was designed to be easily replaced by the function generating Legend of Grimrock doors +function Maze:CreateDoor(closed) + local door = {} + door._closed = closed and true or false + + function door:isClosed() + return self._closed + end + + function door:isOpened() + return not self._closed + end + + function door:close() + self._closed = true + end + + function door:open() + self._closed = false + end + + function door:setOpened(opened) + if opened then + self:open() + else + self:close() + end + end + + return door +end diff --git a/Task/Maze-generation/Lua/maze-generation-3.lua b/Task/Maze-generation/Lua/maze-generation-3.lua new file mode 100644 index 0000000000..9a579c437c --- /dev/null +++ b/Task/Maze-generation/Lua/maze-generation-3.lua @@ -0,0 +1,41 @@ +require "maze" + +-- Backtracker algorithm (a variation of the recursive backtracker algorithm made without recursion) +function Maze:Backtracker(maze) + maze:resetDoors(true) + + local stack = Stack:Create() + + local cell = { x = 1, y = 1 } + while true do + maze[cell.y][cell.x].visited = true + + -- Gathering all possible travel direction in a list + local directions = {} + for key, value in pairs(self.directions) do + local newPos = { x = cell.x + value.x, y = cell.y + value.y } + -- Checking if the targeted cell is in bounds and was not visited previously + if maze[newPos.y] and maze[newPos.y][newPos.x] and not maze[newPos.y][newPos.x].visited then + directions[#directions + 1] = { name = key, pos = newPos } + end + end + + -- If there are no possible travel directions - backtracking + if #directions == 0 then + if #stack > 0 then + cell = stack:pop() + goto countinue + else break end -- Stack is empty and there are no possible directions - maze is generated + end + + -- Choosing a random direction from a list of possible direction and carving + stack:push(cell) + local dir = directions[math.random(#directions)] + maze[cell.y][cell.x][dir.name]:open() + cell = dir.pos + + ::countinue:: + end + + maze:resetVisited() +end diff --git a/Task/Maze-generation/Lua/maze-generation-4.lua b/Task/Maze-generation/Lua/maze-generation-4.lua new file mode 100644 index 0000000000..be684280ac --- /dev/null +++ b/Task/Maze-generation/Lua/maze-generation-4.lua @@ -0,0 +1,9 @@ +require "maze" +require "backtracker" + +maze = Maze:Create(30, 10, true) +--[[ Maze generation depends on the random seed, so you will get exactly + identical maze every time you pass exactly identical seed ]] +math.randomseed(os.time()) +Maze:Backtracker(maze) +print(maze:tostring()) diff --git a/Task/Maze-solving/00DESCRIPTION b/Task/Maze-solving/00DESCRIPTION index 28e3200a1a..55c5cc1104 100644 --- a/Task/Maze-solving/00DESCRIPTION +++ b/Task/Maze-solving/00DESCRIPTION @@ -1,5 +1,4 @@ -For a maze generated by [[Maze generation|this task]], write a function that -finds (and displays) the shortest path between two cells. Note that because these -mazes are generated by the [[wp:Maze_generation_algorithm#Depth-first_search|Depth-first search]] -algorithm, they contain no circular paths, and a simple depth-first tree search -can be used. +For a maze generated by [[Maze generation|this task]], write a function +that finds (and displays) the shortest path between two cells. +Note that because these mazes are generated by the [[wp:Maze_generation_algorithm#Depth-first_search|Depth-first search]] algorithm, they contain no circular paths, +and a simple depth-first tree search can be used. diff --git a/Task/Maze-solving/00META.yaml b/Task/Maze-solving/00META.yaml index 614358d5a2..3501582b0c 100644 --- a/Task/Maze-solving/00META.yaml +++ b/Task/Maze-solving/00META.yaml @@ -1,4 +1,5 @@ --- category: - Recursion +- Puzzles note: Games diff --git a/Task/Maze-solving/D/maze-solving.d b/Task/Maze-solving/D/maze-solving.d index 7f377b42cd..ffbac9bd79 100644 --- a/Task/Maze-solving/D/maze-solving.d +++ b/Task/Maze-solving/D/maze-solving.d @@ -1,16 +1,16 @@ import std.stdio, std.random, std.string, std.array, std.algorithm, - std.file; + std.file, std.conv; 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 { +bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow @safe @nogc { if (s == end) return true; - foreach (d; [V2(0, -cy), V2(+cx, 0), V2(0, +cy), V2(-cx, 0)]) + foreach (immutable d; [V2(0, -cy), V2(+cx, 0), V2(0, +cy), V2(-cx, 0)]) if (maze[s.y + (d.y / 2)][s.x + (d.x / 2)] == ' ' && maze[s.y + d.y][s.x + d.x] == ' ') { maze[s.y + d.y][s.x + d.x] = pathSymbol; @@ -23,15 +23,13 @@ bool solveMaze(char[][] maze, in V2 s, in V2 end) pure nothrow { } void main() { - auto maze = "maze.txt".readText.splitLines.map!(r => r.dup).array; - immutable int h = ((cast(int)maze.length) - 1) / cy; + auto maze = "maze.txt".File.byLine.map!(r => r.chomp.dup).array; + immutable h = (maze.length.signed - 1) / cy; assert (h > 0); - immutable int w = ((cast(int)maze[0].length) - 1) / cx; + immutable w = (maze[0].length.signed - 1) / cx; - immutable start = V2(cx2 + cx * uniform(0, w), - cy2 + cy * uniform(0, h)); - immutable end = V2(cx2 + cx * uniform(0, w), - cy2 + cy * uniform(0, h)); + immutable start = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h)); + immutable end = V2(cx2 + cx * uniform(0, w), cy2 + cy * uniform(0, h)); maze[start.y][start.x] = pathSymbol; if (!solveMaze(maze, start, end)) diff --git a/Task/Maze-solving/J/maze-solving.j b/Task/Maze-solving/J/maze-solving.j index ab64be8f51..08878e07de 100644 --- a/Task/Maze-solving/J/maze-solving.j +++ b/Task/Maze-solving/J/maze-solving.j @@ -1,3 +1,28 @@ +maze=:4 :0 + assert.0<:n=.<:x*y + horiz=. 0$~x,y-1 + verti=. 0$~(x-1),y + path=.,:here=. ?x,y + unvisited=.0 ( {:p do. p =. p,y{~{:p @@ -56,7 +81,7 @@ solve=:3 :0 path , > {: 0 Dijkstra_equal_weights graph ) -display=:3 :0 NB. Monadic display copied from maze generation task +display=:3 :0 size=. >.&$&>/y text=. (}:1 3$~2*1+{:size)#"1":size$<' ' 'hdoor vdoor'=. 2 4&*&.>&.> (#&,{@;&i./@$)&.> y @@ -66,16 +91,5 @@ display=:3 :0 NB. Monadic display copied from maze generation task size=. >.&$&>/y columns=. {: size cells =. <"1(1 2&p.@<.@(%&columns) ,. 2 4&p.@(columns&|))x - '+' cells } a NB. exercise, replace cells with a gerund to draw arrows on the path. + 'o' cells } a NB. exercise, replace cells with a gerund to draw arrows on the path. ) - - 4 (display~ solve)@maze 9 -┌ ┬───┬───┬───┬───┬───┬───┬───┬───┐ -│ + │ │ │ -├ ┼───┼ ┼ ┼ ┼───┼ ┼ ┼ ┤ -│ + + │ │ │ │ │ -├───┼ ┼───┼───┼───┼───┼───┼ ┼───┤ -│ │ + + + │ + + + │ │ -├ ┼───┼───┼ ┼ ┼───┼ ┼───┼───┤ -│ + + │ + + + -└───┴───┴───┴───┴───┴───┴───┴───┴───┘ diff --git a/Task/Median-filter/D/median-filter.d b/Task/Median-filter/D/median-filter.d index 7b70df605b..771ee2eb18 100644 --- a/Task/Median-filter/D/median-filter.d +++ b/Task/Median-filter/D/median-filter.d @@ -1,12 +1,15 @@ import grayscale_image; Image!Color medianFilter(uint radius=10, Color)(in Image!Color img) -pure nothrow if (radius > 0) { +pure nothrow @safe if (radius > 0) in { + assert(img.nx >= radius && img.ny >= radius); +} body { alias Hist = uint[256]; - static ubyte median(uint no)(in ref Hist cumulative) pure nothrow { + static ubyte median(uint no)(in ref Hist cumulative) + pure nothrow @safe @nogc { size_t localSum = 0; - foreach (immutable ubyte k, immutable v; cumulative) + foreach (immutable k, immutable v; cumulative) if (v) { localSum += v; if (localSum > no / 2) @@ -19,8 +22,8 @@ pure nothrow if (radius > 0) { auto result = new Image!Color(img.nx, img.ny); foreach (immutable y; 0 .. img.ny) foreach (immutable x; 0 .. img.nx) - if (x < radius || x > img.nx - radius || - y < radius || y > img.ny - radius) + if (x < radius || x > img.nx - radius - 1 || + y < radius || y > img.ny - radius - 1) result[x, y] = img[x, y]; enum edge = 2 * radius + 1; @@ -65,10 +68,9 @@ pure nothrow if (radius > 0) { return result; } -version (median_filter_main) { +version (median_filter_main) void main() { // Demo. - loadPGM!Gray(null, "lena.pgm") - .medianFilter!10() + loadPGM!Gray(null, "lena.pgm"). + medianFilter!10 .savePGM("lena_median_r10.pgm"); } -} diff --git a/Task/Memory-allocation/D/memory-allocation.d b/Task/Memory-allocation/D/memory-allocation.d index 1597d72a1c..c6856f8aa6 100644 --- a/Task/Memory-allocation/D/memory-allocation.d +++ b/Task/Memory-allocation/D/memory-allocation.d @@ -10,18 +10,18 @@ enum int nInts = 10; // Compile-time constant. // This is thread-local: -int data1[nInts]; +int[nInts] data1; // This is global: -__gshared int data2[nInts]; +__gshared int[nInts] data2; void main() { // Static memory, it's thread-local but its name is usable // only locally: - static int data3[nInts]; + static int[nInts] data3; // Static memory, it's global but its name is usable only locally: - __gshared static int data4[nInts]; + __gshared static int[nInts] data4; // ---------------------- // D supports the functions that manage memory of the C heap: diff --git a/Task/Memory-allocation/Maple/memory-allocation-1.maple b/Task/Memory-allocation/Maple/memory-allocation-1.maple new file mode 100644 index 0000000000..77fd8b0aba --- /dev/null +++ b/Task/Memory-allocation/Maple/memory-allocation-1.maple @@ -0,0 +1 @@ +a := Array( 1 .. 10^6, datatype = integer[1] ): diff --git a/Task/Memory-allocation/Maple/memory-allocation-2.maple b/Task/Memory-allocation/Maple/memory-allocation-2.maple new file mode 100644 index 0000000000..3f0f4ad19b --- /dev/null +++ b/Task/Memory-allocation/Maple/memory-allocation-2.maple @@ -0,0 +1 @@ +unassign( a ): diff --git a/Task/Memory-allocation/Maple/memory-allocation-3.maple b/Task/Memory-allocation/Maple/memory-allocation-3.maple new file mode 100644 index 0000000000..e2f0908ebc --- /dev/null +++ b/Task/Memory-allocation/Maple/memory-allocation-3.maple @@ -0,0 +1 @@ +a := 'a': diff --git a/Task/Memory-layout-of-a-data-structure/Go/memory-layout-of-a-data-structure.go b/Task/Memory-layout-of-a-data-structure/Go/memory-layout-of-a-data-structure.go index a89c1f0fd9..f1d9c4efc7 100644 --- a/Task/Memory-layout-of-a-data-structure/Go/memory-layout-of-a-data-structure.go +++ b/Task/Memory-layout-of-a-data-structure/Go/memory-layout-of-a-data-structure.go @@ -5,19 +5,19 @@ import "fmt" type rs232p9 uint16 const ( - CD9 = 1 << iota // Carrier detect - RD9 // Received data - TD9 // Transmitted data - DTR9 // Data terminal ready - SG9 // signal ground - DSR9 // Data set ready - RTS9 // Request to send - CTS9 // Clear to send - RI9 // Ring indicator + CD9 rs232p9 = 1 << iota // Carrier detect + RD9 // Received data + TD9 // Transmitted data + DTR9 // Data terminal ready + SG9 // signal ground + DSR9 // Data set ready + RTS9 // Request to send + CTS9 // Clear to send + RI9 // Ring indicator ) func main() { - // set some nonsense bits just for example - var p rs232p9 = RI9 | TD9 | CD9 - fmt.Printf("%04x\n", p) + // set some nonsense bits just for example + p := RI9 | TD9 | CD9 + fmt.Printf("Type=%T value=%#04x\n", p, p) } diff --git a/Task/Menu/Prolog/menu-1.pro b/Task/Menu/Prolog/menu-1.pro new file mode 100644 index 0000000000..9ebed969b1 --- /dev/null +++ b/Task/Menu/Prolog/menu-1.pro @@ -0,0 +1,17 @@ +rosetta_menu([], "") :- !. %% Incase of an empty list. +rosetta_menu(Items, SelectedItem) :- + repeat, %% Repeat until everything that follows is true. + display_menu(Items), %% IO + get_choice(Choice), %% IO + number(Choice), %% True if Choice is a number. + nth1(Choice, Items, SelectedItem), %% True if SelectedItem is the 1-based nth member of Items, (fails if Choice is out of range) + !. + +display_menu(Items) :- + nl, + foreach( nth1(Index, Items, Item), + format('~w) ~s~n', [Index, Item]) ). + +get_choice(Choice) :- + prompt1('Select a menu item by number:'), + read(Choice). diff --git a/Task/Menu/Prolog/menu-2.pro b/Task/Menu/Prolog/menu-2.pro new file mode 100644 index 0000000000..6248bf019a --- /dev/null +++ b/Task/Menu/Prolog/menu-2.pro @@ -0,0 +1,20 @@ +?- rosetta_menu(["fee fie", "huff and puff", "mirror mirror", "tick tock"], String). + +1) fee fie +2) huff and puff +3) mirror mirror +4) tick tock +Select a menu item by number:a. + +1) fee fie +2) huff and puff +3) mirror mirror +4) tick tock +Select a menu item by number:10. + +1) fee fie +2) huff and puff +3) mirror mirror +4) tick tock +Select a menu item by number:3. +String = "mirror mirror". diff --git a/Task/Metaprogramming/Mathematica/metaprogramming.math b/Task/Metaprogramming/Mathematica/metaprogramming.math new file mode 100644 index 0000000000..5566eb9dd9 --- /dev/null +++ b/Task/Metaprogramming/Mathematica/metaprogramming.math @@ -0,0 +1,2 @@ +CircleTimes[x_, y_] := Mod[x, 10] Mod[y, 10] +14\[CircleTimes]13 diff --git a/Task/Metaprogramming/Python/metaprogramming-1.py b/Task/Metaprogramming/Python/metaprogramming-1.py new file mode 100644 index 0000000000..ed55780ef0 --- /dev/null +++ b/Task/Metaprogramming/Python/metaprogramming-1.py @@ -0,0 +1,9 @@ +from macropy.core.macros import * +from macropy.core.quotes import macros, q, ast, u + +macros = Macros() + +@macros.expr +def expand(tree, **kw): + addition = 10 + return q[lambda x: x * ast[tree] + u[addition]] diff --git a/Task/Metaprogramming/Python/metaprogramming-2.py b/Task/Metaprogramming/Python/metaprogramming-2.py new file mode 100644 index 0000000000..6158a05620 --- /dev/null +++ b/Task/Metaprogramming/Python/metaprogramming-2.py @@ -0,0 +1,2 @@ +func = expand[1 + 2] +print func(5) diff --git a/Task/Metronome/Go/metronome.go b/Task/Metronome/Go/metronome.go new file mode 100644 index 0000000000..6f31f7a0f5 --- /dev/null +++ b/Task/Metronome/Go/metronome.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + "time" +) + +func main() { + var bpm = 72.0 // Beats Per Minute + var bpb = 4 // Beats Per Bar + + d := time.Duration(float64(time.Minute) / bpm) + fmt.Println("Delay:", d) + t := time.NewTicker(d) + i := 1 + for _ = range t.C { + i-- + if i == 0 { + i = bpb + fmt.Printf("\nTICK ") + } else { + fmt.Printf("tick ") + } + } +} diff --git a/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg new file mode 100644 index 0000000000..e111739e61 --- /dev/null +++ b/Task/Middle-three-digits/ALGOL-68/middle-three-digits.alg @@ -0,0 +1,92 @@ +# we define a UNION MODE so that our middle 3 digits PROC can # +# return either an integer on success or a error message if # +# the middle 3 digits couldn't be extracted # + +MODE EINT = UNION( INT # success value #, STRING # error message # ); + + +# PROC to return the middle 3 digits of an integer. # +# if this is not possible, an error message is returned # +# instead # + +PROC middle 3 digits = ( INT number ) EINT: +BEGIN + + # convert the absolute value of the number to a string with the # + # minumum possible number characters # + STRING digits = whole( ABS number, 0 ); + INT len = UPB digits; + + + IF len < 3 + THEN + # number has less than 3 digits # + # return an error message # + + "number must have at least three digits" + + ELIF ( len MOD 2 ) = 0 + THEN + # the number has an even number of digits # + # return an error message # + + "number must have an odd number of digits" + + ELSE + # the number is suitable for extraction of the middle 3 digits # + + INT first digit pos = 1 + ( ( len - 3 ) OVER 2 ); + + # the result is the integer value of the three digits # + + ( ( ( ABS digits[ first digit pos ] - ABS "0" ) * 100 ) + + ( ( ABS digits[ first digit pos + 1 ] - ABS "0" ) * 10 ) + + ( ( ABS digits[ first digit pos + 2 ] - ABS "0" ) ) + ) + + FI + +END; # middle 3 digits # + + + +main: ( + + # test the middle 3 digits PROC # + + []INT test values = ( 123, 12345, 1234567, 987654321 + , 10001, -10001, -123, -100 + , 100, -12345 + # the following values should fail # + , 1, 2, -1, -10, 2002, -2002, 0 + ); + + FOR test number FROM LWB test values TO UPB test values + DO + + CASE middle 3 digits( test values[ test number ] ) + IN + ( INT success value ): # got the middle 3 digits # + + printf( ( $ 11z-d, " : ", 3d $ + , test values[ test number ] + , success value + ) + ) + , + + ( STRING error message ): # got an error message # + + printf( ( $ 11z-d, " : ", n( UPB error message )a $ + , test values[ test number ] + , error message + ) + ) + + ESAC; + + print( ( newline ) ) + + OD + +) diff --git a/Task/Middle-three-digits/C++/middle-three-digits.cpp b/Task/Middle-three-digits/C++/middle-three-digits.cpp index dc747aac78..7bf5dbd53d 100644 --- a/Task/Middle-three-digits/C++/middle-three-digits.cpp +++ b/Task/Middle-three-digits/C++/middle-three-digits.cpp @@ -1,84 +1,27 @@ #include -#include -#include -// @author Martin Ettl -// @date 2013-02-04 - -/** - * Convert variables of type T to std::string - * - * - * @param d --> digit of type T - * - * @return <-- the corresponding string value - */ -template const std::string toString(const T &d) +std::string middleThreeDigits(int n) { - std::ostringstream result; - result << d; - return result.str(); -} + auto number = std::to_string(std::abs(n)); + auto length = number.size(); -/** - * Determine the middle n digits of the integer. If it is not possible to determine the - * the middle n digits, an empty string is provided. - * - * @param iDigit --> The digit to test - * @param n --> The number of digits inbetween - * - * @return <-- the middle three digits - */ -std::string strMiddleNDigits(int iDigit, const int &n) -{ - // is negative: --> convert to a positive number - if(iDigit<0) - { - iDigit*=-1; + if (length < 3) { + return "less than three digits"; + } else if (length % 2 == 0) { + return "even number of digits"; + } else { + return number.substr(length / 2 - 1, 3); } - // convert to string - std::string strNumber (toString(iDigit)); - size_t len(strNumber.length()); - if( (len < n) || (len % 2 == 0) ) - { - return ""; - } - size_t mid(len/2); - return strNumber.substr(mid-n/2, n); -} - -/** - * Determine the middle three digits of the integer. If it is not possible to determine the - * the middle three digits, an empty string is provided. - * - * @param iDigit --> The digit to test - * - * @return <-- the middle three digits - */ -std::string strMiddleThreeDigits(int iDigit) -{ - return strMiddleNDigits(iDigit,3); } int main() { - const int iPassing[] = {123, 12345, 1234567, 987654321, 10001, -10001, - -123, -100, 100, -12345 - }; - for(unsigned int ui = 0; ui < 10; ++ui) - { - std::cout << "strMiddleThreeDigits("<< iPassing[ui] <<"): " - << strMiddleThreeDigits(iPassing[ui])<< "\n"; - } + auto values {123, 12345, 1234567, 987654321, 10001, + -10001, -123, -100, 100, -12345, + 1, 2, -1, -10, 2002, -2002, 0}; - const int iFailing[] = {1, 2, -1, -10, 2002, -2002, 0}; - for(unsigned int ui = 0; ui < 7; ++ui) - { - std::string strResult = strMiddleThreeDigits(iFailing[ui]); - std::cout << "strMiddleThreeDigits("<< iFailing[ui] <<"): " - << (strResult.empty()?"Need odd and >= 3 digits":strResult) - << "\n"; + for (auto&& v : values) { + std::cout << "middleThreeDigits(" << v << "): " << + middleThreeDigits(v) << "\n"; } - - return 0; } diff --git a/Task/Middle-three-digits/D/middle-three-digits-1.d b/Task/Middle-three-digits/D/middle-three-digits-1.d index 2bb5990917..021c638e77 100644 --- a/Task/Middle-three-digits/D/middle-three-digits-1.d +++ b/Task/Middle-three-digits/D/middle-three-digits-1.d @@ -1,7 +1,7 @@ -import std.stdio, std.traits, std.conv, std.range; +import std.stdio, std.traits, std.conv; -string middleThreeDigits(T)(in T n) if (isIntegral!T) { - auto s = n < 0 ? n.text().dropOne : n.text(); +string middleThreeDigits(T)(in T n) pure nothrow if (isIntegral!T) { + auto s = n < 0 ? n.text[1 .. $] : n.text; auto len = s.length; if (len < 3 || len % 2 == 0) return "Need odd and >= 3 digits"; @@ -12,10 +12,10 @@ string middleThreeDigits(T)(in T n) if (isIntegral!T) { void main() { immutable passing = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, long.min, long.max]; - foreach (n; passing) + foreach (immutable n; passing) writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n)); - immutable failing = [1, 2, -1, -10, 2002, -2002, 0, int.min, int.max]; - foreach (n; failing) + immutable failing = [1, 2, -1, -10, 2002, -2002, 0,int.min,int.max]; + foreach (immutable n; failing) writefln("middleThreeDigits(%s): %s", n, middleThreeDigits(n)); } diff --git a/Task/Middle-three-digits/Prolog/middle-three-digits-1.pro b/Task/Middle-three-digits/Prolog/middle-three-digits-1.pro new file mode 100644 index 0000000000..d8ba1902b8 --- /dev/null +++ b/Task/Middle-three-digits/Prolog/middle-three-digits-1.pro @@ -0,0 +1,14 @@ +middle_3_digits(Number, [D1,D2,D3]) :- + verify_middle_3_able(Number, Digits), + append(FrontDigits, [D1,D2,D3| BackDigits], Digits), + same_length(FrontDigits, BackDigits). + +verify_middle_3_able(Number, Digits) :- + must_be(number, Number), + AbsNumber is abs(Number), + number_chars(AbsNumber, Digits), + length(Digits, NumDigits), + ( 3 > NumDigits -> domain_error('at least 3 digits', Number) + ; 0 is NumDigits mod 2 -> domain_error('odd number of digits', Number) + ; true + ). diff --git a/Task/Middle-three-digits/Prolog/middle-three-digits-2.pro b/Task/Middle-three-digits/Prolog/middle-three-digits-2.pro new file mode 100644 index 0000000000..cfe652a854 --- /dev/null +++ b/Task/Middle-three-digits/Prolog/middle-three-digits-2.pro @@ -0,0 +1,6 @@ +test_correct :- + TestCases = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345], + foreach( ( member(TestCase, TestCases), + middle_3_digits(TestCase, Result) ), + format('Middle 3 digits of ~w ~30|: ~w~n', [TestCase, Result]) + ). diff --git a/Task/Middle-three-digits/Ruby/middle-three-digits-1.rb b/Task/Middle-three-digits/Ruby/middle-three-digits-1.rb new file mode 100644 index 0000000000..a50ac81a68 --- /dev/null +++ b/Task/Middle-three-digits/Ruby/middle-three-digits-1.rb @@ -0,0 +1,14 @@ +def middle_three_digits(num) + # minus sign doesn't factor into digit count, + # and calling #abs acts as a duck-type assertion + num = num.abs + + # convert to string and find length + length = (str = num.to_s).length + + # check validity + raise ArgumentError, "Number must have at least three digits" if length < 3 + raise ArgumentError, "Number must have an odd number of digits" if length.even? + + return str[length/2 - 1, 3].to_i +end diff --git a/Task/Middle-three-digits/Ruby/middle-three-digits-2.rb b/Task/Middle-three-digits/Ruby/middle-three-digits-2.rb new file mode 100644 index 0000000000..c9f3e4aedc --- /dev/null +++ b/Task/Middle-three-digits/Ruby/middle-three-digits-2.rb @@ -0,0 +1,14 @@ +samples = [ + 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, + 1, 2, -1, -10, 2002, -2002, 0 +] + +left_column_width = samples.map { |n| n.to_s.length }.max +samples.each do |n| + print "%#{left_column_width}d: " % n + begin + puts "%03d" % middle_three_digits(n) + rescue ArgumentError => e + puts e + end +end diff --git a/Task/Middle-three-digits/Ruby/middle-three-digits.rb b/Task/Middle-three-digits/Ruby/middle-three-digits.rb deleted file mode 100644 index 37f8b56187..0000000000 --- a/Task/Middle-three-digits/Ruby/middle-three-digits.rb +++ /dev/null @@ -1,30 +0,0 @@ -def middle_three_digits(n) - # minus sign doesn't factor into digit count, - # and calling #abs acts as a duck-type assertion - n = n.abs - - # convert to string and find length - l = (s = n.to_s).length - - # check validity - raise ArgumentError, "Number must have at least three digits" if l < 3 - raise ArgumentError, "Number must have an odd number of digits" if l.even? - - return s[l/2-1,3].to_i -end - -samples = [ - 123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, - 1, 2, -1, -10, 2002, -2002, 0 -] - -width = samples.map { |n| n.to_s.length }.max - -samples.each do |n| - print "%#{width}d: " % n - begin - puts "%03d" % middle_three_digits(n) - rescue ArgumentError => e - puts e - end -end diff --git a/Task/Middle-three-digits/SQL/middle-three-digits.sql b/Task/Middle-three-digits/SQL/middle-three-digits.sql new file mode 100644 index 0000000000..84ed25c4e2 --- /dev/null +++ b/Task/Middle-three-digits/SQL/middle-three-digits.sql @@ -0,0 +1,12 @@ +;WITH DATA + AS (SELECT CAST(ABS(NUMBER) AS NVARCHAR(MAX)) charNum, + NUMBER, + LEN(CAST(ABS(NUMBER) AS NVARCHAR(MAX))) LcharNum + FROM TABLE1) +SELECT CASE + WHEN ( LCHARNUM >= 3 + AND LCHARNUM % 2 = 1 ) THEN SUBSTRING(CHARNUM, LCHARNUM / 2, 3) + ELSE 'Error!' + END Output, + NUMBER Input +FROM DATA diff --git a/Task/Miller-Rabin-primality-test/00DESCRIPTION b/Task/Miller-Rabin-primality-test/00DESCRIPTION index cc41003e11..1f7d1064c0 100644 --- a/Task/Miller-Rabin-primality-test/00DESCRIPTION +++ b/Task/Miller-Rabin-primality-test/00DESCRIPTION @@ -1,5 +1,8 @@ {{Wikipedia|Miller–Rabin primality test}} -The [[wp:Miller–Rabin primality test|Miller–Rabin primality test]] or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. The algorithm, as modified by [[wp:Michael O. Rabin|Michael O. Rabin]] to avoid the [[wp:generalized Riemann hypothesis|generalized Riemann hypothesis]], is a probabilistic algorithm. + +The [[wp:Miller–Rabin primality test|Miller–Rabin primality test]] or Rabin–Miller primality test is a primality test: an algorithm which determines whether a given number is prime or not. + +The algorithm, as modified by [[wp:Michael O. Rabin|Michael O. Rabin]] to avoid the [[wp:generalized Riemann hypothesis|generalized Riemann hypothesis]], is a probabilistic algorithm. The pseudocode, from [[wp:Miller-Rabin primality test#Algorithm_and_running_time|Wikipedia]] is: '''Input''': ''n'' > 2, an odd integer to be tested for primality; diff --git a/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d b/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d index cbce59f050..6d958ac4cd 100644 --- a/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d +++ b/Task/Miller-Rabin-primality-test/D/miller-rabin-primality-test.d @@ -1,14 +1,13 @@ import std.random; -bool isProbablePrime(in ulong n, in int k) { - static long modPow(long b, long e, in long m) - pure nothrow { - long result = 1; +bool isProbablePrime(in ulong n, in uint k=10) /*nothrow*/ @safe /*@nogc*/ { + static ulong modPow(ulong b, ulong e, in ulong m) + pure nothrow @safe @nogc { + ulong result = 1; while (e > 0) { - if ((e & 1) == 1) { + if ((e & 1) == 1) result = (result * b) % m; - } - b = (b * b) % m; + b = (b ^^ 2) % m; e >>= 1; } return result; @@ -26,15 +25,17 @@ bool isProbablePrime(in ulong n, in int k) { assert(2 ^^ s * d == n - 1); outer: - foreach (_; 0 .. k) { - ulong a = uniform(2, n); + foreach (immutable _; 0 .. k) { + immutable ulong a = uniform(2, n); ulong x = modPow(a, d, n); if (x == 1 || x == n - 1) continue; - foreach (__; 1 .. s) { + foreach (immutable __; 1 .. s) { x = modPow(x, 2, n); - if (x == 1) return false; - if (x == n - 1) continue outer; + if (x == 1) + return false; + if (x == n - 1) + continue outer; } return false; } @@ -42,7 +43,8 @@ bool isProbablePrime(in ulong n, in int k) { return true; } -void main() { // demo code +void main() { // Demo code. import std.stdio, std.range, std.algorithm; - writeln(filter!(n => isProbablePrime(n, 10))(iota(2, 30))); + + iota(2, 30).filter!isProbablePrime.writeln; } diff --git a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test.java b/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java similarity index 100% rename from Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test.java rename to Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-1.java diff --git a/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java b/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java new file mode 100644 index 0000000000..900c4001bb --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Java/miller-rabin-primality-test-2.java @@ -0,0 +1,79 @@ +import java.math.BigInteger; + +public class Prime { + + // this is the RabinMiller test, deterministically correct for n < 341,550,071,728,321 + // http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python:_Proved_correct_up_to_large_N + public static boolean isPrime(BigInteger n, int precision) { + + if (n.compareTo(new BigInteger("341550071728321")) >= 0) { + return n.isProbablePrime(precision); + } + + int intN = n.intValue(); + if (intN == 1 || intN == 4 || intN == 6 || intN == 8) return false; + if (intN == 2 || intN == 3 || intN == 5 || intN == 7) return true; + + int[] primesToTest = getPrimesToTest(n); + if (n.equals(new BigInteger("3215031751"))) { + return false; + } + BigInteger d = n.subtract(BigInteger.ONE); + BigInteger s = BigInteger.ZERO; + while (d.mod(BigInteger.valueOf(2)).equals(BigInteger.ZERO)) { + d = d.shiftRight(1); + s = s.add(BigInteger.ONE); + } + for (int a : primesToTest) { + if (try_composite(a, d, n, s)) { + return false; + } + } + return true; + } + + public static boolean isPrime(BigInteger n) { + return isPrime(n, 100); + } + + public static boolean isPrime(int n) { + return isPrime(BigInteger.valueOf(n), 100); + } + + public static boolean isPrime(long n) { + return isPrime(BigInteger.valueOf(n), 100); + } + + private static int[] getPrimesToTest(BigInteger n) { + if (n.compareTo(new BigInteger("3474749660383")) >= 0) { + return new int[]{2, 3, 5, 7, 11, 13, 17}; + } + if (n.compareTo(new BigInteger("2152302898747")) >= 0) { + return new int[]{2, 3, 5, 7, 11, 13}; + } + if (n.compareTo(new BigInteger("118670087467")) >= 0) { + return new int[]{2, 3, 5, 7, 11}; + } + if (n.compareTo(new BigInteger("25326001")) >= 0) { + return new int[]{2, 3, 5, 7}; + } + if (n.compareTo(new BigInteger("1373653")) >= 0) { + return new int[]{2, 3, 5}; + } + return new int[]{2, 3}; + } + + private static boolean try_composite(int a, BigInteger d, BigInteger n, BigInteger s) { + BigInteger aB = BigInteger.valueOf(a); + if (aB.modPow(d, n).equals(BigInteger.ONE)) { + return false; + } + for (int i = 0; BigInteger.valueOf(i).compareTo(s) < 0; i++) { + // if pow(a, 2**i * d, n) == n-1 + if (aB.modPow(BigInteger.valueOf(2).pow(i).multiply(d), n).equals(n.subtract(BigInteger.ONE))) { + return false; + } + } + return true; + } +} diff --git a/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js b/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js index 8a20c83b71..e7e8edaaa0 100644 --- a/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js +++ b/Task/Miller-Rabin-primality-test/JavaScript/miller-rabin-primality-test.js @@ -1,31 +1,33 @@ -function modProd(a,b,n){ - if(b==0) return 0; - if(b==1) return a%n; - return (modProd(a,(b-b%10)/10,n)*10+(b%10)*a)%n; -} -function modPow(a,b,n){ - if(b==0) return 1; - if(b==1) return a%n; - if(b%2==0){ - var c=modPow(a,b/2,n); - return modProd(c,c,n); - } - return modProd(a,modPow(a,b-1,n),n); -} -function isPrime(n){ - if(n==2||n==3||n==5) return true; - if(n%2==0||n%3==0||n%5==0) return false; - if(n<25) return true; - for(var a=[2,3,5,7,11,13,17,19],b=n-1,d,t,i,x;b%2==0;b/=2); - for(i=0;i 3: false + N > integer(3), + (N mod integer(2)) = integer(0), + P = integer(0). + %%-------------deterministic-------- +is_prime(N, P) :- %% 3 < odd number < 3.415e+14 + N > integer(3), + (N mod integer(2)) = integer(1), + N < integer(341550071728321), + deterministic_witnesses(N, DList), + is_mr_prime(N, DList, R), + P = R. + %%-------------probabilistic-------- +is_prime(N, P) :- %% 3.415e+14 =< odd number + N > integer(3), + (N mod integer(2)) = integer(1), + N >= integer(341550071728321), + random_witnesses(N, 20, RList), + is_mr_prime(N, RList, R), + P = R. +is_prime(_N, P) :- P = -integer(1). + +%----------------------------------------------------------------------% +% returns list of deterministic witnesses + +:- pred deterministic_witnesses(integer::in, + list(integer)::out) is multi. + +deterministic_witnesses(N, L) :- N < integer(1373653), + L = [integer(2), integer(3)]. +deterministic_witnesses(N, L) :- N < integer(9080191), + L = [integer(31), integer(73)]. +deterministic_witnesses(N, L) :- N < integer(25326001), + L = [integer(2), integer(3), integer(5)]. +deterministic_witnesses(N, L) :- N < integer(3215031751), + L = [integer(2), integer(3), integer(5), integer(7)]. +deterministic_witnesses(N, L) :- N < integer(4759123141), + L = [integer(2), integer(7), integer(61)]. +deterministic_witnesses(N, L) :- N < integer(1122004669633), + L = [integer(2), integer(13), integer(23), integer(1662803)]. +deterministic_witnesses(N, L) :- N < integer(2152302898747), + L = [integer(2), integer(3), integer(5), integer(7), integer(11)]. +deterministic_witnesses(N, L) :- N < integer(3474749660383), + L = [integer(2), integer(3), integer(5), integer(7), integer(11), + integer(13)]. +deterministic_witnesses(N, L) :- N < integer(341550071728321), + L = [integer(2), integer(3), integer(5), integer(7), + integer(11), integer(13), integer(17)]. +deterministic_witnesses(_N, L) :- L = []. %% signals failure + +%----------------------------------------------------------------------% + %% random_witnesses/3 receives an integer, X, an int, K, and + %% returns a list, P, of K pseudo-random integers in a range + %% 1 to X-1. + +:- pred random_witnesses(integer::in, int::in, + list(integer)::out) is det. + +random_witnesses(X, K, P) :- + A = integer(6364136223846793005), + B = integer(1442695040888963407), + C = X - integer(2), + rw_loop(X, A, B, C, K, [], P). + +:- pred rw_loop(integer::in, integer::in, integer::in, integer::in, + int::in, list(integer)::in, list(integer)::out) is det. + +rw_loop(X, A, B, C, K, L, P) :- + X1 = (((X * A) + B) mod C) + integer(1), + ( if K = 0 then P = L + else rw_loop(X1, A, B, C, K-1, [X1|L], P) + ). + +%----------------------------------------------------------------------% + % is_mr_prime/2 receives integer N and list As and returns true if + % N is probably prime, and false otherwise + +:- pred is_mr_prime(integer::in, list(integer)::in, integer::out) is nondet. + +is_mr_prime(N, As, R) :- + find_ds(N, L), + L = [D|T], + T = [S|_], + outer_loop(N, As, D, S, R). + +:- pred outer_loop(integer::in, list(integer)::in, integer::in, + integer::in, integer::out) is nondet. + +outer_loop(N, As, D, S, R) :- + As = [A|At], + Base = powm(A, D, N), %% = A^D mod N + inner_loop(Base, N, integer(0), S, U), + ( if U = integer(0) then R = integer(0) + else ( if At = [] then R = integer(1) + else outer_loop(N, At, D, S, R) + ) + ). + +:- pred inner_loop(integer::in, integer::in, integer::in, + integer::in, integer::out) is multi. + +inner_loop(Base, N, Loop, S, U) :- + Next_Base = (Base * Base) mod N, + Next_Loop = Loop + integer(1), + ( if Loop = integer(0) then + ( if Base = integer(1) then U = integer(1) % true + else if Base = N - integer(1) then U = integer(1) % true + else if Next_Loop = S then U = integer(0) % false + else inner_loop(Next_Base, N, Next_Loop, S, U) + ) + else if Base = N - integer(1) then U = integer(1) % true + else if Next_Loop = S then U = integer(0) % false + else inner_loop(Next_Base, N, Next_Loop, S, U) + ). + +%----------------------------------------------------------------------% + % find_ds/2 receives odd integer N + % and returns [D, S] such that N-1 = 2^S * D + +:- pred find_ds(integer::in, list(integer)::out) is multi. + +find_ds(N, L) :- + A = N - integer(1), + find_ds1(A, integer(0), L). + +:- pred find_ds1(integer::in, integer::in, list(integer)::out) is multi. + +find_ds1(D, S, L) :- + D mod integer(2) = integer(0), + P = D div integer(2), + Q = S + integer(1), + find_ds1(P, Q, L). +find_ds1(D, S, L) :- + L = [D, S]. + +%----------------------------------------------------------------------% +:- func powm(integer, integer, integer) = integer. + + % computes A^D mod N + +powm(A, D, N) = + ( if D = integer(0) then integer(1) + else ( if (D mod integer(2)) = integer(0) then + (integer.pow(powm(A, (D div integer(2)), N), + integer(2))) mod N + else (A * powm(A, D - integer(1), N)) mod N + ) + ). + +%----------------------------------------------------------------------% +:- end_module primality. + +% A means of testing the predicate is_prime/2 +%----------------------------------------------------------------------% + +:- module test_is_prime. + +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is cc_multi. + +%----------------------------------------------------------------------% + +:- implementation. + +:- import_module bool, char, int, integer, list, math, require, string. +:- import_module primality. + +%----------------------------------------------------------------------% + % TEST THE IS_PRIME PREDICATE + % $ ./test_is_prime + %---------------------------------------------% + +main(!IO) :- + command_line_arguments(Args, !IO), + filter(is_all_digits, Args, CleanArgs), + Arg1 = list.det_index0(CleanArgs, 0), + M = integer.det_from_string(Arg1), + is_prime(M,P), + io.format(" is_prime(%s) = ", [s(integer.to_string(M))], !IO), + ( if P = integer(0) then io.write_string("false.\n", !IO) + else if P = integer(1) then io.write_string("true.\n", !IO) + else if P = -integer(1) then + io.write_string("N fails all tests.\n", !IO) + else io.write_string("Has reported neither true nor false + nor any error condition.\n", !IO) + ). + +%----------------------------------------------------------------------% +:- end_module test_is_prime. diff --git a/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz b/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz new file mode 100644 index 0000000000..40882568ac --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Oz/miller-rabin-primality-test.oz @@ -0,0 +1,104 @@ +%--------------------------------------------------------------------------% +% module: Primality +% file: Primality.oz +% version: 17 DEC 2014 @ 6:50AM +%--------------------------------------------------------------------------% + +declare +%--------------------------------------------------------------------------% + +fun {IsPrime N} % main interface of module + if N < 2 then false + elseif N < 4 then true + elseif (N mod 2) == 0 then false + elseif N < 341330071728321 then {IsMRprime N {DetWit N}} + else {IsMRprime N {ProbWit N 20}} + end +end +%--------------------------------------------------------------------------% + +fun {DetWit N} % deterministic witnesses + if N < 1373653 then [2 3] + elseif N < 9080191 then [31 73] + elseif N < 25326001 then [2 3 5] + elseif N < 3215031751 then [2 3 5 7] + elseif N < 4759123141 then [2 7 61] + elseif N < 1122004669633 then [2 13 23 1662803] + elseif N < 2152302898747 then [2 3 5 7 11] + elseif N < 3474749660383 then [2 3 5 7 11 13] + elseif N < 341550071728321 then [2 3 5 7 11 13 17] + else nil + end +end +%--------------------------------------------------------------------------% + +fun {ProbWit N K} % probabilistic witnesses + local A B C in + A = 6364136223846793005 + B = 1442695040888963407 + C = N - 2 + {RWloop N A B C K nil} + end +end + +fun {RWloop N A B C K L} + local N1 in + N1 = (((N * A) + B) mod C) + 1 + if K == 0 then L + else {RWloop N1 A B C (K - 1) N1|L} + end + end +end +%--------------------------------------------------------------------------% + +fun {IsMRprime N As} % the Miller-Rabin algorithm + local D S T Ts in + {FindDS N} = D|S + {OuterLoop N As D S} + end +end + +fun {OuterLoop N As D S} + local A At Base C in + As = A|At + Base = {Powm A D N} + C = {InnerLoop Base N 0 S} + if {Not C} then false + elseif {And C (At == nil)} then true + else {OuterLoop N At D S} + end + end +end + +fun {InnerLoop Base N Loop S} + local NextBase NextLoop in + NextBase = (Base * Base) mod N + NextLoop = Loop + 1 + if {And (Loop == 0) (Base == 1)} then true + elseif Base == (N - 1) then true + elseif NextLoop == S then false + else {InnerLoop NextBase N NextLoop S} + end + end +end +%--------------------------------------------------------------------------% + +fun {FindDS N} + {FindDS1 (N - 1) 0} +end + +fun {FindDS1 D S} + if (D mod 2 == 0) then {FindDS1 (D div 2) (S + 1)} + else D|S + end +end +%--------------------------------------------------------------------------% + +fun {Powm A D N} % returns (A ^ D) mod N + if D == 0 then 1 + elseif (D mod 2) == 0 then {Pow {Powm A (D div 2) N} 2} mod N + else (A * {Powm A (D - 1) N}) mod N + end +end +%--------------------------------------------------------------------------% +% end_module Primality diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl similarity index 100% rename from Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test.pl rename to Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-1.pl diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl new file mode 100644 index 0000000000..5e93b4e8ba --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-2.pl @@ -0,0 +1,10 @@ +use ntheory qw/is_strong_pseudoprime miller_rabin_random/; +sub is_prime_mr { + my $n = shift; + # If 32-bit, we can do this with 3 bases. + return is_strong_pseudoprime($n, 2, 7, 61) if ($n >> 32) == 0; + # If 64-bit, 7 is all we need. + return is_strong_pseudoprime($n, 2, 325, 9375, 28178, 450775, 9780504, 1795265022) if ($n >> 64) == 0; + # Otherwise, perform a number of random base tests, and the result is a probable prime test. + return miller_rabin_random($n, 20); +} diff --git a/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl new file mode 100644 index 0000000000..f9de5c5498 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Perl/miller-rabin-primality-test-3.pl @@ -0,0 +1,10 @@ +use Math::Primality qw/is_strong_pseudoprime/; +sub is_prime_mr { + my $n = shift; + return 0 if $n < 2; + for (2,3,5,7,11,13,17,19,23,29,31,37) { + return 0 unless $n <= $_ || is_strong_pseudoprime($n,$_); + } + 1; +} +for (1..100) { say if is_prime_mr($_) } diff --git a/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro b/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro new file mode 100644 index 0000000000..db250b459a --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Prolog/miller-rabin-primality-test.pro @@ -0,0 +1,83 @@ +:- module(primality, [is_prime/2]). + +% is_prime/2 returns false if N is composite, true if N probably prime +% implements a Miller-Rabin primality test and is deterministic for N < 3.415e+14, +% and is probabilistic for larger N. Adapted from the Erlang version. +is_prime(1, Ret) :- Ret = false, !. % 1 is non-prime +is_prime(2, Ret) :- Ret = true, !. % 2 is prime +is_prime(3, Ret) :- Ret = true, !. % 3 is prime +is_prime(N, Ret) :- + N > 3, (N mod 2 =:= 0), Ret = false, !. % even number > 3 is composite +is_prime(N, Ret) :- + N > 3, (N mod 2 =:= 1), % odd number > 3 + N < 341550071728321, + deterministic_witnesses(N, L), + is_mr_prime(N, L, Ret), !. % deterministic test +is_prime(N, Ret) :- + random_witnesses(N, 100, [], Out), + is_mr_prime(N, Out, Ret), !. % probabilistic test + +% returns list of deterministic witnesses +deterministic_witnesses(N, L) :- N < 1373653, + L = [2, 3]. +deterministic_witnesses(N, L) :- N < 9080191, + L = [31, 73]. +deterministic_witnesses(N, L) :- N < 25326001, + L = [2, 3, 5]. +deterministic_witnesses(N, L) :- N < 3215031751, + L = [2, 3, 5, 7]. +deterministic_witnesses(N, L) :- N < 4759123141, + L = [2, 7, 61]. +deterministic_witnesses(N, L) :- N < 1122004669633, + L = [2, 13, 23, 1662803]. +deterministic_witnesses(N, L) :- N < 2152302898747, + L = [2, 3, 5, 7, 11]. +deterministic_witnesses(N, L) :- N < 3474749660383, + L = [2, 3, 5, 7, 11, 13]. +deterministic_witnesses(N, L) :- N < 341550071728321, + L = [2, 3, 5, 7, 11, 13, 17]. + +% random_witnesses/4 returns a list of K witnesses selected at random with range 2 -> N-2 +random_witnesses(_, 0, T, T). +random_witnesses(N, K, T, Out) :- + G is N - 2, + H is 1 + random(G), + I is K - 1, + random_witnesses(N, I, [H | T], Out), !. + +% find_ds/2 receives odd integer N and returns [D, S] s.t. N-1 = 2^S * D +find_ds(N, L) :- + A is N - 1, + find_ds(A, 0, L), !. + +find_ds(D, S, L) :- + D mod 2 =:= 0, + P is D // 2, + Q is S + 1, + find_ds(P, Q, L), !. +find_ds(D, S, L) :- + L = [D, S]. + +is_mr_prime(N, As, Ret) :- + find_ds(N, L), + L = [D | T], + T = [S | _], + outer_loop(N, As, D, S, Ret), !. + +outer_loop(N, As, D, S, Ret) :- + As = [A | At], + Base is powm(A, D, N), + inner_loop(Base, N, 0, S, Result), + ( Result == false -> Ret = false + ; Result == true, At == [] -> Ret = true + ; outer_loop(N, At, D, S, Ret) + ). + +inner_loop(Base, N, Loop, S, Result) :- + Next_Base is (Base * Base) mod N, + Next_Loop is Loop + 1, + ( Loop =:= 0, Base =:= 1 -> Result = true + ; Base =:= N-1 -> Result = true + ; Next_Loop =:= S -> Result = false + ; inner_loop(Next_Base, N, Next_Loop, S, Result) + ). diff --git a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx index cfe4f194c6..34dcc2b712 100644 --- a/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx +++ b/Task/Miller-Rabin-primality-test/REXX/miller-rabin-primality-test.rexx @@ -1,31 +1,26 @@ -/*REXX program puts Miller-Rabin primality test through its paces. */ - -arg limit accur . /*get some arguments (if any). */ -if limit=='' | limit==',' then limit=1000 /*maybe assume LIMIT default*/ -if accur=='' | accur==',' then accur=10 /* " " ACCUR " */ -numeric digits max(200,2*limit) /*we're dealing with some biggies*/ -tell=accur<0 /*show primes if K is negative.*/ -accur=abs(accur) /*now, make K positive. */ -call suspenders /*suspenders now, belt later... */ +/*REXX program puts the Miller-Rabin primality test through its paces.*/ +parse arg limit accur . /*get some optional arguments*/ +if limit=='' | limit==',' then limit=1000 /*maybe assume LIMIT default.*/ +if accur=='' | accur==',' then accur=10 /* " " ACCUR " */ +numeric digits max(200, 2*limit) /*we're dealing with some biggies*/ +tell= accur<0 /*show primes if K is negative.*/ +accur=abs(accur) /*now, use absolute value of K.*/ +call suspenders limit /*suspenders now, belt later ··· */ primePi=# /*save the count of (real) primes*/ -say "There are" primePi 'primes ≤' limit /*might as well crow a wee bit.*/ +say "There are" primePi 'primes ≤' limit /*might as well crow a wee bit*/ say /*nothing wrong with whitespace. */ - do a=2 to accur /*(skipping 1) do range of K's.*/ + do a=2 to accur /*(skipping 1) do range of K's.*/ say copies('─',79) /*show separator for the eyeballs*/ mrp=0 /*prime counter for this pass. */ - - do z=1 for limit /*now, let's get busy and crank. */ + do z=1 for limit /*now, let's get busy and crank. */ p=Miller_Rabin(z,a) /*invoke and pray... */ - if p==0 then iterate /*Not prime? Then try another. */ + if p==0 then iterate /*Not prime? Then try another. */ mrp=mrp+1 /*well, found another one, by gum*/ - - if tell then say z, /*maybe should do a show & tell ?*/ + if tell then say z, /*maybe should do a show & tell ?*/ 'is prime according to Miller-Rabin primality test with K='a - - if !.z\==0 then iterate + if !.z\==0 then iterate say '[K='a"] " z "isn't prime !" /*oopsy-doopsy & whoopsy-daisy!*/ end /*z*/ - say 'for 1──►'limit", K="a', Miller-Rabin primality test found' mrp, 'primes {out of' primePi"}" end /*a*/ @@ -33,40 +28,35 @@ exit /*stick a fork in it, we're done.*/ /*─────────────────────────────────────Miller─Rabin primality test.─────*/ /*─────────────────────────────────────Rabin─Miller (also known as)─────*/ Miller_Rabin: procedure; parse arg n,k -if n==2 then return 1 /*special case of an even prime. */ -if n<2 | n//2==0 then return 0 /*check for low, or even number.*/ -d=n-1 +if n==2 then return 1 /*special case of an even prime. */ +if n<2 | n//2==0 then return 0 /*check for low, or even number.*/ +d=n-1 /*just a temp variable for speed.*/ nL=n-1 /*saves a bit of time, down below*/ -s=0 +s=0 /*teeter-toter variable (see-saw)*/ + do while d//2==0; d=d%2; s=s+1; end /*while d//2==0*/ - do while d//2==0; d=d%2; s=s+1; end /*while d//2==0 */ - - do k - a=random(2,nL) - x=(a**d) // n /*this number can get big fast. */ - if x==1 | x==nL then iterate - - do r=1 for s-1 - x=(x*x) // n - if x==1 then return 0 /*it's definitely not prime. */ - if x==nL then leave - end /*r*/ - - if x\==nL then return 0 /*nope, it ain't prime nohows. */ - end /*k*/ + do k; a=random(2,nL) + x=(a**d) // n /*this number can get big fast. */ + if x==1 | x==nL then iterate /*if so, try another power of A. */ + do r=1 for s-1; x=(x*x)//n /*compute new X ≡ X² modulus N.*/ + if x==1 then return 0 /*it's definitely not prime. */ + if x==nL then leave + end /*r*/ + if x\==nL then return 0 /*nope, it ain't prime nohows. */ + end /*k*/ /*maybe it is, maybe it ain't ...*/ return 1 /*coulda/woulda/shoulda be prime.*/ /*──────────────────────────────────SUSPENDERS subroutine───────────────*/ -suspenders: @.=0; !.=0 /*crank up the ole prime factory.*/ -@.1=2; @.2=3; @.3=5; #=3 /*prime the pump with low primes.*/ -!.2=1; !.3=1; !.5=1 /*and don't forget the water jar.*/ - - do j =@.#+2 by 2 to limit /*just process the odd integers. */ - do k=2 while @.k**2<=j /*let's do the ole primality test*/ - if j//@.k==0 then iterate j /*the Greek way, in days of yore.*/ - end /*k*/ /*a useless comment, but hey!! */ - #=#+1 /*bump the prime counter. */ - @.#=j /*keep priming the prime pump. */ - !.j=1 /*and keep filling the water jar.*/ +suspenders: parse arg high; @.=0; !.=0 /*crank up the ole prime factory.*/ +_='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' + do #=1 for words(_); p=word(_,#); @.#=p; s.#=p*p; !.p=1; end /*#*/ +#=#-1 /*adjust the # of primes so far. */ + do j=@.#+2 by 2 to high /*just process the odd integers. */ + if j//3==0 then iterate /*divisible by three? Yes, ¬prime*/ + if right(j,1)==5 then iterate /* " " five? " " */ + do k=4 while s.k<=j /*let's do the ole primality test*/ + if j//@.k==0 then iterate j /*the Greek way, in days of yore.*/ + end /*k*/ /*a useless comment, but hey!! */ + #=#+1; @.#=j; s.#=j*j; !.j=1 /*bump prime ctr, prime, primeidx*/ end /*j*/ /*this comment not left blank. */ return /*whew! All done with the primes*/ diff --git a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala new file mode 100644 index 0000000000..74cca99470 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-1.scala @@ -0,0 +1,6 @@ +import scala.math.BigInt + +object MillerRabinPrimalityTest extends App { + val (n, certainty )= (BigInt(args(0)), args(1).toInt) + println(s"$n is ${if (n.isProbablePrime(certainty)) "probably prime" else "composite"}") +} diff --git a/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala new file mode 100644 index 0000000000..2b3e896c00 --- /dev/null +++ b/Task/Miller-Rabin-primality-test/Scala/miller-rabin-primality-test-2.scala @@ -0,0 +1,38 @@ +import scala.annotation.tailrec +import scala.language.{implicitConversions, postfixOps} +import scala.util.Random + +object MillerRabin { + + implicit def int2Bools(b: Int): Seq[Boolean] = 31 to 0 by -1 map isBitSet(b) + + def isBitSet(byte: Int)(bit: Int): Boolean = ((byte >> bit) & 1) == 1 + + def mod(num: Int, denom: Int) = if (num % denom >= 0) num % denom else (num % denom) + denom + + @tailrec + def isSimple(p: Int, s: Int): Boolean = { + if (s == 0) { + true + } + else if (witness(Random.nextInt(p - 1), p)) { + false + } + else { + isSimple(p, s - 1) + } + } + + def witness(a: Int, p: Int): Boolean = { + val b: Seq[Boolean] = p - 1 + + b.foldLeft(1)((d, b) => if (mod(d * d, p) == 1 && d != 1 && d != p - 1) { + return true + } else { + b match { + case true => mod(mod(d*d, p)*a,p) + case false => mod(d*d, p) + } + }) != 1 + } +} diff --git a/Task/Minesweeper-game/00DESCRIPTION b/Task/Minesweeper-game/00DESCRIPTION index 50d11d44c3..8269177909 100644 --- a/Task/Minesweeper-game/00DESCRIPTION +++ b/Task/Minesweeper-game/00DESCRIPTION @@ -11,7 +11,7 @@ Positions in the grid are modified by entering their coordinates where the first :* If the point is free space then it is cleared, as are any adjacent points that are also free space- this is repeated recursively for subsequent adjacent free points unless that point is marked as a mine or is a mine. ::* Points marked as a mine show as a '?'. ::* Other free points show as an integer count of the number of adjacent true mines in its immediate neighbourhood, or as a single space ' ' if the free point is not adjacent to any true mines. -* Of course you lose if you try to clear space that has a hidden mine. +* Of course you lose if you try to cjhlear space that has a hidden mine. * You win when you have correctly identified all mines. The Task is to '''create a program that allows you to play minesweeper on a 6 by 4 grid, and that assumes all user input is formatted correctly''' and so checking inputs for correct form may be omitted. diff --git a/Task/Minesweeper-game/C++/minesweeper-game.cpp b/Task/Minesweeper-game/C++/minesweeper-game.cpp new file mode 100644 index 0000000000..837b2cd076 --- /dev/null +++ b/Task/Minesweeper-game/C++/minesweeper-game.cpp @@ -0,0 +1,223 @@ +#include +#include +#include +using namespace std; +typedef unsigned char byte; + +enum fieldValues : byte { OPEN, CLOSED = 10, MINE, UNKNOWN, FLAG, ERR }; + +class fieldData +{ +public: + fieldData() : value( CLOSED ), open( false ) {} + byte value; + bool open, mine; +}; + +class game +{ +public: + ~game() + { if( field ) delete [] field; } + + game( int x, int y ) + { + go = false; wid = x; hei = y; + field = new fieldData[x * y]; + memset( field, 0, x * y * sizeof( fieldData ) ); + oMines = ( ( 22 - rand() % 11 ) * x * y ) / 100; + mMines = 0; + int mx, my, m = 0; + for( ; m < oMines; m++ ) + { + do + { mx = rand() % wid; my = rand() % hei; } + while( field[mx + wid * my].mine ); + field[mx + wid * my].mine = true; + } + graphs[0] = ' '; graphs[1] = '.'; graphs[2] = '*'; + graphs[3] = '?'; graphs[4] = '!'; graphs[5] = 'X'; + } + + void gameLoop() + { + string c, r, a; + int col, row; + while( !go ) + { + drawBoard(); + cout << "Enter column, row and an action( c r a ):\nActions: o => open, f => flag, ? => unknown\n"; + cin >> c >> r >> a; + if( c[0] > 'Z' ) c[0] -= 32; if( a[0] > 'Z' ) a[0] -= 32; + col = c[0] - 65; row = r[0] - 49; + makeMove( col, row, a ); + } + } + +private: + void makeMove( int x, int y, string a ) + { + fieldData* fd = &field[wid * y + x]; + if( fd->open && fd->value < CLOSED ) + { + cout << "This cell is already open!"; + Sleep( 3000 ); return; + } + if( a[0] == 'O' ) openCell( x, y ); + else if( a[0] == 'F' ) + { + fd->open = true; + fd->value = FLAG; + mMines++; + checkWin(); + } + else + { + fd->open = true; + fd->value = UNKNOWN; + } + } + + bool openCell( int x, int y ) + { + if( !isInside( x, y ) ) return false; + if( field[x + y * wid].mine ) boom(); + else + { + if( field[x + y * wid].value == FLAG ) + { + field[x + y * wid].value = CLOSED; + field[x + y * wid].open = false; + mMines--; + } + recOpen( x, y ); + checkWin(); + } + return true; + } + + void drawBoard() + { + system( "cls" ); + cout << "Marked mines: " << mMines << " from " << oMines << "\n\n"; + for( int x = 0; x < wid; x++ ) + cout << " " << ( char )( 65 + x ) << " "; + cout << "\n"; int yy; + for( int y = 0; y < hei; y++ ) + { + yy = y * wid; + for( int x = 0; x < wid; x++ ) + cout << "+---"; + + cout << "+\n"; fieldData* fd; + for( int x = 0; x < wid; x++ ) + { + fd = &field[x + yy]; cout<< "| "; + if( !fd->open ) cout << ( char )graphs[1] << " "; + else + { + if( fd->value > 9 ) + cout << ( char )graphs[fd->value - 9] << " "; + else + { + if( fd->value < 1 ) cout << " "; + else cout << ( char )(fd->value + 48 ) << " "; + } + } + } + cout << "| " << y + 1 << "\n"; + } + for( int x = 0; x < wid; x++ ) + cout << "+---"; + + cout << "+\n\n"; + } + + void checkWin() + { + int z = wid * hei - oMines, yy; + fieldData* fd; + for( int y = 0; y < hei; y++ ) + { + yy = wid * y; + for( int x = 0; x < wid; x++ ) + { + fd = &field[x + yy]; + if( fd->open && fd->value != FLAG ) z--; + } + } + if( !z ) lastMsg( "Congratulations, you won the game!"); + } + + void boom() + { + int yy; fieldData* fd; + for( int y = 0; y < hei; y++ ) + { + yy = wid * y; + for( int x = 0; x < wid; x++ ) + { + fd = &field[x + yy]; + if( fd->value == FLAG ) + { + fd->open = true; + fd->value = fd->mine ? MINE : ERR; + } + else if( fd->mine ) + { + fd->open = true; + fd->value = MINE; + } + } + } + lastMsg( "B O O O M M M M M !" ); + } + + void lastMsg( string s ) + { + go = true; drawBoard(); + cout << s << "\n\n"; + } + + bool isInside( int x, int y ) { return ( x > -1 && y > -1 && x < wid && y < hei ); } + + void recOpen( int x, int y ) + { + if( !isInside( x, y ) || field[x + y * wid].open ) return; + int bc = getMineCount( x, y ); + field[x + y * wid].open = true; + field[x + y * wid].value = bc; + if( bc ) return; + + for( int yy = -1; yy < 2; yy++ ) + for( int xx = -1; xx < 2; xx++ ) + { + if( xx == 0 && yy == 0 ) continue; + recOpen( x + xx, y + yy ); + } + } + + int getMineCount( int x, int y ) + { + int m = 0; + for( int yy = -1; yy < 2; yy++ ) + for( int xx = -1; xx < 2; xx++ ) + { + if( xx == 0 && yy == 0 ) continue; + if( isInside( x + xx, y + yy ) && field[x + xx + ( y + yy ) * wid].mine ) m++; + } + + return m; + } + + int wid, hei, mMines, oMines; + fieldData* field; bool go; + int graphs[6]; +}; + +int main( int argc, char* argv[] ) +{ + srand( GetTickCount() ); + game g( 4, 6 ); g.gameLoop(); + return system( "pause" ); +} diff --git a/Task/Minesweeper-game/Julia/minesweeper-game-1.julia b/Task/Minesweeper-game/Julia/minesweeper-game-1.julia new file mode 100644 index 0000000000..98ae901594 --- /dev/null +++ b/Task/Minesweeper-game/Julia/minesweeper-game-1.julia @@ -0,0 +1,117 @@ +# Minesweeper: + +type Field + size::(Int, Int) + numbers::Array{Int, 2} + possible_mines::Array{Bool, 2} + actual_mines::Array{Bool, 2} + visible::Array{Bool, 2} +end + +function Field(x, y) + size = (x, y) + actual_mines = convert(Array{Bool, 2}, rand(x, y) .< 0.15) + possible_mines = zeros(Bool, x, y) + numbers = zeros(Int, x, y) + visible = zeros(Bool, x, y) + for i = 1:x + for j = 1:y + n = 0 + for di = -1:1 + for dj = -1:1 + n += (0 < di+i <= x && 0 < dj+j <= y) ? + (actual_mines[di+i, dj+j] ? 1 : 0) : 0 + end + end + numbers[i, j] = n + end + end + return Field(size, numbers, possible_mines, actual_mines, visible) +end + +function printfield(f::Field; showall = false) + spaces = int(floor(log(10, f.size[2]))) + + str = " "^(4+spaces) + for i in 1:f.size[1] + str *= string(" ", i, " ") + end + str *= "\n" * " "^(4+spaces) * "___"^f.size[1] * "\n" + for j = 1:f.size[2] + str *= " " * string(j) * " "^(floor(log(10, j)) > 0 ? 1 : spaces+1) * "|" + for i = 1:f.size[1] + if showall + str *= f.actual_mines[i, j] ? " * " : " " + else + if f.visible[i, j] + str *= " " * string(f.numbers[i, j] > 0 ? f.numbers[i, j] : " ") * " " + elseif f.possible_mines[i, j] + str *= " ? " + else + str *= " . " + end + end + end + str *= "\r\n" + end + println("Found " * string(length(f.possible_mines[f.possible_mines.==true])) * + " of " * string(length(f.actual_mines[f.actual_mines.==true])) * " mines.\n") + print(str) +end + +function parse_input(str::ASCIIString) + input = split(chomp(str), " ") + mode = input[1] + coords = length(input) > 1 ? (int(input[2]), int(input[3])) : (0, 0) + return mode, coords +end + +function eval_input(f::Field, str::ASCIIString) + mode, coords = parse_input(str) + (coords[1] > f.size[1] || coords[2] > f.size[2]) && return true + if mode == "o" + reveal(f, coords...) || return false + elseif mode == "m" && f.visible[coords...] == false + f.possible_mines[coords...] = !f.possible_mines[coords...] + elseif mode == "close" + error("You closed the game.") + end + return true +end + +function reveal(f::Field, x::Int, y::Int) + (x > f.size[1] || y > f.size[2]) && return true # check for index out of bounds + f.actual_mines[x, y] && return false # check for mines + f.visible[x, y] = true + if f.numbers[x, y] == 0 + for di = -1:1 + for dj = -1:1 + if (0 < di+x <= f.size[1] && 0 < dj+y <= f.size[2]) && + f.actual_mines[x+di, y+dj] == false && + f.visible[x+di, y+dj] == false + reveal(f, x+di, y+dj) + end + end + end + end + return true +end + +function play() + print("\nWelcome to Minesweeper\n\nEnter the gridsize (x y):\n") + s = split(readline(), " ") + f = Field(int(s[1]), int(s[2])) + won = false + while true + printfield(f) + print("\nWhat do you do? (\"o x y\" to reveal a field; \"m x y\" to toggle a mine; close)\n") + eval_input(f, readline()) || break + print("_"^80 * "\n") + (f.actual_mines == f.possible_mines || + f.visible == !f.actual_mines) && (won = true; break) + end + println(won ? "You won the game!" : "You lost the game:\n") + printfield(f, showall = true) +end + +play() diff --git a/Task/Minesweeper-game/Julia/minesweeper-game-2.julia b/Task/Minesweeper-game/Julia/minesweeper-game-2.julia new file mode 100644 index 0000000000..f3d9567784 --- /dev/null +++ b/Task/Minesweeper-game/Julia/minesweeper-game-2.julia @@ -0,0 +1,83 @@ +julia> include("minesweeper.jl") + +Welcome to Minesweeper + +Enter the gridsize (x y): +6 4 +Found 0 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | . . . . . . + 2 | . . . . . . + 3 | . . . . . . + 4 | . . . . . . + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +o 1 1 +________________________________________________________________________________ + +Found 0 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | 1 . . . . . + 2 | . . . . . . + 3 | . . . . . . + 4 | . . . . . . + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +o 1 2 +________________________________________________________________________________ + +Found 0 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | 1 . . . . . + 2 | 2 . . . . . + 3 | . . . . . . + 4 | . . . . . . + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +o 2 1 +________________________________________________________________________________ + +Found 0 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | 1 2 . . . . + 2 | 2 . . . . . + 3 | . . . . . . + 4 | . . . . . . + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +o 6 4 +________________________________________________________________________________ + +Found 0 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | 1 2 . . . . + 2 | 2 . 2 1 1 1 + 3 | . . 2 + 4 | . . 1 + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +m 2 2 +________________________________________________________________________________ + +Found 1 of 5 mines. + + 1 2 3 4 5 6 + __________________ + 1 | 1 2 . . . . + 2 | 2 ? 2 1 1 1 + 3 | . . 2 + 4 | . . 1 + +What do you do? ("o x y" to reveal a field; "m x y" to toggle a mine; close) +close +ERROR: You closed the game. diff --git a/Task/Minesweeper-game/MATLAB/minesweeper-game.m b/Task/Minesweeper-game/MATLAB/minesweeper-game.m new file mode 100644 index 0000000000..fb48a63565 --- /dev/null +++ b/Task/Minesweeper-game/MATLAB/minesweeper-game.m @@ -0,0 +1,243 @@ +function Minesweeper + + % Game parameters (should be modified by user) + nRows = 6; + nCols = 4; + percentMines = 0.15; + + % Create minefield + nMines = ceil(percentMines*nRows*nCols); + field = makeGrid(nRows, nCols, nMines); + + % Create timer for updating in axes title + stopwatch = timer('TimerFcn', {@updateTime, field}, ... + 'ExecutionMode', 'fixedRate', 'Period', 1, 'StartDelay', 1, ... + 'TasksToExecute', 999); + + % Specify callbacks + set(gcf, 'CloseRequestFcn', {@cleanUp, stopwatch}) + set(gca, 'ButtonDownFcn', {@onClick, field, stopwatch}) + + +end + +function field = makeGrid(nRows, nCols, nMines) + % Create minefield with unit squares + % Use quadrant IV to make indexing semi-consistent + % i.e. square in ith row, jth column has lower-right corner at (j, -i) + figure + set(gcf, 'Color', [1 1 1]) + axis([0 nCols -nRows 0]) + axis square + axis manual + hold on + set(gca, 'GridLineStyle', '-') + grid on + set(gca, 'XTick', 0:nCols) + set(gca, 'YTick', -nRows:0) + set(gca, 'XTickLabel', []) + set(gca, 'YTickLabel', []) + set(gca, 'Color', [0.6 0.6 0.6]) + setTitle(nMines, ': )', 0) + xlabel('left-click to dig, right-click to mark') + + % Set up field structure + % text will contain the handles to the labels in each square + % One character per square (or other functions will break) + % . Nothing noted + % M Marked as mine + % ? Marked as unknown + % 1-8 Digits indicate how many mines this square touches + % * Mine (game over) + % (blank) Square has been (dug) and is not mined nor touching any mines + % squares will contain handles to the colored "fill" objects + % fill objects will be deleted once square is "dug" + % Use ishandle() to determine if square is not yet dug + % mines will contain a logical array indicating positions of mines + % true Mine + % false No mine + % Later versions of MATLAB use gobjects() to preallocate text and squares + field = struct('text', zeros(nRows, nCols), ... + 'squares', zeros(nRows, nCols), ... + 'mines', false(nRows, nCols)); + + % Create individual square color and label objects + for r = 1:nRows + for c = 1:nCols + field.squares(r, c) = ... + fill([c-1 c-1 c c c-1], [-r+1 -r -r -r+1 -r+1], [0.9 0.9 0.9]); + set(field.squares(r, c), 'HitTest', 'off') + field.text(r, c) = text(c-0.5, -r+0.5, '.'); + set(field.text(r, c), 'FontSize', 12, 'FontWeight', 'bold', ... + 'HorizontalAlignment', 'center', 'HitTest', 'off'); + end + end + + % Place mines randomly without repeats + k = 0; + while k < nMines + idx = randi(nRows*nCols); + if ~field.mines(idx) + field.mines(idx) = true; + k = k+1; + end + end +end + +function onClick(obj, event, field, stopwatch) + if strcmp(stopwatch.Running, 'off') + start(stopwatch) + end + + pt = get(obj, 'CurrentPoint'); + r = ceil(-pt(1, 2)); + c = ceil(pt(1, 1)); + + if r > 0 && c > 0 && r <= size(field.squares, 1) && ... % Not yet been "dug" + c <= size(field.squares, 2) && ishandle(field.squares(r, c)) + buttons = {'normal' 'alt' 'extend'}; + btn = find(strcmp(get(get(obj, 'Parent'), 'SelectionType'), buttons)); + labels = '.M?'; % Unmarked, mine flag, unknown flag + currLabel = get(field.text(r, c), 'String'); + + if btn == 1 % Left click + if currLabel ~= labels(2); % Don't dig if flagged as mine + if field.mines(r, c) % Mine there -> you lose + gameLost(field, stopwatch, r, c) + else % No mine -> free to dig + minesLeft = countMineFlags(field); + digSquare(field, r, c) + if all(all(ishandle(field.squares) == field.mines)) + gameWon(field, stopwatch) + else + faceTimer = timer('StartDelay', 0.5, ... + 'StartFcn', {@setTitleOnTimer, minesLeft, ... + ': o', stopwatch.TasksExecuted}, ... + 'TimerFcn', {@setTitleOnTimer, minesLeft, ... + ': )', stopwatch.TasksExecuted}, ... + 'StopFcn', @deleteTimer); + start(faceTimer) + end + end + end + + elseif btn == 2 % Right-click + % Rotate through labels list to the next one + switch find(currLabel == labels) + case 1 + newLabel = labels(2); + case 2 + newLabel = labels(3); + case 3 + newLabel = labels(1); + end + set(field.text(r, c), 'String', newLabel); + setTitle(countMineFlags(field), ': )', stopwatch.TasksExecuted) + + elseif btn == 3 % Middle-click + % Mark/unmark unknown flag + if currLabel == labels(1) + set(field.text(r, c), 'String', labels(3)); + elseif currLabel == labels(3) + set(field.text(r, c), 'String', labels(1)); + end + end + end +end + +function updateTime(obj, event, field) + setTitle(countMineFlags(field), ': )', obj.TasksExecuted) +end + +function deleteTimer(obj, event) + delete(obj) +end + +function setTitleOnTimer(obj, event, mines, face, time) + setTitle(mines, face, time) +end + +function setTitle(mines, face, time) + title(sprintf('%03d Mines %s Timer %03d', mines, face, time)) +end + +function minesLeft = countMineFlags(field) +% Determine how many mines are unmarked (negative means too many mines marked) + minesLeft = sum(field.mines(:)); + for k = 1:numel(field.text) + if get(field.text(k), 'String') % Not an empty string + minesLeft = minesLeft-(get(field.text(k), 'String') == 'M'); + end + end +end + +function digSquare(field, r, c) +% If square is touching one or more mines then indicate the number +% Otherwise indicate no mines and dig surrounding squares recursively +% Assumes current square is clear of mines + delete(field.squares(r, c)) + [nRows, nCols] = size(field.mines); + surrR = [r-1 r r+1 r-1 r+1 r-1 r r+1]; + surrC = [c-1 c-1 c-1 c c c+1 c+1 c+1]; + toDelete = surrR < 1 | surrR > nRows | surrC < 1 | surrC > nCols; + surrR(toDelete) = []; + surrC(toDelete) = []; + nearMines = sum(field.mines(sub2ind([nRows nCols], surrR, surrC))); + label = sprintf('%d', nearMines); + textColor = [0 0 0 ; 0 0 1 ; 0 1 0 ; 1 0 0 ; 0.5 0.1 0.9 ; ... + 0.6 0 0 ; 0.2 0.5 0.3 ; 0.2 0.2 0.1 ; 0 0 0]; + if ~nearMines + label = ''; + for k = 1:length(surrR) + if ~field.mines(surrR(k), surrC(k)) && ... + ishandle(field.squares(surrR(k), surrC(k))) && ... + ~strcmp(get(field.text(k), 'String'), 'M') + digSquare(field, surrR(k), surrC(k)) + end + end + end + set(field.text(r, c), 'String', label, 'Color', textColor(nearMines+1, :)) +end + +function gameLost(field, stopwatch, r, c) + stop(stopwatch) + setTitle(countMineFlags(field), 'X (', stopwatch.TasksExecuted) + set(field.squares(r, c), 'FaceColor', [1 0 0]) + for k = 1:numel(field.text) + if field.mines(k) && any(get(field.text(k), 'String') == '.?') + set(field.text(k), 'String', '*', 'FontSize', 20) + elseif ~field.mines(k) && ishandle(field.squares(k)) && ... + get(field.text(k), 'String') == 'M' + set(field.text(k), 'String', 'X', 'Color', [1 0 0]) + end + end + set(gca, 'HitTest', 'off') + queryPlayAgain('Game over') +end + +function gameWon(field, stopwatch) +% Flag any leftover mines and indicate win + stop(stopwatch) + set(field.text(ishandle(field.squares)), 'String', 'M') + setTitle(0, 'B )', stopwatch.TasksExecuted) + set(gca, 'HitTest', 'off') + queryPlayAgain('Minefield cleared!') +end + +function queryPlayAgain(msg) +% Ask player if they want to play again +% Reset game by closing and reopening figure + choice = questdlg(sprintf('%s\nWould you like to play again?', msg), ... + '', 'Yes', 'No', 'No'); + if strcmp(choice, 'Yes') + close + Minesweeper + end +end + +function cleanUp(obj, event, stopwatch) +% Stop and close down all necessary processes + stop(stopwatch) + delete(stopwatch) + delete(obj) +end diff --git a/Task/Modular-exponentiation/D/modular-exponentiation.d b/Task/Modular-exponentiation/D/modular-exponentiation.d index c03044b1ec..385e1d4ce4 100644 --- a/Task/Modular-exponentiation/D/modular-exponentiation.d +++ b/Task/Modular-exponentiation/D/modular-exponentiation.d @@ -1,23 +1,30 @@ -import std.stdio, std.bigint; +module modular_exponentiation; -BigInt powMod(BigInt base, BigInt exponent, BigInt modulus) -in { +private import std.bigint; + +BigInt powMod(BigInt base, BigInt exponent, in BigInt modulus) +pure nothrow /*@safe*/ in { assert(exponent >= 0); } body { BigInt result = 1; - while (exponent > 0) { - if (exponent % 2 == 1) + + while (exponent) { + if (exponent & 1) result = (result * base) % modulus; exponent /= 2; base = base ^^ 2 % modulus; } + return result; } -void main() { - powMod(BigInt("29883481620585741369158914214988194" ~ - "66320163312926952423791023078876139"), - BigInt("235139930337346448646612254452369009" ~ - "4744975233415544072992656881240319"), - BigInt(10) ^^ 40).writeln(); -} +version (modular_exponentiation) + void main() { + import std.stdio; + + powMod(BigInt("29883481620585741369158914214988194" ~ + "66320163312926952423791023078876139"), + BigInt("235139930337346448646612254452369009" ~ + "4744975233415544072992656881240319"), + BigInt(10) ^^ 40).writeln; + } diff --git a/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx b/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx new file mode 100644 index 0000000000..8b05ceab08 --- /dev/null +++ b/Task/Modular-exponentiation/REXX/modular-exponentiation-1.rexx @@ -0,0 +1,25 @@ +/*REXX program displays modular exponentation: a**b mod M */ +parse arg a b mm /*get optional args from CL.*/ +if a=='' | a==',' then a=2988348162058574136915891421498819466320163312926952423791023078876139 +if b=='' | b==',' then b=2351399303373464486466122544523690094744975233415544072992656881240319 +if mm='' | mm=',' then mm=40 /*MM specified? Use default.*/ +say 'a=' a; say ' ('length(a) "digits)" /*show value of A.*/ +say 'b=' b; say ' ('length(b) "digits)" /* " " " B.*/ + + do j=1 for words(mm); m=word(mm,j) /*use one of the MM powers.*/ + say copies('─',linesize()-1) /*show a nice separator line*/ + say 'a**b (mod 10**'m")=" powerModulated(a,b,10**m) /*show ans*/ + end /*j*/ +exit /*stick a fork in it; done.*/ +/*──────────────────────────────────────POWERMODULATED subroutine───────*/ +powerModulated: procedure; parse arg x,p,n /*fast modular exponentation*/ +if p==0 then return 1 /*special case of P = zero. */ +if p==1 then return x /* " " " " = unity.*/ +if p<0 then do; say '***error!*** power is negative:' p; exit 13; end +parse value max(x**2,p,n)'E0' with "E" e /*pick biggest of the three.*/ +numeric digits max(20,e*2) /*big enough to handle A² */ +_=1 /*use this for the 1st value*/ + do while p\==0; if p//2==1 then _=_*x//n /*is P odd? */ + p=p%2; x=x*x//n /*halve P; calc x² mod n */ + end /*while*/ /* [↑] keep moding 'til =0.*/ +return _ diff --git a/Task/Modular-exponentiation/REXX/modular-exponentiation-2.rexx b/Task/Modular-exponentiation/REXX/modular-exponentiation-2.rexx new file mode 100644 index 0000000000..267c378be2 --- /dev/null +++ b/Task/Modular-exponentiation/REXX/modular-exponentiation-2.rexx @@ -0,0 +1,22 @@ +/* Modular exponentiation */ + +numeric digits 100 +say powerMod(, + 2988348162058574136915891421498819466320163312926952423791023078876139,, + 2351399303373464486466122544523690094744975233415544072992656881240319,, + 1e40) +exit + +powerMod: procedure + +parse arg base, exponent, modulus + +exponent = strip(x2b(d2x(exponent)), 'L', '0') +result = 1 +base = base // modulus +do exponentPos=length(exponent) to 1 by -1 + if substr(exponent, exponentPos, 1) = '1' + then result = (result * base) // modulus + base = (base * base) // modulus +end +return result diff --git a/Task/Modular-exponentiation/REXX/modular-exponentiation.rexx b/Task/Modular-exponentiation/REXX/modular-exponentiation.rexx deleted file mode 100644 index 32a0c2311f..0000000000 --- a/Task/Modular-exponentiation/REXX/modular-exponentiation.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX program to show modular exponentation: a**b mod M */ -parse arg a b mm /*get the arguments (maybe).*/ -if a=='' | a==',' then a=, - 2988348162058574136915891421498819466320163312926952423791023078876139 - -if b=='' | b==',' then b=, - 2351399303373464486466122544523690094744975233415544072992656881240319 - -if mm=='' then mm=40 -say 'a=' a; say ' ('length(a) "digits)" -say 'b=' b; say ' ('length(b) "digits)" - - do j=1 for words(mm); m=word(mm,j); say copies('─',linesize()-1) - say 'a**b (mod 10**'m")=" powerModulated(a,b,10**m) - end /*j*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────────POWERMODULATED subroutine───────*/ -powerModulated: procedure; parse arg x,p,n /*fast modular exponentation*/ -if p==0 then return 1 /*special case. */ -if p==1 then return x /*special case. */ -if p<0 then do; say '***error!*** power is negative:' p; exit 13; end -parse value max(x**2,p,n)'E0' with "E" e /*pick biggest of the three.*/ -numeric digits max(20,e*2) /*big enough to handle A² */ -_=1 - do while p\==0; if p//2==1 then _=_*x//n - p=p%2; x=x*x // n - end /*while*/ -return _ diff --git a/Task/Modular-exponentiation/Racket/modular-exponentiation.rkt b/Task/Modular-exponentiation/Racket/modular-exponentiation.rkt new file mode 100644 index 0000000000..ea35a93e0e --- /dev/null +++ b/Task/Modular-exponentiation/Racket/modular-exponentiation.rkt @@ -0,0 +1,6 @@ +#lang racket +(require math) +(define a 2988348162058574136915891421498819466320163312926952423791023078876139) +(define b 2351399303373464486466122544523690094744975233415544072992656881240319) +(define m (expt 10 40)) +(modular-expt a b m) diff --git a/Task/Modular-inverse/00DESCRIPTION b/Task/Modular-inverse/00DESCRIPTION index c9071c1a1a..77540281ff 100644 --- a/Task/Modular-inverse/00DESCRIPTION +++ b/Task/Modular-inverse/00DESCRIPTION @@ -9,4 +9,6 @@ Or in other words, such that: It can be shown that such an inverse exists if and only if a and m are [[wp:coprime|coprime]], but we will ignore this for this task. -Either by implementing the algorithm, by using a dedicated library or by using a builtin function in your language, compute the modular inverse of 42 modulo 2017. +Either by implementing the algorithm, by using a dedicated library +or by using a builtin function in your language, +compute the modular inverse of 42 modulo 2017. diff --git a/Task/Modular-inverse/AWK/modular-inverse.awk b/Task/Modular-inverse/AWK/modular-inverse.awk new file mode 100644 index 0000000000..ef6e78dc49 --- /dev/null +++ b/Task/Modular-inverse/AWK/modular-inverse.awk @@ -0,0 +1,27 @@ +# syntax: GAWK -f MODULAR_INVERSE.AWK +# converted from C +BEGIN { + printf("%s\n",mod_inv(42,2017)) + exit(0) +} +function mod_inv(a,b, b0,t,q,x0,x1) { + b0 = b + x0 = 0 + x1 = 1 + if (b == 1) { + return(1) + } + while (a > 1) { + q = int(a / b) + t = b + b = int(a % b) + a = t + t = x0 + x0 = x1 - q * x0 + x1 = t + } + if (x1 < 0) { + x1 += b0 + } + return(x1) +} diff --git a/Task/Modular-inverse/Ada/modular-inverse-1.ada b/Task/Modular-inverse/Ada/modular-inverse-1.ada new file mode 100644 index 0000000000..144737c41b --- /dev/null +++ b/Task/Modular-inverse/Ada/modular-inverse-1.ada @@ -0,0 +1,11 @@ +package Mod_Inv is + + procedure X_GCD(A, B: in Natural; D, X, Y: out Integer); + -- the Extended Euclidean Algorithm + -- finds (D, X, Y) with D = GCD(A, B) = A*X + B*Y + + function Inverse(A, M: Integer) return Integer; + -- computes the multiplicative inverse Inv_A of A mod M, using X_GCD + -- raises Constraint_Error if Inv_A does not exist + +end Mod_Inv; diff --git a/Task/Modular-inverse/Ada/modular-inverse.ada b/Task/Modular-inverse/Ada/modular-inverse-2.ada similarity index 80% rename from Task/Modular-inverse/Ada/modular-inverse.ada rename to Task/Modular-inverse/Ada/modular-inverse-2.ada index fc8cdfbc54..69a034dd24 100644 --- a/Task/Modular-inverse/Ada/modular-inverse.ada +++ b/Task/Modular-inverse/Ada/modular-inverse-2.ada @@ -1,6 +1,4 @@ -with Ada.Text_IO; - -procedure Mod_Inv is +package body Mod_Inv is procedure X_GCD(A, B: in Natural; D, X, Y: out Integer) is -- the Extended Euclidean Algorithm @@ -35,8 +33,4 @@ procedure Mod_Inv is end if; end Inverse; -begin - Ada.Text_IO.Put_Line(Natural'Image(Inverse(42, 2017))); - -- Ada.Text_IO.Put_Line(Natural'Image(Inverse(154, 3311))); - -- The above would raise CONSTRAINT_ERROR : GCD ( 154, 3311 ) = 77 /= 1 end Mod_Inv; diff --git a/Task/Modular-inverse/Ada/modular-inverse-3.ada b/Task/Modular-inverse/Ada/modular-inverse-3.ada new file mode 100644 index 0000000000..c8fdf4306d --- /dev/null +++ b/Task/Modular-inverse/Ada/modular-inverse-3.ada @@ -0,0 +1,9 @@ +with Ada.Text_IO; with Mod_Inv; use Mod_Inv, Ada.text_IO; + +procedure Mod_Inv_Test is +begin + -- Put_Line(Natural'Image(Inverse(154, 3311))); + -- The above would raise CONSTRAINT_ERROR : GCD ( 154, 3311 ) = 77 /= 1 + + Put_Line(Natural'Image(Inverse(42, 2017))); +end Mod_Inv_Test; diff --git a/Task/Modular-inverse/C/modular-inverse-1.c b/Task/Modular-inverse/C/modular-inverse-1.c new file mode 100644 index 0000000000..b9fb3014a0 --- /dev/null +++ b/Task/Modular-inverse/C/modular-inverse-1.c @@ -0,0 +1,20 @@ +#include + +int mul_inv(int a, int b) +{ + int b0 = b, t, q; + int x0 = 0, x1 = 1; + if (b == 1) return 1; + while (a > 1) { + q = a / b; + t = b, b = a % b, a = t; + t = x0, x0 = x1 - q * x0, x1 = t; + } + if (x1 < 0) x1 += b0; + return x1; +} + +int main(void) { + printf("%d\n", mul_inv(42, 2017)); + return 0; +} diff --git a/Task/Modular-inverse/C/modular-inverse-2.c b/Task/Modular-inverse/C/modular-inverse-2.c new file mode 100644 index 0000000000..c37cfbf21d --- /dev/null +++ b/Task/Modular-inverse/C/modular-inverse-2.c @@ -0,0 +1,25 @@ +#include + +int mul_inv(int a, int b) +{ + int t, nt, r, nr, q, tmp; + if (b < 0) b = -b; + if (a < 0) a = b - (-a % b); + t = 0; nt = 1; r = b; nr = a % b; + while (nr != 0) { + q = r/nr; + tmp = nt; nt = t - q*nt; t = tmp; + tmp = nr; nr = r - q*nr; r = tmp; + } + if (r > 1) return -1; /* No inverse */ + if (t < 0) t += b; + return t; +} +int main(void) { + printf("%d\n", mul_inv(42, 2017)); + printf("%d\n", mul_inv(40, 1)); + printf("%d\n", mul_inv(52, -217)); /* Pari semantics for negative modulus */ + printf("%d\n", mul_inv(-486, 217)); + printf("%d\n", mul_inv(40, 2018)); + return 0; +} diff --git a/Task/Modular-inverse/C/modular-inverse.c b/Task/Modular-inverse/C/modular-inverse.c deleted file mode 100644 index eb2ef6b5a0..0000000000 --- a/Task/Modular-inverse/C/modular-inverse.c +++ /dev/null @@ -1,18 +0,0 @@ -#include -int modularinverse( int a, int b){ - int c=b/a,x=0; - do{ - if((a ',modinv(x,y)) + (Skip,3(a,f(4))); + modinv: Proc(a,b) Returns(Bin Fixed(31)); + Dcl (a,b,ob,ox,d,t) Bin Fixed(31); + ob=b; + ox=0; + d=1; + + If b=1 Then; + Else Do; + Do While(a>1); + q=a/b; + r=mod(a,b); + a=b; + b=r; + t=ox; + ox=d-q*ox; + d=t; + End; + End; + If d<0 Then + d=d+ob; + Return(d); + End; + End; diff --git a/Task/Modular-inverse/Perl/modular-inverse-1.pl b/Task/Modular-inverse/Perl/modular-inverse-1.pl new file mode 100644 index 0000000000..6fac101f33 --- /dev/null +++ b/Task/Modular-inverse/Perl/modular-inverse-1.pl @@ -0,0 +1,9 @@ +use bigint; say 42->bmodinv(2017); +# or +use Math::ModInt qw/mod/; say mod(42, 2017)->inverse->residue; +# or +use Math::Pari qw/PARI lift/; say lift PARI "Mod(1/42,2017)"; +# or +use Math::GMP qw/:constant/; say 42->bmodinv(2017); +# or +use ntheory qw/invmod/; say invmod(42, 2017); diff --git a/Task/Modular-inverse/Perl/modular-inverse-2.pl b/Task/Modular-inverse/Perl/modular-inverse-2.pl new file mode 100644 index 0000000000..bb42b29c47 --- /dev/null +++ b/Task/Modular-inverse/Perl/modular-inverse-2.pl @@ -0,0 +1,15 @@ +sub invmod { + my($a,$n) = @_; + my($t,$nt,$r,$nr) = (0, 1, $n, $a % $n); + while ($nr != 0) { + # Use this instead of int($r/$nr) to get exact unsigned integer answers + my $quot = int( ($r - ($r % $nr)) / $nr ); + ($nt,$t) = ($t-$quot*$nt,$nt); + ($nr,$r) = ($r-$quot*$nr,$nr); + } + return if $r > 1; + $t += $n if $t < 0; + $t; +} + +say invmod(42,2017); diff --git a/Task/Modular-inverse/Perl/modular-inverse.pl b/Task/Modular-inverse/Perl/modular-inverse.pl deleted file mode 100644 index 8cedc10c73..0000000000 --- a/Task/Modular-inverse/Perl/modular-inverse.pl +++ /dev/null @@ -1,2 +0,0 @@ -use Math::ModInt qw(mod); -print mod(42, 2017)->inverse diff --git a/Task/Modular-inverse/PicoLisp/modular-inverse.l b/Task/Modular-inverse/PicoLisp/modular-inverse.l new file mode 100644 index 0000000000..e3c0b60df0 --- /dev/null +++ b/Task/Modular-inverse/PicoLisp/modular-inverse.l @@ -0,0 +1,17 @@ +(de modinv (A B) + (let (B0 B X0 0 X1 1 Q 0 T1 0) + (while (< 1 A) + (setq + Q (/ A B) + T1 B + B (% A B) + A T1 + T1 X0 + X0 (- X1 (* Q X0)) + X1 T1 ) ) + (if (lt0 X1) (+ X1 B0) X1) ) ) + +(println + (modinv 42 2017) ) + +(bye) diff --git a/Task/Monte-Carlo-methods/00DESCRIPTION b/Task/Monte-Carlo-methods/00DESCRIPTION index e6c4b0c62b..1b0e87e385 100644 --- a/Task/Monte-Carlo-methods/00DESCRIPTION +++ b/Task/Monte-Carlo-methods/00DESCRIPTION @@ -1,6 +1,22 @@ -A '''Monte Carlo Simulation''' is a way of approximating the value of a function where calculating the actual value is difficult or impossible. It uses random sampling to define constraints on the value and then makes a sort of "best guess." +A '''Monte Carlo Simulation''' is a way of approximating the value of a function +where calculating the actual value is difficult or impossible.
+It uses random sampling to define constraints on the value +and then makes a sort of "best guess." -A simple Monte Carlo Simulation can be used to calculate the value for π. If you had a circle and a square where the length of a side of the square was the same as the diameter of the circle, the ratio of the area of the circle to the area of the square would be π/4. So, if you put this circle inside the square and select many random points inside the square, the number of points inside the circle divided by the number of points inside the square and the circle would be approximately π/4. +A simple Monte Carlo Simulation can be used to calculate the value for π. +If you had a circle and a square where the length of a side of the square +was the same as the diameter of the circle, the ratio of the area of the circle +to the area of the square would be π/4. -Write a function to run a simulation like this with a variable number of random points to select. Also, show the results of a few different sample sizes. -For software where the number π is not built-in, we give π to a couple of digits: 3.141592653589793238462643383280 +So, if you put this circle inside the square and select many random points +inside the square, the number of points inside the circle +divided by the number of points inside the square and the circle +would be approximately π/4. + +Write a function to run a simulation like this, with a variable number +of random points to select.
+Also, show the results of a few different sample sizes. + +For software where the number π is not built-in, +we give π to a couple of digits: +3.141592653589793238462643383280 diff --git a/Task/Monte-Carlo-methods/C/monte-carlo-methods.c b/Task/Monte-Carlo-methods/C/monte-carlo-methods.c index 6e779b8792..d7d95dda9f 100644 --- a/Task/Monte-Carlo-methods/C/monte-carlo-methods.c +++ b/Task/Monte-Carlo-methods/C/monte-carlo-methods.c @@ -16,7 +16,7 @@ double pi(double tolerance) } val = (double) hit / sampled; - error = val * sqrt(val * (1 - val) / sampled) * 4; + error = sqrt(val * (1 - val) / sampled) * 4; val *= 4; /* some feedback, or user gets bored */ diff --git a/Task/Monte-Carlo-methods/D/monte-carlo-methods-1.d b/Task/Monte-Carlo-methods/D/monte-carlo-methods-1.d index 5c952bdd4d..cd0a9eb0ab 100644 --- a/Task/Monte-Carlo-methods/D/monte-carlo-methods-1.d +++ b/Task/Monte-Carlo-methods/D/monte-carlo-methods-1.d @@ -1,14 +1,14 @@ import std.stdio, std.random, std.math; -double pi(in int nthrows) { - int inside; - foreach (i; 0 .. nthrows) - if (hypot(uniform(0, 1.0), uniform(0, 1.0)) <= 1) +double pi(in uint nthrows) /*nothrow*/ @safe /*@nogc*/ { + uint inside; + foreach (immutable i; 0 .. nthrows) + if (hypot(uniform01, uniform01) <= 1) inside++; return 4.0 * inside / nthrows; } 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/D/monte-carlo-methods-2.d b/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d index 5545d1ce42..498f71c8c7 100644 --- a/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d +++ b/Task/Monte-Carlo-methods/D/monte-carlo-methods-2.d @@ -1,9 +1,9 @@ -import std.stdio, std.random, std.math, std.algorithm, std.range; - -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() { + import std.stdio, std.random, std.math, std.algorithm, std.range; + + immutable isIn = (int) => hypot(uniform01, uniform01) <= 1; + immutable pi = (in int n) => 4.0 * n.iota.count!isIn / n; + foreach (immutable p; 1 .. 8) writefln("%10s: %07f", 10 ^^ p, pi(10 ^^ p)); } diff --git a/Task/Monte-Carlo-methods/Haskell/monte-carlo-methods.hs b/Task/Monte-Carlo-methods/Haskell/monte-carlo-methods.hs index f7a1aad3da..76eca419c2 100644 --- a/Task/Monte-Carlo-methods/Haskell/monte-carlo-methods.hs +++ b/Task/Monte-Carlo-methods/Haskell/monte-carlo-methods.hs @@ -2,7 +2,7 @@ import System.Random import Control.Monad get_pi throws = do results <- replicateM throws one_trial - return (4 * fromIntegral (foldl' (+) 0 results) / fromIntegral throws) + return (4 * fromIntegral (foldl (+) 0 results) / fromIntegral throws) where one_trial = do rand_x <- randomRIO (-1, 1) rand_y <- randomRIO (-1, 1) diff --git a/Task/Monte-Carlo-methods/Java/monte-carlo-methods.java b/Task/Monte-Carlo-methods/Java/monte-carlo-methods-1.java similarity index 100% rename from Task/Monte-Carlo-methods/Java/monte-carlo-methods.java rename to Task/Monte-Carlo-methods/Java/monte-carlo-methods-1.java diff --git a/Task/Monte-Carlo-methods/Java/monte-carlo-methods-2.java b/Task/Monte-Carlo-methods/Java/monte-carlo-methods-2.java new file mode 100644 index 0000000000..8b99c658b3 --- /dev/null +++ b/Task/Monte-Carlo-methods/Java/monte-carlo-methods-2.java @@ -0,0 +1,44 @@ +package montecarlo; + +import java.util.stream.IntStream; +import java.util.stream.DoubleStream; + +import static java.lang.Math.random; +import static java.lang.Math.hypot; +import static java.lang.System.out; + +public interface MonteCarlo { + public static void main(String... arguments) { + IntStream.of( + 10000, + 100000, + 1000000, + 10000000, + 100000000 + ) + .mapToDouble(MonteCarlo::pi) + .forEach(out::println) + ; + } + + public static double range() { + //a square with a side of length 2 centered at 0 has + //x and y range of -1 to 1 + return (random() * 2) - 1; + } + + public static double pi(int numThrows){ + long inCircle = DoubleStream.generate( + //distance from (0,0) = hypot(x, y) + () -> hypot(range(), range()) + ) + .limit(numThrows) + .unordered() + .parallel() + //circle with diameter of 2 has radius of 1 + .filter(d -> d < 1) + .count() + ; + return (4.0 * inCircle) / numThrows; + } +} diff --git a/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima b/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima index cf825ed96a..07d5030725 100644 --- a/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima +++ b/Task/Monte-Carlo-methods/Maxima/monte-carlo-methods.maxima @@ -1,8 +1,8 @@ -load(distrib); +load("distrib"); approx_pi(n):= block( [x: random_continuous_uniform(0, 1, n), y: random_continuous_uniform(0, 1, n), - r, cin: 0], + r, cin: 0, listarith: true], r: x^2 + y^2, for r0 in r do if r0<1 then cin: cin + 1, 4*cin/n); diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 index 8ad5416e1c..2b2c50251d 100644 --- a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 +++ b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-1.pl6 @@ -1,10 +1,9 @@ -sub approximate_pi (Int $sample_size) { - my Int $in = 0; - (rand - 1/2)**2 + (rand - 1/2)**2 < 1/4 and ++$in - for ^$sample_size; - return 4 * $in / $sample_size; +my @random_distances := ([+] rand**2 xx 2) xx *; + +sub approximate_pi(Int $n) { + 4 * @random_distances[^$n].grep(* < 1) / $n } -say 'n = 100: ', approximate_pi 100; -say 'n = 1,000: ', approximate_pi 1_000; -say 'n = 10,000: ', approximate_pi 10_000; +say "Monte-Carlo π approximation:"; +say "$_ iterations: ", approximate_pi $_ + for 100, 1_000, 10_000; diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 index a38ae8df2e..e5e73c32ba 100644 --- a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 +++ b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods-2.pl6 @@ -1,6 +1,2 @@ -sub approximate_pi (Int $sample_size) { - $sample_size R/ [+] - 4 xx grep 0 ..^ 1/4, - (rand - 1/2)**2 + (rand - 1/2)**2 xx - $sample_size; -} +my @pi := ([\+] 4 * (1 > [+] rand**2 xx 2) xx *) Z/ 1 .. *; +say @pi[10, 1000, 10_000]; diff --git a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 b/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 deleted file mode 100644 index 2b2c50251d..0000000000 --- a/Task/Monte-Carlo-methods/Perl-6/monte-carlo-methods.pl6 +++ /dev/null @@ -1,9 +0,0 @@ -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/Monte-Carlo-methods/Python/monte-carlo-methods-3.py b/Task/Monte-Carlo-methods/Python/monte-carlo-methods-3.py index c4c9b77987..3b12da3dc8 100644 --- a/Task/Monte-Carlo-methods/Python/monte-carlo-methods-3.py +++ b/Task/Monte-Carlo-methods/Python/monte-carlo-methods-3.py @@ -1,4 +1,4 @@ import numpy as np n = input('Number of samples: ') -print np.sum(np.random.rand(n)**2+np.random.rand(n)<1)/float(n)*4 +print np.sum(np.random.rand(n)**2+np.random.rand(n)**2<1)/float(n)*4 diff --git a/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx b/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx index 75c088fa57..2b6f83b8c8 100644 --- a/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx +++ b/Task/Monte-Carlo-methods/REXX/monte-carlo-methods.rexx @@ -1,36 +1,33 @@ -/*REXX program uses the Monte Carlo method to compute pi÷4 */ +/*REXX program computes pi÷4 using the Monte Carlo algorithm. */ parse arg times chunks . /*does user want a specific num? */ -if times=='' then times=1000000000 /*one billion should do it. */ -if chunks=='' then chunks=10000 /*do Monte Carle in 10k chunks. */ +if times=='' then times=1000000000 /*one billion should do it. */ +if chunks=='' then chunks=10000 /*do Monte Carlo in 10k chunks. */ limit=10000-1 /*REXX random gens only integers.*/ -limitSq=limit**2 /*...so, instead of 1, use lim**2*/ +limitSq=limit**2 /*···so, instead of 1, use lim**2*/ !=0 /*number of "pi hits" so far. */ accur=0 /*accuracy of the Monte Carlo pi.*/ -if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */ - else piChar='e3'x /*if ASCII, then use symbol. */ +if 1=='f1'x then piChar='pi' /*if EBCDIC, then use literal. */ + else piChar='e3'x /*if ASCII, then use pi symbol.*/ pi=3.14159265358979323846264338327950288419716939937511 /*da real McCoy*/ numeric digits length(pi) /*at least, we'll use these digs.*/ say 'real pi='pi"+" /*might was well brag about it. */ say /*just for the eyeballs. */ - do j=1 for times%chunks - do chunks /*do Monte Carlo, chunk-at-a-time*/ - if random(0,limit)**2+random(0,limit)**2<=limitSq then !=!+1 - end + do j=1 for times%chunks + do chunks /*do Monte Carlo, chunk-at-a-time*/ + if random(0,limit)**2 + random(0,limit)**2 <=limitSq then !=!+1 + end /*chunks*/ reps=chunks*j /*compute number of repetitions. */ piX=4*!/reps /*let's see how this puppy does. */ - _=compare(piX,pi) /*compare apples & ...crabapples.*/ - if _<=accur then iterate /*if not better accuracy, pout. */ + _=compare(piX,pi) /*compare apples & ···crabapples.*/ + if _<=accur then iterate /*if not better accuracy, pout. */ say right(comma(reps),20) 'repetitions: Monte Carlo' piChar, "is accurate to" _-1 'places.' /*subtract 1 for dec point.*/ accur=_ /*use this accuracy for baseline.*/ - end /*j*/ + end /*j*/ exit /*stick a fork in it, we're done.*/ -/*────────────────────────────────COMMA subroutine──────────────────────*/ -comma: procedure; parse arg _,c,p,t; arg ,cu; c=word(c ",",1) -if cu=='BLANK' then c=' '; o=word(p 3,1); p=abs(o); t=word(t 999999999,1) -if \datatype(p,'W') | \datatype(t,'W')|p==0|arg()>4 then return _; n=_'.9' -#=123456789; k=0; if o<0 then do; b=verify(_,' '); if b==0 then return _ -e=length(_) - verify(reverse(_),' ') + 1; end; else do; b=verify(n,#,"M") -e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end -do j=e to b by -p while k4 then return _; n=_'.9'; #=123456789; k=0; if o<0 then do; b=verify(_,' ') +if b==0 then return _; e=length(_) - verify(reverse(_),' ') + 1; end; else do; +b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end; do j=e to b by -p while kand show the results in such a way as to make it easy to compare the effects of each strategy. + +;Reference: +* [https://www.youtube.com/watch?v=4Lb-6rxZxx0 Monty Hall Problem - Numberphile]. (Video). diff --git a/Task/Monty-Hall-problem/Python/monty-hall-problem.py b/Task/Monty-Hall-problem/Python/monty-hall-problem-1.py similarity index 100% rename from Task/Monty-Hall-problem/Python/monty-hall-problem.py rename to Task/Monty-Hall-problem/Python/monty-hall-problem-1.py diff --git a/Task/Monty-Hall-problem/Python/monty-hall-problem-2.py b/Task/Monty-Hall-problem/Python/monty-hall-problem-2.py new file mode 100644 index 0000000000..fd741d487d --- /dev/null +++ b/Task/Monty-Hall-problem/Python/monty-hall-problem-2.py @@ -0,0 +1,33 @@ +import random + #1 represents a car + #0 represent a goat + +stay = 0 #amount won if stay in the same position +switch = 0 # amount won if you switch + +for i in range(1000): + lst = [1,0,0] # one car and two goats + random.shuffle(lst) # shuffles the list randomly + + ran = random.randrange(3) # gets a random number for the random guess + + user = lst[ran] #storing the random guess + + del(lst[ran]) # deleting the random guess + + huh = 0 + for i in lst: # getting a value 0 and deleting it + if i ==0: + del(lst[huh]) # deletes a goat when it finds it + break + huh+=1 + + if user ==1: # if the original choice is 1 then stay adds 1 + stay+=1 + + if lst[0] == 1: # if the switched value is 1 then switch adds 1 + switch+=1 + +print("Stay =",stay) +print("Switch = ",switch) +#Done by Sam Witton 09/04/2014 diff --git a/Task/Monty-Hall-problem/Scilab/monty-hall-problem.scilab b/Task/Monty-Hall-problem/Scilab/monty-hall-problem.scilab new file mode 100644 index 0000000000..98b5fa8d96 --- /dev/null +++ b/Task/Monty-Hall-problem/Scilab/monty-hall-problem.scilab @@ -0,0 +1,38 @@ +// How it works: +// MontyHall() is a function with argument switch: +// it will be called 100000 times with switch=%T, +// and another 100000 times with switch=%F + +function win=MontyHall(switch) //If switch==%T the player will switch + doors=zeros(1,3) //All goats + car=grand(1,1,'uin',1,3) + a(car)=1 //Place a car somewher + pick=grand(1,1,'uin',1,3) //The player picks... + if pick==car then //If the player picks right... + if switch==%T then //...and switches he will be wrong + win=%F + else //...but if he doesn't, he will be right + win=%T + end + else //If the player picks a goat... + if switch==%T then //...and switches: the other door with the goat shall be + win=%T // opened: the player will switch to the car and win + else //...but if he doesn't, he will remain by his goat + win=%F + end + end +endfunction + +wins_switch=0 +wins_stay=0 +games=100000 +for i=1:games + if MontyHall(%T)==%T then + wins_switch=wins_switch+1 + end + if MontyHall(%F)==%T then + wins_stay=wins_stay+1 + end +end +disp("Switching, one wins"+ascii(10)+string(wins_switch)+" games out of "+string(games)) +disp("Staying, one wins"+ascii(10)+string(wins_stay)+" games out of "+string(games)) diff --git a/Task/Morse-code/00DESCRIPTION b/Task/Morse-code/00DESCRIPTION index d19bbc3454..0bf9cf96d2 100644 --- a/Task/Morse-code/00DESCRIPTION +++ b/Task/Morse-code/00DESCRIPTION @@ -1,6 +1,11 @@ -[[wp:Morse_code|Morse code]] is one of the simplest and most versatile methods of telecommunication in -existence. It has been in use for more than 160 years — longer than any other electronic encoding system. +{{omit from|ML/I}} -The task: Send a string as audible morse code to an audio device (e.g., the PC speaker). +[[wp:Morse_code|Morse code]] is one of the simplest and most versatile methods of telecommunication in existence. +It has been in use for more than 160 years — longer than any other electronic encoding system. -As the standard Morse code does not contain all possible characters, you may either ignore unknown characters in the file, or indicate them somehow (e.g. with a different pitch). +The task: Send a string as audible morse code to an audio device +(e.g., the PC speaker). + +As the standard Morse code does not contain all possible characters, +you may either ignore unknown characters in the file, +or indicate them somehow (e.g. with a different pitch). diff --git a/Task/Morse-code/00META.yaml b/Task/Morse-code/00META.yaml index ab402b0d06..54bc464f9d 100644 --- a/Task/Morse-code/00META.yaml +++ b/Task/Morse-code/00META.yaml @@ -1,4 +1,6 @@ --- -note: Temporal media +category: +- Temporal media +note: Sound requires: - Sound diff --git a/Task/Morse-code/AWK/morse-code.awk b/Task/Morse-code/AWK/morse-code.awk index a6e78055a0..e97fb7ac64 100644 --- a/Task/Morse-code/AWK/morse-code.awk +++ b/Task/Morse-code/AWK/morse-code.awk @@ -1,3 +1,4 @@ +# usage: awk -f morse.awk [inputfile] BEGIN { FS=""; m="A.-B-...C-.-.D-..E.F..-.G--.H....I..J.---K-.-L.-..M--N-."; m=m "O---P.--.Q--.-R.-.S...T-U..-V...-W.--X-..-Y-.--Z--.. "; @@ -17,8 +18,3 @@ BEGIN { FS=""; } printf("\n"); } - -usage: awk -f morse.awk [inputfile] - -sos sos titanic -...|---|...||...|---|...||-|..|-|.-|-.|..|-.-.| diff --git a/Task/Mouse-position/00DESCRIPTION b/Task/Mouse-position/00DESCRIPTION index 32b6cb8207..e33ba5ada7 100644 --- a/Task/Mouse-position/00DESCRIPTION +++ b/Task/Mouse-position/00DESCRIPTION @@ -1 +1,21 @@ -Get the current location of the mouse cursor relative to the active window. Please specify if the window may be externally created. +{{omit from|ACL2}} +{{omit from|AWK|Does not have an active window concept}} +{{omit from|Befunge|No mouse support}} +{{omit from|Brainf***}} +{{omit from|GolfScript}} +{{omit from|GUISS}} +{{omit from|Logtalk}} +{{omit from|Lotus 123 Macro Scripting}} +{{omit from|Maxima}} +{{omit from|ML/I}} +{{omit from|PARI/GP}} +{{omit from|PHP}} +{{omit from|PostScript}} +{{omit from|R}} +{{omit from|TI-83 BASIC|Does not have a pointing device.}} +{{omit from|TI-89 BASIC|Does not have a pointing device.}} +{{omit from|UNIX Shell}} +{{omit from|ZX Spectrum Basic|Does not have a pointing device interface or windowing engine}} + +Get the current location of the mouse cursor relative to the active window. +Please specify if the window may be externally created. diff --git a/Task/Mouse-position/00META.yaml b/Task/Mouse-position/00META.yaml index b5b7d9296e..6cde0dd403 100644 --- a/Task/Mouse-position/00META.yaml +++ b/Task/Mouse-position/00META.yaml @@ -1,4 +1,6 @@ --- category: - Testing +- Hardware +- Pointing devices note: GUI diff --git a/Task/Mouse-position/MAXScript/mouse-position.max b/Task/Mouse-position/MAXScript/mouse-position.max new file mode 100644 index 0000000000..4d370b43aa --- /dev/null +++ b/Task/Mouse-position/MAXScript/mouse-position.max @@ -0,0 +1,20 @@ +try destroydialog mousePos catch () + +rollout mousePos "Mouse position" width:200 +( + label mousePosText "Current mouse position:" pos:[0,0] + label mousePosX "" pos:[130,0] + label mousePosSep "x" pos:[143,0] + label mousePosY "" pos:[160,0] + + timer updateTimer interval:50 active:true + + on updateTimer tick do + ( + mousePosX.text = (mouse.screenpos.x as integer) as string + mousePosY.text = (mouse.screenpos.y as integer) as string + ) + +) + +createdialog mousepos diff --git a/Task/Mouse-position/Scala/mouse-position.scala b/Task/Mouse-position/Scala/mouse-position.scala index 5fde904d4c..dcc534b2ab 100644 --- a/Task/Mouse-position/Scala/mouse-position.scala +++ b/Task/Mouse-position/Scala/mouse-position.scala @@ -1,6 +1,5 @@ import java.awt.MouseInfo - object MousePosition extends App { - val mouseLocation = MouseInfo.getPointerInfo().getLocation() + val mouseLocation = MouseInfo.getPointerInfo.getLocation println (mouseLocation) } diff --git a/Task/Mouse-position/Smalltalk/mouse-position.st b/Task/Mouse-position/Smalltalk/mouse-position.st new file mode 100644 index 0000000000..2179e3f9cf --- /dev/null +++ b/Task/Mouse-position/Smalltalk/mouse-position.st @@ -0,0 +1 @@ +World activeHand position. " (394@649.0)" diff --git a/Task/Multifactorial/Clojure/multifactorial.clj b/Task/Multifactorial/Clojure/multifactorial.clj index cb20dbd971..959f4e7815 100644 --- a/Task/Multifactorial/Clojure/multifactorial.clj +++ b/Task/Multifactorial/Clojure/multifactorial.clj @@ -1,5 +1,5 @@ (defn !! [m n] - (apply * (take-while pos? (iterate #(- % m) n)))) + (->> (iterate #(- % m) n) (take-while pos?) (apply *))) (doseq [m (range 1 6)] (prn m (map #(!! m %) (range 1 11)))) diff --git a/Task/Multifactorial/Java/multifactorial.java b/Task/Multifactorial/Java/multifactorial.java new file mode 100644 index 0000000000..efb528fba9 --- /dev/null +++ b/Task/Multifactorial/Java/multifactorial.java @@ -0,0 +1,19 @@ +public class MultiFact { + private static long multiFact(long n, int deg){ + long ans = 1; + for(long i = n; i > 0; i -= deg){ + ans *= i; + } + return ans; + } + + public static void main(String[] args){ + for(int deg = 1; deg <= 5; deg++){ + System.out.print("degree " + deg + ":"); + for(long n = 1; n <= 10; n++){ + System.out.print(" " + multiFact(n, deg)); + } + System.out.println(); + } + } +} diff --git a/Task/Multifactorial/Perl-6/multifactorial.pl6 b/Task/Multifactorial/Perl-6/multifactorial.pl6 index d73f334265..5bfd32bd91 100644 --- a/Task/Multifactorial/Perl-6/multifactorial.pl6 +++ b/Task/Multifactorial/Perl-6/multifactorial.pl6 @@ -1,5 +1,4 @@ -sub mfact($n, :$degree = 1) { [*] $n, *-$degree ...^ * <= 0 } - for 1 .. 5 -> $degree { - say "$degree: ", map &mfact.assuming(:$degree), 1 .. 10; + sub mfact($n) { [*] $n, *-$degree ...^ * <= 0 }; + say "$degree: ", map &mfact, 1..10 } diff --git a/Task/Multiple-distinct-objects/J/multiple-distinct-objects.j b/Task/Multiple-distinct-objects/J/multiple-distinct-objects-1.j similarity index 100% rename from Task/Multiple-distinct-objects/J/multiple-distinct-objects.j rename to Task/Multiple-distinct-objects/J/multiple-distinct-objects-1.j diff --git a/Task/Multiple-distinct-objects/J/multiple-distinct-objects-2.j b/Task/Multiple-distinct-objects/J/multiple-distinct-objects-2.j new file mode 100644 index 0000000000..7e1c0cc812 --- /dev/null +++ b/Task/Multiple-distinct-objects/J/multiple-distinct-objects-2.j @@ -0,0 +1,2 @@ + i. 4 +0 1 2 3 diff --git a/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects.pl6 b/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects.pl6 new file mode 100644 index 0000000000..1cfaa118fa --- /dev/null +++ b/Task/Multiple-distinct-objects/Perl-6/multiple-distinct-objects.pl6 @@ -0,0 +1 @@ +my @a = Foo.new xx $n; diff --git a/Task/Multiple-regression/00DESCRIPTION b/Task/Multiple-regression/00DESCRIPTION index 14e39cbfd1..ab28c8a349 100644 --- a/Task/Multiple-regression/00DESCRIPTION +++ b/Task/Multiple-regression/00DESCRIPTION @@ -9,4 +9,5 @@ Compute the vector \beta = \{ \beta_1, \beta_2, ..., \beta_k \} usi y_j = \Sigma_i \beta_i \cdot x_{ij} , j \in 1..n -You can assume y is given to you as a vector (a one-dimensional array), and X is given to you as a two-dimensional array (i.e. matrix). +You can assume y is given to you as a vector (a one-dimensional array), +and X is given to you as a two-dimensional array (i.e. matrix). diff --git a/Task/Multiple-regression/J/multiple-regression-3.j b/Task/Multiple-regression/J/multiple-regression-3.j index 169c405bdb..3021501034 100644 --- a/Task/Multiple-regression/J/multiple-regression-3.j +++ b/Task/Multiple-regression/J/multiple-regression-3.j @@ -3,4 +3,7 @@ NB. |:X is transpose of X (%.(|:X) mp X) mp (|:X) mp y +128.814 _143.163 61.9606 + xpy=: mp~ |: NB. Or factoring out "X prime y" (monadically "X prime X") + X (%.@:xpy@[ mp xpy) y 128.814 _143.163 61.9606 diff --git a/Task/Multiple-regression/Racket/multiple-regression-2.rkt b/Task/Multiple-regression/Racket/multiple-regression-2.rkt index abe4ffa447..c56c3530f9 100644 --- a/Task/Multiple-regression/Racket/multiple-regression-2.rkt +++ b/Task/Multiple-regression/Racket/multiple-regression-2.rkt @@ -6,5 +6,5 @@ [2] [3] [9]])) -; Output: +{{out}} (array #[#[9 1/3] #[-3 1/3]]) diff --git a/Task/Multiple-regression/Ruby/multiple-regression-3.rb b/Task/Multiple-regression/Ruby/multiple-regression-3.rb new file mode 100644 index 0000000000..d171f630b1 --- /dev/null +++ b/Task/Multiple-regression/Ruby/multiple-regression-3.rb @@ -0,0 +1 @@ +puts regression_coefficients([3,4,5], [ [1,2,1], [1,1,2] ]) diff --git a/Task/Multiplication-tables/00META.yaml b/Task/Multiplication-tables/00META.yaml index 8644b2ad9b..5065df2172 100644 --- a/Task/Multiplication-tables/00META.yaml +++ b/Task/Multiplication-tables/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Arithmetic operations diff --git a/Task/Multiplication-tables/AWK/multiplication-tables.awk b/Task/Multiplication-tables/AWK/multiplication-tables.awk index e859ce00d1..36cad55f0b 100644 --- a/Task/Multiplication-tables/AWK/multiplication-tables.awk +++ b/Task/Multiplication-tables/AWK/multiplication-tables.awk @@ -1,22 +1,9 @@ -BEGIN{ - for(i=1;i<13;i++){ - for(j=1;j<13;j++){ - if(j>=i||j==1){printf "%4d",i*j} - else {printf " "} +BEGIN { + for(i=1;i<=12;i++){ + for(j=1;j<=12;j++){ + if(j>=i||j==1){printf "%4d",i*j} + else {printf " "} } print } } - - 1 2 3 4 5 6 7 8 9 10 11 12 - 2 4 6 8 10 12 14 16 18 20 22 24 - 3 9 12 15 18 21 24 27 30 33 36 - 4 16 20 24 28 32 36 40 44 48 - 5 25 30 35 40 45 50 55 60 - 6 36 42 48 54 60 66 72 - 7 49 56 63 70 77 84 - 8 64 72 80 88 96 - 9 81 90 99 108 - 10 100 110 120 - 11 121 132 - 12 144 diff --git a/Task/Multiplication-tables/C/multiplication-tables.c b/Task/Multiplication-tables/C/multiplication-tables.c new file mode 100644 index 0000000000..ae132d1d00 --- /dev/null +++ b/Task/Multiplication-tables/C/multiplication-tables.c @@ -0,0 +1,13 @@ +int main() +{ + int i, j, n = 12; + + for (j = 1; j <= n; j++) printf("%3d%c", j, j - n ? ' ':'\n'); + for (j = 0; j <= n; j++) printf(j - n ? "----" : "+\n"); + + for (i = 1; i <= n; printf("| %d\n", i++)) + for (j = 1; j <= n; j++) + printf(j < i ? " " : "%3d ", i * j); + + return 0; +} diff --git a/Task/Multiplication-tables/CoffeeScript/multiplication-tables.coffee b/Task/Multiplication-tables/CoffeeScript/multiplication-tables.coffee new file mode 100644 index 0000000000..d9b87b39fd --- /dev/null +++ b/Task/Multiplication-tables/CoffeeScript/multiplication-tables.coffee @@ -0,0 +1,31 @@ +print_multiplication_tables = (n) -> + width = 4 + + pad = (s, n=width, c=' ') -> + s = s.toString() + result = '' + padding = n - s.length + while result.length < padding + result += c + result + s + + s = pad('') + '|' + for i in [1..n] + s += pad i + console.log s + + s = pad('', width, '-') + '+' + for i in [1..n] + s += pad '', width, '-' + console.log s + + + for i in [1..n] + s = pad i + s += '|' + s += pad '', width*(i - 1) + for j in [i..n] + s += pad i*j + console.log s + +print_multiplication_tables 12 diff --git a/Task/Multiplication-tables/R/multiplication-tables.r b/Task/Multiplication-tables/R/multiplication-tables.r new file mode 100644 index 0000000000..ff51afb0db --- /dev/null +++ b/Task/Multiplication-tables/R/multiplication-tables.r @@ -0,0 +1,10 @@ +multiplication_table <- function(n=12) +{ + one_to_n <- 1:n + x <- matrix(one_to_n) %*% t(one_to_n) + x[lower.tri(x)] <- 0 + rownames(x) <- colnames(x) <- one_to_n + print(as.table(x), zero.print="") + invisible(x) +} +multiplication_table() diff --git a/Task/Multiplication-tables/REXX/multiplication-tables.rexx b/Task/Multiplication-tables/REXX/multiplication-tables.rexx index 3969fd9c74..61a1f15c57 100644 --- a/Task/Multiplication-tables/REXX/multiplication-tables.rexx +++ b/Task/Multiplication-tables/REXX/multiplication-tables.rexx @@ -1,35 +1,35 @@ /*REXX program displays a 12x12 multiplication boxed grid table, grid */ /* will be displayed in "boxing" characters for ASCII or EBCDIC.*/ -parse arg high . /*get optional grid size. */ -if high=='' then high=12 /*not specified? Use default. */ -ebcdic='f0'==1 /*is this an EBCDIC machine? */ +parse arg high . /*get optional grid size from CL.*/ +if high=='' then high=12 /*not specified? Use default. */ +ebcdic= 'f0'==1 /*is this an EBCDIC machine? */ -if ebcdic then do /*══════════EBCDIC═══════════════*/ - bar='fa'x /*vertical bar. */ - dash='bf'x /*horizontal dash. */ - bj ='cb'x /*bottom junction. */ - tj ='cc'x /* top junction. */ - cj ='8f'x /*center junction (cross). */ - lj ='eb'x /* left junction. */ - rj ='ec'x /* right junction. */ - tlc='ac'x /*top left corner. */ - trc='bc'x /*top right corner. */ - blc='ab'x /*bottom left corner. */ - brc='bb'x /*bottom right corner. */ - end - else do /*══════════ASCII════════════════*/ - bar='b3'x /*vertical bar. */ - dash='c4'x /*horizontal dash. */ - bj ='c1'x /*bottom junction. */ - tj ='c2'x /* top junction. */ - cj ='c5'x /*center junction (cross). */ - lj ='c3'x /* left junction. */ - rj ='b4'x /* right junction. */ - tlc='da'x /*top left corner. */ - trc='bf'x /*top right corner. */ - blc='c0'x /*bottom left corner. */ - brc='d9'x /*bottom right corner. */ - end +if ebcdic then do /*══════════EBCDIC═══════════════*/ + bar='fa'x /*vertical bar. */ + dash='bf'x /*horizontal dash. */ + bj ='cb'x /*bottom junction. */ + tj ='cc'x /* top junction. */ + cj ='8f'x /*center junction (cross). */ + lj ='eb'x /* left junction. */ + rj ='ec'x /* right junction. */ + tlc='ac'x /*top left corner. */ + trc='bc'x /*top right corner. */ + blc='ab'x /*bottom left corner. */ + brc='bb'x /*bottom right corner. */ + end + else do /*══════════ASCII════════════════*/ + bar='b3'x /*vertical bar. */ + dash='c4'x /*horizontal dash. */ + bj ='c1'x /*bottom junction. */ + tj ='c2'x /* top junction. */ + cj ='c5'x /*center junction (cross). */ + lj ='c3'x /* left junction. */ + rj ='b4'x /* right junction. */ + tlc='da'x /*top left corner. */ + trc='bf'x /*top right corner. */ + blc='c0'x /*bottom left corner. */ + brc='d9'x /*bottom right corner. */ + end cell=cj || copies(dash,5) /*define the top of the cell. */ sep=copies(cell,high+1)rj /*build the table separator. */ @@ -38,7 +38,7 @@ width=length(cell)-1 /*width of the table cells. */ size=width-1 /*width for table numbers. */ box.=left('',width) /*construct all the cells. */ - do j=0 to high /*step through zero to H (12). */ + do j=0 to high /*step through zero to H (12). */ _=right(j,size-1)'x ' /*build "label"/border number. */ box.0.j=_ /*build top label cell. */ box.j.0=_ /*build left label cell. */ @@ -49,22 +49,22 @@ box.0.0=centre('times',width) /*redefine box.0.0 with 'X'. */ do row=1 for high /*step through 1 to H (12). */ do col=row to high /*step through row to H (12). */ box.row.col=right(row*col,size)' ' /*build a mult. cell. */ - end /*col*/ - end /*row*/ + end /*col*/ + end /*row*/ - do row=0 to high /*step through all the lines. */ + do row=0 to high /*step through all the lines. */ asep=sep /*allow use of a modified sep. */ - if row==0 then do - asep=overlay(tlc,asep,1) /*make a better tlc. */ - asep=overlay(trc,asep,sepL) /*make a better trc. */ - asep=translate(asep,tj,cj) /*make a better tj. */ - end - else asep=overlay(lj,asep,1) /*make a better lj. */ + if row==0 then do + asep=overlay(tlc,asep,1) /*make a better tlc. */ + asep=overlay(trc,asep,sepL) /*make a better trc. */ + asep=translate(asep,tj,cj) /*make a better tj. */ + end + else asep=overlay(lj,asep,1) /*make a better lj. */ say asep /*display a table grid line. */ - if row==0 then call buildLine 00 /*display a blank grid line. */ - call buildLine row /*build one line of the grid. */ - if row==0 then call buildLine 00 /*display a blank grid line. */ + if row==0 then call buildLine 00 /*display a blank grid line. */ + call buildLine row /*build one line of the grid. */ + if row==0 then call buildLine 00 /*display a blank grid line. */ end /*row*/ asep=sep /*allow use of a modified sep. */ @@ -74,7 +74,7 @@ asep=translate(asep,bj,cj) /*make a better bot junction. */ say asep /*display a table grid line. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BUILDLINE subroutine────────────────*/ -buildLine: w=; parse arg arow /*start with a blank cell. */ +buildLine: w=; parse arg arow /*start with a blank cell. */ do col=0 to high /*step through 0 to H (12). */ w=w||bar||box.arow.col /*build one cell at a time. */ diff --git a/Task/Multiplication-tables/Visual-Basic/multiplication-tables.vb b/Task/Multiplication-tables/Visual-Basic/multiplication-tables.vb new file mode 100644 index 0000000000..19074f9bff --- /dev/null +++ b/Task/Multiplication-tables/Visual-Basic/multiplication-tables.vb @@ -0,0 +1,24 @@ +Sub Main() + Const nmax = 12, xx = 3 + Const x = xx + 1 + Dim i As Integer, j As Integer, s As String + s = String(xx, " ") & " |" + For j = 1 To nmax + s = s & Right(String(x, " ") & j, x) + Next j + Debug.Print s + s = String(xx, "-") & " +" + For j = 1 To nmax + s = s & " " & String(xx, "-") + Next j + Debug.Print s + For i = 1 To nmax + s = Right(String(xx, " ") & i, xx) & " |" + For j = 1 To nmax + If j >= i _ + Then s = s & Right(String(x, " ") & i * j, x) _ + Else s = s & String(x, " ") + Next j + Debug.Print s + Next i +End Sub 'Main diff --git a/Task/Multiplicative-order/Maple/multiplicative-order-1.maple b/Task/Multiplicative-order/Maple/multiplicative-order-1.maple new file mode 100644 index 0000000000..a5d1067613 --- /dev/null +++ b/Task/Multiplicative-order/Maple/multiplicative-order-1.maple @@ -0,0 +1 @@ +numtheory:-order( a, n ) diff --git a/Task/Multiplicative-order/Maple/multiplicative-order-2.maple b/Task/Multiplicative-order/Maple/multiplicative-order-2.maple new file mode 100644 index 0000000000..e317f6771b --- /dev/null +++ b/Task/Multiplicative-order/Maple/multiplicative-order-2.maple @@ -0,0 +1,2 @@ +> numtheory:-order( 37, 1000 ); + 100 diff --git a/Task/Multiplicative-order/Perl/multiplicative-order-1.pl b/Task/Multiplicative-order/Perl/multiplicative-order-1.pl new file mode 100644 index 0000000000..b2c5f2c6b5 --- /dev/null +++ b/Task/Multiplicative-order/Perl/multiplicative-order-1.pl @@ -0,0 +1,3 @@ +use ntheory qw/znorder/; +say znorder(54, 100001); +use bigint; say znorder(11, 1 + 10**100); diff --git a/Task/Multiplicative-order/Perl/multiplicative-order-2.pl b/Task/Multiplicative-order/Perl/multiplicative-order-2.pl new file mode 100644 index 0000000000..8c83469fab --- /dev/null +++ b/Task/Multiplicative-order/Perl/multiplicative-order-2.pl @@ -0,0 +1,3 @@ +use Math::Pari qw/znorder Mod/; +say znorder(Mod(54, 100001)); +say znorder(Mod(11, 1 + Math::Pari::PARI(10)**100)); diff --git a/Task/Multisplit/00DESCRIPTION b/Task/Multisplit/00DESCRIPTION index 92b31afa7c..5d4e0e0981 100644 --- a/Task/Multisplit/00DESCRIPTION +++ b/Task/Multisplit/00DESCRIPTION @@ -1,9 +1,24 @@ -It is often necessary to split a string into pieces based on several different (potentially multi-character) separator strings, while still retaining the information about which separators were present in the input. This is particularly useful when doing small parsing tasks. The task is to write code to demonstrate this. +It is often necessary to split a string into pieces +based on several different (potentially multi-character) separator strings, +while still retaining the information about which separators were present in the input. -The function (or procedure or method, as appropriate) should take an input string and an ordered collection of separators. The order of the separators is significant: The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. In cases where there would be an ambiguity as to which separator to use at a particular point (e.g., because one separator is a prefix of another) the separator with the highest priority should be used. Delimiters can be reused and the output from the function should be an ordered sequence of substrings. +This is particularly useful when doing small parsing tasks.
+The task is to write code to demonstrate this. + +The function (or procedure or method, as appropriate) should +take an input string and an ordered collection of separators. + +The order of the separators is significant:
+The delimiter order represents priority in matching, with the first defined delimiter having the highest priority. +In cases where there would be an ambiguity as to +which separator to use at a particular point +(e.g., because one separator is a prefix of another) +the separator with the highest priority should be used. +Delimiters can be reused and the output from the function should be an ordered sequence of substrings. Test your code using the input string “a!===b=!=c” and the separators “==”, “!=” and “=”. -For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". Note that the quotation marks are shown for clarity and do not form part of the output. +For these inputs the string should be parsed as "a" (!=) "" (==) "b" (=) "" (!=) "c", where matched delimiters are shown in parentheses, and separated strings are quoted, so our resulting output is "a", empty string, "b", empty string, "c". +Note that the quotation marks are shown for clarity and do not form part of the output. '''Extra Credit:''' provide information that indicates which separator was matched at each separation point and where in the input string that separator was matched. diff --git a/Task/Multisplit/00META.yaml b/Task/Multisplit/00META.yaml new file mode 100644 index 0000000000..12b5b405fb --- /dev/null +++ b/Task/Multisplit/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- String manipulation diff --git a/Task/Multisplit/D/multisplit.d b/Task/Multisplit/D/multisplit.d index 0fa57b1a11..0492854ebc 100644 --- a/Task/Multisplit/D/multisplit.d +++ b/Task/Multisplit/D/multisplit.d @@ -1,16 +1,15 @@ import std.stdio, std.array, std.algorithm; -string[] multiSplit(in string s, in string[] divisors) -pure /*nothrow*/ { +string[] multiSplit(in string s, in string[] divisors) pure nothrow { string[] result; - auto rest = s.idup; // Not nothrow. + auto rest = s.idup; while (true) { bool done = true; string delim; { string best; - foreach (div; divisors) { + foreach (const div; divisors) { const maybe = rest.find(div); if (maybe.length > best.length) { best = maybe; diff --git a/Task/Multisplit/Haskell/multisplit.hs b/Task/Multisplit/Haskell/multisplit.hs new file mode 100644 index 0000000000..cf5d0f8276 --- /dev/null +++ b/Task/Multisplit/Haskell/multisplit.hs @@ -0,0 +1,27 @@ +import Data.List as L +import Data.Maybe + +trysplit :: Eq a => [a] -> [[a]] -> Maybe ([a], [a]) +trysplit s delims = + case filter (`L.isPrefixOf` s) delims of + [] -> Nothing + (d:_) -> Just (d, fromJust $ L.stripPrefix d s) + +multisplit :: (Eq a, Num n) => [a] -> [[a]] -> [([a], [a], n)] +multisplit list delims = + let ms [] acc pos = [(acc, [], pos)] + ms l@(s:sx) acc pos = + case trysplit l delims of + Nothing -> ms sx (s:acc) (pos + 1) + Just (d, sxx) -> (acc, d, pos) : ms sxx [] (pos + L.genericLength d) + in ms list [] 0 + +main :: IO () +main = do + let test = "a!===b=!=c" + delims = ["==", "!=", "="] + parsed = multisplit test delims + putStrLn "split string:" + putStrLn $ L.intercalate "," $ map (\(a, _, _) -> a) parsed + putStrLn "with [(string, delimiter, offset)]:" + print parsed diff --git a/Task/Multisplit/Java/multisplit.java b/Task/Multisplit/Java/multisplit.java new file mode 100644 index 0000000000..27470b1bff --- /dev/null +++ b/Task/Multisplit/Java/multisplit.java @@ -0,0 +1,33 @@ +import java.util.*; + +public class MultiSplit { + + public static void main(String[] args) { + System.out.println("Regex split:"); + System.out.println(Arrays.toString("a!===b=!=c".split("==|!=|="))); + + System.out.println("\nManual split:"); + for (String s : multiSplit("a!===b=!=c", new String[]{"==", "!=", "="})) + System.out.printf("\"%s\" ", s); + } + + static List multiSplit(String txt, String[] separators) { + List result = new ArrayList<>(); + int txtLen = txt.length(), from = 0; + + for (int to = 0; to < txtLen; to++) { + for (String sep : separators) { + int sepLen = sep.length(); + if (txt.regionMatches(to, sep, 0, sepLen)) { + result.add(txt.substring(from, to)); + from = to + sepLen; + to = from - 1; // compensate for the increment + break; + } + } + } + if (from < txtLen) + result.add(txt.substring(from)); + return result; + } +} diff --git a/Task/Multisplit/REXX/multisplit.rexx b/Task/Multisplit/REXX/multisplit.rexx index fcdd8c416a..65f26a3bd1 100644 --- a/Task/Multisplit/REXX/multisplit.rexx +++ b/Task/Multisplit/REXX/multisplit.rexx @@ -1,26 +1,26 @@ -/*REXX program to split a string based on different separator strings. */ +/*REXX program splits a string based on different separator strings.*/ parse arg ? /*get string from command line. */ -if ?=='' then ? = 'a!===b=!=c' /*None specified? Use default.*/ +if ?=='' then ? = "a!===b=!=c" /*None specified? Use default.*/ say 'old string='? /*echo the old string to screen. */ zz = '0'x /*null char, can be most anything*/ -seps = '== != =' /*a list of seperaters to be used*/ - +seps = '== != =' /*a list of seperators to be used*/ + /* [↓] process tokens in SEPS.*/ do j=1 for words(seps) /*parse string with all the seps.*/ - sep=word(seps,j) /*pick a separater to use now. */ - + sep=word(seps,j) /*pick a separator to use now. */ + /* [↓] process chars in the sep*/ do k=1 for length(sep) /*parse for various sep versions.*/ sep=strip(insert(zz,sep,k),,zz) /*allow imbedded "nulls" in sep. */ ?=changestr(sep,?,zz) /* ··· but not trailing "nulls". */ - + /* [↓] process strings in input*/ do until ?==??; ??=? /*keep changing until no more chg*/ ?=changestr(zz || zz, ?, zz) /*reduce replicated "nulls". */ end /*until···*/ - + /* [↓] use BIF or external prog.*/ sep=changestr(zz, sep, '') /*remove true nulls from the sep.*/ end /*k*/ end /*j*/ -showNull = ' {} ' /*one last change, allow the ... */ -?=changestr(zz,?,showNull) /*showing of "null" characters. */ -say 'new string='? /*now, show and tell time. */ +showNull = ' {} ' /*one more thing, display the ···*/ +?=changestr(zz,?,showNull) /* ··· showing of "null" chars. */ +say 'new string='? /*now, display the new string. */ /*stick a fork in it, we're done.*/ diff --git a/Task/Multisplit/Ruby/multisplit-1.rb b/Task/Multisplit/Ruby/multisplit-1.rb index 07d2728d00..1dc36673f0 100644 --- a/Task/Multisplit/Ruby/multisplit-1.rb +++ b/Task/Multisplit/Ruby/multisplit-1.rb @@ -2,13 +2,7 @@ text = 'a!===b=!=c' separators = ['==', '!=', '='] def multisplit_simple(text, separators) - sep_regex = Regexp.new(separators.collect {|sep| Regexp.escape(sep)}.join('|')) - text.split(sep_regex) + text.split(Regexp.union(separators)) end -p multisplit_simple(text, separators) -["a", "", "b", "", "c"] -=> nil -p multisplit_simple(text, ['=', '!=', '==']) -["a", "", "", "b", "", "c"] -=> nil +p multisplit_simple(text, separators) # => ["a", "", "b", "", "c"] diff --git a/Task/Multisplit/Ruby/multisplit-2.rb b/Task/Multisplit/Ruby/multisplit-2.rb index cc29563aaf..a81c8a4d31 100644 --- a/Task/Multisplit/Ruby/multisplit-2.rb +++ b/Task/Multisplit/Ruby/multisplit-2.rb @@ -1,5 +1,5 @@ def multisplit(text, separators) - sep_regex = Regexp.new(separators.collect {|sep| Regexp.escape(sep)}.join('|')) + sep_regex = Regexp.union(separators) separator_info = [] pieces = [] i = prev = 0 diff --git a/Task/Multisplit/Scheme/multisplit.ss b/Task/Multisplit/Scheme/multisplit.ss new file mode 100644 index 0000000000..07423bb01d --- /dev/null +++ b/Task/Multisplit/Scheme/multisplit.ss @@ -0,0 +1,15 @@ +(use srfi-13) +(use srfi-42) + +(define (shatter separators the-string) + (let loop ((str the-string) (tmp "")) + (if (string=? "" str) + (list tmp) + (if-let1 sep (find (^s (string-prefix? s str)) separators) + (cons* tmp sep + (loop (string-drop str (string-length sep)) "")) + (loop (string-drop str 1) (string-append tmp (string-take str 1))))))) + +(define (glean shards) + (list-ec (: x (index i) shards) + (if (even? i)) x)) diff --git a/Task/Multisplit/UNIX-Shell/multisplit.sh b/Task/Multisplit/UNIX-Shell/multisplit.sh new file mode 100644 index 0000000000..8bb5b99450 --- /dev/null +++ b/Task/Multisplit/UNIX-Shell/multisplit.sh @@ -0,0 +1,29 @@ +multisplit() { + local str=$1 + shift + local regex=$( IFS='|'; echo "$*" ) + local sep + while [[ $str =~ $regex ]]; do + sep=${BASH_REMATCH[0]} + words+=( "${str%%${sep}*}" ) + seps+=( "$sep" ) + str=${str#*$sep} + done + words+=( "$str" ) +} + +words=() seps=() + +original="a!===b=!=c" +recreated="" + +multisplit "$original" "==" "!=" "=" + +for ((i=0; i<${#words[@]}; i++)); do + printf 'w:"%s"\ts:"%s"\n' "${words[i]}" "${seps[i]}" + recreated+="${words[i]}${seps[i]}" +done + +if [[ $original == $recreated ]]; then + echo "successfully able to recreate original string" +fi diff --git a/Task/Mutual-recursion/00DESCRIPTION b/Task/Mutual-recursion/00DESCRIPTION index b0598fcefa..139500c563 100644 --- a/Task/Mutual-recursion/00DESCRIPTION +++ b/Task/Mutual-recursion/00DESCRIPTION @@ -1,4 +1,5 @@ -Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. +Two functions are said to be mutually recursive if the first calls the second, +and in turn the second calls the first. Write two mutually recursive functions that compute members of the [[wp:Hofstadter sequence#Hofstadter Female and Male sequences|Hofstadter Female and Male sequences]] defined as: : @@ -9,4 +10,5 @@ M(n)&=n-F(M(n-1)), \quad n>0. \end{align} -
(If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means). +
(If a language does not allow for a solution using mutually recursive functions +then state this rather than give a solution by other means). diff --git a/Task/Mutual-recursion/Elixir/mutual-recursion.elixir b/Task/Mutual-recursion/Elixir/mutual-recursion.elixir new file mode 100644 index 0000000000..a83682a6af --- /dev/null +++ b/Task/Mutual-recursion/Elixir/mutual-recursion.elixir @@ -0,0 +1,6 @@ +defmodule MutualRecursion do + def f(0), do: 1 + def f(n), do: n - m(f(n - 1)) + def m(0), do: 0 + def m(n), do: n - f(m(n - 1)) +end diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx index 0e42dd5587..1b2e0ffd81 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-1.rexx @@ -1,11 +1,11 @@ /*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ -arg lim .; if lim=='' then lim=40; pad=left('',20) +parse arg lim .; if lim='' then lim=40; pad=left('',20) - do j=0 to lim; jj=Jw(j); ff=F(j); mm=M(j) - say pad 'F('jj") =" Jw(ff) pad 'M('jj") =" Jw(mm) + do j=0 to lim; jj=Jw(j); ff=F(j); mm=M(j) + say pad 'F('jj") =" Jw(ff) pad 'M('jj") =" Jw(mm) end /*j*/ exit /*stick a fork in it, we're done.*/ /*─────────────────────────────────────F, M, Jw subroutines────────────*/ -F: procedure; arg n; if n==0 then return 1; return n-M(F(n-1)) -M: procedure; arg n; if n==0 then return 0; return n-F(M(n-1)) +F: procedure; parse arg n; if n==0 then return 1; return n-M(F(n-1)) +M: procedure; parse arg n; if n==0 then return 0; return n-F(M(n-1)) Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx index 99964cee39..e97c3c1a44 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-2.rexx @@ -1,14 +1,15 @@ /*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ -arg lim .;if lim=='' then lim=99; hm.=; hm.0=0; hf.=; hf.0=1; Js=; Fs=; Ms= +parse arg lim .; if lim=='' then lim=99 /*get or assume LIM.*/ +hm.=; hm.0=0; hf.=; hf.0=1; Js=; Fs=; Ms= - do j=0 to lim; ff=F(j); mm=M(j) - Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) + do j=0 to lim; ff=F(j); mm=M(j) + Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) end /*j*/ -say 'Js=' Js -say 'Fs=' Fs -say 'Ms=' Ms +say 'Js=' Js +say 'Fs=' Fs +say 'Ms=' Ms exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────F, M, Jw subroutines────────────*/ -F: procedure expose hm. hf.; arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n -M: procedure expose hm. hf.; arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n -Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ +/*──────────────────────────────────one─liner subroutines──────────────────────────────*/ +F: procedure expose hm. hf.; parse arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n +M: procedure expose hm. hf.; parse arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n +Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ diff --git a/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx b/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx index 00fc3b269c..a2490c5973 100644 --- a/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx +++ b/Task/Mutual-recursion/REXX/mutual-recursion-3.rexx @@ -1,18 +1,18 @@ /*REXX program shows mutual recursion (via Hofstadter Male & Female seq)*/ /*If LIM is negative, only show a single result for the abs(lim) entry.*/ -parse arg lim .; if lim=='' then lim=99; aLim=abs(lim) +parse arg lim .; if lim=='' then lim=99; aLim=abs(lim) parse var lim . hm. hf. Js Fs Ms; hm.0=0; hf.0=1 - do j=0 to Alim; ff=F(j); mm=M(j) - Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) - end + do j=0 to Alim; ff=F(j); mm=M(j) + Js=Js jW(j); Fs=Fs jw(ff); Ms=Ms jW(mm) + end if lim>0 then say 'Js=' Js; else say 'J('aLim")=" word(Js,aLim+1) if lim>0 then say 'Fs=' Fs; else say 'F('aLim")=" word(Fs,aLim+1) if lim>0 then say 'Ms=' Ms; else say 'M('aLim")=" word(Ms,aLim+1) exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────F, M, Jw subroutines────────────*/ -F: procedure expose hm. hf.; arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n -M: procedure expose hm. hf.; arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n -Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ +/*──────────────────────────────────one─liner subroutines──────────────────────────────*/ +F: procedure expose hm. hf.; parse arg n; if hf.n=='' then hf.n=n-M(F(n-1)); return hf.n +M: procedure expose hm. hf.; parse arg n; if hm.n=='' then hm.n=n-F(M(n-1)); return hm.n +Jw: return right(arg(1),length(lim)) /*right justifies # for nice look*/ diff --git a/Task/N-queens-problem/00DESCRIPTION b/Task/N-queens-problem/00DESCRIPTION index 20880a2556..7cd15eefb4 100644 --- a/Task/N-queens-problem/00DESCRIPTION +++ b/Task/N-queens-problem/00DESCRIPTION @@ -1,4 +1,7 @@ -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]. +Solve the [[WP:Eight_queens_puzzle|eight queens puzzle]]. + +You can extend the problem to solve the puzzle with a board of side NxN. +For the number of solutions for small values of N, see [http://oeis.org/A000170 oeis.org]. ;Cf. * [[Knight's tour]] diff --git a/Task/N-queens-problem/ABAP/n-queens-problem.abap b/Task/N-queens-problem/ABAP/n-queens-problem.abap new file mode 100644 index 0000000000..5bfb8b08d4 --- /dev/null +++ b/Task/N-queens-problem/ABAP/n-queens-problem.abap @@ -0,0 +1,285 @@ +TYPES: BEGIN OF gty_matrix, + 1 TYPE c, + 2 TYPE c, + 3 TYPE c, + 4 TYPE c, + 5 TYPE c, + 6 TYPE c, + 7 TYPE c, + 8 TYPE c, + 9 TYPE c, + 10 TYPE c, + END OF gty_matrix, + gty_t_matrix TYPE STANDARD TABLE OF gty_matrix INITIAL SIZE 8. + +DATA: gt_matrix TYPE gty_t_matrix, + gs_matrix TYPE gty_matrix, + gv_count TYPE i VALUE 0, + gv_solut TYPE i VALUE 0. + + +SELECTION-SCREEN BEGIN OF BLOCK b01 WITH FRAME TITLE text-b01. +PARAMETERS: p_number TYPE i OBLIGATORY DEFAULT 8. +SELECTION-SCREEN END OF BLOCK b01. + +" Filling empty table +START-OF-SELECTION. + DO p_number TIMES. + APPEND gs_matrix TO gt_matrix. + ENDDO. + +" Recursive Function + PERFORM fill_matrix USING gv_count 1 1 CHANGING gt_matrix. + BREAK-POINT. +*&---------------------------------------------------------------------* +*& Form FILL_MATRIX +*----------------------------------------------------------------------* +FORM fill_matrix USING p_count TYPE i + p_i TYPE i + p_j TYPE i + CHANGING p_matrix TYPE gty_t_matrix. + + DATA: lv_i TYPE i, + lv_j TYPE i, + lv_result TYPE c LENGTH 1, + lt_matrix TYPE gty_t_matrix, + lv_count TYPE i, + lv_value TYPE c. + + lt_matrix[] = p_matrix[]. + lv_count = p_count. + lv_i = p_i. + lv_j = p_j. + + WHILE lv_i LE p_number. + WHILE lv_j LE p_number. + CLEAR lv_result. + PERFORM check_position USING lv_i lv_j CHANGING lv_result lt_matrix. + IF lv_result NE 'X'. + MOVE 'X' TO lv_value. + PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix. + ADD 1 TO lv_count. + IF lv_count EQ p_number. + PERFORM show_matrix USING lt_matrix. + ELSE. + PERFORM fill_matrix USING lv_count lv_i lv_j CHANGING lt_matrix. + ENDIF. + lv_value = space. + PERFORM get_position USING lv_i lv_j 'U' CHANGING lv_value lt_matrix. + SUBTRACT 1 FROM lv_count. + ENDIF. + ADD 1 TO lv_j. + ENDWHILE. + ADD 1 TO lv_i. + lv_j = 1. + ENDWHILE. +ENDFORM. " FILL_MATRIX + +*&---------------------------------------------------------------------* +*& Form CHECK_POSITION +*&---------------------------------------------------------------------* +FORM check_position USING value(p_i) TYPE i + value(p_j) TYPE i + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + + PERFORM get_position USING p_i p_j 'R' CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + + PERFORM check_horizontal USING p_i p_j CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + + PERFORM check_vertical USING p_i p_j CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + + PERFORM check_diagonals USING p_i p_j CHANGING p_result p_matrix. + +ENDFORM. " CHECK_POSITION + +*&---------------------------------------------------------------------* +*& Form GET_POSITION +*&---------------------------------------------------------------------* +FORM get_position USING value(p_i) TYPE i + value(p_j) TYPE i + value(p_action) TYPE c + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + + FIELD-SYMBOLS: TYPE gty_matrix, + TYPE any. + + READ TABLE p_matrix ASSIGNING INDEX p_i. + ASSIGN COMPONENT p_j OF STRUCTURE TO . + + CASE p_action. + WHEN 'U'. + = p_result. + WHEN 'R'. + p_result = . + WHEN OTHERS. + ENDCASE. + +ENDFORM. " GET_POSITION + +*&---------------------------------------------------------------------* +*& Form CHECK_HORIZONTAL +*&---------------------------------------------------------------------* +FORM check_horizontal USING value(p_i) TYPE i + value(p_j) TYPE i + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + DATA: lv_j TYPE i, + ls_matrix TYPE gty_matrix. + + FIELD-SYMBOLS TYPE c. + + lv_j = 1. + READ TABLE p_matrix INTO ls_matrix INDEX p_i. + WHILE lv_j LE p_number. + ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO . + IF EQ 'X'. + p_result = 'X'. + RETURN. + ENDIF. + ADD 1 TO lv_j. + ENDWHILE. +ENDFORM. " CHECK_HORIZONTAL + +*&---------------------------------------------------------------------* +*& Form CHECK_VERTICAL +*&---------------------------------------------------------------------* +FORM check_vertical USING value(p_i) TYPE i + value(p_j) TYPE i + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + DATA: lv_i TYPE i, + ls_matrix TYPE gty_matrix. + + FIELD-SYMBOLS TYPE c. + + lv_i = 1. + WHILE lv_i LE p_number. + READ TABLE p_matrix INTO ls_matrix INDEX lv_i. + ASSIGN COMPONENT p_j OF STRUCTURE ls_matrix TO . + IF EQ 'X'. + p_result = 'X'. + RETURN. + ENDIF. + ADD 1 TO lv_i. + ENDWHILE. +ENDFORM. " CHECK_VERTICAL + +*&---------------------------------------------------------------------* +*& Form CHECK_DIAGONALS +*&---------------------------------------------------------------------* +FORM check_diagonals USING value(p_i) TYPE i + value(p_j) TYPE i + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + DATA: lv_dx TYPE i, + lv_dy TYPE i. + +* I++ J++ (Up Right) + lv_dx = 1. + lv_dy = 1. + PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + +* I-- J-- (Left Down) + lv_dx = -1. + lv_dy = -1. + PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + +* I++ J-- (Right Down) + lv_dx = 1. + lv_dy = -1. + PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. + CHECK p_result NE 'X'. + +* I-- J++ (Left Up) + lv_dx = -1. + lv_dy = 1. + PERFORM check_diagonal USING p_i p_j lv_dx lv_dy CHANGING p_result p_matrix. + CHECK p_result NE 'X'. +ENDFORM. " CHECK_DIAGONALS + +*&---------------------------------------------------------------------* +*& Form CHECK_DIAGONAL +*&---------------------------------------------------------------------* +FORM check_diagonal USING value(p_i) TYPE i + value(p_j) TYPE i + value(p_dx) TYPE i + value(p_dy) TYPE i + CHANGING p_result TYPE c + p_matrix TYPE gty_t_matrix. + DATA: lv_i TYPE i, + lv_j TYPE i, + ls_matrix TYPE gty_matrix. + + FIELD-SYMBOLS TYPE c. + + lv_i = p_i. + lv_j = p_j. + WHILE 1 EQ 1. + ADD: p_dx TO lv_i, p_dy TO lv_j. + + IF p_dx EQ 1. + IF lv_i GT p_number. EXIT. ENDIF. + ELSE. + IF lv_i LT 1. EXIT. ENDIF. + ENDIF. + + IF p_dy EQ 1. + IF lv_j GT p_number. EXIT. ENDIF. + ELSE. + IF lv_j LT 1. EXIT. ENDIF. + ENDIF. + + READ TABLE p_matrix INTO ls_matrix INDEX lv_i. + ASSIGN COMPONENT lv_j OF STRUCTURE ls_matrix TO . + IF EQ 'X'. + p_result = 'X'. + RETURN. + ENDIF. + ENDWHILE. +ENDFORM. " CHECK_DIAGONAL +*&---------------------------------------------------------------------* +*& Form SHOW_MATRIX +*----------------------------------------------------------------------* +FORM show_matrix USING p_matrix TYPE gty_t_matrix. + DATA: lt_matrix TYPE gty_t_matrix, + lv_j TYPE i VALUE 1, + lv_colum TYPE string VALUE '-'. + + FIELD-SYMBOLS: TYPE gty_matrix, + TYPE c. + + ADD 1 TO gv_solut. + + WRITE:/ 'Solution: ', gv_solut. + + DO p_number TIMES. + CONCATENATE lv_colum '----' INTO lv_colum. + ENDDO. + + LOOP AT p_matrix ASSIGNING . + IF sy-tabix EQ 1. + WRITE:/ lv_colum. + ENDIF. + WRITE:/ '|'. + DO p_number TIMES. + ASSIGN COMPONENT lv_j OF STRUCTURE TO . + IF EQ space. + WRITE: ,'|'. + ELSE. + WRITE: COLOR 2 HOTSPOT ON,'|'. + ENDIF. + ADD 1 TO lv_j. + ENDDO. + lv_j = 1. + WRITE: / lv_colum. + ENDLOOP. + + SKIP 1. +ENDFORM. " SHOW_MATRIX diff --git a/Task/N-queens-problem/Bracmat/n-queens-problem.bracmat b/Task/N-queens-problem/Bracmat/n-queens-problem.bracmat new file mode 100644 index 0000000000..bc4d43597d --- /dev/null +++ b/Task/N-queens-problem/Bracmat/n-queens-problem.bracmat @@ -0,0 +1,61 @@ +( ( printBoard + = board M L x y S R row line + . :?board + & !ups:? [?M + & whl + ' ( !arg:(?x.?y) ?arg + & !M:?L + & :?row:?line + & whl + ' ( !L+-1:~<0:?L + & !x+1:~>!M:?x + & "---+" !line:?line + & " |" !row:?row + ) + & "---+" !line:?line + & " Q |" !row:?row + & whl + ' ( !L+-1:~<0:?L + & "---+" !line:?line + & " |" !row:?row + ) + & "\n|" !row "\n+" !line !board:?board + ) + & str$("\n+" !line !board) + ) + ( queens + = hor ver up down ups downs a z A Z x y Q + . !arg:(?hor.?ver.?ups.?downs.?Q) + & !ver + : ( + & 1+!solutions:?solutions + { Comment the line below if you only want a count. } + & out$(str$("\nsolution " !solutions) printBoard$!Q) + & ~ { Fail! (and backtrack to find more solutions)} + | #%?y + ( ?z + & !hor + : ?A + #%?x + ( ?Z + & !x+!y:?up + & !x+-1*!y:?down + & ~(!ups:? !up ?) + & ~(!downs:? !down ?) + & queens + $ ( !A !Z + . !z + . !up !ups + . !down !downs + . (!x.!y) !Q + ) + ) + ) + ) + ) +& 0:?solutions +& 1 2 3 4 5 6 7 8:?H:?V {You can edit this line to find solutions for other sizes.} +& ( queens$(!H.!V...) + | out$(found !solutions solutions) + ) +); diff --git a/Task/N-queens-problem/C++/n-queens-problem-1.cpp b/Task/N-queens-problem/C++/n-queens-problem-1.cpp index 83a56c113d..c973060621 100644 --- a/Task/N-queens-problem/C++/n-queens-problem-1.cpp +++ b/Task/N-queens-problem/C++/n-queens-problem-1.cpp @@ -1,100 +1,103 @@ -#include +// Much shorter than the version below; +// uses C++11 threads to parallelize the computation; also uses backtracking +// Outputs all solutions for any table size +#include #include -#include +#include +#include +#include -//-------------------------------------------------------------------------------------------------- -using namespace std; - -//-------------------------------------------------------------------------------------------------- -class point +// Print table. 'pos' is a vector of positions – the index in pos is the row, +// and the number at that index is the column where the queen is placed. +static void print(const std::vector &pos) { -public: - int x, y; - point(){ x = y = 0; } - void set( int a, int b ){ x = a; y = b; } -}; -//-------------------------------------------------------------------------------------------------- -class nQueens -{ -public: - void solve( int c ) - { - _count = c; int len = ( c + 1 ) * ( c + 1 ); _queens = new bool[len]; memset( _queens, 0, len ); - _cl = new bool[c]; memset( _cl, 0, c ); _ln = new bool[c]; memset( _ln, 0, c ); - point pt; pt.set( rand() % c, rand() % c ); putQueens( pt, c ); displayBoard(); - delete [] _queens; delete [] _ln; delete [] _cl; - } - -private: - void displayBoard() - { - system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; - COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); - for( int y = 0, cy = 0; y < _count; y++ ) - { - int yy = y * _count; - for( int x = 0; x < _count; x++ ) - { - SetConsoleCursorPosition( h, c ); cout << t; - c.Y++; SetConsoleCursorPosition( h, c ); - if( _queens[x + yy] ) cout << q; else cout << s; - c.Y++; SetConsoleCursorPosition( h, c ); - cout << t; c.Y = cy; c.X += 4; - } - cy += 2; c.X = 0; c.Y = cy; - } - } - - bool checkD( int x, int y, int a, int b ) - { - if( x < 0 || y < 0 || x >= _count || y >= _count ) return true; - if( _queens[x + y * _count] ) return false; - if( checkD( x + a, y + b, a, b ) ) return true; - return false; - } - - bool check( int x, int y ) - { - if( _ln[y] || _cl[x] ) return false; - if( !checkD( x, y, -1, -1 ) ) return false; - if( !checkD( x, y, 1, -1 ) ) return false; - if( !checkD( x, y, -1, 1 ) ) return false; - if( !checkD( x, y, 1, 1 ) ) return false; - return true; - } - - bool putQueens( point pt, int cnt ) - { - int it = _count; - while( it ) - { - if( !cnt ) return true; - if( check( pt.x, pt.y ) ) - { - _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true; - point tmp = pt; if( ++tmp.x >= _count ) tmp.x = 0; if( ++tmp.y >= _count ) tmp.y = 0; - if( putQueens( tmp, cnt - 1 ) ) return true; - _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false; - } - if( ++pt.x >= _count ) pt.x = 0; - it--; + // print table header + for (int i = 0; i < pos.size(); i++) { + std::cout << std::setw(3) << char('a' + i); } - return false; - } - int _count; - bool* _queens, *_ln, *_cl; -}; -//-------------------------------------------------------------------------------------------------- -int main( int argc, char* argv[] ) -{ - nQueens n; int nq; - while( true ) - { - system( "cls" ); cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq; - if( nq < 4 ) return 0; n.solve( nq ); cout << endl << endl; - system( "pause" ); - } - return 0; + std::cout << '\n'; + + for (int row = 0; row < pos.size(); row++) { + int col = pos[row]; + std::cout << row + 1 << std::setw(3 * col + 3) << " # "; + std::cout << '\n'; + } + + std::cout << "\n\n"; +} + +static bool threatens(int row_a, int col_a, int row_b, int col_b) +{ + return row_a == row_b // same row + or col_a == col_b // same column + or std::abs(row_a - row_b) == std::abs(col_a - col_b); // diagonal +} + +// the i-th queen is in the i-th row +// we only check rows up to end_idx +// so that the same function can be used for backtracking and checking the final solution +static bool good(const std::vector &pos, int end_idx) +{ + for (int row_a = 0; row_a < end_idx; row_a++) { + for (int row_b = row_a + 1; row_b < end_idx; row_b++) { + int col_a = pos[row_a]; + int col_b = pos[row_b]; + if (threatens(row_a, col_a, row_b, col_b)) { + return false; + } + } + } + + return true; +} + +static std::mutex print_count_mutex; // mutex protecting 'n_sols' +static int n_sols = 0; // number of solutions + +// recursive DFS backtracking solver +static void n_queens(std::vector &pos, int index) +{ + // if we have placed a queen in each row (i. e. we are at a leaf of the search tree), check solution and return + if (index >= pos.size()) { + if (good(pos, index)) { + std::lock_guard lock(print_count_mutex); + print(pos); + n_sols++; + } + + return; + } + + // backtracking step + if (not good(pos, index)) { + return; + } + + // optimization: the first level of the search tree is parallelized + if (index == 0) { + std::vector> fts; + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + auto ft = std::async(std::launch::async, [=]{ auto cpos(pos); n_queens(cpos, index + 1); }); + fts.push_back(std::move(ft)); + } + + for (const auto &ft : fts) { + ft.wait(); + } + } else { // deeper levels are not + for (int col = 0; col < pos.size(); col++) { + pos[index] = col; + n_queens(pos, index + 1); + } + } +} + +int main() +{ + std::vector start(12); // 12: table size + n_queens(start, 0); + std::cout << n_sols << " solutions found.\n"; + return 0; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/N-queens-problem/C++/n-queens-problem-2.cpp b/Task/N-queens-problem/C++/n-queens-problem-2.cpp index 0e2a19d453..afe2df064b 100644 --- a/Task/N-queens-problem/C++/n-queens-problem-2.cpp +++ b/Task/N-queens-problem/C++/n-queens-problem-2.cpp @@ -1,88 +1,257 @@ -#include +// A straight-forward brute-force C++ version with formatted output, +// eschewing obfuscation and C-isms, producing ALL solutions, which +// works on any OS with a text terminal. +// +// Two basic optimizations are applied: +// +// It uses backtracking to only construct potentially valid solutions. +// +// It only computes half the solutions by brute -- once we get the +// queen halfway across the top row, any remaining solutions must be +// reflections of the ones already computed. +// +// This is a bare-bones example, without any progress feedback or output +// formatting controls, which a more complete program might provide. +// +// Beware that computing anything larger than N=14 might take a while. +// (Time gets exponentially worse the higher the number.) + +// Copyright 2014 Michael Thomas Greer +// Distributed under the Boost Software License, Version 1.0. +// http://www.boost.org/LICENSE_1_0.txt + +#include +#include +#include #include +#include +#include +#include #include #include -#include -//-------------------------------------------------------------------------------------------------- -using namespace std; -//-------------------------------------------------------------------------------------------------- -typedef unsigned int uint; - -//-------------------------------------------------------------------------------------------------- -class nQueens_Heuristic +// /////////////////////////////////////////////////////////////////////////// +struct queens +/////////////////////////////////////////////////////////////////////////// // { -public: - void solve( uint n ) { makeList( n ); drawBoard( n ); } + // TYPES ------------------------------------------------------------------- -private: - void drawBoard( uint n ) + // A row or column index. (May be signed or unsigned.) + // + typedef signed char index_type; + + // A 'solution' is a row --> column lookup of queens on the board. + // + // It has lexicographical order and can be transformed with a variety of + // reflections, which, when properly combined, produce all possible + // orientations of a solution. + // + struct solution_type: std::vector + { + typedef std::vector base_type; + + // constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + solution_type( std::size_t N ): base_type( N, -1 ) { } + solution_type( const solution_type& s ): base_type( s ) { } + + // compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . + bool operator < ( const solution_type& s ) const { - system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; - COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); - uint w = 0; - for( uint y = 0, cy = 0; y < n; y++ ) - { - for( uint x = 0; x < n; x++ ) - { - SetConsoleCursorPosition( h, c ); cout << t; - c.Y++; SetConsoleCursorPosition( h, c ); - if( x + 1 == solution[w] ) cout << q; else cout << s; - c.Y++; SetConsoleCursorPosition( h, c ); - cout << t; c.Y = cy; c.X += 4; - } - cy += 2; c.X = 0; c.Y = cy; w++; - } - solution.clear(); odd.clear(); evn.clear(); + auto mm = std::mismatch( begin(), end(), s.begin() ); + return (mm.first != end()) and (*mm.first < *mm.second); } - void makeList( uint n ) + // transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . + void vflip() { std::reverse( begin(), end() ); } + + void hflip() { for (auto& x : *this) x = size() - 1 - x; } + + void transpose() { - uint r = n % 6; - for( uint x = 1; x <= n; x++ ) - { - if( x & 1 ) odd.push_back( x ); - else evn.push_back( x ); - } - if( r == 2 ) - { - swap( odd[0], odd[1] ); - odd.erase( find( odd.begin(), odd.end(), 5 ) ); - odd.push_back( 5 ); - } - else if( r == 3 ) - { - odd.erase( odd.begin() ); odd.erase( odd.begin() ); - odd.push_back( 1 ); odd.push_back( 3 ); - evn.erase( evn.begin() ); evn.push_back( 2 ); - } - vector::iterator it = evn.begin(); - while( it != evn.end() ) - { - solution.push_back( ( *it ) ); - it++; - } - it = odd.begin(); - while( it != odd.end() ) - { - solution.push_back( ( *it ) ); - it++; - } + solution_type result( size() ); + for (index_type y = 0; (std::size_t)y < size(); y++) + result[ (*this)[ y ] ] = y; + swap( result ); + } + }; + + // MEMBER VALUES ----------------------------------------------------------- + + const int N; + std::set solutions; + + // SOLVER ------------------------------------------------------------------ + + queens( int N = 8 ): + N( (N < 0) ? 0 : N ) + { + // Row by row we create a potentially valid solution. + // If a queen can be placed in a valid spot by the time + // we get to the last row, then we've found a solution. + + solution_type solution( N ); + index_type row = 0; + while (true) + { + // Advance the queen along the row + ++solution[ row ]; + + // (If we get past halfway through the first row, we're done.) + if ((row == 0) and (solution[ 0 ] > N/2)) break; + + if (solution[ row ] < N) + { + // If the queen is in a good spot... + if (ok( solution, row, solution[ row ] )) + { + // ...and we're on the last row + if (row == N-1) + { + // Add the solution we found plus all it's reflections + solution_type + s = solution; solutions.insert( s ); + s.vflip(); solutions.insert( s ); + s.hflip(); solutions.insert( s ); + s.vflip(); solutions.insert( s ); + s.transpose(); solutions.insert( s ); + s.vflip(); solutions.insert( s ); + s.hflip(); solutions.insert( s ); + s.vflip(); solutions.insert( s ); + } + // otherwise begin marching a queen along the next row + else solution[ ++row ] = -1; + } + + // When we get to the end of a row's columns then + // we need to backup a row and continue from there. + } + else --row; + } + } + + // HELPER ------------------------------------------------------------------ + // This routine helps the solver by identifying column locations + // that do not conflict with queens already placed in prior rows. + + bool ok( const solution_type& columns, index_type row, index_type column ) + { + for (index_type r = 0; r < row; r++) + { + index_type c = columns[ r ]; + index_type delta_row = row - r; + index_type delta_col = (c < column) ? (column - c) : (c - column); + + if ((c == column) or (delta_row == delta_col)) + return false; + } + return true; + } + + // OUTPUT A SINGLE SOLUTION ------------------------------------------------ + // + // Formatted as (for example): + // + // d1 b2 g3 c4 f5 h6 e7 a8 + // Q - - - - - - - + // - - - - Q - - - + // - - - - - - - Q + // - - - - - Q - - + // - - Q - - - - - + // - - - - - - Q - + // - Q - - - - - - + // - - - Q - - - - + // + friend + std::ostream& + operator << ( std::ostream& outs, const queens::solution_type& solution ) + { + static const char* squares[] = { "- ", "Q " }; + index_type N = solution.size(); + + // Display the queen positions + for (auto n = N; n--; ) + outs << (char)('a' + solution[ n ]) << (N - n) << " "; + + // Display the board + for (auto queen : solution) + { + outs << "\n"; + for (index_type col = 0; col < N; col++) + outs << squares[ col == queen ]; + } + return outs; + } + + // OUTPUT ALL SOLUTIONS ---------------------------------------------------- + // + // Display "no solutions" or "N solutions" followed by + // each individual solution, separated by blank lines. + + friend + std::ostream& + operator << ( std::ostream& outs, const queens& q ) + { + if (q.solutions.empty()) outs << "no"; + else outs << q.solutions.size(); + outs << " solutions"; + + std::size_t n = 1; + for (auto solution : q.solutions) + { + outs << "\n\n#" << n++ << "\n" << solution; } - vector odd, evn, solution; + return outs; + } }; -//-------------------------------------------------------------------------------------------------- -int main( int argc, char* argv[] ) + + +/* /////////////////////////////////////////////////////////////////////////// +string_to ( x ) +/////////////////////////////////////////////////////////////////////////// */ + +template +T string_to( const std::string& s ) { - uint n; nQueens_Heuristic nQH; - while( true ) - { - cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> n; - if( n < 4 ) return 0; - nQH.solve( n ); cout << endl << endl; - } - return 0; + T result; + std::istringstream ss( s ); + ss >> result; + if (!ss.eof()) throw std::runtime_error( "to_string(): invalid conversion" ); + return result; +} + +template +T string_to( const std::string& s ) +{ + try { return string_to ( s ); } + catch (...) { return default_value; } +} + + +/* /////////////////////////////////////////////////////////////////////////// +main program +/////////////////////////////////////////////////////////////////////////// */ + +int usage( const std::string& name ) +{ + std::cerr << + "usage:\n " << name << " 8\n\n" + "" + "Solve the N-Queens problem, brute-force,\n" + "and show all solutions for an 8x8 board.\n\n" + "" + "(Specify a value other than 8 for the board size you want.)\n"; + return 1; +} + +int main( int argc, char** argv ) +{ + signed N = + (argc < 2) ? 8 : + (argc > 2) ? 0 : string_to ( argv[ 1 ] ); + + if (N <= 0) return usage( argv[ 0 ] ); + + std::cout << queens( N ) << "\n"; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/N-queens-problem/C++/n-queens-problem-3.cpp b/Task/N-queens-problem/C++/n-queens-problem-3.cpp new file mode 100644 index 0000000000..83a56c113d --- /dev/null +++ b/Task/N-queens-problem/C++/n-queens-problem-3.cpp @@ -0,0 +1,100 @@ +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +class point +{ +public: + int x, y; + point(){ x = y = 0; } + void set( int a, int b ){ x = a; y = b; } +}; +//-------------------------------------------------------------------------------------------------- +class nQueens +{ +public: + void solve( int c ) + { + _count = c; int len = ( c + 1 ) * ( c + 1 ); _queens = new bool[len]; memset( _queens, 0, len ); + _cl = new bool[c]; memset( _cl, 0, c ); _ln = new bool[c]; memset( _ln, 0, c ); + point pt; pt.set( rand() % c, rand() % c ); putQueens( pt, c ); displayBoard(); + delete [] _queens; delete [] _ln; delete [] _cl; + } + +private: + void displayBoard() + { + system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; + COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); + for( int y = 0, cy = 0; y < _count; y++ ) + { + int yy = y * _count; + for( int x = 0; x < _count; x++ ) + { + SetConsoleCursorPosition( h, c ); cout << t; + c.Y++; SetConsoleCursorPosition( h, c ); + if( _queens[x + yy] ) cout << q; else cout << s; + c.Y++; SetConsoleCursorPosition( h, c ); + cout << t; c.Y = cy; c.X += 4; + } + cy += 2; c.X = 0; c.Y = cy; + } + } + + bool checkD( int x, int y, int a, int b ) + { + if( x < 0 || y < 0 || x >= _count || y >= _count ) return true; + if( _queens[x + y * _count] ) return false; + if( checkD( x + a, y + b, a, b ) ) return true; + return false; + } + + bool check( int x, int y ) + { + if( _ln[y] || _cl[x] ) return false; + if( !checkD( x, y, -1, -1 ) ) return false; + if( !checkD( x, y, 1, -1 ) ) return false; + if( !checkD( x, y, -1, 1 ) ) return false; + if( !checkD( x, y, 1, 1 ) ) return false; + return true; + } + + bool putQueens( point pt, int cnt ) + { + int it = _count; + while( it ) + { + if( !cnt ) return true; + if( check( pt.x, pt.y ) ) + { + _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = true; + point tmp = pt; if( ++tmp.x >= _count ) tmp.x = 0; if( ++tmp.y >= _count ) tmp.y = 0; + if( putQueens( tmp, cnt - 1 ) ) return true; + _queens[pt.x + pt.y * _count] = _cl[pt.x] = _ln[pt.y] = false; + } + if( ++pt.x >= _count ) pt.x = 0; + it--; + } + return false; + } + + int _count; + bool* _queens, *_ln, *_cl; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + nQueens n; int nq; + while( true ) + { + system( "cls" ); cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> nq; + if( nq < 4 ) return 0; n.solve( nq ); cout << endl << endl; + system( "pause" ); + } + return 0; +} +//-------------------------------------------------------------------------------------------------- diff --git a/Task/N-queens-problem/C++/n-queens-problem-4.cpp b/Task/N-queens-problem/C++/n-queens-problem-4.cpp new file mode 100644 index 0000000000..0e2a19d453 --- /dev/null +++ b/Task/N-queens-problem/C++/n-queens-problem-4.cpp @@ -0,0 +1,88 @@ +#include +#include +#include +#include +#include + +//-------------------------------------------------------------------------------------------------- +using namespace std; + +//-------------------------------------------------------------------------------------------------- +typedef unsigned int uint; + +//-------------------------------------------------------------------------------------------------- +class nQueens_Heuristic +{ +public: + void solve( uint n ) { makeList( n ); drawBoard( n ); } + +private: + void drawBoard( uint n ) + { + system( "cls" ); string t = "+---+", q = "| Q |", s = "| |"; + COORD c = { 0, 0 }; HANDLE h = GetStdHandle( STD_OUTPUT_HANDLE ); + uint w = 0; + for( uint y = 0, cy = 0; y < n; y++ ) + { + for( uint x = 0; x < n; x++ ) + { + SetConsoleCursorPosition( h, c ); cout << t; + c.Y++; SetConsoleCursorPosition( h, c ); + if( x + 1 == solution[w] ) cout << q; else cout << s; + c.Y++; SetConsoleCursorPosition( h, c ); + cout << t; c.Y = cy; c.X += 4; + } + cy += 2; c.X = 0; c.Y = cy; w++; + } + solution.clear(); odd.clear(); evn.clear(); + } + + void makeList( uint n ) + { + uint r = n % 6; + for( uint x = 1; x <= n; x++ ) + { + if( x & 1 ) odd.push_back( x ); + else evn.push_back( x ); + } + if( r == 2 ) + { + swap( odd[0], odd[1] ); + odd.erase( find( odd.begin(), odd.end(), 5 ) ); + odd.push_back( 5 ); + } + else if( r == 3 ) + { + odd.erase( odd.begin() ); odd.erase( odd.begin() ); + odd.push_back( 1 ); odd.push_back( 3 ); + evn.erase( evn.begin() ); evn.push_back( 2 ); + } + vector::iterator it = evn.begin(); + while( it != evn.end() ) + { + solution.push_back( ( *it ) ); + it++; + } + it = odd.begin(); + while( it != odd.end() ) + { + solution.push_back( ( *it ) ); + it++; + } + } + + vector odd, evn, solution; +}; +//-------------------------------------------------------------------------------------------------- +int main( int argc, char* argv[] ) +{ + uint n; nQueens_Heuristic nQH; + while( true ) + { + cout << "Enter board size bigger than 3 (0 - 3 to QUIT): "; cin >> n; + if( n < 4 ) return 0; + nQH.solve( n ); cout << endl << endl; + } + return 0; +} +//-------------------------------------------------------------------------------------------------- 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 index b84ee246e3..d195cef13d 100644 --- a/Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp +++ b/Task/N-queens-problem/Common-Lisp/n-queens-problem-1.lisp @@ -1,22 +1,19 @@ -(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 queens (n &optional (m n)) + (if (zerop n) + (list nil) + (loop for solution in (queens (1- n) m) + nconc (loop for new-col from 1 to m + when (loop for row from 1 to n + for col in solution + always (/= new-col col (+ col row) (- col row))) + collect (cons new-col solution))))) -(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 " ". ")))) +(defun print-solution (solution) + (loop for queen-col in solution + do (loop for col from 1 to (length solution) + do (write-char (if (= col queen-col) #\Q #\.))) + (terpri)) (terpri)) -(let ((i 0) (n 8)) - (mapc #'(lambda (s) - (format t "Solution ~a:~%" (incf i)) - (show-solution s n)) - (n-queens n n))) +(defun print-queens (n) + (mapc #'print-solution (queens n))) diff --git a/Task/N-queens-problem/Curry/n-queens-problem-4.curry b/Task/N-queens-problem/Curry/n-queens-problem-4.curry new file mode 100644 index 0000000000..94b41bc710 --- /dev/null +++ b/Task/N-queens-problem/Curry/n-queens-problem-4.curry @@ -0,0 +1,19 @@ +import CLPFD +import Findall + +queens n qs = + qs =:= [_ | _ <- [1..n]] + & domain qs 1 (length qs) + & allDifferent qs + & allSafe qs + & labeling [FirstFail] qs + +allSafe [] = success +allSafe (q:qs) = safe q qs 1 & allSafe qs + +safe :: Int -> [Int] -> Int -> Success +safe _ [] _ = success +safe q (q1:qs) p = q /=# q1+#p & q /=# q1-#p & safe q qs (p+#1) + +-- oneSolution = unpack $ queens 8 +-- allSolutions = findall $ queens 8 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 0a49b9e595..c594facf9d 100644 --- a/Task/N-queens-problem/D/n-queens-problem-2.d +++ b/Task/N-queens-problem/D/n-queens-problem-2.d @@ -1,7 +1,7 @@ enum side = 8; __gshared int[side] board; -bool isUnsafe(in int y) nothrow { +bool isUnsafe(in int y) nothrow @nogc { immutable int x = board[y]; foreach (immutable i; 1 .. y + 1) { immutable int t = board[y - i]; @@ -12,7 +12,7 @@ bool isUnsafe(in int y) nothrow { return false; } -void showBoard() nothrow { +void showBoard() nothrow @nogc { import core.stdc.stdio; static int s = 1; @@ -24,7 +24,7 @@ void showBoard() nothrow { } } -void main() nothrow { +void main() nothrow @nogc { int y = 0; board[0] = -1; diff --git a/Task/N-queens-problem/D/n-queens-problem-3.d b/Task/N-queens-problem/D/n-queens-problem-3.d index c32e2ec6da..48c1875810 100644 --- a/Task/N-queens-problem/D/n-queens-problem-3.d +++ b/Task/N-queens-problem/D/n-queens-problem-3.d @@ -1,4 +1,4 @@ -ulong nQueens(in uint nn) pure nothrow +ulong nQueens(in uint nn) pure nothrow @nogc @safe in { assert(nn > 0 && nn <= 27, "'side' value must be in 1 .. 27."); @@ -38,7 +38,7 @@ in { // Because !d is often faster than d != n. while (d) { // immutable uint pos = 1U << bits.bsf; // Slower. - immutable uint pos = -(cast(int)bits) & bits; + immutable uint pos = -int(bits) & bits; // Mark bit used. Only put current bits on // stack if not zero, so backtracking will diff --git a/Task/N-queens-problem/Eiffel/n-queens-problem.e b/Task/N-queens-problem/Eiffel/n-queens-problem.e new file mode 100644 index 0000000000..8be7bcfb27 --- /dev/null +++ b/Task/N-queens-problem/Eiffel/n-queens-problem.e @@ -0,0 +1,68 @@ +class + QUEENS + +create + make + +feature {NONE} + counter: INTEGER + + place_queens(board: ARRAY[INTEGER]; level: INTEGER) + local + i, j: INTEGER + safe: BOOLEAN + do + if level > board.count + then + counter := counter + 1 + else + from + i := 1 + until + i > board.count + loop + safe := True + from + j := 1 + until + j = level or not safe + loop + if (board[j] = i) + or (j - level = i - board[j]) + or (j - level = board[j] - i) + then + safe := False + end + j := j + 1 + end + if safe + then + board[level] := i + place_queens(board, level + 1) + end + i := i + 1 + end + end + end + +feature + possible_positions_of_n_queens(n: INTEGER): INTEGER + local + board: ARRAY[INTEGER] + do + create board.make_filled (0, 1, n) + counter := 0 + place_queens(board, 1) + Result := counter + end + + make + local + n: INTEGER + do + io.put_string ("Please enter the number of queens: ") + io.read_integer + n := io.last_integer + print("%NPossible number of placings: " + possible_positions_of_n_queens(n).out + "%N") + end +end 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 92cf5a1547..3dce5b80df 100644 --- a/Task/N-queens-problem/Fortran/n-queens-problem-3.f +++ b/Task/N-queens-problem/Fortran/n-queens-problem-3.f @@ -1,122 +1,53 @@ -program queens - use omp_lib +!The preceding program implements recursion using arrays, since Fortran 77 does not allow recursive +!functions. The same algorithm is much easier to follow in Fortran 90, using the RECURSIVE keyword. +!Like previously, the program only counts solutions. It's pretty straightforward to adapt it to print +!them too: one has to replace the 'm = m + 1' instruction with a PRINT statement. + +function numq(n) 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 + integer :: i, n, m, a(n), numq + logical :: up(2*n - 1), down(2*n - 1) + do i = 1, n + a(i) = i end do - + up = .true. + down = .true. + m = 0 + call sub(1) + numq = m 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 + recursive subroutine sub(i) + integer :: i, j, k, p, q, s + do k = i, n + j = a(k) + p = i + j - 1 + q = i - j + n + if(up(p) .and. down(q)) then + if(i == n) then + m = m + 1 + else + up(p) = .false. + down(q) = .false. + s = a(i) + a(i) = a(k) + a(k) = s + call sub(i + 1) + up(p) = .true. + down(q) = .true. + s = a(i) + a(i) = a(k) + a(k) = s + end if + end if end do + end subroutine +end function - 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 +program queens + implicit none + integer :: numq, n, m + do n = 4, 16 + m = numq(n) + print *, n, m + end do end program diff --git a/Task/N-queens-problem/Fortran/n-queens-problem-4.f b/Task/N-queens-problem/Fortran/n-queens-problem-4.f new file mode 100644 index 0000000000..92cf5a1547 --- /dev/null +++ b/Task/N-queens-problem/Fortran/n-queens-problem-4.f @@ -0,0 +1,122 @@ +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/GAP/n-queens-problem.gap b/Task/N-queens-problem/GAP/n-queens-problem.gap index e9f1a405df..617412ddf6 100644 --- a/Task/N-queens-problem/GAP/n-queens-problem.gap +++ b/Task/N-queens-problem/GAP/n-queens-problem.gap @@ -1,37 +1,78 @@ -# Quick and dirty solution, checking all permutations without backtracking (thus it's slow) -IsSafe := function(a) - local n, i, j; - n := Length(a); - for i in [1 .. n - 1] do - for j in [i + 1 .. n] do - if AbsInt(a[j] - a[i]) = j - i then - return false; +NrQueens := function(n) + local a, up, down, m, sub; + a := [1 .. n]; + up := ListWithIdenticalEntries(2*n - 1, true); + down := ListWithIdenticalEntries(2*n - 1, true); + m := 0; + sub := function(i) + local j, k, p, q; + for k in [i .. n] do + j := a[k]; + p := i + j - 1; + q := i - j + n; + if up[p] and down[q] then + if i = n then + m := m + 1; + else + up[p] := false; + down[q] := false; + a[k] := a[i]; + a[i] := j; + sub(i + 1); + up[p] := true; + down[q] := true; + a[i] := a[k]; + a[k] := j; + fi; fi; od; - od; - return true; + end; + sub(1); + return m; end; Queens := function(n) - local p, a, v; + local a, up, down, v, sub; + a := [1 .. n]; + up := ListWithIdenticalEntries(2*n - 1, true); + down := ListWithIdenticalEntries(2*n - 1, true); v := []; - for p in SymmetricGroup(n) do - a := List([1 .. n], i -> i^p); - if IsSafe(a) then - Add(v, a); - fi; - od; + sub := function(i) + local j, k, p, q; + for k in [i .. n] do + j := a[k]; + p := i + j - 1; + q := i - j + n; + if up[p] and down[q] then + if i = n then + Add(v, ShallowCopy(a)); + else + up[p] := false; + down[q] := false; + a[k] := a[i]; + a[i] := j; + sub(i + 1); + up[p] := true; + down[q] := true; + a[i] := a[k]; + a[k] := j; + fi; + fi; + od; + end; + sub(1); return v; end; -v := Queens(8);; -Length(v); -PrintArray(PermutationMat(PermListList([1 .. 8], v[1]), 8)); -[ [ 0, 0, 1, 0, 0, 0, 0, 0 ], - [ 0, 0, 0, 0, 0, 1, 0, 0 ], - [ 0, 1, 0, 0, 0, 0, 0, 0 ], +NrQueens(8); +a := Queens(8);; +PrintArray(PermutationMat(PermList(a[1]), 8)); + +[ [ 1, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0, 1 ], - [ 1, 0, 0, 0, 0, 0, 0, 0 ], + [ 0, 0, 0, 0, 0, 1, 0, 0 ], + [ 0, 0, 1, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 1, 0 ], + [ 0, 1, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 1, 0, 0, 0, 0 ] ] diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-1.hs b/Task/N-queens-problem/Haskell/n-queens-problem-1.hs index d857c8f2a9..5e4436a91e 100644 --- a/Task/N-queens-problem/Haskell/n-queens-problem-1.hs +++ b/Task/N-queens-problem/Haskell/n-queens-problem-1.hs @@ -15,11 +15,10 @@ queens n = map fst $ foldM oneMoreQueen ([],[1..n]) [1..n] where -- given a safe arrangement y of queens in the first i rows, and a list of -- possible choices, "oneMoreQueen y _" returns a list of all the safe -- arrangements of queens in the first (i+1) rows along with remaining choices - oneMoreQueen (y,d) _ = [ (x:y, d\\[x]) | x <- d, safe x y] + oneMoreQueen (y,d) _ = [(x:y, delete x d) | x <- d, safe x] where --- "safe x y" tests whether a queen at column x is safe from previous --- queens as recorded in y -safe x y = and [ x /= c && x /= c + n && x /= c - n | (n,c) <- zip [1..] y] + -- "safe x" tests whether a queen at column x is safe from previous queens + safe x = and [x /= c + n && x /= c - n | (n,c) <- zip [1..] y] -- prints what the board looks like for a solution; with an extra newline printSolution y = do diff --git a/Task/N-queens-problem/Haskell/n-queens-problem-2.hs b/Task/N-queens-problem/Haskell/n-queens-problem-2.hs index d9eac355f8..4836d68251 100644 --- a/Task/N-queens-problem/Haskell/n-queens-problem-2.hs +++ b/Task/N-queens-problem/Haskell/n-queens-problem-2.hs @@ -7,5 +7,5 @@ main = mapM_ print $ queens 8 queens :: Int -> [[Int]] queens n = foldM f [] [1..n] where - f qs k = [q:qs | q <- [1..n] \\ qs, q `notDiag` qs] + f qs _ = [q:qs | q <- [1..n] \\ qs, q `notDiag` qs] q `notDiag` qs = and [abs (q - qi) /= i | (qi,i) <- qs `zip` [1..]] diff --git a/Task/N-queens-problem/MUMPS/n-queens-problem-1.mumps b/Task/N-queens-problem/MUMPS/n-queens-problem-1.mumps new file mode 100644 index 0000000000..a391f1096b --- /dev/null +++ b/Task/N-queens-problem/MUMPS/n-queens-problem-1.mumps @@ -0,0 +1,59 @@ +Queens New count,flip,row,sol + Set sol=0 + For row(1)=1:1:4 Do try(2) ; Not 8, the other 4 are symmetric... + ; + ; Remove symmetric solutions + Set sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do + . New xx,yy + . Kill sol($Translate(sol,12345678,87654321)) ; Vertical flip + . Kill sol($Reverse(sol)) ; Horizontal flip + . Set flip="--------" for xx=1:1:8 Do ; Flip over top left to bottom right diagonal + . . New nx,ny + . . Set yy=$Extract(sol,xx),nx=8+1-xx,ny=8+1-yy + . . Set $Extract(flip,ny)=nx + . . Quit + . Kill sol(flip) + . Set flip="--------" for xx=1:1:8 Do ; Flip over top right to bottom left diagonal + . . New nx,ny + . . Set yy=$Extract(sol,xx),nx=xx,ny=yy + . . Set $Extract(flip,ny)=nx + . . Quit + . Kill sol(flip) + . Quit + ; + ; Display remaining solutions + Set count=0,sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do Quit:sol="" + . New s1,s2,s3,txt,x,y + . Set s1=sol,s2=$Order(sol(s1)),s3="" Set:s2'="" s3=$Order(sol(s2)) + . Set txt="+--+--+--+--+--+--+--+--+" + . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt + . For y=8:-1:1 Do + . . Write !,y," |" + . . For x=1:1:8 Write $Select($Extract(s1,x)=y:" Q",x+y#2:" ",1:"##"),"|" + . . If s2'="" Write " |" + . . If s2'="" For x=1:1:8 Write $Select($Extract(s2,x)=y:" Q",x+y#2:" ",1:"##"),"|" + . . If s3'="" Write " |" + . . If s3'="" For x=1:1:8 Write $Select($Extract(s3,x)=y:" Q",x+y#2:" ",1:"##"),"|" + . . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt + . . Quit + . Set txt=" A B C D E F G H" + . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt Write ! + . Set sol=s3 + . Quit + Quit +try(col) New ok,pcol + If col>8 Do Quit + . New out,x + . Set out="" For x=1:1:8 Set out=out_row(x) + . Set sol(out)=1 + . Quit + For row(col)=1:1:8 Do + . Set ok=1 + . For pcol=1:1:col-1 If row(pcol)=row(col) Set ok=0 Quit + . Quit:'ok + . For pcol=1:1:col-1 If col-pcol=$Translate(row(pcol)-row(col),"-") Set ok=0 Quit + . Quit:'ok + . Do try(col+1) + . Quit + Quit +Do Queens diff --git a/Task/N-queens-problem/MUMPS/n-queens-problem.mumps b/Task/N-queens-problem/MUMPS/n-queens-problem-2.mumps similarity index 88% rename from Task/N-queens-problem/MUMPS/n-queens-problem.mumps rename to Task/N-queens-problem/MUMPS/n-queens-problem-2.mumps index 19b9a533f6..abb582e598 100644 --- a/Task/N-queens-problem/MUMPS/n-queens-problem.mumps +++ b/Task/N-queens-problem/MUMPS/n-queens-problem-2.mumps @@ -1,63 +1,3 @@ -Queens New count,flip,row,sol - Set sol=0 - For row(1)=1:1:4 Do try(2) ; Not 8, the other 4 are symmetric... - ; - ; Remove symmetric solutions - Set sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do - . New xx,yy - . Kill sol($Translate(sol,12345678,87654321)) ; Vertical flip - . Kill sol($Reverse(sol)) ; Horizontal flip - . Set flip="--------" for xx=1:1:8 Do ; Flip over top left to bottom right diagonal - . . New nx,ny - . . Set yy=$Extract(sol,xx),nx=8+1-xx,ny=8+1-yy - . . Set $Extract(flip,ny)=nx - . . Quit - . Kill sol(flip) - . Set flip="--------" for xx=1:1:8 Do ; Flip over top right to bottom left diagonal - . . New nx,ny - . . Set yy=$Extract(sol,xx),nx=xx,ny=yy - . . Set $Extract(flip,ny)=nx - . . Quit - . Kill sol(flip) - . Quit - ; - ; Display remaining solutions - Set count=0,sol="" For Set sol=$Order(sol(sol)) Quit:sol="" Do Quit:sol="" - . New s1,s2,s3,txt,x,y - . Set s1=sol,s2=$Order(sol(s1)),s3="" Set:s2'="" s3=$Order(sol(s2)) - . Set txt="+--+--+--+--+--+--+--+--+" - . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt - . For y=8:-1:1 Do - . . Write !,y," |" - . . For x=1:1:8 Write $Select($Extract(s1,x)=y:" Q",x+y#2:" ",1:"##"),"|" - . . If s2'="" Write " |" - . . If s2'="" For x=1:1:8 Write $Select($Extract(s2,x)=y:" Q",x+y#2:" ",1:"##"),"|" - . . If s3'="" Write " |" - . . If s3'="" For x=1:1:8 Write $Select($Extract(s3,x)=y:" Q",x+y#2:" ",1:"##"),"|" - . . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt - . . Quit - . Set txt=" A B C D E F G H" - . Write !," ",txt Write:s2'="" " ",txt Write:s3'="" " ",txt Write ! - . Set sol=s3 - . Quit - Quit -try(col) New ok,pcol - If col>8 Do Quit - . New out,x - . Set out="" For x=1:1:8 Set out=out_row(x) - . Set sol(out)=1 - . Quit - For row(col)=1:1:8 Do - . Set ok=1 - . For pcol=1:1:col-1 If row(pcol)=row(col) Set ok=0 Quit - . Quit:'ok - . For pcol=1:1:col-1 If col-pcol=$Translate(row(pcol)-row(col),"-") Set ok=0 Quit - . Quit:'ok - . Do try(col+1) - . Quit - Quit -Do Queens - +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ 8 | |##| Q|##| |##| |##| | |##| Q|##| |##| |##| | |##| | Q| |##| |##| +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ +--+--+--+--+--+--+--+--+ diff --git a/Task/N-queens-problem/Mathematica/n-queens-problem-1.math b/Task/N-queens-problem/Mathematica/n-queens-problem-1.math index cb01104e3a..ad7a34caf0 100644 --- a/Task/N-queens-problem/Mathematica/n-queens-problem-1.math +++ b/Task/N-queens-problem/Mathematica/n-queens-problem-1.math @@ -2,8 +2,8 @@ safe[q_List, n_] := With[{l = Length@q}, Length@Union@q == Length@Union[q + Range@l] == Length@Union[q - Range@l] == l] -nQueen[q_List:{}, n_] := +nQueen[q_List: {}, n_] := If[safe[q, n], - If[Length[q] == n, q, - Cases[Flatten[{nQueen[Append[q, #], n]}, 2] & /@ Range[n], - Except[{Null} | {}]]], Null] + If[Length[q] == n, {q}, + Cases[nQueen[Append[q, #], n] & /@ Range[n], + Except[{Null} | {}], {2}]], Null] diff --git a/Task/N-queens-problem/Mathematica/n-queens-problem-4.math b/Task/N-queens-problem/Mathematica/n-queens-problem-4.math new file mode 100644 index 0000000000..a87286c862 --- /dev/null +++ b/Task/N-queens-problem/Mathematica/n-queens-problem-4.math @@ -0,0 +1,44 @@ +dispSol[sol_] := sol /. {1 -> "Q" , 0 -> "-"} // Grid + +solveNqueens[n_] := + Module[{c, m, b, vars}, c = cqueens[n]; m = mqueens[n]; + vars = mqueens2[n]; b = bqueens[Length[m]]; + Partition[LinearProgramming[c, m, b, vars, Integers], n]] + +cqueens[n_] := Table[-1, {i, n^2}] + +bqueens[l_] := Table[{1, -1}, {i, l}] + +mqueens2[n_] := Table[{0, 1}, {i, n^2}] + +mqueens[n_] := + Module[{t, t2, t3, t4}, t = mqueensh[n]; t2 = Append[t, mqueensv[n]]; + t3 = Append[t2, mqueensd[n]]; t4 = Append[t3, mqueensdm[n]]; + Partition[Flatten[t4], n^2]] + +mqueensh[n_] := + Module[{t}, t = Table[0, {i, n}, {j, n^2}]; + For[i = 1, i <= n, i++, + For[j = 1, j <= n, j++, t[[i, ((i - 1)*n) + j]] = 1]]; t] + +mqueensv[n_] := + Module[{t}, t = Table[0, {i, n}, {j, n^2}]; + For[i = 1, i <= n, i++, + For[j = 1, j <= n, j++, t[[j, ((i - 1)*n) + j]] = 1]]; t] + +mqueensd[n_] := + Module[{t}, t = Table[0, {i, (2*n) - 1}, {j, n^2}]; + For[k = 2, k <= 2 n, k++, + For[i = 1, i <= n, i++, + For[j = 1, j <= n, j++, + If[i + j == k, t[[k - 1, ((i - 1)*n) + j]] = 1]]]]; t] + +mqueensdm[n_] := + Module[{t}, t = Table[0, {i, Sum[1, {i, 1 - n, n - 1}]}, {j, n^2}]; + For[k = 1 - n, k <= n - 1, k++, + For[i = 1, i <= n, i++, + For[j = 1, j <= n, j++, + If[i == j - k, t[[k + n, ((i - 1)*n) + j]] = 1]]]]; t] + + +solveNqueens[8] // dispSol diff --git a/Task/N-queens-problem/Pascal/n-queens-problem.pascal b/Task/N-queens-problem/Pascal/n-queens-problem-1.pascal similarity index 100% rename from Task/N-queens-problem/Pascal/n-queens-problem.pascal rename to Task/N-queens-problem/Pascal/n-queens-problem-1.pascal diff --git a/Task/N-queens-problem/Pascal/n-queens-problem-2.pascal b/Task/N-queens-problem/Pascal/n-queens-problem-2.pascal new file mode 100644 index 0000000000..92b7279557 --- /dev/null +++ b/Task/N-queens-problem/Pascal/n-queens-problem-2.pascal @@ -0,0 +1,112 @@ +program NQueens; +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON}{$OPTIMIZATION REGVAR}{$OPTIMIZATION PeepHole} + {$OPTIMIZATION CSE}{$OPTIMIZATION ASMCSE} +{$ELSE} + {$Apptype console} +{$ENDIF} + +uses + sysutils;// TDatetime +const + nmax = 17; +type +{$IFNDEF FPC} + NativeInt = longInt; +{$ENDIF} + //ala Nikolaus Wirth A-1 = H - 8 + //diagonal left (A1) to rigth (H8) + tLR_diagonale = array[-nmax-1..nmax-1] of char; + //diagonal right (A8) to left (H1) + tRL_diagonale = array[0..2*nmax-2] of char; + //up to Col are the used Cols, after that the unused + tFreeCol = array[0..nmax-1] of nativeInt; +var + LR_diagonale:tLR_diagonale; + RL_diagonale:tRL_diagonale; + //Using pChar, cause it is implicit an array + //It is always set to + //@LR_diagonale[row] ,@RL_diagonale[row] + pLR,pRL : pChar; + FreeCol : tFreeCol; + i, + n : nativeInt; + gblCount : nativeUInt; + T0,T1 : TdateTime; +procedure Solution; +var + i : NativeInt; +begin +// Take's a lot of time under DOS/Win32 + If gblCount AND $FFF = 0 then + write(gblCount:10,#8#8#8#8#8#8#8#8#8#8); + // IF n< 9 then + IF n < 0 then + begin + For i := 1 to n do + write(FreeCol[i]:4); + writeln; + end; +end; + +procedure SetQueen(Row:nativeInt); +var + i,Col : nativeInt; +begin +IF row <= n then + begin + For i := row to n do + begin + Col := FreeCol[i]; + //check diagonals occupied + If (ORD(pLR[-Col]) AND ORD(pRL[Col]))<>0 then + begin + //a "free" position is found + //mark it + pRL[ Col]:=#0; //RL_Diagonale[ Row +Col] := 0; + pLR[-Col]:=#0; //LR_Diagonale[ Row -Col] := 0; + //swap FreeRow[Row<->i] + FreeCol[i] := FreeCol[Row]; + //next row + inc(pRL); + inc(pLR); + FreeCol[Row] := Col; + // check next row + SetQueen(Row+1); + //Undo + dec(pLR); + dec(pRL); + FreeCol[Row] := FreeCol[i]; + FreeCol[i] := Col; + pRL[ Col]:=#1; + pLR[-Col]:=#1; + end; + end; + end +else + begin + //solution ist found + inc(gblCount); + //Solution + end; +end; + +begin + For i := 0 to nmax-1 do + FreeCol[i] := i; + //diagonals filled with True = #1 , something <>0 + fillchar(LR_Diagonale[low(LR_Diagonale)],sizeof(tLR_Diagonale),#1); + fillchar(RL_Diagonale[low(RL_Diagonale)],sizeof(tRL_Diagonale),#1); + For n := 1 to nMax do + begin + t0 := time; + pLR:=@LR_Diagonale[0]; + pRL:=@RL_Diagonale[0]; + gblCount := 0; + SetQueen(1); + t1:= time; + WriteLn(n:6,gblCount:12,FormatDateTime(' NN:SS.ZZZ',T1-t0),' secs'); + end; + WriteLn('Fertig'); +end. diff --git a/Task/N-queens-problem/Prolog/n-queens-problem-4.pro b/Task/N-queens-problem/Prolog/n-queens-problem-4.pro index 5cb0a4f6c3..4a5d730491 100644 --- a/Task/N-queens-problem/Prolog/n-queens-problem-4.pro +++ b/Task/N-queens-problem/Prolog/n-queens-problem-4.pro @@ -1,23 +1,16 @@ -% 8 queens problem. -% q(Row) represents a queen, allocated one per row. No rows ever clash. -% The columns are chosen iteratively from available columns held in a -% list, reduced with each allocation, so we need never check verticals. -% For diagonals, we check prior to allocation whether each newly placed -% queen will clash with any of the prior placements. This prevents -% most invalid permutations from ever being attempted. -can_place(_, []) :- !. % success for empty board -can_place(q(R,C),Board) :- % check diagonals against allocated queens - member(q(Ra,Ca), Board), abs(Ra-R) =:= abs(Ca-C), !, fail. -can_place(_,_). % succeed if no diagonals failed +:- initialization(main). -queens([], [], Board, Board). % found a solution -queens([q(R)|Queens], Columns, Board, Solution) :- - nth0(_,Columns,C,Free), can_place(q(R,C),Board), % find all solutions - queens(Queens,Free,[q(R,C)|Board], Solution). % recursively -queens :- - findall(q(N), between(0,7,N), Queens), findall(N, between(0,7,N), Columns), - findall(B, queens(Queens, Columns, [], B), Boards), % backtrack over all - length(Boards, Len), writef('%w solutions:\n', [Len]), % Output solutions - member(R,Boards), reverse(R,Board), writef(' - %w\n', [Board]), fail. -queens. +queens(N,Qs) :- bagof(X, between(1,N,X), Xs), place(Xs,[],Qs). + +place(Xs,Qs,Res) :- + Xs = [] -> Res = Qs + ; select(Q,Xs,Ys), not_diag(Q,Qs,1), place(Ys,[Q|Qs],Res) + . + +not_diag(_, [] , _). +not_diag(Q, [Qh|Qs], D) :- + abs(Q - Qh) =\= D, D1 is D + 1, not_diag(Q,Qs,D1). + + +main :- findall(Qs, (queens(8,Qs), write(Qs), nl), _), halt. diff --git a/Task/N-queens-problem/Prolog/n-queens-problem-5.pro b/Task/N-queens-problem/Prolog/n-queens-problem-5.pro new file mode 100644 index 0000000000..5cb0a4f6c3 --- /dev/null +++ b/Task/N-queens-problem/Prolog/n-queens-problem-5.pro @@ -0,0 +1,23 @@ +% 8 queens problem. +% q(Row) represents a queen, allocated one per row. No rows ever clash. +% The columns are chosen iteratively from available columns held in a +% list, reduced with each allocation, so we need never check verticals. +% For diagonals, we check prior to allocation whether each newly placed +% queen will clash with any of the prior placements. This prevents +% most invalid permutations from ever being attempted. +can_place(_, []) :- !. % success for empty board +can_place(q(R,C),Board) :- % check diagonals against allocated queens + member(q(Ra,Ca), Board), abs(Ra-R) =:= abs(Ca-C), !, fail. +can_place(_,_). % succeed if no diagonals failed + +queens([], [], Board, Board). % found a solution +queens([q(R)|Queens], Columns, Board, Solution) :- + nth0(_,Columns,C,Free), can_place(q(R,C),Board), % find all solutions + queens(Queens,Free,[q(R,C)|Board], Solution). % recursively + +queens :- + findall(q(N), between(0,7,N), Queens), findall(N, between(0,7,N), Columns), + findall(B, queens(Queens, Columns, [], B), Boards), % backtrack over all + length(Boards, Len), writef('%w solutions:\n', [Len]), % Output solutions + member(R,Boards), reverse(R,Board), writef(' - %w\n', [Board]), fail. +queens. diff --git a/Task/N-queens-problem/Python/n-queens-problem-5.py b/Task/N-queens-problem/Python/n-queens-problem-5.py new file mode 100644 index 0000000000..81b2282462 --- /dev/null +++ b/Task/N-queens-problem/Python/n-queens-problem-5.py @@ -0,0 +1,20 @@ +def queens(n): + a = list(range(n)) + up = [True]*(2*n - 1) + down = [True]*(2*n - 1) + def sub(i): + nonlocal a, up, down + for k in range(i, n): + j = a[k] + p = i + j + q = i - j + n - 1 + if up[p] and down[q]: + if i == n - 1: + yield tuple(a) + else: + up[p] = down[q] = False + a[i], a[k] = a[k], a[i] + yield from sub(i + 1) + up[p] = down[q] = True + a[i], a[k] = a[k], a[i] + yield from sub(0) diff --git a/Task/N-queens-problem/REXX/n-queens-problem.rexx b/Task/N-queens-problem/REXX/n-queens-problem.rexx index f339a72f28..cd221cbd0e 100644 --- a/Task/N-queens-problem/REXX/n-queens-problem.rexx +++ b/Task/N-queens-problem/REXX/n-queens-problem.rexx @@ -1,64 +1,51 @@ -/*REXX program place N queens on a NxN chessboard (the 8 queens problem)*/ +/*REXX program places N queens on a NxN chessboard; the 8 queens problem*/ parse arg N . /*get board size arg (if any). */ -if N=='' then N=8 /*No argument? Use the default.*/ -file=1; rank=1; q=0 /*starting place, # of queens. */ +if N=='' then N=8; if N<1 then call noSol /*No arg? Use the default.*/ +rank=1; file=1; q=0 /*starting rank & file; # queens.*/ @.=0; !=left('', 9* (N<18)) /*define empty board, indentation*/ /*═════════════════════════════════════find solution: N queens problem.*/ - do while qN; rank=rank-1 - if rank==0 then call noSol - do j=1 for N - if @.j.rank then do; file=j; @.file.rank=0 - q=q-1; file=j+1 - leave /*j*/ - end - end /*j*/ - end /*do while file>N*/ - end /*else do*/ - end /*while qN; rank=rank-1; if rank==0 then call noSol + do j=1 for N; if \@.j.rank then iterate /*occupied?*/ + file=j; @.file.rank=0; q=q-1; file=j+1; leave /*j*/ + end /*j*/ + end /*while file>N*/ + end /*while qo s" Bob" given-name $! s" Hall" surname $! hiya o> diff --git a/Task/Named-parameters/Perl/named-parameters-1.pl b/Task/Named-parameters/Perl/named-parameters-1.pl index 5a1f09a9c2..8a70bf8457 100644 --- a/Task/Named-parameters/Perl/named-parameters-1.pl +++ b/Task/Named-parameters/Perl/named-parameters-1.pl @@ -1,12 +1,12 @@ -sub funkshun - {my %h = @_; - # Print every argument and its value. +sub funkshun { +my %h = @_; + # Print every argument and its value. print qq(Argument "$_" has value "$h{$_}".\n) foreach sort keys %h; - # If a 'verbosity' argument was passed in, print its value, - # whatever that value may be. - exists $h{verbosity} - and print "Verbosity specified as $h{verbosity}.\n"; - # Say that safe mode is on if 'safe' is set to a true value. - # Otherwise, say that it's off. - print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n";} + # If a 'verbosity' argument was passed in, print its value + # whatever that value may be. + print "Verbosity specified as $h{verbosity}.\n" if exists $h{verbosity}; + # Say that safe mode is on if 'safe' is set to a true value. + # Otherwise, say that it's off. + print "Safe mode ", ($h{safe} ? 'on' : 'off'), ".\n"; +} diff --git a/Task/Named-parameters/Perl/named-parameters-2.pl b/Task/Named-parameters/Perl/named-parameters-2.pl index ab294b3797..708863d6d2 100644 --- a/Task/Named-parameters/Perl/named-parameters-2.pl +++ b/Task/Named-parameters/Perl/named-parameters-2.pl @@ -1,3 +1,7 @@ -funkshun - verbosity => 3, password => 'foobie blech', - extra_lives => 3, '42' => 'answer', password => 'joshua'; +funkshun( + verbosity => 3, + password => 'foobie blech', + extra_lives => 3, + '42' => 'answer', + password => 'joshua' +); diff --git a/Task/Named-parameters/Perl/named-parameters-3.pl b/Task/Named-parameters/Perl/named-parameters-3.pl new file mode 100644 index 0000000000..d61eb166f1 --- /dev/null +++ b/Task/Named-parameters/Perl/named-parameters-3.pl @@ -0,0 +1,37 @@ +sub event +{ + my ($params_ref, $name) = @_; + my %params = %$params_ref; + my @known_params = qw(attendees event food time); + + printf "%s called event() with the following named parameters:\n", + $name // 'Anonymous'; + + say sort map { + sprintf "%s: %s\n", + ucfirst $_, + ref $params{$_} eq ref [] + ? join ', ', @{ $params{$_} } + : $params{$_}; + } grep exists $params{$_}, @known_params; + delete $params{$_} foreach @known_params; + + say "But I didn't recognize these ones:"; + while (my ($key, $val) = each %params) + { + say "$key: $val"; + } +} + +event( + { # Curly braces with no label (e.g. 'sub' before it) + # create a reference to an anonymous hash + attendees => ['Bob', 'Betty', 'George', 'Bertha'], + event => 'birthday', + foo => 'bar', + food => 'cake', + frogblast => 'vent core', + time => 3, + }, + "Joe Schmoe" +); diff --git a/Task/Named-parameters/REXX/named-parameters.rexx b/Task/Named-parameters/REXX/named-parameters-1.rexx similarity index 100% rename from Task/Named-parameters/REXX/named-parameters.rexx rename to Task/Named-parameters/REXX/named-parameters-1.rexx diff --git a/Task/Named-parameters/REXX/named-parameters-2.rexx b/Task/Named-parameters/REXX/named-parameters-2.rexx new file mode 100644 index 0000000000..81cc70065e --- /dev/null +++ b/Task/Named-parameters/REXX/named-parameters-2.rexx @@ -0,0 +1,21 @@ +/* REXX --------------------------------------------------------------- +* 01.07.2014 Walter Pachl +* Argument values must not start with 'arg' +*--------------------------------------------------------------------*/ +x=f(2,3) +Say x +Say '' +y=f('arg2='3,'arg1='2) +Say y +Exit +f: Procedure +Parse Arg p1,p2 +Do i=1 to arg() + If left(arg(i),3)='arg' Then + Parse Value arg(i) With 'arg' j '=' p.j + Else p.i=arg(i) + End +Do i=1 To arg() + Say 'p.'i'='p.i + End +Return p.1**p.2 diff --git a/Task/Narcissist/AutoHotkey/narcissist-1.ahk b/Task/Narcissist/AutoHotkey/narcissist-1.ahk new file mode 100644 index 0000000000..ad1c3bac8b --- /dev/null +++ b/Task/Narcissist/AutoHotkey/narcissist-1.ahk @@ -0,0 +1,4 @@ +Narcissist(Input) { + FileRead, Source, % A_ScriptFullPath + return Input == Source ? "accept" : "reject" +} diff --git a/Task/Narcissist/AutoHotkey/narcissist-2.ahk b/Task/Narcissist/AutoHotkey/narcissist-2.ahk new file mode 100644 index 0000000000..0c86cb7cc1 --- /dev/null +++ b/Task/Narcissist/AutoHotkey/narcissist-2.ahk @@ -0,0 +1,2 @@ +MsgBox, % Narcissist(FileOpen(A_ScriptFullPath, "r").Read()) "`n" + . Narcissist("This isn't the text you're looking for.") diff --git a/Task/Narcissist/C-sharp/narcissist.cs b/Task/Narcissist/C-sharp/narcissist.cs new file mode 100644 index 0000000000..df274cb9c4 --- /dev/null +++ b/Task/Narcissist/C-sharp/narcissist.cs @@ -0,0 +1,28 @@ +using System; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +namespace Narcisisst +{ + class Program + { + public static void Main(string[] args) + { + const string path = @"E:\Narcisisst"; + string[] thisFile = Directory.GetFiles(path , "Program.cs"); + StringBuilder sb = new StringBuilder(); + + foreach (string readLine in File.ReadLines(thisFile[0])) + { + sb.Append(readLine); + sb.Append("\n"); + } + + Console.WriteLine(sb); + string input =String.Empty; + input = Console.ReadLine(); + Console.WriteLine((Regex.IsMatch(sb.ToString(),input))?"accept":"reject"); + Console.ReadKey(); + } + } +} diff --git a/Task/Narcissist/Haskell/narcissist.hs b/Task/Narcissist/Haskell/narcissist.hs new file mode 100644 index 0000000000..370274d501 --- /dev/null +++ b/Task/Narcissist/Haskell/narcissist.hs @@ -0,0 +1 @@ +main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q "main = let fi t e c = if c then t else e in do ct <- getContents; putStrLn $ fi ['a','c','c','e','p','t'] ['r','e','j','e','c','t'] $ take (length ct - 1) ct == let q s = (s ++ show s) in q " diff --git a/Task/Narcissist/JavaScript/narcissist.js b/Task/Narcissist/JavaScript/narcissist-1.js similarity index 100% rename from Task/Narcissist/JavaScript/narcissist.js rename to Task/Narcissist/JavaScript/narcissist-1.js diff --git a/Task/Narcissist/JavaScript/narcissist-2.js b/Task/Narcissist/JavaScript/narcissist-2.js new file mode 100644 index 0000000000..2b9ea05956 --- /dev/null +++ b/Task/Narcissist/JavaScript/narcissist-2.js @@ -0,0 +1,20 @@ +var oFSO = new ActiveXObject("Scripting.FileSystemObject"); +function readfile(fname) { + var h = oFSO.OpenTextFile(fname, 1, false); + var result = h.ReadAll(); + h.Close(); + return result; +} + +if (0 === WScript.Arguments.UnNamed.Count) { + WScript.Echo(WScript.ScriptName,"filename"); + WScript.Quit(); +} + +// first read self +var self = readfile(WScript.ScriptFullName); +// read whatever file is given on commmand line +var whatever = readfile(WScript.Arguments.UnNamed(0)); + +// compare and contrast +WScript.Echo(self === whatever ? "Accept" : "Reject"); diff --git a/Task/Nautical-bell/Haskell/nautical-bell.hs b/Task/Nautical-bell/Haskell/nautical-bell.hs new file mode 100644 index 0000000000..a823b089ad --- /dev/null +++ b/Task/Nautical-bell/Haskell/nautical-bell.hs @@ -0,0 +1,77 @@ +import Control.Concurrent +import Control.Monad +import Data.Time +import Text.Printf + +type Microsecond = Int +type Scheduler = TimeOfDay -> Microsecond + +-- Scheduling +-------------- + +getTime :: TimeZone -> IO TimeOfDay +getTime tz = do + t <- getCurrentTime + return $ localTimeOfDay $ utcToLocalTime tz t + +getGMTTime = getTime utc +getLocalTime = getCurrentTimeZone >>= getTime + +-- Returns the difference between 'y' and the closest higher multiple of 'x' +nextInterval x y + | x > y = x - y + | mod y x > 0 = x - mod y x + | otherwise = 0 + +-- Given a interval in seconds, this function returns time delta in microseconds. +onInterval :: Int -> Scheduler +onInterval interval time = toNext dMS + where + toNext = nextInterval (1000000 * interval) + tDelta = timeOfDayToTime time + dMS = truncate $ 1000000 * tDelta + +doWithScheduler :: Scheduler -> (Int -> IO ()) -> IO ThreadId +doWithScheduler sched task = forkIO $ forM_ [0..] exec + where + exec n = do + t <- getLocalTime + threadDelay $ sched t + task n + +-- Output +--------- + +watchNames = words "Middle Morning Forenoon Afternoon Dog First" +countWords = words "One Two Three Four Five Six Seven Eight" + +-- Executes IO action and then waits for n microseconds +postDelay n fn = fn >> threadDelay n + +termBell = putStr "\a" +termBells n = replicateM_ n $ postDelay 100000 termBell +termBellSeq seq = forM_ seq $ postDelay 500000 . termBells + +toNoteGlyph 1 = "♪" +toNoteGlyph 2 = "♫" +toNoteGlyph _ = "" + +ringBells :: Int -> IO () +ringBells n = do + t <- getLocalTime + let numBells = 1 + (mod n 8) + watch = watchNames!!(mod (div n 8) 8) + count = countWords!!(numBells - 1) + (twos,ones) = quotRem numBells 2 + pattern = (replicate twos 2) ++ (replicate ones 1) + notes = unwords $ map toNoteGlyph pattern + plural = if numBells > 1 then "s" else "" + strFMT = show t ++ ": %s watch, %5s bell%s: " ++ notes ++ "\n" + printf strFMT watch count plural + termBellSeq pattern + +-- Usage +--------- + +bellRinger :: IO ThreadId +bellRinger = doWithScheduler (onInterval (30*60)) ringBells diff --git a/Task/Nautical-bell/J/nautical-bell.j b/Task/Nautical-bell/J/nautical-bell.j new file mode 100644 index 0000000000..3445132def --- /dev/null +++ b/Task/Nautical-bell/J/nautical-bell.j @@ -0,0 +1,61 @@ +require 'strings printf' + +WATCH =: <;._1 ' Middle Morning Forenoon Afternoon Dog First' +ORDINAL =: <;._1 ' One Two Three Four Five Six Seven Eight' +BELL =: 7{a. NB. Terminal bell code (\a or ^G) + +time =: 6!:0 +sleep =: 6!:3 +print =: ucp 1!:2 4: + +shipsWatch =: verb define + PREV_MARK =. _1 _1 + while. do. NB. Loop forever + now =. 3 4 { time '' NB. Current hour & minute + + NB. If we just flipped over to a new half-hour mark + if. (0 30 e.~ {: now) > now -: PREV_MARK do. + PREV_MARK =. now + 'allsWell notes'=.callWatch now + + print allsWell + (ringBell"0~ -@# {. 2|#) notes + print CRLF + end. + + sleep 15.0 + end. +) + +callWatch =: verb define + 'watch bells' =. clock2ship y + + NB. Plural for 0~:bells ordinals are origin-1, not origin-0 + NB. (and similarly 1+bells for notes). + fields=.(0{y);(1{y);(watch{::WATCH);(bells{::ORDINAL);('s'#~0~:bells) + notes =. ; (0 2#:1+bells) #&.> u:16b266b 16b266a NB. ♫♪ + + notes ;~ '%02d:%02d %s watch, %s Bell%s Gone: \t' sprintf fields +) + +clock2ship =: verb define"1 + NB. Convert from "24 hours of 60 minutes" to + NB. "6 watches of 8 bells", and move midnight + NB. from index-origin 0 (0 hrs, 0 minutes) + NB. index-origin 1 (0 watches, 1 bell). + 6 8 #: 48 | _1 + 24 2 #. (, (30-1)&I.)/ y +) + +ringBell =: dyad define + print BELL,y + + NB. x indicates two rings (0) or just one (1) + if. 0=x do. + sleep 0.75 + print BELL + sleep 0.25 + else. + sleep 1.0 + end. + y +) diff --git a/Task/Nautical-bell/Java/nautical-bell.java b/Task/Nautical-bell/Java/nautical-bell.java new file mode 100644 index 0000000000..a42edb783c --- /dev/null +++ b/Task/Nautical-bell/Java/nautical-bell.java @@ -0,0 +1,50 @@ +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.TimeZone; + +public class NauticalBell extends Thread { + + public static void main(String[] args) { + NauticalBell bells = new NauticalBell(); + bells.setDaemon(true); + bells.start(); + try { + bells.join(); + } catch (InterruptedException e) { + System.out.println(e); + } + } + + @Override + public void run() { + DateFormat sdf = new SimpleDateFormat("HH:mm:ss"); + sdf.setTimeZone(TimeZone.getTimeZone("UTC")); + + int numBells = 0; + long time = System.currentTimeMillis(); + long next = time - (time % (24 * 60 * 60 * 1000)); // midnight + + while (next < time) { + next += 30 * 60 * 1000; // 30 minutes + numBells = 1 + (numBells % 8); + } + + while (true) { + long wait = 100L; + time = System.currentTimeMillis(); + if (time - next >= 0) { + String bells = numBells == 1 ? "bell" : "bells"; + String timeString = sdf.format(time); + System.out.printf("%s : %d %s\n", timeString, numBells, bells); + next += 30 * 60 * 1000; + wait = next - time; + numBells = 1 + (numBells % 8); + } + try { + Thread.sleep(wait); + } catch (InterruptedException e) { + System.out.println(e); + } + } + } +} diff --git a/Task/Nautical-bell/Ruby/nautical-bell.rb b/Task/Nautical-bell/Ruby/nautical-bell.rb new file mode 100644 index 0000000000..84923634f7 --- /dev/null +++ b/Task/Nautical-bell/Ruby/nautical-bell.rb @@ -0,0 +1,23 @@ +watches = [ "First", "Middle", "Morning", "Forenoon", "Afternoon", "First dog", "Last dog", "First" ] +watch_ends = [ "00:00", "04:00", "08:00", "12:00", "16:00", "18:00", "20:00", "23:59" ] +words = ["One","Two","Three","Four","Five","Six","Seven","Eight"] +sound = "ding!" + +loop do + time = Time.now + if time.sec == 0 and time.min % 30 == 0 + num = (time.hour * 60 + time.min) / 30 % 8 + num = 8 if num == 0 + hr_min = time.strftime "%H:%M" + idx = watch_ends.find_index {|t| hr_min <= t} + text = "%s - %s watch, %s bell%s gone" % [ + hr_min, + watches[idx], + words[num-1], + num==1 ? "" : "s" + ] + bells = (sound * num).gsub(sound + sound) {|dd| dd + ' '} + puts "%-45s %s" % [text, bells] + end + sleep 1 +end diff --git a/Task/Nautical-bell/Seed7/nautical-bell.seed7 b/Task/Nautical-bell/Seed7/nautical-bell.seed7 new file mode 100644 index 0000000000..89242ab0de --- /dev/null +++ b/Task/Nautical-bell/Seed7/nautical-bell.seed7 @@ -0,0 +1,37 @@ +$ include "seed7_05.s7i"; + include "time.s7i"; + include "duration.s7i"; + include "keybd.s7i"; + +const array string: watch is [] ("Middle", "Morning", "Forenoon", "Afternoon", "Dog", "First"); +const array string: bells is [] ("One Bell", "Two Bells", "Three Bells", "Four Bells", "Five Bells", "Six Bells", "Seven Bells", "Eight Bells"); + +const func time: truncToHalfHour (in time: aTime) is func + result + var time: truncatedTime is time.value; + begin + truncatedTime := aTime; + truncatedTime.minute := aTime.minute div 30 * 30; + truncatedTime.second := 0; + truncatedTime.micro_second := 0; + end func; + +const proc: main is func + local + var time: nextTime is time.value; + var time: midnight is time.value; + var integer: minutes is 0; + begin + writeln; + nextTime := truncToHalfHour(time(NOW)); + midnight := truncToDay(nextTime); + while TRUE do + nextTime +:= 30 . MINUTES; + await(nextTime); + minutes := toMinutes(nextTime - midnight); + writeln(str_hh_mm(nextTime, ":") <& " - " <& + watch[succ((minutes - 30) mdiv 240 mod 6)] <& " watch - " <& + bells[succ((minutes - 30) mdiv 30 mod 8)] <& " Gone."); + flush(OUT); + end while; + end func; diff --git a/Task/Non-continuous-subsequences/00DESCRIPTION b/Task/Non-continuous-subsequences/00DESCRIPTION index 1a69a354d5..0a7ec01075 100644 --- a/Task/Non-continuous-subsequences/00DESCRIPTION +++ b/Task/Non-continuous-subsequences/00DESCRIPTION @@ -4,7 +4,8 @@ A ''subsequence'' contains some subset of the elements of this sequence, in the A ''continuous'' subsequence is one in which no elements are missing between the first and last elements of the subsequence. -Note: Subsequences are defined ''structurally'', not by their contents. So a sequence ''a,b,c,d'' will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. +Note: Subsequences are defined ''structurally'', not by their contents. +So a sequence ''a,b,c,d'' will always have the same subsequences and continuous subsequences, no matter which values are substituted; it may even be the same value. '''Task''': Find all non-continuous subsequences for a given sequence. Example: For the sequence ''1,2,3,4'', there are five non-continuous subsequences, namely ''1,3''; ''1,4''; ''2,4''; ''1,3,4'' and ''1,2,4''. diff --git a/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp new file mode 100644 index 0000000000..0ee85f9c37 --- /dev/null +++ b/Task/Non-continuous-subsequences/C++/non-continuous-subsequences.cpp @@ -0,0 +1,57 @@ +/* + Not best code, wrote it really quick. Will add updated code using more C++11 features soon! +*/ + +#include +#include +#include +#include + +int main() { + std::vector sequence = { 0, 1, 2, 3, 4 }; + std::vector work = { 0 }; + std::vector> results; + while (work != sequence) { + bool zeroed = false; + size_t index_zero_started = 0; + for (size_t i = 0; i < work.size(); ++i) { + if (work[i] >= sequence.size()) { + if (i == 0) { + work[i] = 0; + work.push_back(0); + index_zero_started = i; + } else { + ++work[i - 1]; + for (size_t j = i; j < work.size(); ++j) { + work[j] = 0; + } + index_zero_started = i - 1; + } + zeroed = true; + break; + } + } + if (zeroed) { + for (size_t i = index_zero_started + 1; i < work.size(); ++i) { + work[i] = work[i - 1] + 1; + } + } else { + std::vector temp_differences; + std::adjacent_difference(std::begin(work), std::end(work), std::back_inserter(temp_differences)); + if (std::find_if(std::begin(temp_differences) + 1, std::end(temp_differences), + [](const int& n) { return n > 1; }) != std::end(temp_differences)) { + results.push_back(work); + } + ++work.back(); + } + } + std::cout << "Non-continuous subsequences of "; + std::copy(std::begin(sequence), std::end(sequence), std::ostream_iterator(std::cout, " ")); + std::cout << std::endl; + for (auto& e: results) { + std::cout << "- "; + std::copy(std::begin(e), std::end(e), std::ostream_iterator(std::cout, " ")); + std::cout << std::endl; + } + return 0; +} diff --git a/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences.coffee b/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences.coffee new file mode 100644 index 0000000000..083089fd98 --- /dev/null +++ b/Task/Non-continuous-subsequences/CoffeeScript/non-continuous-subsequences.coffee @@ -0,0 +1,57 @@ +is_contigous_binary = (n) -> + # return true if binary representation of n is + # of the form 1+0+ + # examples: + # 0 true + # 1 true + # 100 true + # 110 true + # 1001 false + # 1010 false + + # special case zero, or you'll get an infinite loop later + return true if n == 0 + + # first remove 0s from end + while n % 2 == 0 + n = n / 2 + + # next, take advantage of the fact that a continuous + # run of 1s would be of the form 2^n - 1 + is_power_of_two(n + 1) + +is_power_of_two = (m) -> + while m % 2 == 0 + m = m / 2 + m == 1 + +seq_from_bitmap = (arr, n) -> + # grabs elements from array according to a bitmap + # e.g. if n == 13 (1101), and arr = ['a', 'b', 'c', 'd'], + # then return ['a', 'c', 'd'] (flipping bits to 1011, so + # that least significant bit comes first) + i = 0 + new_arr = [] + while n > 0 + if n % 2 == 1 + new_arr.push arr[i] + n -= 1 + n /= 2 + i += 1 + new_arr + +non_contig_subsequences = (arr) -> + # Return all subsqeuences from an array that have a "hole" in + # them. The order of the subsequences is not specified here. + + # This algorithm uses binary counting, so it is limited to + # small lists, but large lists would be unwieldy regardless. + bitmasks = [0...Math.pow(2, arr.length)] + (seq_from_bitmap arr, n for n in bitmasks when !is_contigous_binary n) + +arr = [1,2,3,4] +console.log non_contig_subsequences arr +for n in [1..10] + arr = [1..n] + num_solutions = non_contig_subsequences(arr).length + console.log "for n=#{n} there are #{num_solutions} solutions" diff --git a/Task/Non-continuous-subsequences/D/non-continuous-subsequences-1.d b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-1.d index d28fc9fdf3..7f40789594 100644 --- a/Task/Non-continuous-subsequences/D/non-continuous-subsequences-1.d +++ b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-1.d @@ -1,18 +1,18 @@ -import std.stdio; - -T[][] ncsub(T)(in T[] seq, in int s=0) pure nothrow { +T[][] ncsub(T)(in T[] seq, in uint s=0) pure nothrow @safe { if (seq.length) { - T[][] aux; - foreach (ys; ncsub(seq[1..$], s + !(s % 2))) + typeof(return) aux; + foreach (ys; ncsub(seq[1 .. $], s + !(s % 2))) aux ~= seq[0] ~ ys; - return aux ~ ncsub(seq[1..$], s + s % 2); + return aux ~ ncsub(seq[1 .. $], s + s % 2); } else - return new T[][](s >= 3, 0); + return new typeof(return)(s >= 3, 0); } -void main() { - writeln(ncsub([1, 2, 3])); - writeln(ncsub([1, 2, 3, 4])); - foreach (nc; ncsub([1, 2, 3, 4, 5])) - writeln(nc); +void main() @safe { + import std.stdio; + + [1, 2, 3].ncsub.writeln; + [1, 2, 3, 4].ncsub.writeln; + foreach (const nc; [1, 2, 3, 4, 5].ncsub) + nc.writeln; } diff --git a/Task/Non-continuous-subsequences/D/non-continuous-subsequences-2.d b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-2.d index 3c74a151e3..3b912956f4 100644 --- a/Task/Non-continuous-subsequences/D/non-continuous-subsequences-2.d +++ b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-2.d @@ -1,29 +1,28 @@ struct Ncsub(T) { T[] seq; - int opApply(int delegate(ref int[]) dg) const { - immutable int n = seq.length; + int opApply(int delegate(ref T[]) dg) const { + immutable n = seq.length; int result; - auto S = new int[n]; + auto S = new T[n]; - FOR_I: - foreach (i; 1 .. 1 << seq.length) { - int len_S; + OUTER: foreach (immutable i; 1 .. 1 << n) { + uint lenS; bool nc = false; - foreach (j; 0 .. seq.length + 1) { - immutable int k = i >> j; + foreach (immutable j; 0 .. n + 1) { + immutable k = i >> j; if (k == 0) { if (nc) { - auto auxS = S[0 .. len_S]; + auto auxS = S[0 .. lenS]; result = dg(auxS); if (result) - break FOR_I; + break OUTER; } break; } else if (k % 2) { - S[len_S] = seq[j]; - len_S++; - } else if (len_S) + S[lenS] = seq[j]; + lenS++; + } else if (lenS) nc = true; } } @@ -34,9 +33,10 @@ struct Ncsub(T) { void main() { import std.array, std.range; - //assert(iota(24).array().Ncsub!int().walkLength() == 16_776_915); - auto r = array(iota(24)); - int counter; + + //assert(24.iota.array.Ncsub!int.walkLength == 16_776_915); + auto r = 24.iota.array; + uint counter = 0; foreach (s; Ncsub!int(r)) counter++; assert(counter == 16_776_915); diff --git a/Task/Non-continuous-subsequences/D/non-continuous-subsequences-3.d b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-3.d new file mode 100644 index 0000000000..3d60df8961 --- /dev/null +++ b/Task/Non-continuous-subsequences/D/non-continuous-subsequences-3.d @@ -0,0 +1,34 @@ +import std.stdio, std.array, std.range, std.concurrency; + +Generator!(T[]) ncsub(T)(in T[] seq) { + return new typeof(return)({ + immutable n = seq.length; + auto S = new T[n]; + + foreach (immutable i; 1 .. 1 << n) { + uint lenS = 0; + bool nc = false; + foreach (immutable j; 0 .. n + 1) { + immutable k = i >> j; + if (k == 0) { + if (nc) + yield(S[0 .. lenS]); + break; + } else if (k % 2) { + S[lenS] = seq[j]; + lenS++; + } else if (lenS) + nc = true; + } + } + }); +} + +void main() { + assert(24.iota.array.ncsub.walkLength == 16_776_915); + + [1, 2, 3].ncsub.writeln; + [1, 2, 3, 4].ncsub.writeln; + foreach (const nc; [1, 2, 3, 4, 5].ncsub) + nc.writeln; +} diff --git a/Task/Non-continuous-subsequences/Java/non-continuous-subsequences.java b/Task/Non-continuous-subsequences/Java/non-continuous-subsequences.java new file mode 100644 index 0000000000..db596fdbe0 --- /dev/null +++ b/Task/Non-continuous-subsequences/Java/non-continuous-subsequences.java @@ -0,0 +1,16 @@ +public class NonContinuousSubsequences { + + public static void main(String args[]) { + seqR("1234", "", 0, 0); + } + + private static void seqR(String s, String c, int i, int added) { + if (i == s.length()) { + if (c.trim().length() > added) + System.out.println(c); + } else { + seqR(s, c + s.charAt(i), i + 1, added + 1); + seqR(s, c + ' ', i + 1, added); + } + } +} diff --git a/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences.pop11 b/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences.pop11 new file mode 100644 index 0000000000..7e11154186 --- /dev/null +++ b/Task/Non-continuous-subsequences/Pop11/non-continuous-subsequences.pop11 @@ -0,0 +1,24 @@ +define ncsubseq(l); + lvars acc = [], gap_started = false, is_continuous = true; + define do_it(l1, l2); + dlocal gap_started; + lvars el, save_is_continuous = is_continuous; + if l2 = [] then + if not(is_continuous) then + cons(l1, acc) -> acc; + endif; + else + front(l2) -> el; + back(l2) -> l2; + not(gap_started) and is_continuous -> is_continuous; + do_it(cons(el, l1), l2); + save_is_continuous -> is_continuous; + not(l1 = []) or gap_started -> gap_started; + do_it(l1, l2); + endif; + enddefine; + do_it([], rev(l)); + acc; +enddefine; + +ncsubseq([1 2 3 4 5]) => diff --git a/Task/Non-continuous-subsequences/Seed7/non-continuous-subsequences.seed7 b/Task/Non-continuous-subsequences/Seed7/non-continuous-subsequences.seed7 new file mode 100644 index 0000000000..d746a0637f --- /dev/null +++ b/Task/Non-continuous-subsequences/Seed7/non-continuous-subsequences.seed7 @@ -0,0 +1,30 @@ +$ include "seed7_05.s7i"; + +const func array bitset: ncsub (in bitset: seq, in integer: s) is func + result + var array bitset: subseq is 0 times {}; + local + var bitset: x is {}; + var bitset: xs is {}; + var bitset: ys is {}; + begin + if seq <> {} then + x := {min(seq)}; + xs := seq - x; + for ys range ncsub(xs, s + 1 - s rem 2) do + subseq &:= x | ys; + end for; + subseq &:= ncsub(xs, s + s rem 2); + elsif s >= 3 then + subseq &:= {}; + end if; + end func; + +const proc: main is func + local + var bitset: seq is {}; + begin + for seq range ncsub({1, 2, 3, 4}, 0) do + writeln(seq); + end for; + end func; 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 50fababd8d..10fb3fb320 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,8 +1,8 @@ -import std.stdio, std.algorithm, std.ascii, std.array; +import std.stdio, std.algorithm, std.ascii, std.array, std.string; alias Digits = ubyte[]; -Digits toBase(ulong number, in ubyte base) pure nothrow { +Digits toBase(ulong number, in ubyte base) pure nothrow @safe { Digits result; while (number) { result = number % base ~ result; @@ -11,19 +11,19 @@ Digits toBase(ulong number, in ubyte base) pure nothrow { return result; } -enum fromBase = (in Digits digits, in ubyte base) pure nothrow => +enum fromBase = (in Digits digits, in ubyte base) pure nothrow @safe @nogc => reduce!((n, k) => n * base + k)(0UL, digits); immutable myDigits = digits ~ lowercase; -enum fromDigits = (in Digits digits) pure nothrow => +enum fromDigits = (in Digits digits) pure nothrow /*@safe*/ => digits.map!(d => myDigits[d]).array; -enum convert = (in dchar d) pure nothrow => - cast(ubyte)(d.isDigit ? d - '0' : d.toLower - 'a' + 10); +enum convert = (in dchar d) pure nothrow @safe @nogc => + cast(ubyte)(d.isDigit ? d - '0' : std.ascii.toLower(d) - 'a' + 10); -enum toDigits = (in string number) pure /*nothrow*/ => - number.map!convert.array; +enum toDigits = (in string number) pure nothrow @safe => + number.representation.map!convert.array; void main() { "1ABcd".toDigits.fromBase(16).writeln; diff --git a/Task/Non-decimal-radices-Convert/Perl/non-decimal-radices-convert-3.pl b/Task/Non-decimal-radices-Convert/Perl/non-decimal-radices-convert-3.pl new file mode 100644 index 0000000000..ffa6da015a --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Perl/non-decimal-radices-convert-3.pl @@ -0,0 +1,3 @@ +use Math::BaseCnv 'cnv'; +print cnv("1a", 16, 10),"\n"; # "1a" from hex to decimal prints 26 +print lc(cnv(26, 10, 16)),"\n"; # 26 from decimal to hex prints "1a" diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx new file mode 100644 index 0000000000..b09919bbb1 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-1.rexx @@ -0,0 +1,12 @@ + ┌────────────────────────────────────────────────────────────────────┐ +┌─┘ Input to this program (bases must be positive integers > 1): └─┐ +│ │ +│ x is required (it may have a sign). │ +│ toBase the base to convert X to. │ +│ inBase the base X is expressed in. │ +│ │ +│ If X has a leading sign, it is maintained (kept) after conversion. │ +│ │ +│ toBase or inBase can be a comma (,) which causes the default │ +└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘ + └────────────────────────────────────────────────────────────────────┘ diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx new file mode 100644 index 0000000000..bc81c530d7 --- /dev/null +++ b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert-2.rexx @@ -0,0 +1,37 @@ +/*REXX pgm converts integers from one base to another (base 2 ──► 90). */ +@abc = 'abcdefghijklmnopqrstuvwxyz' /*the lowercase (Latin) alphabet.*/ +parse upper var @abc @abcU /*uppercase a version of @abc. */ +@@ = 0123456789 || @abc || @abcU /*prefix 'em with numeric digits.*/ +@@ = @@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ + /* [↑] all chars must be viewable*/ +numeric digits 3000 /*what da hey, support gihugeics.*/ +maxB=length(@@) /*max base (radix) supported here*/ +parse arg x toB inB 1 ox . 1 sigX 2 x2 . /*get: 3 args, origX, sign···*/ +if pos(sigX,"+-")\==0 then x=x2 /*Does X have a leading sign? */ + else sigX= /*Nope. No leading sign for X. */ +if x=='' then call erm /*if no X number, issue error.*/ +if toB=='' | toB=="," then toB=10 /*if skipped, assume default (10)*/ +if inB=='' | inB=="," then inB=10 /* " " " " " */ +if inB<2 | inb>maxB | \datatype(inB,'W') then call erb 'inBase ' inB +if toB<2 | toB>maxB | \datatype(toB,'W') then call erb 'toBase ' toB +#=0 /*result of converted X (base 10)*/ + do j=1 for length(x) /*convert X, base inB ──► base 10*/ + ?=substr(x,j,1) /*pick off a numeral/digit from X*/ + _=pos(?, @@) /*calculate this numeral's value.*/ + if _==0 | _>inB then call erd x /*_ character an illegal numeral?*/ + #=#*inB+_-1 /*build a new number, dig by dig.*/ + end /*j*/ /* [↑] this also verifies digits*/ +y= /*the value of X in base B. */ + do while # >= toB /*convert #, base 10 ──► base toB*/ + y=substr(@@, (#//toB)+1, 1)y /*construct the output number. */ + #=#%toB /*··· and whittle # down also. */ + end /*while*/ /* [↑] process leaves a residual*/ + /* [↓] Y is the residual*/ +y=sigX || substr(@@, #+1, 1)y /*prepend the sign if it existed.*/ +say ox "(base" inB')' center('is',20) y "(base" toB')' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────one─liner subroutines───────────────*/ +erb: call ser 'illegal' arg(1)", it must be in the range: 2──►"maxB +erd: call ser 'illegal digit/numeral ['?"] in: " x +erm: call ser 'no argument specified.' +ser: say; say '***error!***'; say arg(1); exit 13 diff --git a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx b/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx deleted file mode 100644 index 8561942af0..0000000000 --- a/Task/Non-decimal-radices-Convert/REXX/non-decimal-radices-convert.rexx +++ /dev/null @@ -1,46 +0,0 @@ -/*REXX program converts numbers from one base to another, from 2 ──► 90.*/ -/*┌────────────────────────────────────────────────────────────────────┐ -┌─┘ Input to this program (bases must be positive whole numbers): └─┐ -│ │ -│ x is required (it may have a sign). │ -│ toBase the base to convert X to. │ -│ inBase the base X is expressed in. │ -│ │ -│ toBase or inBase can be a comma (,) which causes the default │ -└─┐ of 10 to be used. The limits of bases are: 2 ──► 90. ┌─┘ - └────────────────────────────────────────────────────────────────────┘*/ -@abc='abcdefghijklmnopqrstuvwxyz' /*lowercase Latin alphabet. */ -@abcU=@abc; upper @abcU /*go whole hog and extend 'em. */ -@@@=0123456789||@abc||@abcU /*prefix 'em with numeric digits.*/ -@@@=@@@'<>[]{}()?~!@#$%^&*_=|\/;:¢¬≈' /*add some special chars as well.*/ - /*special chars must be viewable.*/ -numeric digits 1000 /*what da hey, support gihugeics.*/ -maxB=length(@@@) /*max base (radix) supported here*/ -parse arg x toB inB 1 ox . /*get a number, toBase, inBase*/ -if toB=='' | toB==',' then toB=10 /*if skipped, assume default (10)*/ -if inB=='' | inB==',' then inB=10 /* " " " " " */ -if inB<2 | inb>maxB then call erb 'inBase',inB /*bad boy inBase.*/ -if toB<2 | tob>maxB then call erb 'toBase',toB /* " " toBase.*/ -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". */ - if v==0 | v>inB then call erd x,j,inB /*illegal "digit"? */ - #=#*inB+v-1 /*construct new num, dig by dig. */ - end /*j*/ - -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*/ - -y=sigX || substr(@@@,#+1,1)y /*prepend the sign if it existed.*/ -say ox "(base" inB')' center('is',20) y "(base" toB')' /*show & tell.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────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 diff --git a/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert.rb b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert.rb new file mode 100644 index 0000000000..5cce70446a --- /dev/null +++ b/Task/Non-decimal-radices-Convert/Ruby/non-decimal-radices-convert.rb @@ -0,0 +1,13 @@ +class String + def convert_base(from, to) + Integer(self, from).to_s(to) + # self.to_i(from).to_s(to) #if you don't want exceptions + end +end + +# first three taken from TCL +p "12345".convert_base(10, 23) # => "107h" +p "107h".convert_base(23, 7) # =>"50664" +p "50664".convert_base(7, 10) # =>"12345" +p "1038334289300125869792154778345043071467300".convert_base(10, 36) # =>"zombieseatingdeadvegetables" +p "ff".convert_base(15, 10) # => ArgumentError diff --git a/Task/Non-decimal-radices-Input/Go/non-decimal-radices-input.go b/Task/Non-decimal-radices-Input/Go/non-decimal-radices-input.go index 5609efb7bf..5e29cf4d80 100644 --- a/Task/Non-decimal-radices-Input/Go/non-decimal-radices-input.go +++ b/Task/Non-decimal-radices-Input/Go/non-decimal-radices-input.go @@ -1,7 +1,6 @@ package main import ( - "bytes" "fmt" "math/big" "strconv" @@ -15,27 +14,31 @@ func main() { // ParseInt handles arbitrary bases from 2 to 36, and returns // a result of the requested size (64 bits shown here.) + // If the base argument is zero the base is determined by prefix + // as with math/big below. x64, _ := strconv.ParseInt("3c2", 19, 64) fmt.Println(x64) - // package bytes+fmt: allows direct conversion from strings - // to integer types for bases 2, 8, 10, and 16. - // (Fscanf and scanf are more common for reading from - // files or stdin than for reading from strings.) - fmt.Fscanf(bytes.NewBufferString("1101"), "%b", &x) + // package fmt: allows direct conversion from strings, standard + // input, or from an io.Reader (file, buffer, etc) to integer types + // for bases 2, 8, 10, and 16 or to any type that implements the + // fmt.Scanner interface (e.g. a big.Int). + // (Fscanf and Scanf are more common for reading from + // an io.Reader or stdin than Sscanf for reading from strings.) + fmt.Sscanf("1101", "%b", &x) fmt.Println(x) - fmt.Fscanf(bytes.NewBufferString("15"), "%o", &x) + fmt.Sscanf("15", "%o", &x) fmt.Println(x) - fmt.Fscanf(bytes.NewBufferString("13"), "%d", &x) + fmt.Sscanf("13", "%d", &x) fmt.Println(x) - fmt.Fscanf(bytes.NewBufferString("d"), "%x", &x) + fmt.Sscanf("d", "%x", &x) fmt.Println(x) - // package big: allows conversion from string to big integer. - // any base from 2 to 16 can be specified as second parameter. + // package math/big: allows conversion from string to big integer. + // any base from 2 to 36 can be specified as second parameter. var z big.Int z.SetString("111", 3) fmt.Println(&z) @@ -52,4 +55,9 @@ func main() { z.SetString("0xd", 0) // 0x -> base 16 fmt.Println(&z) + + // As mentioned, a big.Int (or any type implementing fmt.Scanner) + // can also be use with any of the fmt scanning functions. + fmt.Sscanf("15", "%o", &z) + fmt.Println(&z) } diff --git a/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx b/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx index ce537a4d74..28a6519d16 100644 --- a/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx +++ b/Task/Non-decimal-radices-Input/REXX/non-decimal-radices-input.rexx @@ -1,26 +1,17 @@ /*REXX program demonstrates REXX's ability to handle non-decimal radices*/ -/*┌────────────────────────────────────────────────────────────────────┐ -┌─┘ In REXX, there are no numeric-type variables (integer, float, real,└─┐ -│ logical, complex, double, etc), only character. Everything is stored │ -│ as a character string. Arithmetic is done almost exactly the way a │ -│ schoolchild would perform it. To add, align the two numbers up (right │ -│ justified, with the decimal being the pivot) and simply add the columns│ -│ up, noting carries and the signs. Multiplication and division are │ -└─┐ simarily performed. ┌─┘ - └────────────────────────────────────────────────────────────────────┘*/ a=123 /*all of these assignments are identical: */ -b='123' /*there is no difference in the assignments*/ +b='123' c='1' || "2" || '3' d= 1 || 2 || 3 e= 12 || 3 f=120 + 3 -g=substr(9912388,3,2) +g=substr(9912388,3,3) h=left(123456,3) i=right(777.123,3) -j=12 + ' 3 ' -k=0000000123.0000/1 /*divison "normalizes the number (───► 123)*/ +j=120 + ' 3 ' +k=0000000123.0000/1 /*division "normalizes the number (──► 123)*/ - /*parsing then, of a decimal number is no */ + /*parsing of a decimal number is no */ /*different then parsing a character string*/ /*because decimal numbers ARE character */ /*strings. As such, numbers may have */ @@ -29,7 +20,7 @@ k=0000000123.0000/1 /*divison "normalizes the number (───► 123) /*leading sign). */ aa=' 123 ' /*AA's exact value is different the A, */ - /*but it's numerically equal to A. */ + /*but it's numerically equal to A. */ bb=123. /*the same can be said for the rest of 'em.*/ cc=+123 dd=' + 123' @@ -67,9 +58,9 @@ cyanF=c2b('copernicium') /*some REXXes support this, others don't. */ cyanG=c2d('nilla') /*converts a character string to decimal. */ cyanH=d2c(251) /*converts a decimal number to character. */ -cyanI=x2d(fab) /*converts a hexadcimal string to decinal.*/ -cyanJ=x2c(fab) /*converts a hexadcimal string to chars. */ -cyanK=x2b(fab) /*converts a hexadcimal string to binary. */ +cyanI=x2d(fab) /*converts a hexadecimal string to decimal*/ +cyanJ=x2c(fab) /*converts a hexadecimal string to chars. */ +cyanK=x2b(fab) /*converts a hexadecimal string to binary.*/ befog=d2b(144) /*there's no dec──►binary, but see below.*/ unfog=b2d(101) /*there's no bin──►decimal, but see below.*/ diff --git a/Task/Non-decimal-radices-Output/Bc/non-decimal-radices-output.bc b/Task/Non-decimal-radices-Output/Bc/non-decimal-radices-output.bc new file mode 100644 index 0000000000..475342006a --- /dev/null +++ b/Task/Non-decimal-radices-Output/Bc/non-decimal-radices-output.bc @@ -0,0 +1,7 @@ +for(i=1;i<10;i++) { + obase=10; print i," " + obase=8; print i," " + obase=3; print i," " + obase=2; print i + print "\n" +} diff --git a/Task/Non-decimal-radices-Output/C-sharp/non-decimal-radices-output.cs b/Task/Non-decimal-radices-Output/C-sharp/non-decimal-radices-output.cs new file mode 100644 index 0000000000..4d2280fb6d --- /dev/null +++ b/Task/Non-decimal-radices-Output/C-sharp/non-decimal-radices-output.cs @@ -0,0 +1,20 @@ +using System; + +namespace NonDecimalRadicesOutput +{ + class Program + { + static void Main(string[] args) + { + for (int i = 0; i < 42; i++) + { + string binary = Convert.ToString(i, 2); + string octal = Convert.ToString(i, 8); + string hexadecimal = Convert.ToString(i, 16); + Console.WriteLine(string.Format("Decimal: {0}, Binary: {1}, Octal: {2}, Hexadecimal: {3}", i, binary, octal, hexadecimal)); + } + + Console.ReadKey(); + } + } +} diff --git a/Task/Non-decimal-radices-Output/Go/non-decimal-radices-output.go b/Task/Non-decimal-radices-Output/Go/non-decimal-radices-output.go index 380f6b42ba..4821a8647f 100644 --- a/Task/Non-decimal-radices-Output/Go/non-decimal-radices-output.go +++ b/Task/Non-decimal-radices-Output/Go/non-decimal-radices-output.go @@ -7,22 +7,19 @@ import ( ) func main() { - // package strconv: - // Itoa is the most common int to string conversion. it is base 10 only. - x := strconv.Itoa(13) - fmt.Printf("%q\n", x) - - // FormatInt handles arbitrary bases from 2 to 36. - x = strconv.FormatInt(1313, 19) - fmt.Printf("%q\n", x) - - // package fmt: allows direct conversion from integer - // to string types for bases 2, 8, 10, and 16. + // fmt.Print formats integer types directly as bases 2, 8, 10, and 16. fmt.Printf("%b\n", 13) fmt.Printf("%o\n", 13) fmt.Printf("%d\n", 13) fmt.Printf("%x\n", 13) - - // package big: string conversion is base 10 only. - fmt.Println(big.NewInt(13)) + // big ints work with fmt as well. + d := big.NewInt(13) + fmt.Printf("%b\n", d) + fmt.Printf("%o\n", d) + fmt.Printf("%d\n", d) + fmt.Printf("%x\n", d) + // strconv.FormatInt handles arbitrary bases from 2 to 36 for the + // int64 type. There is also strconv.FormatUInt for the uint64 type. + // There no equivalent for big ints. + fmt.Println(strconv.FormatInt(1313, 19)) } diff --git a/Task/Nth-root/NewLISP/nth-root.newlisp b/Task/Nth-root/NewLISP/nth-root.newlisp new file mode 100644 index 0000000000..47567a8c8c --- /dev/null +++ b/Task/Nth-root/NewLISP/nth-root.newlisp @@ -0,0 +1,11 @@ +(define (nth-root n a) + (let ((x1 a) + (x2 (div a n))) + (until (= x1 x2) + (setq x1 x2 + x2 (div + (add + (mul x1 (- n 1)) + (div a (pow x1 (- n 1)))) + n))) + x2)) diff --git a/Task/Nth-root/Objeck/nth-root.objeck b/Task/Nth-root/Objeck/nth-root.objeck new file mode 100644 index 0000000000..408421d25e --- /dev/null +++ b/Task/Nth-root/Objeck/nth-root.objeck @@ -0,0 +1,18 @@ +class NthRoot { + function : Main(args : String[]) ~ Nil { + NthRoot(5, 34, .001)->PrintLine(); + } + + function : NthRoot(n : Int, A: Float, p : Float) ~ Float { + x := Float->New[2]; + x[0] := A; + x[1] := A / n; + + while((x[1] - x[0])->Abs() > p) { + x[0] := x[1]; + x[1] := ((n - 1.0) * x[1] + A / x[1]->Power(n - 1.0)) / n; + }; + + return x[1]; + } +} diff --git a/Task/Nth-root/PicoLisp/nth-root.l b/Task/Nth-root/PicoLisp/nth-root.l index 6ba97e0386..891aaa849f 100644 --- a/Task/Nth-root/PicoLisp/nth-root.l +++ b/Task/Nth-root/PicoLisp/nth-root.l @@ -12,6 +12,6 @@ N ) ) ) X2 ) ) -(prinl (format (nthroot 2 2.0) *Scl)) -(prinl (format (nthroot 3 12.3) *Scl)) -(prinl (format (nthroot 4 45.6) *Scl)) +(prinl (format (nthRoot 2 2.0) *Scl)) +(prinl (format (nthRoot 3 12.3) *Scl)) +(prinl (format (nthRoot 4 45.6) *Scl)) diff --git a/Task/Nth-root/REXX/nth-root.rexx b/Task/Nth-root/REXX/nth-root.rexx index a3c8430c9b..84a0bc87e0 100644 --- a/Task/Nth-root/REXX/nth-root.rexx +++ b/Task/Nth-root/REXX/nth-root.rexx @@ -21,7 +21,7 @@ r=abs(r); x=abs(x) /*the absolute values of R and X.*/ rm=r-1 /*just a fast version of ROOT -1*/ numeric form /*take a good guess at the root─┐*/ parse value format(x,2,1,,0) 'E0' with ? 'E' _ . /* ◄───────────┘*/ -g=(?/r'E'_%r)+(x>1) /*kinda uses a crude "logrithm". */ +g= (? / r'E'_ % r) + (x>1) /*kinda uses a crude "logarithm".*/ numeric fuzz 3 /*fuzz digits for higher roots. */ d=5 /*start with only five digits. */ do until d==dm; d=min(d+d,dm) /*each interation doubles prec. */ diff --git a/Task/Null-object/C++/null-object-3.cpp b/Task/Null-object/C++/null-object-3.cpp index b15507ce40..f17c4968ee 100644 --- a/Task/Null-object/C++/null-object-3.cpp +++ b/Task/Null-object/C++/null-object-3.cpp @@ -1,5 +1,9 @@ int *p = nullptr; ... -if(p == nullptr){ +if (p == nullptr){ + // do some thing +} +//or just +if (p){ // do some thing } diff --git a/Task/Null-object/Eiffel/null-object.e b/Task/Null-object/Eiffel/null-object.e new file mode 100644 index 0000000000..a41bc905bb --- /dev/null +++ b/Task/Null-object/Eiffel/null-object.e @@ -0,0 +1,22 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature {NONE} -- Initialization + + make + local + i: INTEGER + s: detachable STRING + do + if i = Void then + print("i = Void") + end + if s = Void then + print("s = Void") + end + end +end diff --git a/Task/Null-object/Ruby/null-object.rb b/Task/Null-object/Ruby/null-object.rb index 9ef3c9201e..f9e33b886d 100644 --- a/Task/Null-object/Ruby/null-object.rb +++ b/Task/Null-object/Ruby/null-object.rb @@ -1 +1,7 @@ - puts "object is null" if object.nil? +puts "@object is nil" if @object.nil? # instance variable + +puts "$object is nil" if $object.nil? # global variable, too + +# It recognizes as the local variable even if it isn't executed. +object = 1 if false +puts "object is nil" if object.nil? diff --git a/Task/Number-names/00DESCRIPTION b/Task/Number-names/00DESCRIPTION index fb055349cb..a1740465bb 100644 --- a/Task/Number-names/00DESCRIPTION +++ b/Task/Number-names/00DESCRIPTION @@ -1 +1,3 @@ -Show how to spell out a number in English. You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less). Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. +Show how to spell out a number in English.
+You can use a preexisting implementation or roll your own, but you should support inputs up to at least one million (or the maximum value of your language's default bounded integer type, if that's less).
+Support for inputs other than positive integers (like zero, negative integers, and floating-point numbers) is optional. diff --git a/Task/Number-names/CoffeeScript/number-names.coffee b/Task/Number-names/CoffeeScript/number-names.coffee new file mode 100644 index 0000000000..00571a360c --- /dev/null +++ b/Task/Number-names/CoffeeScript/number-names.coffee @@ -0,0 +1,57 @@ +spell_integer = (n) -> + tens = [null, null, "twenty", "thirty", "forty", + "fifty", "sixty", "seventy", "eighty", "ninety"] + + small = ["zero", "one", "two", "three", "four", "five", + "six", "seven", "eight", "nine", "ten", "eleven", + "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", "seventeen", "eighteen", "nineteen"] + + bl = [null, null, "m", "b", "tr", "quadr", + "quint", "sext", "sept", "oct", "non", "dec"] + + divmod = (n, d) -> + [Math.floor(n / d), n % d] + + nonzero = (c, n) -> + if n == 0 + "" + else + c + spell_integer n + + big = (e, n) -> + if e == 0 + spell_integer n + else if e == 1 + spell_integer(n) + " thousand" + else + spell_integer(n) + " " + bl[e] + "illion" + + base1000_rev = (n) -> + # generates the value of the digits of n in base 1000 + # (i.e. 3-digit chunks), in reverse. + chunks = [] + while n != 0 + [n, r] = divmod n, 1000 + chunks.push r + chunks + + if n < 0 + throw Error "spell_integer: negative input" + else if n < 20 + small[n] + else if n < 100 + [a, b] = divmod n, 10 + tens[a] + nonzero("-", b) + else if n < 1000 + [a, b] = divmod n, 100 + small[a] + " hundred" + nonzero(" ", b) + else + chunks = (big(exp, x) for x, exp in base1000_rev(n) when x) + chunks.reverse().join ', ' + +# example +console.log spell_integer 1278 +console.log spell_integer 1752 +console.log spell_integer 2010 +console.log spell_integer 4000123007913 diff --git a/Task/Number-names/D/number-names.d b/Task/Number-names/D/number-names.d index 833dcc36c3..74f2fd07f6 100644 --- a/Task/Number-names/D/number-names.d +++ b/Task/Number-names/D/number-names.d @@ -10,23 +10,23 @@ immutable huge = ["", ""] ~ ["m", "b", "tr", "quadr", "quint", "sext", "sept", "oct", "non", "dec"] .map!q{ a ~ "illion" }.array; -string spellBigInt(BigInt n) { - static string nonZero(string c, BigInt n, string connect="") { - return n == 0 ? "" : connect ~ c ~ n.spellBigInt; +string spellBigInt(BigInt n) pure /*nothrow @safe*/ { + static string nonZero(string c, BigInt n, string connect="") pure /*nothrow @safe*/ { + return (n == 0) ? "" : (connect ~ c ~ n.spellBigInt); } - static string lastAnd(string num) { - if (num.canFind(",")) { - string pre = num.retro.find(",").retro[0 .. $ - 1]; + static string lastAnd(string num) pure /*nothrow*/ @safe { + if (num.canFind(',')) { + string pre = num.retro.find(',').retro[0 .. $ - 1]; string last = num[pre.length + 1 .. $]; if (!last.canFind(" and ")) last = " and" ~ last; - num = pre ~ "," ~ last; + num = pre ~ ',' ~ last; } return num; } - static string big(in uint e, BigInt n) { + static string big(in uint e, in BigInt n) pure /*nothrow @safe*/ { switch (e) { case 0: return n.spellBigInt; case 1: return n.spellBigInt ~ " thousand"; @@ -39,19 +39,19 @@ string spellBigInt(BigInt n) { } else if (n < 20) { return small[n.toInt]; } else if (n < 100) { - BigInt a = n / 10; - BigInt b = n % 10; + immutable BigInt a = n / 10; + immutable BigInt b = n % 10; return tens[a.toInt] ~ nonZero("-", b); - } else if (n < 1000) { - BigInt a = n / 100; - BigInt b = n % 100; + } else if (n < 1_000) { + immutable BigInt a = n / 100; + immutable BigInt b = n % 100; return small[a.toInt] ~ " hundred" ~ nonZero(" ", b, " and"); } else { string[] bigs; uint e = 0; while (n != 0) { - BigInt r = n % 1000; - n /= 1000; + immutable BigInt r = n % 1_000; + n /= 1_000; if (r != 0) bigs ~= big(e, r); e++; @@ -63,7 +63,7 @@ string spellBigInt(BigInt n) { version(number_names_main) { void main() { - foreach (n; [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]) + foreach (immutable n; [0, -3, 5, -7, 11, -13, 17, -19, 23, -29]) writefln("%+4d -> %s", n, n.BigInt.spellBigInt); writeln; diff --git a/Task/Number-names/MAXScript/number-names-1.max b/Task/Number-names/MAXScript/number-names-1.max index 6a2caa55c9..145577011f 100644 --- a/Task/Number-names/MAXScript/number-names-1.max +++ b/Task/Number-names/MAXScript/number-names-1.max @@ -1,55 +1,37 @@ -fn NumberToWord myNum = ( - local Result = "" - while myNum != 0 do ( - Result += case of ( - (myNum >= 1000):(myNum -= 1000; "one thousand") - (myNum > 900): (myNum -= 900 ; "nine hundred and") - (myNum == 900): (myNum -= 900 ; "nine hundred") - (myNum > 800): (myNum -= 800 ; "eight hundred and") - (myNum == 800): (myNum -= 900 ; "eight hundred") - (myNum > 700): (myNum -= 700 ; "seven hundred and") - (myNum == 700): (myNum -= 900 ; "seven hundred") - (myNum > 600): (myNum -= 600 ; "six hundred and") - (myNum == 600): (myNum -= 900 ; "six hundred") - (myNum > 500): (myNum -= 500 ; "five hundred and") - (myNum == 500): (myNum -= 900 ; "five hundred") - (myNum > 400): (myNum -= 400 ; "four hundred and") - (myNum == 400): (myNum -= 900 ; "four hundred") - (myNum > 300): (myNum -= 300 ; "three hundred and") - (myNum == 300): (myNum -= 900 ; "three hundred") - (myNum > 200): (myNum -= 200 ; "two hundred and") - (myNum == 200): (myNum -= 900 ; "two hundred") - (myNum > 100): (myNum -= 100 ; "one hundred and") - (myNum == 100): (myNum -= 100 ; "one hundred") - (myNum >= 90): (myNum -= 90 ; "ninety") - (myNum >= 80): (myNum -= 80 ; "eighty") - (myNum >= 70): (myNum -= 70 ; "seventy") - (myNum >= 60): (myNum -= 60 ; "sixty") - (myNum >= 50): (myNum -= 50 ; "fifty") - (myNum >= 40): (myNum -= 40 ; "fourty") - (myNum >= 30): (myNum -= 30 ; "thirty") - (myNum >= 20): (myNum -= 20 ; "twenty") - (myNum >= 19): (myNum -= 19 ; "nineteen") - (myNum >= 18): (myNum -= 18 ; "eighteen") - (myNum >= 17): (myNum -= 17 ; "seventeen") - (myNum >= 16): (myNum -= 16 ; "sixteen") - (myNum >= 15): (myNum -= 15 ; "fifteen") - (myNum >= 14): (myNum -= 14 ; "fourteen") - (myNum >= 13): (myNum -= 13 ; "thirteen") - (myNum >= 12): (myNum -= 12 ; "twelve") - (myNum >= 11): (myNum -= 11 ; "eleven") - (myNum >= 10): (myNum -= 10 ; "ten") - (myNum >= 9): (myNum -= 9 ; "nine") - (myNum >= 8): (myNum -= 8 ; "eight") - (myNum >= 7): (myNum -= 7 ; "seven") - (myNum >= 6): (myNum -= 6 ; "six") - (myNum >= 5): (myNum -= 5 ; "five") - (myNum >= 4): (myNum -= 4 ; "four") - (myNum >= 3): (myNum -= 3 ; "three") - (myNum >= 2): (myNum -= 2 ; "two") - (myNum >= 1): (myNum -= 1 ; "one") - ) - if myNum != 0 then result += " " +fn numToEng num = +( + num = num as integer -- convert to int + local originalNumber = num -- store the initial value, to check if it was negative afterwards + + num = abs num -- make positive + local numStr = num as string -- store as string to check the length + + local nonFirstDigits = (if numStr.count > 3 then ((substring numStr ((if mod numStr.count 3 ==0 then 3 else mod numStr.count 3)+1) -1)) else "0") -- this is the string of the number without the beginning, i.e 123456 will give 456, 12035 will give 2035 + local singleDigits = #("One","Two","Three","Four","Five","Six","Seven","Eight","Nine") + local ElevenTwenty = #("Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen") + local tens = #("Ten","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety") + local big = #("Hundred","Thousand","Million","Billion") + local ret = "" -- this is the value to be returned + + case of + ( + (num == 0 ): ret += "Zero" -- number is zero + (num < 10): ret += singleDigits[num] -- number is not and smaller than 10 + (num == 10): ret += tens[1] -- number is 10 + (num < 20): ret += elevenTwenty[abs(10-num)] -- number is between 11 and 19 + (num <= 90 and mod num 10 == 0): ret += tens[num/10] -- number is >= 20 and <= 90 and is dividable by 10 + (num < 100): ret += (numToEng (floor(num/10.0)*10) +" "+ numtoEng (num-(floor(num/10.0))*10)) -- number is >= 20, < 100 and is not dividable by 10 + (num < 1000): ret += (singledigits[floor(num/100) as integer] + " "+big[1]+ (if mod num 100 != 0 then (" and "+numtoeng (num-(floor(num/100.0)*100))) else "")) -- number is >= 100, < 1000 + (num >= 1000): ret += -- number is >= 1000 + ( + numtoeng (substring numStr 1 (if mod numStr.count 3 ==0 then 3 else mod numStr.count 3)) + \ + " " + big[1+((numStr.count-1)/3)] + (if nonFirstDigits as integer == 0 then "" else (if nonFirstDigits as integer < 100 then " and " else ", ")) + \ + (if (mod num 1000 == 0) then "" else (numtoeng nonFirstDigits)) + + ) ) - result + + if originalNumber < 0 and (substring ret 1 8) != "Negative" do ret = ("Negative "+ret) -- if number is negative + ret = (toupper ret[1]) + (tolower (substring ret 2 -1)) -- make the first char uppercase and rest lowercase + return ret ) diff --git a/Task/Number-names/MAXScript/number-names-2.max b/Task/Number-names/MAXScript/number-names-2.max index 84650321ea..452781b751 100644 --- a/Task/Number-names/MAXScript/number-names-2.max +++ b/Task/Number-names/MAXScript/number-names-2.max @@ -1 +1,14 @@ -NumberToWord(123) +numtoeng 0 +"Zero" +numtoeng 50 +"Fifty" +numtoeng 123 +"One hundred and twenty three" +numtoeng -4235 +"Negative four thousand, two hundred and thirty five" +numtoeng 98273 +"Ninety eight thousand, two hundred and seventy three" +numtoeng -92836152 +"Negative ninety two million, eight hundred and thirty six thousand, one hundred and fifty two" +numtoeng 421752302 +"Four hundred and twenty one million, seven hundred and fifty two thousand, three hundred and two" diff --git a/Task/Number-names/Objective-C/number-names.m b/Task/Number-names/Objective-C/number-names.m new file mode 100644 index 0000000000..4b8a1f439a --- /dev/null +++ b/Task/Number-names/Objective-C/number-names.m @@ -0,0 +1,16 @@ +#import + +int main() { + @autoreleasepool { + + NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init]; + numberFormatter.numberStyle = NSNumberFormatterSpellOutStyle; + numberFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; + + for (NSNumber *n in @[@900000001, @1234567890, @-987654321, @0, @3.14]) { + NSLog(@"%@", [numberFormatter stringFromNumber:n]); + } + + } + return 0; +} diff --git a/Task/Number-names/Ruby/number-names.rb b/Task/Number-names/Ruby/number-names.rb index 651944172c..dda35b3c12 100644 --- a/Task/Number-names/Ruby/number-names.rb +++ b/Task/Number-names/Ruby/number-names.rb @@ -8,21 +8,21 @@ TENS = %w(wrong wrong twenty thirty forty fifty sixty seventy BIG = [nil, "thousand"] + %w( m b tr quadr quint sext sept oct non dec).map{ |p| "#{p}illion" } - def wordify number - if number < 0 + case + when number < 0 "negative #{wordify -number}" - elsif number < 20 + when number < 20 SMALL[number] - elsif number < 100 + when number < 100 div, mod = number.divmod(10) - "#{TENS[div]}-#{wordify mod}".chomp("-zero") + TENS[div] + (mod==0 ? "" : "-#{wordify mod}") - elsif number < 1000 + when number < 1000 div, mod = number.divmod(100) - "#{wordify div} hundred and #{wordify mod}".chomp(" and zero") + "#{SMALL[div]} hundred" + (mod==0 ? "" : " and #{wordify mod}") else # separate into 3-digit chunks @@ -30,26 +30,27 @@ def wordify number div = number while div != 0 div, mod = div.divmod(1000) - chunks << mod # will store smallest to largest + chunks << mod # will store smallest to largest end - if chunks.length > BIG.length - raise ArgumentError, "Integer value too large." - end + raise ArgumentError, "Integer value too large." if chunks.size > BIG.size chunks.map{ |c| wordify c }. - zip(BIG). # zip pairs up corresponding elements from the two arrays + zip(BIG). # zip pairs up corresponding elements from the two arrays find_all { |c| c[0] != 'zero' }. - map{ |c| c.join ' '}. # join ["forty", "thousand"] + map{ |c| c.join ' '}. # join ["forty", "thousand"] reverse. - join(', '). # join chunks + join(', '). # join chunks strip end end -[-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889, 23_000_467, - 23_234_467, 2_235_654_234, 12_123_234_543_543_456, - 123890812938219038290489327894327894723897432].each do |n| +data = [-1123, 0, 1, 20, 123, 200, 220, 1245, 2000, 2200, 2220, 467889, + 23_000_467, 23_234_467, 2_235_654_234, 12_123_234_543_543_456, + 987_654_321_098_765_432_109_876_543_210_987_654, + 123890812938219038290489327894327894723897432] + +data.each do |n| print "#{n}: " begin puts "'#{wordify n}'" diff --git a/Task/Number-names/Scala/number-names.scala b/Task/Number-names/Scala/number-names.scala index 6fbbebc9a8..be2b496e8b 100644 --- a/Task/Number-names/Scala/number-names.scala +++ b/Task/Number-names/Scala/number-names.scala @@ -1,10 +1,7 @@ -package org.rosettacode -package numbernames - import scala.annotation.tailrec import scala.collection.parallel.ParSeq -/** Spells a English numeral longhand. The numbers are expressed using words. +/** Spells an English numeral longhand. The numbers are expressed using words. * * The implementation goes up to 1069-1 and also supports negative and zero inputs. * @@ -18,11 +15,11 @@ trait LongHand { * @param showAnd flag the output extra and in output, default off * @param zeroString the word for 0, default to "zero" * @param showHyphen hyphenate all compound numbers e.g. twenty-four, default is on - * @return the numeric value in words + * @return the numeric value expressed in words */ def longhand(numeral: BigInt, - zeroString: String = "zero", showAnd: Boolean = false, + zeroString: String = "zero", showHyphen: Boolean = true): String = { val condAndString = if (showAnd) "and " else "" @@ -37,11 +34,11 @@ trait LongHand { val eval = (nnn.par.map(_.toString.toInt).reverse zip ParSeq('units, 'tens, 'hundreds)).reverse eval.map { - case (d, 'units) if eval.seq.contains((1, 'tens)) => onesAndTeens(d + 10) + 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 && eval.seq.contains(0, 'units) => tens(d) case (d, 'tens) if d > 1 => tens(d) + condHyphenString //' case _ => "" }.mkString + strE3 @@ -52,11 +49,8 @@ trait LongHand { 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(shortScale) // // 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 + if (decGroups.size <= shortScale.size) // Detect overflow + { // Send per group section to composeScale @tailrec def iter(elems: Seq[(String, String)], acc: String): String = { elems match { @@ -65,28 +59,28 @@ trait LongHand { } case _ => acc } - } - iter(decGroups.toList, "").mkString.trim + } // Group of decimals are accompanied with the short scale name. + iter(decGroups.zip(shortScale).reverse.toList, "").mkString.trim } else "###.overflow.###" } // def compose(… // Here starts def longhand(… if (numeral < 0) "minus " + compose(-numeral) else compose(numeral) - } // End def longhand(… @ 91 lines + } // End def longhand(… - val onesAndTeens = { - def lowNumerals = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ") - def tenties = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ") - ParSeq("") ++ lowNumerals ++ tenties + private val onesAndTeens = { + def dozen = "one two three four five six seven eight nine ten eleven twelve".split(' ').map(_ + " ").par + def teens = "thir four fif six seven eigh nine".split(' ').map(_ + "teen ").par + ParSeq("") ++ dozen ++ teens } - val tens = (Array[String]("", "") ++ ("twen thir for fif six seven eigh nine".split(' ')). - map(_ + "ty")).par - def hundredString = "hundred " - lazy val shortScale = { + private val tens = ParSeq("", "") ++ + ("twen thir for fif six seven eigh nine".split(' ')).map(_ + "ty") + private final val hundredString = "hundred " + private val shortScale = { def p1 = "m b tr quadr quint sext sept oct non dec".split(' ').map(_ + "illion ").par def p2 = "un duo tre quattuor quin sex septen octo novem ".split(' ').map(_ + "decillion ").par - def p3 = ("vigint cent".split(' ').map(_ + "illion ") :+ "overflow trap").par + def p3 = "vigint cent".split(' ').map(_ + "illion ").par ParSeq("", "thousand ") ++ p1 ++ p2 ++ p3 } } // trait LongHand diff --git a/Task/Number-reversal-game/Eiffel/number-reversal-game-1.e b/Task/Number-reversal-game/Eiffel/number-reversal-game-1.e new file mode 100644 index 0000000000..7854dd5dad --- /dev/null +++ b/Task/Number-reversal-game/Eiffel/number-reversal-game-1.e @@ -0,0 +1,99 @@ +class + NUMBER_REVERSAL_GAME +feature + + play_game + local + count: INTEGER + do + initialize_game + io.put_string ("Let's play the number reversal game.%N") + across numbers as ar loop io.put_string (ar.item.out + "%T") end + from + + until + is_sorted(numbers,1, numbers.count) + loop + io.put_string ("%NHow many numbers should be reversed?%N") + io.read_integer + reverse_array(io.last_integer) + across numbers as ar loop io.put_string (ar.item.out + "%T") end + count:= count+1 + end + io.put_string ("%NYou needed "+ count.out + " reversals.") + end + +feature {NONE} + initialize_game + local + random: V_RANDOM + item,i: INTEGER + do + create random + create numbers.make_empty + from + i:= 1 + until + numbers.count = 9 + loop + + item :=random.bounded_item (1, 9) + if numbers.has (item)= FALSE then + numbers.force(item, i) + i:= i+1 + end + random.forth + end + end + + numbers: ARRAY[INTEGER] + + reverse_array(upper:INTEGER) + require + upper_positive: upper >0 + ar_not_void: numbers /= void + local + i,j:INTEGER + new_array: ARRAY[INTEGER] + do + create new_array.make_empty + new_array.copy (numbers) + from + i:= 1 + j:=upper + until + i>j + loop + new_array[i]:=numbers[j] + new_array[j]:=numbers[i] + i:=i+1 + j:=j-1 + end + numbers := new_array + end + + is_sorted(ar: ARRAY[INTEGER];l, r: INTEGER): BOOLEAN + require + ar_not_empty: ar.is_empty= FALSE + local + smaller : BOOLEAN + i: INTEGER + do + smaller:= TRUE + from + i:= l + until + i=r + loop + if ar[i]> ar[i+1] then + smaller:= FALSE + end + i:= i+1 + end + if smaller = TRUE then + RESULT := TRUE + else + RESULT:= FALSE + end + end +end diff --git a/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e b/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e new file mode 100644 index 0000000000..922e9adf97 --- /dev/null +++ b/Task/Number-reversal-game/Eiffel/number-reversal-game-2.e @@ -0,0 +1,14 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + make + do + create nr + nr.play_game + end + nr: NUMBER_REVERSAL_GAME +end diff --git a/Task/Number-reversal-game/MATLAB/number-reversal-game.m b/Task/Number-reversal-game/MATLAB/number-reversal-game.m new file mode 100644 index 0000000000..ef507d453a --- /dev/null +++ b/Task/Number-reversal-game/MATLAB/number-reversal-game.m @@ -0,0 +1,27 @@ +function NumberReversalGame + list = randperm(9); + while issorted(list) + list = randperm(9); + end + fprintf('Given a list of numbers, try to put them into ascending order\n') + fprintf('by sequentially reversing everything left of a point you choose\n') + fprintf('in the array. Try to do it in as few reversals as possible.\n') + fprintf('No input will quit the game.\n') + fprintf('Position Num:%s\n', sprintf(' %d', 1:length(list))) + fprintf('Current List:%s', sprintf(' %d', list)) + pivot = 1; + nTries = 0; + while ~isempty(pivot) && ~issorted(list) + pivot = input(' Enter position of reversal limit: '); + if pivot + list(1:pivot) = list(pivot:-1:1); + fprintf('Current List:%s', sprintf(' %d', list)) + nTries = nTries+1; + end + end + if issorted(list) + fprintf('\nCongratulations! You win! Only %d reversals.\n', nTries) + else + fprintf('\nPlay again soon!\n') + end +end diff --git a/Task/Number-reversal-game/REBOL/number-reversal-game.rebol b/Task/Number-reversal-game/REBOL/number-reversal-game.rebol new file mode 100644 index 0000000000..8e4d01654f --- /dev/null +++ b/Task/Number-reversal-game/REBOL/number-reversal-game.rebol @@ -0,0 +1,22 @@ +REBOL [] + +print "NUMBER REVERSAL GAME" + +tries: 0 +goal: [1 2 3 4 5 6 7 8 9] +random/seed now + +until [ + jumble: random goal + jumble != goal ; repeat in the unlikely case that jumble isn't jumbled +] + +while [jumble != goal] [ + prin jumble + prin " How many to flip? " + flip-index: to-integer input ; no validation! + reverse/part jumble flip-index + tries: tries + 1 +] + +print rejoin ["You took " tries " attempts."] diff --git a/Task/Number-reversal-game/Scala/number-reversal-game.scala b/Task/Number-reversal-game/Scala/number-reversal-game.scala new file mode 100644 index 0000000000..7a4fb3c0d9 --- /dev/null +++ b/Task/Number-reversal-game/Scala/number-reversal-game.scala @@ -0,0 +1,29 @@ +object NumberReversalGame extends App { + def play(n: Int, cur: List[Int], goal: List[Int]) { + readLine(s"""$n. ${cur mkString " "} How many to flip? """) match { + case null => println + case s => scala.util.Try(s.toInt) match { + case scala.util.Success(i) if i > 0 && i <= cur.length => + (cur.take(i).reverse ++ cur.drop(i)) match { + case done if done == goal => + println(s"Congratulations! You solved "+goal.mkString(" ")) + println(s"Your score is $n (lower is better)") + case next => play(n + 1, next, goal) + } + case _ => println(s"Choose a number between 1 and ${cur.length}") + play(n + 1, cur, goal) + } + } + } + + def play(size: Int) { + val goal = List.range(1, size + 1) + def init: List[Int] = scala.util.Random.shuffle(goal) match { + case repeat if repeat == goal => init + case done => done + } + play(1, init, goal) + } + + play(9) +} diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-1.axiom b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-1.axiom new file mode 100644 index 0000000000..304c7bb25c --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-1.axiom @@ -0,0 +1,20 @@ +NNI ==> NonNegativeInteger +RECORD ==> Record(x : List Fraction Integer, w : List Fraction Integer) + +gaussCoefficients(n : NNI, eps : Fraction Integer) : RECORD == + p := legendreP(n,z) + q := n/2*D(p, z)*legendreP(subtractIfCan(n,1)::NNI, z) + x := map(rhs,solve(p,eps)) + w := [subst(1/q, z=xi) for xi in x] + [x,w] + +gaussIntegrate(e : Expression Float, segbind : SegmentBinding(Float), n : NNI) : Float == + eps := 1/10^100 + u := gaussCoefficients(n,eps) + interval := segment segbind + var := variable segbind + a := lo interval + b := hi interval + c := (a+b)/2 + h := (b-a)/2 + h*reduce(+,[wi*subst(e,var=c+xi*h) for xi in u.x for wi in u.w]) diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-2.axiom b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-2.axiom new file mode 100644 index 0000000000..abc57227cb --- /dev/null +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/Axiom/numerical-integration-gauss-legendre-quadrature-2.axiom @@ -0,0 +1,8 @@ +digits(50) +gaussIntegrate(4/(1+x^2), x=0..1, 20) + + (1) 3.1415926535_8979323846_2643379815_9534002592_872901276 + Type: Float +% - %pi + + (2) - 0.3463549483_9378821092_475 E -26 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 b45dff3474..dda0d71f52 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 @@ -5,7 +5,7 @@ immutable struct GaussLegendreQuadrature(size_t N, FP=double, immutable static double[N] lroots, weight; alias FP[N + 1][N + 1] CoefMat; - pure nothrow static this() { + pure nothrow @safe @nogc 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]; @@ -15,34 +15,33 @@ immutable struct GaussLegendreQuadrature(size_t N, FP=double, } static FP legendreDiff(in ref CoefMat lcoef, - in int n, in FP x) pure nothrow { + in int n, in FP x) + pure nothrow @safe @nogc { return n * (x * legendreEval(lcoef, n, x) - legendreEval(lcoef, n - 1, x)) / (x ^^ 2 - 1); } - 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); + + // Legendre roots: + 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)); + } } static private void legendreCoefInit(ref CoefMat lcoef) - pure nothrow { + pure nothrow @safe @nogc { 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; @@ -52,8 +51,9 @@ immutable struct GaussLegendreQuadrature(size_t N, FP=double, } } - static public FP integrate(in FP function(FP x) f, - in FP a, in FP b) { + static public FP integrate(in FP function(/*in*/ FP x) pure nothrow @safe @nogc f, + in FP a, in FP b) + pure nothrow @safe @nogc { immutable FP c1 = (b - a) / 2; immutable FP c2 = (b + a) / 2; FP sum = 0.0; @@ -70,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", - 3.0.exp - -3.0.exp); + 3.0.exp - exp(-3.0)); } diff --git a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx index a1a26bbac7..075df68956 100644 --- a/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx +++ b/Task/Numerical-integration-Gauss-Legendre-Quadrature/REXX/numerical-integration-gauss-legendre-quadrature-2.rexx @@ -1,14 +1,14 @@ -/*REXX pgm does numerical integration using Gauss-Legendre Quadrature. */ -parse arg digs .; if digs=='' then digs=40 /*assume the DIGS default?*/ -numeric digits digs*2+10 /*use higher working DIGs.*/ -pi=pi(); a=-3; b=3; bma =b-a; bpa =b+a; tiny ='1E-' || (digs*2) -true = exp(b)-exp(a); bmaH=bma/2; bpaH=bpa/2; times= digs%2 + 1 -numeric digits digs+10 /*use lower working DIGITs*/ -say 'step' center("iterative value",digs+3) ' difference ' /*show hdr*/ -sep='────' copies('─' ,digs+3) '────────────'; say sep +/*REXX pgm does numerical integration using Gauss─Legendre Quadrature. */ +parse arg digs .; if digs=='' then digs=70 /*assume the DIGS default?*/ +numeric digits digs*2+5 /*use higher working DIGs.*/ +times=digs%2; b=3; a=-b; bma=b-a; bmaH=bma/2; tiny='1E-' || (digs*2) +trueV=exp(b)-exp(a); bpa=b+a; bpaH=bpa/2; oldZ= +numeric digits digs+15; pi=pi(); !.=. /*use lower working DIGITs*/ +say ' step ' center("iterative value",digs+5) ' difference' /*show hdr*/ +sep='──────' copies('─' ,digs+5) '─────────────'; say sep - do step=1 for times; p0z=1; p0.1=1; step_=step+.5 - p1z=2; p1.1=1; p1.2=0; r.=0 + do step=1 for times; p0z=1; p0.1=1; step_=step + .5 + p1z=2; p1.1=1; p1.2=0; r.=0 /*█*/ do k=2 to step; km=k-1 /*█*/ do L=1 for p1z; T.L=p1.L /*█*/ end /*L*/ @@ -16,43 +16,43 @@ sep='────' copies('─' ,digs+3) '──────── /*█*/ do L=1 for p0z; L2=L+2; TT.L2=p0.L /*█*/ end /*L*/ /*█*/ -/*█*/ do j=1 for p1z+1;T.j=((k+km)*T.j-km*TT.j)/k; end /*j*/ -/*█*/ p0z=p1z; do j=1 for p0z; p0.j=p1.j ; end /*j*/ -/*█*/ p1z=p1z+1; do j=1 for p1z; p1.j= T.j ; end /*j*/ +/*█*/ kkm=k+km; do j=1 for p1z+1; T.j=(kkm*T.j-km*TT.j)/k ; end /*j*/ +/*█*/ p0z=p1z; do j=1 for p0z; p0.j=p1.j ; end /*j*/ +/*█*/ p1z=p1z+1; do j=1 for p1z; p1.j= T.j ; end /*j*/ /*█*/ end /*k*/ - /*▓*/ do !=1 for step - /*▓*/ x=cos(pi*(!-.25)/step_) - /*▓*/ do times%2 until abs(dx).5 then ix=ix+sign(x) - x=x-ix; z=1; _=1; do j=1 until p==z; p=z; _=_*x/j; z=z+_; end - if z\==0 then z=z*e()**ix; return z -/*──────────────────────────────────PI subroutine──────────────────────────────────────*/ +/*──────────────────────────────────one-liner subroutines───────────────*/ +e: return 2.7182818284590452353602874713526624977572470936999595749669676277240766303535 pi: return 3.1415926535897932384626433832795028841971693993751058209749445923078164062862 -/*──────────────────────────────────R2R subroutine──────────────────────*/ -r2r: return arg(1)//(2*pi()) /*normalize radians►1 unit circle*/ +/*──────────────────────────────────COS subroutine──────────────────────────────────*/ +cos: procedure expose !.; parse arg x; if !.x\==. then return !.x; _=1; z=1; y=x*x + do k=2 by 2 until p==z; p=z; _=-_*y/(k*(k-1)); z=z+_; end; !.x=z; return z +/*──────────────────────────────────EXP subroutine────────────────────────────*/ +exp: procedure; parse arg x; ix=trunc(x); if abs(x-ix)>.5 then ix=ix+sign(x) + x=x-ix; z=1; _=1; do j=1 until p==z; p=z; _=_*x/j; z=z+_; end + if z\==0 then z=z*e()**ix; return z diff --git a/Task/Numerical-integration/Chapel/numerical-integration-1.chapel b/Task/Numerical-integration/Chapel/numerical-integration-1.chapel new file mode 100644 index 0000000000..59302d9851 --- /dev/null +++ b/Task/Numerical-integration/Chapel/numerical-integration-1.chapel @@ -0,0 +1,129 @@ +proc f1(x:real):real { + return x**3; +} + +proc f2(x:real):real { + return 1/x; +} + +proc f3(x:real):real { + return x; +} + +proc leftRectangleIntegration(a: real, b: real, N: int, f): real{ + var h: real = (b - a)/N; + var sum: real = 0.0; + var x_n: real; + for n in 0..N-1 { + x_n = a + n * h; + sum = sum + f(x_n); + } + return h * sum; +} + +proc rightRectangleIntegration(a: real, b: real, N: int, f): real{ + var h: real = (b - a)/N; + var sum: real = 0.0; + var x_n: real; + for n in 0..N-1 { + x_n = a + (n + 1) * h; + sum = sum + f(x_n); + } + return h * sum; +} + +proc midpointRectangleIntegration(a: real, b: real, N: int, f): real{ + var h: real = (b - a)/N; + var sum: real = 0.0; + var x_n: real; + for n in 0..N-1 { + x_n = a + (n + 0.5) * h; + sum = sum + f(x_n); + } + return h * sum; +} + +proc trapezoidIntegration(a: real(64), b: real(64), N: int(64), f): real{ + var h: real(64) = (b - a)/N; + var sum: real(64) = f(a) + f(b); + var x_n: real(64); + for n in 1..N-1 { + x_n = a + n * h; + sum = sum + 2.0 * f(x_n); + } + return (h/2.0) * sum; +} + +proc simpsonsIntegration(a: real(64), b: real(64), N: int(64), f): real{ + var h: real(64) = (b - a)/N; + var sum: real(64) = f(a) + f(b); + var x_n: real(64); + for n in 1..N-1 by 2 { + x_n = a + n * h; + sum = sum + 4.0 * f(x_n); + } + for n in 2..N-2 by 2 { + x_n = a + n * h; + sum = sum + 2.0 * f(x_n); + } + return (h/3.0) * sum; +} + +var exact:real; +var calculated:real; + +writeln("f(x) = x**3 with 100 steps from 0 to 1"); +exact = 0.25; +calculated = leftRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1); +writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = rightRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1); +writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = midpointRectangleIntegration(a = 0.0, b = 1.0, N = 100, f = f1); +writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = trapezoidIntegration(a = 0.0, b = 1.0, N = 100, f = f1); +writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = simpsonsIntegration(a = 0.0, b = 1.0, N = 100, f = f1); +writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +writeln(); + +writeln("f(x) = 1/x with 1000 steps from 1 to 100"); +exact = 4.605170; +calculated = leftRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2); +writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = rightRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2); +writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = midpointRectangleIntegration(a = 1.0, b = 100.0, N = 1000, f = f2); +writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = trapezoidIntegration(a = 1.0, b = 100.0, N = 1000, f = f2); +writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = simpsonsIntegration(a = 1.0, b = 100.0, N = 1000, f = f2); +writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +writeln(); + +writeln("f(x) = x with 5000000 steps from 0 to 5000"); +exact = 12500000; +calculated = leftRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3); +writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = rightRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3); +writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = midpointRectangleIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3); +writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = trapezoidIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3); +writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = simpsonsIntegration(a = 0.0, b = 5000.0, N = 5000000, f = f3); +writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +writeln(); + +writeln("f(x) = x with 6000000 steps from 0 to 6000"); +exact = 18000000; +calculated = leftRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3); +writeln("leftRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = rightRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3); +writeln("rightRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = midpointRectangleIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3); +writeln("midpointRectangleIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = trapezoidIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3); +writeln("trapezoidIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +calculated = simpsonsIntegration(a = 0.0, b = 6000.0, N = 6000000, f = f3); +writeln("simpsonsIntegration: calculated = ", calculated, "; exact = ", exact, "; difference = ", abs(calculated - exact)); +writeln(); diff --git a/Task/Numerical-integration/Chapel/numerical-integration-2.chapel b/Task/Numerical-integration/Chapel/numerical-integration-2.chapel new file mode 100644 index 0000000000..2c04dbd81e --- /dev/null +++ b/Task/Numerical-integration/Chapel/numerical-integration-2.chapel @@ -0,0 +1,27 @@ +f(x) = x**3 with 100 steps from 0 to 1 +leftRectangleIntegration: calculated = 0.245025; exact = 0.25; difference = 0.004975 +rightRectangleIntegration: calculated = 0.255025; exact = 0.25; difference = 0.005025 +midpointRectangleIntegration: calculated = 0.249988; exact = 0.25; difference = 1.25e-05 +trapezoidIntegration: calculated = 0.250025; exact = 0.25; difference = 2.5e-05 +simpsonsIntegration: calculated = 0.25; exact = 0.25; difference = 5.55112e-17 + +f(x) = 1/x with 1000 steps from 1 to 100 +leftRectangleIntegration: calculated = 4.65499; exact = 4.60517; difference = 0.0498211 +rightRectangleIntegration: calculated = 4.55698; exact = 4.60517; difference = 0.0481889 +midpointRectangleIntegration: calculated = 4.60476; exact = 4.60517; difference = 0.000407451 +trapezoidIntegration: calculated = 4.60599; exact = 4.60517; difference = 0.000816058 +simpsonsIntegration: calculated = 4.60517; exact = 4.60517; difference = 3.31627e-06 + +f(x) = x with 5000000 steps from 0 to 5000 +leftRectangleIntegration: calculated = 1.25e+07; exact = 1.25e+07; difference = 2.5 +rightRectangleIntegration: calculated = 1.25e+07; exact = 1.25e+07; difference = 2.5 +midpointRectangleIntegration: calculated = 1.25e+07; exact = 1.25e+07; difference = 0.0 +trapezoidIntegration: calculated = 1.25e+07; exact = 1.25e+07; difference = 1.86265e-09 +simpsonsIntegration: calculated = 1.25e+07; exact = 1.25e+07; difference = 3.72529e-09 + +f(x) = x with 6000000 steps from 0 to 6000 +leftRectangleIntegration: calculated = 1.8e+07; exact = 1.8e+07; difference = 3.0 +rightRectangleIntegration: calculated = 1.8e+07; exact = 1.8e+07; difference = 3.0 +midpointRectangleIntegration: calculated = 1.8e+07; exact = 1.8e+07; difference = 7.45058e-09 +trapezoidIntegration: calculated = 1.8e+07; exact = 1.8e+07; difference = 3.72529e-09 +simpsonsIntegration: calculated = 1.8e+07; exact = 1.8e+07; difference = 0.0 diff --git a/Task/Numerical-integration/REXX/numerical-integration.rexx b/Task/Numerical-integration/REXX/numerical-integration.rexx index 7fb449e055..eded3e6baa 100644 --- a/Task/Numerical-integration/REXX/numerical-integration.rexx +++ b/Task/Numerical-integration/REXX/numerical-integration.rexx @@ -16,45 +16,44 @@ numeric digits 20 /*use twenty digits precision. */ end /*test*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────LEFT_RECT subroutine────────────────*/ -left_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +left_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n sum=0 do x=a by h for n sum=sum+f(x) - end + end /*x*/ return sum*h /*──────────────────────────────────MIDPOINT_RECT subroutine────────────*/ -midpoint_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +midpoint_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n sum=0 do x=a+h/2 by h for n sum=sum+f(x) - end + end /*x*/ return sum*h /*──────────────────────────────────RIGHT_RECT subroutine───────────────*/ -right_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n +right_rect: procedure expose test; parse arg a,b,n; h=(b-a)/n sum=0 do x=a+h by h for n sum=sum+f(x) - end + end /*x*/ return sum*h /*──────────────────────────────────SIMPSON subroutine──────────────────*/ -simpson: procedure expose test; parse arg a,b,n; h=(b-a)/n +simpson: procedure expose test; parse arg a,b,n; h=(b-a)/n sum1=f(a+h/2) -sum2=0 - do x=1 to n-1 +sum2=0; do x=1 to n-1 sum1=sum1+f(a+h*x+h*.5) sum2=sum2+f(a+x*h) - end + end /*x*/ return h*(f(a)+f(b)+4*sum1+2*sum2)/6 /*──────────────────────────────────TRAPEZOID subroutine────────────────*/ -trapezoid: procedure expose test; parse arg a,b,n; h=(b-a)/n +trapezoid: procedure expose test; parse arg a,b,n; h=(b-a)/n sum=0 do x=a to b by h sum=sum+h*(f(x)+f(x+h))*.5 - end + end /*x*/ return sum /*──────────────────────────────────F subroutine────────────────────────*/ -f: procedure expose test; parse arg z -if test==1 then return z**3 -if test==2 then return 1/z - return z +f: procedure expose test; parse arg z +if test==1 then return z**3 +if test==2 then return 1/z + return z diff --git a/Task/Object-serialization/Racket/object-serialization-1.rkt b/Task/Object-serialization/Racket/object-serialization-1.rkt new file mode 100644 index 0000000000..ab261e4cdb --- /dev/null +++ b/Task/Object-serialization/Racket/object-serialization-1.rkt @@ -0,0 +1 @@ +(require racket/serialize) diff --git a/Task/Object-serialization/Racket/object-serialization-2.rkt b/Task/Object-serialization/Racket/object-serialization-2.rkt new file mode 100644 index 0000000000..fe768fdc12 --- /dev/null +++ b/Task/Object-serialization/Racket/object-serialization-2.rkt @@ -0,0 +1,72 @@ +#lang racket +;; Object Serialization: Tim Brown, Oct. 2014 +(require racket/serialize) + +(define (join-person-name-list persons) + (string-join (map (λ (c) (send c ->string)) persons) ", ")) + +(define-serializable-class person% object% + (init-field name [siblings null]) + (define/public (->string #:show (show null)) + (cond + [(and (member 'siblings show) (not (null? siblings))) + (format "~a (~a)" name (join-person-name-list siblings))] + [else name])) + (super-new)) + +(define-serializable-class parent% person% + (init-field [children null]) + (define/override (->string #:show (show null)) + (cond + [(and (member 'children show) (not (null? children))) + (format "~a [~a]" (super ->string #:show show) (join-person-name-list children))] + [else (super ->string #:show show)])) + (super-new)) + +;; horribly out of fashion and probaly no longer PC +(define-serializable-class nuclear-family% object% + (init-field father mother children) + (define/public (->string) + (string-append + (format "~a + ~a -> " (send father ->string) (send mother ->string)) + (format "~a" (join-person-name-list children)))) + (super-new)) + +;; =| TESTS |========================================================================================= +(define jack (new person% [name "Jack"])) +(define joan (new person% [name "Joan"])) +(set-field! siblings jack (list joan)) +(set-field! siblings joan (list jack)) +(define the-kids (list jack joan)) +(define john (new parent% [name "John"] [children the-kids])) +(define jane (new parent% [name "Jane"] [children the-kids])) + +(define the-family + (new nuclear-family% [father john] [mother jane] [children the-kids])) + +(define (duplicate-object-through-file o f-name) + (with-output-to-file f-name #:exists 'replace (λ () (write (serialize o)))) + (with-input-from-file f-name (λ () (deserialize (read))))) + +(define cloned-family (duplicate-object-through-file the-family "objects.dat")) + +(printf "The original family:\t~a~%" (send the-family ->string)) +(printf "The cloned family:\t~a~%~%" (send cloned-family ->string)) +(printf "objects.dat contains ----~%~a~%-------------------~%~%" (file->string "objects.dat")) +(printf "Clones are different?~%") +(define cloned-jack (first (get-field children cloned-family))) +(set-field! name cloned-jack "JACK") +(printf "Jack's name is:\t~s~%" (get-field name jack)) +(printf "Clone's name is:\t~s~%~%" (get-field name cloned-jack)) +(printf "Relationships are maintained?~%") +(define cloned-joan (second (get-field children cloned-family))) +(printf "Joan's description with siblings:\t~s~%" (send joan ->string #:show '(siblings))) +(printf "Clone's description with siblings:\t~s~%~%" + (send cloned-joan ->string #:show '(siblings))) +(printf "After Jack's renaming the cloned family is: ~a~%~%" (send cloned-family ->string)) +(printf "Various descriptions of cloned John:~%") +(define cloned-john (get-field father cloned-family)) +(printf "Just the name:\t~s~%" (send cloned-john ->string)) +(printf "With siblings:\t~s (he hasn't any)~%" (send cloned-john ->string #:show '(siblings))) +(printf "With children:\t~s~%" (send cloned-john ->string #:show '(children))) +(printf "With both:\t~s~%" (send cloned-john ->string #:show '(siblings children))) diff --git a/Task/One-dimensional-cellular-automata/00DESCRIPTION b/Task/One-dimensional-cellular-automata/00DESCRIPTION index 5f77481137..9893a923a4 100644 --- a/Task/One-dimensional-cellular-automata/00DESCRIPTION +++ b/Task/One-dimensional-cellular-automata/00DESCRIPTION @@ -1,6 +1,8 @@ -Assume an array of cells with an initial distribution of live and dead cells, and imaginary cells off the end of the array having fixed values. +Assume an array of cells with an initial distribution of live and dead cells, +and imaginary cells off the end of the array having fixed values. Cells in the next generation of the array are calculated based on the value of the cell and its left and right nearest neighbours in the current generation. + If, in the following table, a live cell is represented by 1 and a dead cell by 0 then to generate the value of the cell at a particular index in the array of cellular values you use the following table: 0'''0'''0 -> 0 # diff --git a/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee b/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee new file mode 100644 index 0000000000..417d619935 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/CoffeeScript/one-dimensional-cellular-automata.coffee @@ -0,0 +1,32 @@ +# We could cheat and count the bits, but let's keep this general. +# . = dead, # = alive, middle cells survives iff one of the configurations +# below is satisified. +survival_scenarios = [ + '.##' # happy neighbors + '#.#' # birth + '##.' # happy neighbors +] + +b2c = (b) -> if b then '#' else '.' + +cell_next_gen = (left_alive, me_alive, right_alive) -> + fingerprint = b2c(left_alive) + b2c(me_alive) + b2c(right_alive) + fingerprint in survival_scenarios + +cells_for_next_gen = (cells) -> + # This function assumes a finite array, i.e. cells can't be born outside + # the original array. + (cell_next_gen(cells[i-1], cells[i], cells[i+1]) for i in [0...cells.length]) + +display = (cells) -> + (b2c(is_alive) for is_alive in cells).join '' + +simulate = (cells) -> + while true + console.log display cells + new_cells = cells_for_next_gen cells + break if display(cells) == display(new_cells) + cells = new_cells + console.log "equilibrium achieved" + +simulate (c == '#' for c in ".###.##.#.#.#.#..#..") 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 index f3c54783ce..f30890f49a 100644 --- 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 @@ -12,9 +12,9 @@ void main() { //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]; + immutable val = (uint(A[i - 1]) << 2) | + (uint(A[i]) << 1) | + uint(A[i + 1]); B[i] = val == 3 || val == 5 || val == 6; } diff --git a/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata.rkt b/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-1.rkt similarity index 100% rename from Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata.rkt rename to Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-1.rkt diff --git a/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-2.rkt b/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-2.rkt new file mode 100644 index 0000000000..67b2e2b5b2 --- /dev/null +++ b/Task/One-dimensional-cellular-automata/Racket/one-dimensional-cellular-automata-2.rkt @@ -0,0 +1,49 @@ +#lang slideshow + +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Simulation of cellular automata, as described by Stephen Wolfram in his 1983 paper. +;; Uses Racket's inline image display capability for visual presentation +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +(require racket/draw) +(require slideshow) + +(define *rules* '((1 1 1) (1 1 0) (1 0 1) (1 0 0) + (0 1 1) (0 1 0) (0 0 1) (0 0 0))) + +(define (bordered-square n) + (filled-rectangle n n #:draw-border? #t)) + +(define (draw-row lst) + (apply hc-append 2 (map (λ (x) (colorize (bordered-square 10) (cond ((= x 0) "gray") + ((= x 1) "red") + (else "gray")))) + lst))) + +(define (extract-neighborhood nth prev-row) + (take (drop (append '(0) prev-row '(0)) nth) 3)) + +(define (automaton-to-bits n) + (reverse (map (λ (y) (if (zero? (bitwise-and y n)) 0 1)) + (map (λ (x) (expt 2 x)) (range 0 8))))) + +(define (get-rules bits) + (map cdr (filter (λ (x) (= (car x) 1)) (map cons bits *rules*)))) + +(define (advance-row old-row rules) + (let ([new '()]) + (for ([i (in-range 0 (length old-row))]) + (set! new (cons (if (member (extract-neighborhood i old-row) + rules) 1 0) new))) + (reverse new))) + +(define (draw-automaton automaton init-row row-number) + (let* ([bit-representation (automaton-to-bits automaton)] + [rules (get-rules bit-representation)] + [rows (list init-row)]) + (for ([i (in-range 1 row-number)]) + (set! rows (cons (advance-row (car rows) rules) + rows))) + (apply vc-append 2 (map draw-row (reverse rows))))) + +(draw-automaton 104 '(0 1 1 1 0 1 1 0 1 0 1 0 1 0 1 0 0 1 0 0) 10) diff --git a/Task/One-of-n-lines-in-a-file/Mathematica/one-of-n-lines-in-a-file.math b/Task/One-of-n-lines-in-a-file/Mathematica/one-of-n-lines-in-a-file.math new file mode 100644 index 0000000000..0f832017c5 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Mathematica/one-of-n-lines-in-a-file.math @@ -0,0 +1,8 @@ +chooseLine[file_] := Block[{strm = OpenRead[file], n = 1, rec, selected}, + rec = selected = Read[strm]; + While[rec =!= EndOfFile, + rec=Read[strm]; + n++; + If[RandomReal[] < 1/n, selected = rec]]; + Close[strm]; + selected] diff --git a/Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file.pascal b/Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-1.pascal similarity index 100% rename from Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file.pascal rename to Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-1.pascal diff --git a/Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-2.pascal b/Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-2.pascal new file mode 100644 index 0000000000..b89497c8ca --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Pascal/one-of-n-lines-in-a-file-2.pascal @@ -0,0 +1,86 @@ +Program OneOfNLines(InPut,Output); +{$h+} //use Ansistring +{type + NativeInt = LongInt;} + +function one_of_n(n: NativeInt): NativeInt; + var + ch,i: LongInt;// doubles speed of random using 64-Bit :-( + begin + ch := 1; + for i := 2 to n do + if random(i) = 0 then + ch := i; + one_of_n := ch; + end; + +function ChooseRNDLine( fileNm : string; + var LnChsn,LnCnt :NativeInt):string; +var + choosen, + n : NativeInt; + f : textFile; + actRow, + chsnRow: string; + buf : array[0..4095] of char;// speed things up +begin + n:= 0; + choosen := n; + chsnRow := ''; + + Assign(f,fileNm); + {$I-} + Reset(f); + {$I+} + IF IoResult <> 0 then + close(f) + else + Begin + SetTextBuf(f,Buf[0]); + + while Not(EOF(f)) do + Begin + readln(f,actRow); + inc(n); + IF Random(n)= 0 then + begin + chsnRow:= actRow; + choosen := n; + end; + end; + close(f); + end; + + LnChsn := choosen; + LnCnt := n; + ChooseRNDLine := chsnRow; +end; + +const + cFn = 'OneOfNLines.s';// compiled with -al assembler output + num_reps = 1000000; + num_lines_in_file = 10; + +var + Ln : String; + LnChsn, + LnCnt, + i : NativeInt; + cntLns: array[1..num_lines_in_file] of NativeUint; +begin + randomize; + Ln := ChooseRNDLine(cFn,LnChsn,LnCnt); + writeln('choosen ', LnChsn,' out of ',LnCnt ); + writeln(Ln);writeln; + + FillChar(cntLns,SizeOf(cntLns),#0); + for i := 1 to num_reps do + inc(cntLns[one_of_n(num_lines_in_file)]); + for i := 1 to num_lines_in_file do + writeln('Number of times line ', i, ' was selected: ', cntLns[i]); + + LnCnt := 0; + For i := Low(cntLns) to High(cntLns) do + inc(LnCnt,cntLns[i]); + writeln('Total number selected: ', LnCnt); +end. diff --git a/Task/One-of-n-lines-in-a-file/R/one-of-n-lines-in-a-file.r b/Task/One-of-n-lines-in-a-file/R/one-of-n-lines-in-a-file.r new file mode 100644 index 0000000000..51e8479564 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/R/one-of-n-lines-in-a-file.r @@ -0,0 +1,14 @@ +one_of_n <- function(n) +{ + choice <- 1L + + for (i in 2:n) + { + if (i*runif(1) < 1) + choice <- i + } + + return(choice) +} + +table(sapply(1:1000000, function(i) one_of_n(10))) diff --git a/Task/One-of-n-lines-in-a-file/Scala/one-of-n-lines-in-a-file.scala b/Task/One-of-n-lines-in-a-file/Scala/one-of-n-lines-in-a-file.scala new file mode 100644 index 0000000000..e35221f008 --- /dev/null +++ b/Task/One-of-n-lines-in-a-file/Scala/one-of-n-lines-in-a-file.scala @@ -0,0 +1,10 @@ +def one_of_n(n: Int, i: Int = 1, j: Int = 1): Int = + if (n < 1) i else one_of_n(n - 1, if (scala.util.Random.nextInt(j) == 0) n else i, j + 1) + +def simulate(lines: Int, iterations: Int) = { + val counts = new Array[Int](lines) + for (_ <- 1 to iterations; i = one_of_n(lines) - 1) counts(i) = counts(i) + 1 + counts +} + +println(simulate(10, 1000000) mkString "\n") diff --git a/Task/OpenGL/Common-Lisp/opengl.lisp b/Task/OpenGL/Common-Lisp/opengl.lisp new file mode 100644 index 0000000000..0079527a28 --- /dev/null +++ b/Task/OpenGL/Common-Lisp/opengl.lisp @@ -0,0 +1,67 @@ +(defun draw-triangle (x y &key (z 0) (type 'right)) + (case type + (right + (gl:with-primitive :triangles + (gl:color 0 0 1) + (gl:vertex x y z) + (gl:color 0 1 0) + (gl:vertex x (- y 1) z) + (gl:color 1 0 0) + (gl:vertex (+ x 1) (1- y) z))) + (equilateral + (gl:with-primitive :triangles + (gl:color 0 0 1) + (gl:vertex (+ x 0.5) y z) + (gl:color 1 0 0) + (gl:vertex (- x 0.5) (- y 1) z) + (gl:color 0 1 0) + (gl:vertex (+ x 1.5) (- y 1) z))))) + +(defun draw-update () + (gl:clear :color-buffer :depth-buffer :color-buffer-bit) + (gl:matrix-mode :modelview) + (gl:load-identity) + + (gl:color 1.0 1.0 1.0) + (gl:translate 0 0 -2) + + (draw-triangle -0.5 0.5 :type 'equilateral)) + +(defun main-loop () + (sdl:with-events () + (:quit-event () t) + (:key-down-event (:key key) + (cond ((sdl:key= key :sdl-key-escape) + (sdl:push-quit-event)))) + (:idle () + (draw-update) + (sdl:update-display)))) + +(defun setup-gl (w h) + (gl:clear-color 0.5 0.5 0.5 1) + (gl:clear-depth 1) + + (gl:viewport 0 0 w h) + + (gl:depth-func :lequal) + (gl:hint :perspective-correction-hint :nicest) + (gl:shade-model :smooth) + (gl:enable :depth-test :cull-face) + + (gl:matrix-mode :projection) + (gl:load-identity) + (glu:perspective 45 (/ w (max h 1)) 0.1 20) + + (gl:matrix-mode :modelview) + (gl:load-identity)) + +(defun triangle (&optional (w 640) (h 480)) + (sdl:with-init () + (sdl:set-gl-attribute :SDL-GL-DEPTH-SIZE 16) + (sdl:window w h + :bpp 32 + :flags sdl:sdl-opengl + :title-caption "Rosettacode.org OpenGL Demo") + (setup-gl w h) + (setf (sdl:frame-rate) 2) + (main-loop))) diff --git a/Task/OpenGL/Euphoria/opengl.euphoria b/Task/OpenGL/Euphoria/opengl.euphoria new file mode 100644 index 0000000000..aa4d790dce --- /dev/null +++ b/Task/OpenGL/Euphoria/opengl.euphoria @@ -0,0 +1,292 @@ +include get.e +include dll.e +include machine.e +include msgbox.e +include constants.ew +include GLfunc.ew +include GLconst.ew + +without warning + +atom hRC, hDC, hWnd, hInstance, ClassName +sequence keys keys = repeat(0,256) -- array to hold key presses + +integer active, fullscreen, retval +active = TRUE +fullscreen = TRUE +hRC = NULL +hDC = NULL +hWnd = NULL +hInstance = NULL + +atom rtri, rquad +rtri = 0.0 +rquad = 0.0 + +integer dmScreenSettings, WindowRect + +procedure ReSizeGLScene(integer width, integer height) + if height = 0 then + height = 1 + end if + c_proc(glViewport,{0,0,width,height}) + c_proc(glMatrixMode,{GL_PROJECTION}) + c_proc(glLoadIdentity,{}) + c_proc(gluPerspective,{45.0,width/height,0.1,100.0}) + c_proc(glMatrixMode,{GL_MODELVIEW}) + c_proc(glLoadIdentity,{}) +end procedure + +procedure InitGL() + c_proc(glShadeModel,{GL_SMOOTH}) + c_proc(glClearColor,{0.0,0.0,0.0,0.0}) + c_proc(glClearDepth,{1.0}) + c_proc(glEnable,{GL_DEPTH_TEST}) + c_proc(glDepthFunc,{GL_LEQUAL}) + c_proc(glHint,{GL_PERSPECTIVE_CORRECTION_HINT,GL_NICEST}) +end procedure + +function DrawGLScene() + c_proc(glClear, {or_bits(GL_COLOR_BUFFER_BIT,GL_DEPTH_BUFFER_BIT)}) + c_proc(glLoadIdentity, {}) + c_proc(glTranslatef, {-1.5,0.0,-6.0}) + c_proc(glRotatef, {rtri,0.0,1.0,0.0}) + c_proc(glBegin, {GL_TRIANGLES}) + c_proc(glColor3f, {1.0,0.0,0.0}) + c_proc(glVertex3f, {0.0,1.0,0.0}) + c_proc(glColor3f, {0.0,1.0,0.0}) + c_proc(glVertex3f, {-1.0,-1.0,0.0}) + c_proc(glColor3f, {0.0,0.0,1.0}) + c_proc(glVertex3f, {1.0,-1.0,0.0}) + c_proc(glEnd, {}) + c_proc(glLoadIdentity, {}) + c_proc(glTranslatef, {1.5,0.0,-6.0}) + c_proc(glRotatef, {rquad,1.0,0.0,0.0}) + c_proc(glColor3f, {0.5,0.5,1.0}) + c_proc(glBegin, {GL_QUADS}) + c_proc(glVertex3f, {1.0,1.0,0.0}) + c_proc(glVertex3f, {-1.0,1.0,0.0}) + c_proc(glVertex3f, {-1.0,-1.0,0.0}) + c_proc(glVertex3f, {1.0,-1.0,0.0}) + c_proc(glEnd, {}) + rtri += 0.2 + rquad -= 0.15 + return TRUE +end function + +procedure KillGLWindow() + if fullscreen then + if c_func(ChangeDisplaySettingsA,{NULL,0}) then end if + if c_func(ShowCursor,{TRUE}) then end if + end if + if hRC then + if c_func(wglMakeCurrent,{NULL,NULL}) then end if + if c_func(wglDeleteContext,{hRC}) then end if + hRC = NULL + end if + if hRC and not c_func(ReleaseDC,{hWnd,hDC}) then + hDC = NULL + end if + if hWnd and not c_func(DestroyWindow,{hWnd}) then + hWnd = NULL + end if + if dmScreenSettings then + free(dmScreenSettings) + end if + free(WindowRect) +end procedure + +function WndProc(atom hWnd, integer uMsg, atom wParam, atom lParam) + if uMsg = WM_ACTIVATE then + if not floor(wParam/#10000) then + active = TRUE + else + active = FALSE + end if + elsif uMsg = WM_SYSCOMMAND then + if wParam = SC_SCREENSAVE then end if + if wParam = SC_MONITORPOWER then end if + elsif uMsg = WM_CLOSE then + c_proc(PostQuitMessage,{0}) + elsif uMsg = WM_KEYDOWN then + keys[wParam] = TRUE + elsif uMsg = WM_KEYUP then + keys[wParam] = FALSE + elsif uMsg = WM_SIZE then + ReSizeGLScene(and_bits(lParam,#FFFF),floor(lParam/#10000)) + end if + return c_func(DefWindowProcA,{hWnd, uMsg, wParam, lParam}) +end function + +integer wc wc = allocate(40) +function ClassRegistration() +integer WndProcAddress, id + id = routine_id("WndProc") + if id = -1 then + puts(1, "routine_id failed!\n") + abort(1) + end if + WndProcAddress = call_back(id) + hInstance = c_func(GetModuleHandleA,{NULL}) + ClassName = allocate_string("OpenGL") + poke4(wc,or_all({CS_HREDRAW, CS_VREDRAW, CS_OWNDC})) + poke4(wc+4,WndProcAddress) + poke4(wc+8,0) + poke4(wc+12,0) + poke4(wc+16,hInstance) + poke4(wc+20,c_func(LoadIconA,{NULL,IDI_WINLOGO})) + poke4(wc+24,c_func(LoadCursorA,{NULL, IDC_ARROW})) + poke4(wc+28,NULL) + poke4(wc+32,NULL) + poke4(wc+36,ClassName) + if not c_func(RegisterClassA,{wc}) then + retval = message_box("Failed to register class","Error", or_bits(MB_OK,MB_ICONINFORMATION)) + return FALSE + else + return TRUE + end if +end function + +integer regd regd = FALSE +procedure CreateGLWindow(atom title, integer width, integer height, integer bits, integer fullscreenflag) + atom PixelFormat, pfd, dwExStyle, dwStyle + sequence s + if regd = FALSE then + if ClassRegistration() then + regd = TRUE + end if + end if + fullscreen = fullscreenflag + if fullscreen then + dmScreenSettings = allocate(156) + mem_set(dmScreenSettings,0,156) + s = int_to_bytes(156) + poke(dmScreenSettings + 36,{s[1],s[2]}) + poke4(dmScreenSettings + 40,or_all({DM_BITSPERPEL,DM_PELSWIDTH,DM_PELSHEIGHT})) + poke4(dmScreenSettings + 104, bits) + poke4(dmScreenSettings + 108, width) + poke4(dmScreenSettings + 112, height) + if c_func(ChangeDisplaySettingsA,{dmScreenSettings,CDS_FULLSCREEN}) != DISP_CHANGE_SUCCESSFUL then + if message_box("The requested fullscreen mode is not supported by\nyour video card. " & + "Use windowed mode instead?","Error", or_bits(MB_YESNO,MB_ICONEXCLAMATION)) = IDYES then + else + retval = message_box("Program will now close","Error",or_bits(MB_OK,MB_ICONSTOP)) + end if + end if + else + dmScreenSettings = NULL + end if + if fullscreen then + dwExStyle = WS_EX_APPWINDOW + dwStyle = WS_POPUP + if c_func(ShowCursor,{FALSE}) then end if + else + dwExStyle = or_bits(WS_EX_APPWINDOW,WS_EX_WINDOWEDGE) + dwStyle = WS_OVERLAPPEDWINDOW + end if + WindowRect = allocate(16) + poke4(WindowRect,0) + poke4(WindowRect + 4,width) + poke4(WindowRect + 8, 0) + poke4(WindowRect + 12, height) + if c_func(AdjustWindowRectEx,{WindowRect, dwStyle, FALSE, dwExStyle}) then end if + hWnd = c_func(CreateWindowExA,{dwExStyle, --extended window style + ClassName, --class + title, --window caption + or_all({WS_CLIPSIBLINGS,WS_CLIPCHILDREN,dwStyle}), --window style + 0, + 0, + peek4u(WindowRect + 4) - peek4u(WindowRect), + peek4u(WindowRect + 12) - peek4u(WindowRect + 8), + NULL, + NULL, + hInstance, + NULL}) + if hWnd = NULL then + KillGLWindow() + retval = message_box("Window creation error","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + pfd = allocate(40) --PIXELFORMATDESCRIPTOR + mem_set(pfd,0,40) + poke(pfd, 40) --size of pfd structure + poke(pfd + 2, 1) --version + poke4(pfd + 4, or_all({PFD_DRAW_TO_WINDOW,PFD_SUPPORT_OPENGL,PFD_DOUBLEBUFFER})) --properties flags + poke(pfd + 8, PFD_TYPE_RGBA) --request an rgba format + poke(pfd + 9, 24) --select color depth + poke(pfd + 23, 24) --32bit Z-buffer + + hDC = c_func(GetDC,{hWnd}) --create GL device context to match window device context + if not hDC then + KillGLWindow() + retval = message_box("Can't create a GL device context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + PixelFormat = c_func(ChoosePixelFormat,{hDC,pfd}) --find a pixel format matching PIXELFORMATDESCRIPTOR + if not PixelFormat then + KillGLWindow() + retval = message_box("Can't find a suitable pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + if not (c_func(SetPixelFormat,{hDC,PixelFormat,pfd})) then --set the pixel format + KillGLWindow() + retval = message_box("Can't set the pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + if not c_func(DescribePixelFormat, {hDC,PixelFormat,40,pfd}) then + retval = message_box("Can't describe the pixel format","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + hRC = c_func(wglCreateContext,{hDC}) --create GL rendering context + if not hRC then + KillGLWindow() + retval = message_box("Can't create a GL rendering context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + if not (c_func(wglMakeCurrent,{hDC,hRC})) then --make the GL rendering context active + KillGLWindow() + retval = message_box("Can't activate the GL rendering context","Error",or_bits(MB_OK,MB_ICONEXCLAMATION)) + end if + retval = c_func(ShowWindow,{hWnd,SW_SHOW}) --show the window + retval = c_func(SetForegroundWindow,{hWnd}) --set it to always be in foreground + retval = c_func(SetFocus,{hWnd}) --give it focus + ReSizeGLScene(width, height) --draw the GL scene to match the window size + InitGL() --initialize OpenGL +end procedure + +integer MSG MSG = allocate(28) +integer title title = allocate_string("OpenGL") +procedure WinMain() +integer done, msg_message + done = FALSE + if message_box("Would you like to run in fullscreen mode?","Start Fullscreen?",or_bits(MB_YESNO,MB_ICONQUESTION)) = IDNO then + fullscreen = FALSE + else + fullscreen = TRUE + end if + CreateGLWindow(title,640,480,24,fullscreen) + while not done do + if c_func(PeekMessageA,{MSG,NULL,0,0,PM_REMOVE}) then + msg_message = peek4u(MSG+4) + if msg_message = WM_QUIT then + done = TRUE + else + retval = c_func(TranslateMessage,{MSG}) + retval = c_func(DispatchMessageA,{MSG}) + end if + else + if ((active and not DrawGLScene()) or keys[VK_ESCAPE]) then + done = TRUE + else + retval = c_func(SwapBuffers,{hDC}) + if keys[VK_F1] then + keys[VK_F1] = FALSE + KillGLWindow() + if fullscreen = 0 then + fullscreen = 1 + else + fullscreen = 0 + end if + CreateGLWindow(title,640,480,24,fullscreen) + end if + end if + end if + end while + KillGLWindow() +end procedure + +WinMain() diff --git a/Task/OpenGL/Scala/opengl.scala b/Task/OpenGL/Scala/opengl.scala new file mode 100644 index 0000000000..7697c1f4f4 --- /dev/null +++ b/Task/OpenGL/Scala/opengl.scala @@ -0,0 +1,39 @@ +import org.lwjgl.opengl.{ Display, DisplayMode } +import org.lwjgl.opengl.GL11._ + +object OpenGlExample extends App { + + def render() { + + glClearColor(0.3f, 0.3f, 0.3f, 0.0f) + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) + + glShadeModel(GL_SMOOTH) + + glLoadIdentity() + glTranslatef(-15.0f, -15.0f, 0.0f) + + glBegin(GL_TRIANGLES) + glColor3f(1.0f, 0.0f, 0.0f) + glVertex2f(0.0f, 0.0f) + glColor3f(0.0f, 1.0f, 0.0f) + glVertex2f(30f, 0.0f) + glColor3f(0.0f, 0.0f, 1.0f) + glVertex2f(0.0f, 30.0f) + glEnd() + } + + Display.setDisplayMode(new DisplayMode(640, 480)) + Display.create() + + glMatrixMode(GL_PROJECTION) + glLoadIdentity() + glOrtho(-30, 30, -30, 30, -30, 30) + glMatrixMode(GL_MODELVIEW) + + while (!Display.isCloseRequested()) { + render() + Display.update() + Thread.sleep(1000) + } +} diff --git a/Task/Operator-precedence/AWK/operator-precedence.awk b/Task/Operator-precedence/AWK/operator-precedence.awk new file mode 100644 index 0000000000..2bc2c55cbe --- /dev/null +++ b/Task/Operator-precedence/AWK/operator-precedence.awk @@ -0,0 +1,61 @@ +# Operators are shown in decreasing order of precedence. +# A blank line separates groups of operators with equal precedence. +# All operators are left associative except: +# . assignment operators +# . conditional operator +# . exponentiation +# which are right associative. +# +# ( ) grouping +# +# $ field reference +# +# ++ increment (both prefix and postfix) +# -- decrement (both prefix and postfix) +# +# ^ exponentiation +# ** exponentiation (not all awk's) +# +# + unary plus +# - unary minus +# ! logical NOT +# +# * multiply +# / divide +# % modulus +# +# + add +# - subtract +# +# string concatenation has no explicit operator +# +# < relational: less than +# <= relational: less than or equal to +# > relational: greater than +# >= relational: greater than or equal to +# != relational: not equal to +# == relational: equal to +# > redirection: output to file +# >> redirection: append output to file +# | redirection: pipe +# |& redirection: coprocess (not all awk's) +# +# ~ regular expression: match +# !~ regular expression: negated match +# +# in array membership +# +# && logical AND +# +# || logical OR +# +# ?: conditional expression +# +# = assignment +# += addition assignment +# -= subtraction assignment +# *= multiplication assignment +# /= division assignment +# %= modulo assignment +# ^= exponentiation assignment +# **= exponentiation assignment (not all awk's) diff --git a/Task/Optional-parameters/Bracmat/optional-parameters.bracmat b/Task/Optional-parameters/Bracmat/optional-parameters.bracmat new file mode 100644 index 0000000000..fb2367662e --- /dev/null +++ b/Task/Optional-parameters/Bracmat/optional-parameters.bracmat @@ -0,0 +1,22 @@ +( ( sortTable + = table ordering column reverse + . !arg + : ( ?table + . ( ? (ordering.?ordering) ? + | ?&lexicographic:?ordering + ) + : ( ? (column.?column) ? + | ?&1:?column + ) + : ( ? (reverse.?reverse) ? + | ?&no:?reverse + ) + ) + & (...) + ) +& (12.Claes.left) + (11.Otto.right) + (8.Frederikke.middle) + : ?table +& sortTable$(!table.(column.2) (reverse.yes)) +); diff --git a/Task/Optional-parameters/Groovy/optional-parameters-1.groovy b/Task/Optional-parameters/Groovy/optional-parameters-1.groovy new file mode 100644 index 0000000000..fa3ca9046b --- /dev/null +++ b/Task/Optional-parameters/Groovy/optional-parameters-1.groovy @@ -0,0 +1,3 @@ +def orderedSort(Collection table, column = 0, reverse = false, ordering = {x, y -> x <=> y } as Comparator) { + table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])} +} diff --git a/Task/Optional-parameters/Groovy/optional-parameters-2.groovy b/Task/Optional-parameters/Groovy/optional-parameters-2.groovy new file mode 100644 index 0000000000..9384554ed8 --- /dev/null +++ b/Task/Optional-parameters/Groovy/optional-parameters-2.groovy @@ -0,0 +1,7 @@ +def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']] + +assert orderedSort(table) == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']] +assert orderedSort(table, 2) == [['zap', 'zip', 'Zot'], ['a', 'b', 'c'], ['', 'q', 'z']] +assert orderedSort(table, 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']] +assert orderedSort(table, 1, true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']] +assert orderedSort(table, 0, false, {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']] diff --git a/Task/Optional-parameters/Groovy/optional-parameters-3.groovy b/Task/Optional-parameters/Groovy/optional-parameters-3.groovy new file mode 100644 index 0000000000..fd85b88130 --- /dev/null +++ b/Task/Optional-parameters/Groovy/optional-parameters-3.groovy @@ -0,0 +1,7 @@ +Collection.metaClass.orderedSort = { params -> + def column = params?.column ?: 0 + def reverse = params?.reverse ?: false + def ordering = params?.ordering ?: {x, y -> x <=> y } as Comparator + + table.sort(false) { x, y -> (reverse ? -1 : 1) * ordering.compare(x[column], y[column])} +} diff --git a/Task/Optional-parameters/Groovy/optional-parameters-4.groovy b/Task/Optional-parameters/Groovy/optional-parameters-4.groovy new file mode 100644 index 0000000000..fca6b3f7db --- /dev/null +++ b/Task/Optional-parameters/Groovy/optional-parameters-4.groovy @@ -0,0 +1,7 @@ +def table = [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']] + +assert table.orderedSort() == [['', 'q', 'z'], ['a', 'b', 'c'], ['zap', 'zip', 'Zot']] +assert table.orderedSort(column: 2) == [['zap', 'zip', 'Zot'], ['a', 'b', 'c'], ['', 'q', 'z']] +assert table.orderedSort(column: 1) == [['a', 'b', 'c'], ['', 'q', 'z'], ['zap', 'zip', 'Zot']] +assert table.orderedSort(column: 1, reverse: true) == [['zap', 'zip', 'Zot'],['', 'q', 'z'],['a', 'b', 'c']] +assert table.orderedSort(ordering: {x, y -> y?.size() <=> x?.size()} as Comparator) == [['zap', 'zip', 'Zot'],['a', 'b', 'c'],['', 'q', 'z']] diff --git a/Task/Optional-parameters/Haskell/optional-parameters-1.hs b/Task/Optional-parameters/Haskell/optional-parameters-1.hs new file mode 100644 index 0000000000..58925d31a7 --- /dev/null +++ b/Task/Optional-parameters/Haskell/optional-parameters-1.hs @@ -0,0 +1,15 @@ +{-# LANGUAGE RecordWildCards #-} + +data SorterArgs = SorterArgs { cmp :: String, col :: Int, rev :: Bool } deriving Show +defSortArgs = SorterArgs "lex" 0 False + + +sorter :: SorterArgs -> [[String]] -> [[String]] +sorter (SorterArgs{..}) = case cmp of + _ -> undefined + +main = do + sorter defSortArgs{cmp = "foo", col=1, rev=True} [[]] + sorter defSortArgs{cmp = "foo"} [[]] + sorter defSortArgs [[]] + return () diff --git a/Task/Optional-parameters/Haskell/optional-parameters-2.hs b/Task/Optional-parameters/Haskell/optional-parameters-2.hs new file mode 100644 index 0000000000..ce3aa4239a --- /dev/null +++ b/Task/Optional-parameters/Haskell/optional-parameters-2.hs @@ -0,0 +1,12 @@ +import Data.Maybe (fromMaybe) +-- Use fromMaybe as an operator because its prettier +(//) = flip fromMaybe + +sorter :: Maybe String -> Maybe Int -> Maybe Bool -> [[String]] -> [[String]] +sorter ((// "lex") -> cmp) + ((// 0) -> col) + ((// False) -> rev) = undefined + +main = do + sorter (Just "foo") (Just 1) (Just True) + sorter Nothing Nothing Nothing diff --git a/Task/Optional-parameters/Maple/optional-parameters-1.maple b/Task/Optional-parameters/Maple/optional-parameters-1.maple new file mode 100644 index 0000000000..1ff827f183 --- /dev/null +++ b/Task/Optional-parameters/Maple/optional-parameters-1.maple @@ -0,0 +1,13 @@ +OptionalSort := proc(input, { + ordering :: Or(procedures,identical("lexicographic")) := "lexicographic", + column :: posint := 1, + reverse :: truefalse := false +} ) + local compare; + if ordering = "lexicographic" then + compare := (x,y)->evalb(`if`(reverse,x[column]>=y[column],x[column]<=y[column])); + else + compare := (x,y)->`if`(reverse,ordering(x[column],y),ordering(y,x)); + end if; + sort( input, compare ); +end proc: diff --git a/Task/Optional-parameters/Maple/optional-parameters-2.maple b/Task/Optional-parameters/Maple/optional-parameters-2.maple new file mode 100644 index 0000000000..0cb4f4deb1 --- /dev/null +++ b/Task/Optional-parameters/Maple/optional-parameters-2.maple @@ -0,0 +1,7 @@ +> L := [[1, 2], [3, 4], [-5, 7]]: +> OptionalSort(L); + [[-5, 7], [1, 2], [3, 4]] +> OptionalSort(L, reverse); + [[3, 4], [1, 2], [-5, 7]] +> OptionalSort(L, reverse, column = 2); + [[-5, 7], [3, 4], [1, 2]] diff --git a/Task/Optional-parameters/REXX/optional-parameters-1.rexx b/Task/Optional-parameters/REXX/optional-parameters-1.rexx index cb275c1729..d3f42e91a2 100644 --- a/Task/Optional-parameters/REXX/optional-parameters-1.rexx +++ b/Task/Optional-parameters/REXX/optional-parameters-1.rexx @@ -1,19 +1,18 @@ sortStrings: procedure expose @. /*stemmed array is named: @. */ -col=1; reverse='NO'; order='LEXICOGRAPHIC' /*set the defaults.*/ +col=1; reverse='NO'; order='LEXICOGRAPHIC' /*set some defaults.*/ arg options - do j=1 for words(options); x=word(options,j) + do j=1 for words(options); x=word(options,j) select - when datatype(x,'W') then col=x/1 - when pos('=',x)==0 then order=x - otherwise parse var x nam '=' value + when datatype(x, 'W') then col=x/1 + when pos('=', x)==0 then order=x + otherwise parse var x nam '=' value end /*select*/ end /*j*/ - - /*check for errors here: COL isn't positive, */ - /* REVERSE value isn't NO or YES, */ - /* ORDER value is recognized ... */ - -... main body of string sort here ... - -return + /*╔═══════════════════════════════════════════════════════════╗ + ║ check for errors here: COL isn't a positive integer ···, ║ + ║ REVERSE value isn't NO or YES, ║ + ║ ORDER value is recognized ··· ║ + ╚═══════════════════════════════════════════════════════════╝*/ + ... main body of string sort here ... +return /*stick a fork in it, we're done.*/ diff --git a/Task/Optional-parameters/REXX/optional-parameters-2.rexx b/Task/Optional-parameters/REXX/optional-parameters-2.rexx index 9752ea399f..ca0d03c9f9 100644 --- a/Task/Optional-parameters/REXX/optional-parameters-2.rexx +++ b/Task/Optional-parameters/REXX/optional-parameters-2.rexx @@ -1,4 +1,4 @@ -/*REXX example to use the SortStrings subroutine with optional args. */ - /*...define array (@.nnn) of strings here...*/ +/*REXX example uses the SortStrings subroutine with optional args. */ + /*···define array (@.nnn) of strings here···*/ call sortStrings 'Reverse=no' 3 /*stick a fork in it, we're done.*/ diff --git a/Task/Order-two-numerical-lists/00DESCRIPTION b/Task/Order-two-numerical-lists/00DESCRIPTION index 29caaae7db..60acaa9d6b 100644 --- a/Task/Order-two-numerical-lists/00DESCRIPTION +++ b/Task/Order-two-numerical-lists/00DESCRIPTION @@ -1,4 +1,7 @@ -Write function that orders two lists or arrays filled with numbers. +Write a function that orders two lists or arrays filled with numbers. The function should accept two lists as arguments and return true if the first list should be ordered before the second, and false otherwise. -The order is determined by [[wp:Lexicographical order#Ordering of sequences of various lengths|lexicographic order]]: Comparing the first element of each list. If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. If the first list runs out of elements the result is true. if the second list or both run out of elements the result is false. +The order is determined by [[wp:Lexicographical order#Ordering of sequences of various lengths|lexicographic order]]: Comparing the first element of each list. +If the first elements are equal, then the second elements should be compared, and so on, until one of the list has no more elements. +If the first list runs out of elements the result is true. +If the second list or both run out of elements the result is false. diff --git a/Task/Order-two-numerical-lists/AWK/order-two-numerical-lists.awk b/Task/Order-two-numerical-lists/AWK/order-two-numerical-lists.awk new file mode 100644 index 0000000000..f16febbfec --- /dev/null +++ b/Task/Order-two-numerical-lists/AWK/order-two-numerical-lists.awk @@ -0,0 +1,24 @@ +# syntax: GAWK -f ORDER_TWO_NUMERICAL_LISTS.AWK +BEGIN { + split("1,2,1,5,2",list1,",") + split("1,2,1,5,2,2",list2,",") + split("1,2,3,4,5",list3,",") + split("1,2,3,4,5",list4,",") + x = compare_array(list1,list2) ? "<" : ">=" ; printf("list1%slist2\n",x) + x = compare_array(list2,list3) ? "<" : ">=" ; printf("list2%slist3\n",x) + x = compare_array(list3,list4) ? "<" : ">=" ; printf("list3%slist4\n",x) + exit(0) +} +function compare_array(arr1,arr2, ans,i) { + ans = 0 + for (i=1; i<=length(arr1); i++) { + if (arr1[i] != arr2[i]) { + ans = 1 + break + } + } + if (length(arr1) != length(arr2)) { + ans = 1 + } + return(ans) +} diff --git a/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-1.lua b/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-1.lua new file mode 100644 index 0000000000..63f855da34 --- /dev/null +++ b/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-1.lua @@ -0,0 +1,11 @@ +function arraycompare(a, b) + for i = 1, #a do + if b[i] == nil then + return true + end + if a[i] ~= b[i] then + return a[i] < b[1] + end + end + return true +end diff --git a/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-2.lua b/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-2.lua new file mode 100644 index 0000000000..83c7f6aa13 --- /dev/null +++ b/Task/Order-two-numerical-lists/Lua/order-two-numerical-lists-2.lua @@ -0,0 +1,20 @@ +function randomarray() + local t = {} + for i = 1, math.random(1, 10) do + t[i] = math.random(1, 10) + end + return t +end + +math.randomseed(os.time()) + +for i = 1, 10 do + local a = randomarray() + local b = randomarray() + + print( + string.format("{%s} %s {%s}", + table.concat(a, ', '), + arraycompare(a, b) and "<=" or ">", + table.concat(b, ', '))) +end diff --git a/Task/Order-two-numerical-lists/PL-I/order-two-numerical-lists.pli b/Task/Order-two-numerical-lists/PL-I/order-two-numerical-lists.pli new file mode 100644 index 0000000000..01ee4ce1f1 --- /dev/null +++ b/Task/Order-two-numerical-lists/PL-I/order-two-numerical-lists.pli @@ -0,0 +1,22 @@ +lists: procedure options (main); /* 8 June 2014 */ + + declare a(10) fixed initial (1, 2, 3, 4, 5, 8, 9, 10, 16, 17), + b(15) fixed initial (5, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18, 20, 22, 23); + + put skip list (compare(a, b)); + put skip list (compare(b, a)); + put skip list (compare(a, a)); + + +compare: procedure (a, b) returns (bit (1)); + declare (a, b)(*) fixed; + declare (i, m, n) fixed binary; + + m = hbound(a,1); n = hbound(b,1); + do i = 1 to min(m, n); + return (a(i) < b(i)); + end; + return (m < n); +end compare; + +end lists; diff --git a/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx b/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx index 0310dde5e3..fba6f4d896 100644 --- a/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx +++ b/Task/Order-two-numerical-lists/REXX/order-two-numerical-lists.rexx @@ -1,19 +1,23 @@ -/*REXX pgm finds if list1b then return 'false' + end /*k*/ if wx false + case (Nil, _) => true + case (a :: _, b :: _) if a != b => a < b + case _ => lessThan2(a.tail, b.tail) +} diff --git a/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-3.scala b/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-3.scala new file mode 100644 index 0000000000..4b47a316b4 --- /dev/null +++ b/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-3.scala @@ -0,0 +1,5 @@ +def lessThan3(a: List[Int], b: List[Int]): Boolean = + a.zipAll(b, Integer.MIN_VALUE, Integer.MIN_VALUE) + .find{case (a, b) => a != b} + .map{case (a, b) => a < b} + .getOrElse(false) diff --git a/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-4.scala b/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-4.scala new file mode 100644 index 0000000000..efab389f19 --- /dev/null +++ b/Task/Order-two-numerical-lists/Scala/order-two-numerical-lists-4.scala @@ -0,0 +1,14 @@ +val tests = List( + (List(1, 2, 3), List(1, 2, 3)) -> false, + (List(3, 2, 1), List(3, 2, 1)) -> false, + (List(1, 2, 3), List(3, 2, 1)) -> true, + (List(3, 2, 1), List(1, 2, 3)) -> false, + (List(1, 2), List(1, 2, 3)) -> true, + (List(1, 2, 3), List(1, 2)) -> false +) + +tests.foreach{case test @ ((a, b), c) => + assert(lessThan1(a, b) == c, test) + assert(lessThan2(a, b) == c, test) + assert(lessThan3(a, b) == c, test) +} diff --git a/Task/Ordered-Partitions/00DESCRIPTION b/Task/Ordered-Partitions/00DESCRIPTION index 6ec99c23ee..0278b77309 100644 --- a/Task/Ordered-Partitions/00DESCRIPTION +++ b/Task/Ordered-Partitions/00DESCRIPTION @@ -33,6 +33,6 @@ Note: Do not use functions that are not in the standard library of the programmi '''Notation''' -Remarks on the used notation for the task in order to understand it easierly. +Here are some explanatory remarks on the notation used in the task description: \{1, \ldots, n\} denotes the set of consecutive numbers from 1 to n, e.g. \{1,2,3\} if n = 3. \Sigma is the mathematical notation for summation, e.g. \Sigma_{i=1}^3 i = 6 (see also [http://en.wikipedia.org/wiki/Summation#Capital-sigma_notation]). \mathit{arg}_1,\mathit{arg}_2,...,\mathit{arg}_n are the arguments — natural numbers — that the sought function receives. diff --git a/Task/Ordered-Partitions/D/ordered-partitions-1.d b/Task/Ordered-Partitions/D/ordered-partitions-1.d new file mode 100644 index 0000000000..e945bc36ad --- /dev/null +++ b/Task/Ordered-Partitions/D/ordered-partitions-1.d @@ -0,0 +1,25 @@ +import std.stdio, std.algorithm, std.range, std.array, std.conv, + combinations3; + +alias iRNG = int[]; + +iRNG[][] orderPart(iRNG blockSize...) { + iRNG tot = iota(1, 1 + blockSize.sum).array; + + iRNG[][] p(iRNG s, in iRNG b) { + if (b.empty) + return [[]]; + iRNG[][] res; + foreach (c; s.combinations(b[0])) + foreach (r; p(setDifference(s, c).array, b.dropOne)) + res ~= c.dup ~ r; + return res; + } + + return p(tot, blockSize); +} + +void main(in string[] args) { + auto b = args.length > 1 ? args.dropOne.to!(int[]) : [2, 0, 2]; + writefln("%(%s\n%)", b.orderPart); +} diff --git a/Task/Ordered-Partitions/D/ordered-partitions-2.d b/Task/Ordered-Partitions/D/ordered-partitions-2.d new file mode 100644 index 0000000000..db6ece2320 --- /dev/null +++ b/Task/Ordered-Partitions/D/ordered-partitions-2.d @@ -0,0 +1,44 @@ +import core.stdc.stdio; + +void genBits(size_t N)(ref uint[N] bits, in ref uint[N] parts, + uint mask, uint all, uint res, uint n, uint pid) +nothrow @nogc { + static void showPart(in uint x) nothrow @nogc { + '['.putchar; + for (uint i = 0; (1 << i) <= x; i++) + if (x & (1 << i)) + printf("%d ", i + 1); + ']'.putchar; + } + + while (!n) { + bits[pid] = res; + pid++; + if (pid == N) { + foreach (immutable b; bits) + showPart(b); + '\n'.putchar; + return; + } + all &= ~res; + mask = all; + res = 0; + n = parts[pid]; + } + + while (mask) { + immutable uint i = mask & -int(mask); + mask &= ~i; + genBits(bits, parts, mask, all, res | i, n - 1, pid); + } +} + +void main() nothrow @nogc { + immutable uint[3] parts = [2, 0, 2]; + uint m = 1; + foreach (immutable p; parts) + m <<= p; + + uint[parts.length] bits; + genBits(bits, parts, m - 1, m - 1, 0, parts[0], 0); +} diff --git a/Task/Ordered-Partitions/D/ordered-partitions.d b/Task/Ordered-Partitions/D/ordered-partitions.d deleted file mode 100644 index be79eddedc..0000000000 --- a/Task/Ordered-Partitions/D/ordered-partitions.d +++ /dev/null @@ -1,29 +0,0 @@ -import std.stdio, std.algorithm, std.range, std.array, std.conv; -import combinations4: Comb; - -alias iRNG = int[]; - -iRNG setDiff(iRNG s, iRNG c) { - return setDifference(s, c).array; -} - -iRNG[][] orderPart(iRNG blockSize...) { - iRNG sum = iota(1, 1 + blockSize.sum).array; - - iRNG[][] p(iRNG s, in iRNG b) { - if (b.length == 0) - return [[]]; - iRNG[][] res; - foreach (c; Comb.On(s, b[0])) - foreach (r; p(setDiff(s, c), b.dropOne)) - res ~= c.dup ~ r; - return res; - } - - return p(sum, blockSize); -} - -void main(in string[] args) { - auto b = args.length > 1 ? args.dropOne.to!(int[]) : [2, 0, 2]; - writefln("%(%s\n%)", b.orderPart); -} diff --git a/Task/Ordered-Partitions/Groovy/ordered-partitions-1.groovy b/Task/Ordered-Partitions/Groovy/ordered-partitions-1.groovy index 1ecb219280..0e880e3f51 100644 --- a/Task/Ordered-Partitions/Groovy/ordered-partitions-1.groovy +++ b/Task/Ordered-Partitions/Groovy/ordered-partitions-1.groovy @@ -4,9 +4,9 @@ def partitions = { int... sizes -> Set parts = perms.collect { p -> sizes.collect { s -> (0.. if (!a) return 0 - def comp = [a,b].transpose().find { it[0] != it[1] } - if (!comp) return 0 - def recomp = comp.collect{ it as List }.transpose().find { it[0] != it[1] } + def comp = [a,b].transpose().find { aa, bb -> aa != bb } + if (!comp) return 0 + def recomp = comp.collect{ it as List }.transpose().find { aa, bb -> aa != bb } if (!recomp) return 0 return recomp[0] <=> recomp[1] } diff --git a/Task/Ordered-Partitions/Perl/ordered-partitions-2.pl b/Task/Ordered-Partitions/Perl/ordered-partitions-2.pl index c73b4463af..2025dacfb9 100644 --- a/Task/Ordered-Partitions/Perl/ordered-partitions-2.pl +++ b/Task/Ordered-Partitions/Perl/ordered-partitions-2.pl @@ -1,48 +1,19 @@ -sub partitions { - my $sum = 0; - $sum += $_ for @_; # total number of elements - make_part ( $_[-1], # desired partition size - 0, # initial trial position - [ (0) x $sum ], # table recording of used element - [], # current pick for current partition - [ $#_, # total number of partitions - \@_, # partition sizes - [] # for output, each partition's elements - ] # Note: last group of args wrapped in array ref - ); # to reduce argument passing overhead +use List::Util 1.33 qw(sum pairmap); + +sub partition { + my @mask = @_; + my $last = sum @mask or return [map {[]} 0..$#mask]; + + return pairmap { + $b ? do { + local $mask[$a] = $b - 1; + map { push @{$_->[$a]}, $last; $_ } + partition(@mask); + } : () + } %mask[0..$#mask]; } -sub make_part { - my ($n, $pos, $used, $picked, $more) = @_; - return if $pos > @$used; +# Input & Output handling: - # the making-next-partition part - if (!$n) { - my ($part_idx, $sizes, $q) = @$more; - push @$q, $picked; - if ($part_idx > 1) { - make_part($sizes->[$part_idx-1], 0, $used, [], - [ $part_idx-1, $sizes, $q]); - } else { - my @x = grep { !$used->[$_] } 0 .. (@$used-1); - print "[ @$_ ]" for @$q; - print "[ @x ]\n"; - } - pop @$q; - return; - } - - # the picking-element-to-make-partition part - for my $i ($pos .. @$used - 1) { - next if $used->[$i]; - push @$picked, $i; - $used->[$i] = 1; - - make_part($n - 1, $i + 1, $used, $picked, $more); - - $used->[$i] = 0; - pop @$picked; - } -} - -partitions(4, 2, 4); +print "(" . join(', ', map { "{".join(', ', @$_)."}" } @$_) . ")\n" + for partition( @ARGV ? @ARGV : (2, 0, 2) ); diff --git a/Task/Ordered-Partitions/REXX/ordered-partitions.rexx b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx new file mode 100644 index 0000000000..a5b6a47552 --- /dev/null +++ b/Task/Ordered-Partitions/REXX/ordered-partitions.rexx @@ -0,0 +1,48 @@ +/*REXX program displays ordered partitions: orderedPartitions(i,j,k,···)*/ +call orderedPartitions 2,0,2 /*Note: 2,,2 will also work*/ +call orderedPartitions 1,1,1 +call orderedPartitions 1,2,0,1 /*Note: 1,2,1 will also work*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ORDEREDPARTITIONS subroutine────────*/ +orderedPartitions: procedure; #=arg(); hdr=; bot.=; top.=; low=; high= +d=123456789 /*handy-dandy literal for digits.*/ +t=0 /*T: is the sum of all arguments.*/ + do i=1 for #; t=t+('0'arg(i)) /*sum all the highest #s in parts*/ + end /*i*/ + /* [↓] process each of arguments*/ + do j=1 for #; _=arg(j) /* _: is the Jth argument.*/ + len.j=max(1,_) /*LEN: length of args, 0=special*/ + bot.j=left(d,_); if _==0 then bot.j=0 /*define the bottom num*/ + top.j=right(left(d,t),_); if _==0 then top.j=0 /* " " top " */ + @.j=left(d,t); if _==0 then @.j=0 /*define VERIFY digits.*/ + hdr=hdr _ /*build display header.*/ + low=low || bot.j; high=high || top.j /*low and high of loop.*/ + end /*j*/ + +okD=left(0||d,t+1) /*define legal digits to be used.*/ +say center(' partitions for: ' hdr" ",50,'─'); say + + do g=low to high /* [↑] generate ordered parts. */ + if verify(g,okD)\==0 then iterate /*filter out the unwanted digits.*/ + p=1 /*P: is the position of a digit.*/ + $= /*$: will be the transformed #s.*/ + do k=1 for # /*verify the partitions numbers. */ + /*validate#: dups/ordered/repeats*/ + _=substr(g,p,len.k) /*ordered part num. to be tested.*/ + if verify(_,@.k)\==0 then iterate g /*is digit ¬ valid ? */ + != /* [↓] validate num.*/ + if @.k\==0 then do j=1 for length(_); z=substr(_,j,1) + if pos(z,$)\==0 then iterate g /*prev*/ + !=!','z + if j==1 then iterate + if z<=substr(_,j-1,1) then iterate g /*ord.*/ + if pos(z,_,1+pos(z,_))\==0 then iterate g /*dup.*/ + end /*j*/ + p=p+len.k /*point to next #.*/ + $=$ ' {'strip(translate(!,,0),,',')"}" /*dress the # up. */ + end /*k*/ + + say $ + end /*g*/ +say +return diff --git a/Task/Ordered-Partitions/Ruby/ordered-partitions-1.rb b/Task/Ordered-Partitions/Ruby/ordered-partitions-1.rb new file mode 100644 index 0000000000..2d34a85bfb --- /dev/null +++ b/Task/Ordered-Partitions/Ruby/ordered-partitions-1.rb @@ -0,0 +1,6 @@ +def partition(mask) + return [[]] if mask.empty? + [*1..mask.inject(:+)].permutation.map {|perm| + mask.map {|num_elts| perm.shift(num_elts).sort } + }.uniq +end diff --git a/Task/Ordered-Partitions/Ruby/ordered-partitions-2.rb b/Task/Ordered-Partitions/Ruby/ordered-partitions-2.rb new file mode 100644 index 0000000000..4c9fe332b4 --- /dev/null +++ b/Task/Ordered-Partitions/Ruby/ordered-partitions-2.rb @@ -0,0 +1,10 @@ +def part(s, args) + return [[]] if args.empty? + s.combination(args[0]).each_with_object([]) do |c, res| + part(s - c, args[1..-1]).each{|r| res << ([c] + r)} + end +end +def partitions(args) + return [[]] if args.empty? + part((1..args.inject(:+)).to_a, args) +end diff --git a/Task/Ordered-Partitions/Ruby/ordered-partitions-3.rb b/Task/Ordered-Partitions/Ruby/ordered-partitions-3.rb new file mode 100644 index 0000000000..ee9799a91c --- /dev/null +++ b/Task/Ordered-Partitions/Ruby/ordered-partitions-3.rb @@ -0,0 +1,5 @@ +[[],[0,0,0],[1,1,1],[2,0,2]].each do |test_case| + puts "partitions #{test_case}:" + partition(test_case).each{|part| p part } + puts +end diff --git a/Task/Ordered-Partitions/Ruby/ordered-partitions.rb b/Task/Ordered-Partitions/Ruby/ordered-partitions.rb deleted file mode 100644 index 3d7e6b568c..0000000000 --- a/Task/Ordered-Partitions/Ruby/ordered-partitions.rb +++ /dev/null @@ -1,15 +0,0 @@ -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/D/ordered-words-1.d b/Task/Ordered-words/D/ordered-words-1.d index eaa4013a1c..7c0d0be4ad 100644 --- a/Task/Ordered-words/D/ordered-words-1.d +++ b/Task/Ordered-words/D/ordered-words-1.d @@ -1,13 +1,13 @@ -import std.stdio, std.algorithm, std.range, std.string; - void main() { + import std.stdio, std.algorithm, std.range, std.string; + string[] result; size_t maxLen; - foreach (string word; File("unixdict.txt").lines()) { - word = word.chomp(); - immutable len = walkLength(word); - if (len < maxLen || !isSorted(word)) + foreach (string word; "unixdict.txt".File.lines) { + word = word.chomp; + immutable len = word.walkLength; + if (len < maxLen || !word.isSorted) continue; if (len > maxLen) { result = [word]; @@ -16,5 +16,5 @@ void main() { result ~= word; } - writeln(result.join("\n")); + writefln("%-(%s\n%)", result); } diff --git a/Task/Ordered-words/D/ordered-words-2.d b/Task/Ordered-words/D/ordered-words-2.d index 482bdc7ec8..3b01164104 100644 --- a/Task/Ordered-words/D/ordered-words-2.d +++ b/Task/Ordered-words/D/ordered-words-2.d @@ -1,5 +1,6 @@ void main() { import std.stdio, std.algorithm, std.file, std.range; + string[] result; size_t maxWalkLen; diff --git a/Task/Ordered-words/D/ordered-words-3.d b/Task/Ordered-words/D/ordered-words-3.d index d13e4d9258..2f340aaf53 100644 --- a/Task/Ordered-words/D/ordered-words-3.d +++ b/Task/Ordered-words/D/ordered-words-3.d @@ -1,6 +1,6 @@ -import std.stdio, std.algorithm, std.range, std.file, std.string; - void main() { + import std.stdio, std.algorithm, std.range, std.file, std.string; + auto words = "unixdict.txt".readText.split.filter!isSorted; immutable maxLen = words.map!q{a.length}.reduce!max; writefln("%-(%s\n%)", words.filter!(w => w.length == maxLen)); diff --git a/Task/Ordered-words/D/ordered-words-4.d b/Task/Ordered-words/D/ordered-words-4.d index fffbc0bcfe..4fa434ab6e 100644 --- a/Task/Ordered-words/D/ordered-words-4.d +++ b/Task/Ordered-words/D/ordered-words-4.d @@ -1,17 +1,14 @@ import std.stdio, core.stdc.string, std.mmfile, std.algorithm; -const(char)[] findWord(const char[] s) pure nothrow @safe { - // return s.takeWhile!(c => c !in "\n\r"); +const(char)[] findWord(const char[] s) pure nothrow @safe @nogc { size_t wordEnd = 0; - while (wordEnd < s.length && s[wordEnd] != '\n' - && s[wordEnd] != '\r') + while (wordEnd < s.length && s[wordEnd] != '\n' && s[wordEnd] != '\r') wordEnd++; return s[0 .. wordEnd]; } void main() { - auto mmf = new MmFile("unixdict.txt", - MmFile.Mode.readCopyOnWrite, 0, null); + auto mmf = new MmFile("unixdict.txt", MmFile.Mode.readCopyOnWrite, 0, null); auto txt = cast(char[])(mmf[]); size_t maxLen = 0, outStart = 0; @@ -22,7 +19,7 @@ void main() { const word = findWord(txt[wordStart .. $]); wordStart += word.length; - if (word.length < maxLen || !word.isSorted()) + if (word.length < maxLen || !word.isSorted) continue; if (word.length > maxLen) { // Longer ordered word found, reset the out buffer. @@ -40,5 +37,5 @@ void main() { txt[outStart++] = '\n'; // Words separator in out buffer. } - write(txt[0 .. outStart]); + txt[0 .. outStart].write; } diff --git a/Task/Ordered-words/REXX/ordered-words.rexx b/Task/Ordered-words/REXX/ordered-words.rexx index 2bf8f90954..dd7ac6fb92 100644 --- a/Task/Ordered-words/REXX/ordered-words.rexx +++ b/Task/Ordered-words/REXX/ordered-words.rexx @@ -2,27 +2,26 @@ ifid = 'UNIXDICT.TXT' /*filename of the word dictionary*/ @.= /*placeholder for list of words. */ mL=0 /*maximum length of ordered words*/ -call linein ifid,1,0 /*point to the first word in dict*/ - /*(above)───in case file is open.*/ - do j=1 while lines(ifid)\==0 /*keep reading until exhausted. */ +call linein ifid, 1, 0 /*point to the first word in dict*/ + /* [↑] in case the file is open.*/ + do j=1 while lines(ifid)\==0 /*keep reading until exhausted. */ x=linein(ifid); w=length(x) /*get a word and also its length.*/ - if w An example of a Latin palindrome is the sentence "''In girum imus nocte et consumimur igni''", -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. +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. -'''Clarifiation'''
+'''Clarification'''
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'''
+'''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/00META.yaml b/Task/Palindrome-detection/00META.yaml index 448dce149a..be514df841 100644 --- a/Task/Palindrome-detection/00META.yaml +++ b/Task/Palindrome-detection/00META.yaml @@ -1,5 +1,6 @@ --- category: - Recursion +- String manipulation - Classic CS problems and programs note: Text processing diff --git a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg index 2d4a286146..0d7bcdafa8 100644 --- a/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg +++ b/Task/Palindrome-detection/ALGOL-68/palindrome-detection.alg @@ -2,7 +2,7 @@ PROC palindrome = (STRING s)BOOL:( FOR i TO UPB s OVER 2 DO IF s[i] /= s[UPB s-i+1] THEN GO TO return false FI - OD; + OD;Power else: TRUE EXIT return false: FALSE ); diff --git a/Task/Palindrome-detection/Batch-File/palindrome-detection-1.bat b/Task/Palindrome-detection/Batch-File/palindrome-detection-1.bat new file mode 100644 index 0000000000..3e536626ee --- /dev/null +++ b/Task/Palindrome-detection/Batch-File/palindrome-detection-1.bat @@ -0,0 +1,15 @@ +@echo off +setlocal enabledelayedexpansion +set /p string=Your string : +set count=0 +:loop + if "!%string%:~%count%,1!" neq "" ( + set reverse=!%string%:~%count%,1!!reverse! + set /a count+=1 + goto loop + ) +set palindrome=isn't +if "%string%"=="%reverse%" set palindrome=is +echo %string% %palindrome% a palindrome. +pause +exit diff --git a/Task/Palindrome-detection/Batch-File/palindrome-detection-2.bat b/Task/Palindrome-detection/Batch-File/palindrome-detection-2.bat new file mode 100644 index 0000000000..15b435856d --- /dev/null +++ b/Task/Palindrome-detection/Batch-File/palindrome-detection-2.bat @@ -0,0 +1,19 @@ +@echo off +set /p testString=Your string (all same case please) : +call :isPalindrome result %testString: =% +if %result%==1 echo %testString% is a palindrome +if %result%==0 echo %testString% isn't a palindrome +pause +goto :eof + +:isPalindrome + set %1=0 + set string=%2 + if "%string:~2,1%"=="" ( + set %1=1 + goto :eof + ) + if "%string:~0,1%"=="%string:~-1%" ( + call :isPalindrome %1 %string:~1,-1% + ) + goto :eof diff --git a/Task/Palindrome-detection/Bracmat/palindrome-detection.bracmat b/Task/Palindrome-detection/Bracmat/palindrome-detection.bracmat new file mode 100644 index 0000000000..c0e16df611 --- /dev/null +++ b/Task/Palindrome-detection/Bracmat/palindrome-detection.bracmat @@ -0,0 +1,34 @@ +( ( palindrome + = a + . @(!arg:(%?a&utf$!a) ?arg !a) + & palindrome$!arg + | utf$!arg + ) +& ( desep + = x + . @(!arg:?x (" "|"-"|",") ?arg) + & !x desep$!arg + | !arg + ) +& "In girum imus nocte et consumimur igni" + "Я иду с мечем, судия" + "The quick brown fox" + "tregða, gón, reiði - er nóg að gert" + "人人為我,我為人人" + "가련하시다 사장집 아들딸들아 집장사 다시 하련가" + : ?candidates +& whl + ' ( !candidates:%?candidate ?candidates + & out + $ ( !candidate + is + ( palindrome$(low$(str$(desep$!candidate))) + & indeed + | not + ) + a + palindrome + ) + ) +& +); diff --git a/Task/Palindrome-detection/D/palindrome-detection-1.d b/Task/Palindrome-detection/D/palindrome-detection-1.d index 88c120a307..693165ad00 100644 --- a/Task/Palindrome-detection/D/palindrome-detection-1.d +++ b/Task/Palindrome-detection/D/palindrome-detection-1.d @@ -2,13 +2,13 @@ import std.traits, std.algorithm; bool isPalindrome1(C)(in C[] s) pure /*nothrow*/ if (isSomeChar!C) { - auto s2 = s.dup; // not nothrow - s2.reverse(); // works on Unicode too, not nothrow + auto s2 = s.dup; + s2.reverse(); // works on Unicode too, not nothrow. return s == s2; } void main() { - alias isPalindrome1 pali; + alias pali = isPalindrome1; assert(pali("")); assert(pali("z")); assert(pali("aha")); diff --git a/Task/Palindrome-detection/Eiffel/palindrome-detection.e b/Task/Palindrome-detection/Eiffel/palindrome-detection.e new file mode 100644 index 0000000000..71de113e29 --- /dev/null +++ b/Task/Palindrome-detection/Eiffel/palindrome-detection.e @@ -0,0 +1,18 @@ + is_palindrome (a_string: STRING): BOOLEAN + -- Is `a_string' a palindrome? + require + string_attached: a_string /= Void + local + l_index, l_count: INTEGER + do + from + Result := True + l_index := 1 + l_count := a_string.count + until + l_index >= l_count - l_index + 1 or not Result + loop + Result := (Result and a_string [l_index] = a_string [l_count - l_index + 1]) + l_index := l_index + 1 + end + end diff --git a/Task/Palindrome-detection/Elixir/palindrome-detection.elixir b/Task/Palindrome-detection/Elixir/palindrome-detection.elixir new file mode 100644 index 0000000000..d9c42449cf --- /dev/null +++ b/Task/Palindrome-detection/Elixir/palindrome-detection.elixir @@ -0,0 +1,3 @@ +defmodule PalindromeDetection do + def is_palindrome(str), do: str == String.reverse(str) +end diff --git a/Task/Palindrome-detection/FBSL/palindrome-detection.fbsl b/Task/Palindrome-detection/FBSL/palindrome-detection.fbsl new file mode 100644 index 0000000000..e06e6b794e --- /dev/null +++ b/Task/Palindrome-detection/FBSL/palindrome-detection.fbsl @@ -0,0 +1,27 @@ +#APPTYPE CONSOLE + +FUNCTION stripNonAlpha(BYVAL s AS STRING) AS STRING + DIM sTemp AS STRING = "" + DIM c AS STRING + FOR DIM i = 1 TO LEN(s) + c = MID(s, i, 1) + IF INSTR("ABCDEFGHIJKLMNOPQRSTUVWXYZ", c, 0, 1) THEN + sTemp = stemp & c + END IF + NEXT + RETURN sTemp +END FUNCTION + +FUNCTION IsPalindrome(BYVAL s AS STRING) AS INTEGER + FOR DIM i = 1 TO STRLEN(s) \ 2 ' only check half of the string, as scanning from both ends + IF s{i} <> s{STRLEN - (i - 1)} THEN RETURN FALSE 'comparison is not case sensitive + NEXT + + RETURN TRUE +END FUNCTION + +PRINT IsPalindrome(stripNonAlpha("A Toyota")) +PRINT IsPalindrome(stripNonAlpha("Madam, I'm Adam")) +PRINT IsPalindrome(stripNonAlpha("the rain in Spain falls mainly on the rooftops")) + +PAUSE diff --git a/Task/Palindrome-detection/Frink/palindrome-detection.frink b/Task/Palindrome-detection/Frink/palindrome-detection-1.frink similarity index 100% rename from Task/Palindrome-detection/Frink/palindrome-detection.frink rename to Task/Palindrome-detection/Frink/palindrome-detection-1.frink diff --git a/Task/Palindrome-detection/Frink/palindrome-detection-2.frink b/Task/Palindrome-detection/Frink/palindrome-detection-2.frink new file mode 100644 index 0000000000..d52ffe5a89 --- /dev/null +++ b/Task/Palindrome-detection/Frink/palindrome-detection-2.frink @@ -0,0 +1 @@ +isPalindrome["x\u{1f638}x"] diff --git a/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js b/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js index 2333520a1c..6cff555cd5 100644 --- a/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js +++ b/Task/Palindrome-detection/JavaScript/palindrome-detection-1.js @@ -1,5 +1,9 @@ -String.prototype.reverse = function(){ return this.split("").reverse().join(""); } +function reverseString(str){ + return str.split("").reverse().join(""); +} -function palindrome(str) { return str == str.reverse(); } +function isPalindrome(str) { + return str == reverseString(str); +} -alert(palindrome("ingirumimusnocteetconsumimurigni")); +alert(isPalindrome("ingirumimusnocteetconsumimurigni")); diff --git a/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js b/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js index 36c29a353d..dbc200473b 100644 --- a/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js +++ b/Task/Palindrome-detection/JavaScript/palindrome-detection-2.js @@ -1,15 +1,17 @@ -String.prototype.reverse = function () { - return this.split('').reverse().join(''); +function reverseStr(s) { + var i, o = ''; + for (i = s.length - 1; i >= 0; o += s[i--]); + return o; }; -String.prototype.isPalindrome = function () { - var s = this.toLowerCase().replace(/[^a-z]/g, ''); - return (s.reverse() === s); +function isPalindrome(str) { + var s = str.toLowerCase().replace(/[^a-z]/g, ''); + return (reverseStr(s) === s); }; -('A man, a plan, a canoe, pasta, heros, rajahs, ' + -'a coloratura, maps, snipe, percale, macaroni, ' + -'a gag, a banana bag, a tan, a tag, ' + -'a banana bag again (or a camel), a crepe, pins, ' + -'Spam, a rut, a Rolo, cash, a jar, sore hats, ' + -'a peon, a canal – Panama!').isPalindrome(); +isPalindrome('A man, a plan, a canoe, pasta, heros, rajahs, ' + + 'a coloratura, maps, snipe, percale, macaroni, ' + + 'a gag, a banana bag, a tan, a tag, ' + + 'a banana bag again (or a camel), a crepe, pins, ' + + 'Spam, a rut, a Rolo, cash, a jar, sore hats, ' + + 'a peon, a canal – Panama!'); diff --git a/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty new file mode 100644 index 0000000000..bca4d4cedd --- /dev/null +++ b/Task/Palindrome-detection/Liberty-BASIC/palindrome-detection.liberty @@ -0,0 +1,22 @@ +print isPalindrome("In girum imus nocte et consumimur igni") +print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "S")) +print isPalindrome(removePunctuation$("In girum imus nocte et consumimur igni", "SC")) + +function isPalindrome(string$) + isPalindrome = 1 + for i = 1 to int(len(string$)/2) + if mid$(string$, i, 1) <> mid$(string$, len(string$)-i+1, 1) then isPalindrome = 0 : exit function + next i +end function + +function removePunctuation$(string$, remove$) + 'P = remove puctuation. S = remove spaces C = remove case + If instr(upper$(remove$), "C") then string$ = lower$(string$) + If instr(upper$(remove$), "P") then removeCharacters$ = ",.!'()-&*?<>:;~[]{}" + If instr(upper$(remove$), "S") then removeCharacters$ = removeCharacters$;" " + + for i = 1 to len(string$) + if instr(removeCharacters$, mid$(string$, i, 1)) then string$ = left$(string$, i-1);right$(string$, len(string$)-i) : i = i - 1 + next i + removePunctuation$ = string$ +end function diff --git a/Task/Palindrome-detection/PL-I/palindrome-detection-1.pli b/Task/Palindrome-detection/PL-I/palindrome-detection-1.pli new file mode 100644 index 0000000000..fadccd82ec --- /dev/null +++ b/Task/Palindrome-detection/PL-I/palindrome-detection-1.pli @@ -0,0 +1 @@ +is_palindrome = (text = reverse(text)); diff --git a/Task/Palindrome-detection/PL-I/palindrome-detection.pli b/Task/Palindrome-detection/PL-I/palindrome-detection-2.pli similarity index 100% rename from Task/Palindrome-detection/PL-I/palindrome-detection.pli rename to Task/Palindrome-detection/PL-I/palindrome-detection-2.pli diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx index 662b2eea0a..fd37c2b663 100644 --- a/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx +++ b/Task/Palindrome-detection/REXX/palindrome-detection-1.rexx @@ -9,7 +9,6 @@ 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.*/ diff --git a/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx index 9e383faf17..7791016fa2 100644 --- a/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx +++ b/Task/Palindrome-detection/REXX/palindrome-detection-2.rexx @@ -9,7 +9,6 @@ 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 ··· */ diff --git a/Task/Palindrome-detection/Ruby/palindrome-detection-1.rb b/Task/Palindrome-detection/Ruby/palindrome-detection-1.rb index dd705131cd..c1ab43d456 100644 --- a/Task/Palindrome-detection/Ruby/palindrome-detection-1.rb +++ b/Task/Palindrome-detection/Ruby/palindrome-detection-1.rb @@ -1,3 +1,3 @@ -def is_palindrome(s) +def palindrome?(s) s == s.reverse end diff --git a/Task/Palindrome-detection/Ruby/palindrome-detection-2.rb b/Task/Palindrome-detection/Ruby/palindrome-detection-2.rb index 72aabd7b1a..2353258145 100644 --- a/Task/Palindrome-detection/Ruby/palindrome-detection-2.rb +++ b/Task/Palindrome-detection/Ruby/palindrome-detection-2.rb @@ -1,9 +1,9 @@ -def is_palindrome_r(s) +def r_palindrome?(s) if s.length <= 1 true elsif s[0] != s[-1] false else - is_palindrome_r(s[1..-2]) + r_palindrome?(s[1..-2]) end end diff --git a/Task/Palindrome-detection/Ruby/palindrome-detection-3.rb b/Task/Palindrome-detection/Ruby/palindrome-detection-3.rb index d8d8e368c8..b42a5654a3 100644 --- a/Task/Palindrome-detection/Ruby/palindrome-detection-3.rb +++ b/Task/Palindrome-detection/Ruby/palindrome-detection-3.rb @@ -1,9 +1,9 @@ str = "A man, a plan, a caret, [...2110 chars deleted...] a canal--Panama.".downcase.delete('^a-z') -puts is_palindrome(str) # => true -puts is_palindrome_r(str) # => true +puts palindrome?(str) # => true +puts r_palindrome?(str) # => true require 'benchmark' Benchmark.bm do |b| - b.report('iterative') {10000.times {is_palindrome(str)}} - b.report('recursive') {10000.times {is_palindrome_r(str)}} + b.report('iterative') {10000.times {palindrome?(str)}} + b.report('recursive') {10000.times {r_palindrome?(str)}} end diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-1.scala b/Task/Palindrome-detection/Scala/palindrome-detection-1.scala index 36634618f7..829dce68c3 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-1.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-1.scala @@ -1,4 +1 @@ - def isPalindrome(s: String): Boolean = { - if (s.size < 2) return false - s == s.reverse - } + def isPalindrome(s: String): Boolean = (s.size >= 2) && s == s.reverse diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-2.scala b/Task/Palindrome-detection/Scala/palindrome-detection-2.scala index 16a9f7fdcd..44ad7bc3c7 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-2.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-2.scala @@ -1,5 +1,5 @@ - def isPalindromeSentence(s: String): Boolean = { - if (s.size < 2) return false - val p = s.replaceAll("[^\\p{L}]", "").toLowerCase; - p == p.reverse - } + def isPalindromeSentence(s: String): Boolean = + (s.size >= 2) && { + 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 d000f7a66d..cc2d8a74b7 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-3.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-3.scala @@ -1,7 +1,9 @@ +import scala.annotation.tailrec + 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) + @tailrec + def inner(s: String): Boolean = + (s.length <= 1) || (s.head == s.last) && inner(s.tail.init) + + (s.size >= 2) && inner(s) } diff --git a/Task/Palindrome-detection/Scala/palindrome-detection-4.scala b/Task/Palindrome-detection/Scala/palindrome-detection-4.scala index 1d86007a97..b0b0431ceb 100644 --- a/Task/Palindrome-detection/Scala/palindrome-detection-4.scala +++ b/Task/Palindrome-detection/Scala/palindrome-detection-4.scala @@ -20,4 +20,4 @@ assert(isPalindromeRec("1 2 1")) assert(!isPalindromeRec("A man a plan a canal Panama.")) - println("Succesfully completed without errors.") + println("Successfully completed without errors.") diff --git a/Task/Pangram-checker/00DESCRIPTION b/Task/Pangram-checker/00DESCRIPTION index 82cb2a4ce4..b2a0a6a302 100644 --- a/Task/Pangram-checker/00DESCRIPTION +++ b/Task/Pangram-checker/00DESCRIPTION @@ -1,3 +1,6 @@ -Write a function or method to check a sentence to see if it is a [[wp:Pangram|pangram]] or not and show its use. +{{omit from|Lilypond}} +Write a function or method to check a sentence +to see if it is a [[wp:Pangram|pangram]] or not and show its use. -A pangram is a sentence that contains all the letters of the English alphabet at least once, for example: ''The quick brown fox jumps over the lazy dog''. +A pangram is a sentence that contains all the letters of the English alphabet +at least once, for example: ''The quick brown fox jumps over the lazy dog''. diff --git a/Task/Pangram-checker/00META.yaml b/Task/Pangram-checker/00META.yaml new file mode 100644 index 0000000000..12b5b405fb --- /dev/null +++ b/Task/Pangram-checker/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- String manipulation diff --git a/Task/Pangram-checker/AWK/pangram-checker.awk b/Task/Pangram-checker/AWK/pangram-checker-1.awk similarity index 69% rename from Task/Pangram-checker/AWK/pangram-checker.awk rename to Task/Pangram-checker/AWK/pangram-checker-1.awk index 68722c7737..005ee504cf 100644 --- a/Task/Pangram-checker/AWK/pangram-checker.awk +++ b/Task/Pangram-checker/AWK/pangram-checker-1.awk @@ -1,6 +1,6 @@ #!/usr/bin/awk -f BEGIN { - convert="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + allChars="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; print isPangram("The quick brown fox jumps over the lazy dog."); print isPangram("The quick brown fo."); } @@ -10,8 +10,8 @@ function isPangram(string) { for (k=1; k= 'a' && c <= 'z') bitset |= (1u << (c - 'a')); else if (c >= 'A' && c <= 'Z') @@ -12,8 +12,8 @@ bool isPangram(in string text) pure nothrow { } void main() { - assert(isPangram("the quick brown fox jumps over the lazy dog")); - assert(!isPangram("ABCDEFGHIJKLMNOPQSTUVWXYZ")); - assert(!isPangram("ABCDEFGHIJKL.NOPQRSTUVWXYZ")); - assert(isPangram("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ")); + assert("the quick brown fox jumps over the lazy dog".isPangram); + assert(!"ABCDEFGHIJKLMNOPQSTUVWXYZ".isPangram); + assert(!"ABCDEFGHIJKL.NOPQRSTUVWXYZ".isPangram); + assert("ABC.D.E.FGHI*J/KL-M+NO*PQ R\nSTUVWXYZ".isPangram); } diff --git a/Task/Parallel-calculations/00DESCRIPTION b/Task/Parallel-calculations/00DESCRIPTION index 7f2affa406..9bf86343c8 100644 --- a/Task/Parallel-calculations/00DESCRIPTION +++ b/Task/Parallel-calculations/00DESCRIPTION @@ -1,18 +1,22 @@ -Many programming languages allow you to specify computations to be run in -parallel. While [[Concurrent computing]] is focused on concurrency, the purpose -of this task is to distribute time-consuming calculations on as many CPUs as -possible. +Many programming languages allow you to specify computations to be run in parallel. +While [[Concurrent computing]] is focused on concurrency, +the purpose of this task is to distribute time-consuming calculations +on as many CPUs as possible. -Assume we have a collection of numbers, and want to find the one with the -largest minimal prime factor (that is, the one that contains relatively large -factors). To speed up the search, the factorization should be done in parallel -using separate threads or processes, to take advantage of multi-core CPUs. +Assume we have a collection of numbers, and want to find the one +with the largest minimal prime factor +(that is, the one that contains relatively large factors). +To speed up the search, the factorization should be done +in parallel using separate threads or processes, +to take advantage of multi-core CPUs. -Show how this can be formulated in your language. Parallelize the factorization -of those numbers, then search the returned list of numbers and factors for the -largest minimal factor, and return that number and its prime factors. +Show how this can be formulated in your language. +Parallelize the factorization of those numbers, +then search the returned list of numbers and factors +for the largest minimal factor, +and return that number and its prime factors. -For the prime number decomposition you may use the solution of the -[[Prime decomposition]] task. +For the prime number decomposition +you may use the solution of the [[Prime decomposition]] task. {{omit from|J}} diff --git a/Task/Parallel-calculations/Factor/parallel-calculations-1.factor b/Task/Parallel-calculations/Factor/parallel-calculations-1.factor new file mode 100644 index 0000000000..7c36538b9f --- /dev/null +++ b/Task/Parallel-calculations/Factor/parallel-calculations-1.factor @@ -0,0 +1,18 @@ +USING: io kernel fry locals sequences arrays math.primes.factors math.parser channels threads prettyprint ; +IN: + +:: map-parallel ( seq quot -- newseq ) + :> ch + seq [ '[ _ quot call ch to ] "factors" spawn ] { } map-as + dup length [ ch from ] replicate nip ; + +{ 576460752303423487 576460752303423487 + 576460752303423487 112272537195293 + 115284584522153 115280098190773 + 115797840077099 112582718962171 + 112272537095293 1099726829285419 } +dup [ factors ] map-parallel +dup [ infimum ] map dup supremum +swap index swap dupd nth -rot swap nth +"Number with largest min. factor is " swap number>string append +", with factors: " append write . diff --git a/Task/Parallel-calculations/Factor/parallel-calculations-2.factor b/Task/Parallel-calculations/Factor/parallel-calculations-2.factor new file mode 100644 index 0000000000..334a27498b --- /dev/null +++ b/Task/Parallel-calculations/Factor/parallel-calculations-2.factor @@ -0,0 +1,7 @@ +USING: kernel io prettyprint sequences arrays math.primes.factors math.parser concurrency.combinators ; +{ 576460752303423487 576460752303423487 576460752303423487 112272537195293 + 115284584522153 115280098190773 115797840077099 112582718962171 } +dup [ factors ] parallel-map dup [ infimum ] map dup supremum +swap index swap dupd nth -rot swap nth +"Number with largest min. factor is " swap number>string append +", with factors: " append write . diff --git a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs index eaea3b3346..42b741402f 100644 --- a/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs +++ b/Task/Parallel-calculations/Haskell/parallel-calculations-1.hs @@ -1,4 +1,4 @@ -mport Control.Parallel.Strategies +import Control.Parallel.Strategies import Control.DeepSeq import Data.List import Data.Function diff --git a/Task/Parallel-calculations/Java/parallel-calculations.java b/Task/Parallel-calculations/Java/parallel-calculations.java new file mode 100644 index 0000000000..d3f328e705 --- /dev/null +++ b/Task/Parallel-calculations/Java/parallel-calculations.java @@ -0,0 +1,40 @@ +import static java.lang.System.out; + +import static java.util.Arrays.stream; +import static java.util.Comparator.comparing; + +public interface ParallelCalculations { + public static final long[] NUMBERS = { + 12757923, + 12878611, + 12878893, + 12757923, + 15808973, + 15780709, + 197622519 + }; + + public static void main(String... arguments) { + stream(NUMBERS) + .unordered() + .parallel() + .mapToObj(ParallelCalculations::minimalPrimeFactor) + .max(comparing(a -> a[0])) + .ifPresent(res -> out.printf( + "%d has the largest minimum prime factor: %d%n", + res[1], + res[0] + )) + ; + } + + public static long[] minimalPrimeFactor(long n) { + return iterate(2, i -> i + 1) + .filter(i -> n >= i * i) + .filter(i -> n % i == 0) + .mapToObj(i -> new long[]{i, n}) + .findFirst() + .orElseGet(() -> new long[]{n, n}) + ; + } +} diff --git a/Task/Parallel-calculations/Python/parallel-calculations.py b/Task/Parallel-calculations/Python/parallel-calculations-1.py similarity index 86% rename from Task/Parallel-calculations/Python/parallel-calculations.py rename to Task/Parallel-calculations/Python/parallel-calculations-1.py index f55878547a..239e662e5b 100644 --- a/Task/Parallel-calculations/Python/parallel-calculations.py +++ b/Task/Parallel-calculations/Python/parallel-calculations-1.py @@ -35,11 +35,11 @@ def prime_factors_of_number_with_lowest_prime_factor(NUMBERS): def main(): - print( 'For these numbers:\n ' + '\n '.join(str(p) for p in NUMBERS) ) + print('For these numbers:') + print('\n '.join(str(p) for p in NUMBERS)) number, all_factors = prime_factors_of_number_with_lowest_prime_factor(NUMBERS) - print(' The one with the largest minimum prime factor is %i:' % number) - print(' All its prime factors in order are: %s' % all_factors) - + print(' The one with the largest minimum prime factor is {}:'.format(number)) + print(' All its prime factors in order are: {}'.format(all_factors)) if __name__ == '__main__': main() diff --git a/Task/Parallel-calculations/Python/parallel-calculations-2.py b/Task/Parallel-calculations/Python/parallel-calculations-2.py new file mode 100644 index 0000000000..e036c8bce2 --- /dev/null +++ b/Task/Parallel-calculations/Python/parallel-calculations-2.py @@ -0,0 +1,46 @@ +import multiprocessing + +# ========== #Python3 - concurrent +from math import floor, sqrt + +numbers = [ + 112272537195293, + 112582718962171, + 112272537095293, + 115280098190773, + 115797840077099, + 1099726829285419] +# numbers = [33, 44, 55, 275] + +def lowest_factor(n, _start=3): + if n % 2 == 0: + return 2 + search_max = int(floor(sqrt(n))) + 1 + for i in range(_start, search_max, 2): + if n % i == 0: + return i + return n + +def prime_factors(n, lowest): + pf = [] + while n > 1: + pf.append(lowest) + n //= lowest + lowest = lowest_factor(n, max(lowest, 3)) + return pf +# ========== #Python3 - concurrent + +def prime_factors_of_number_with_lowest_prime_factor(numbers): + pool = multiprocessing.Pool(processes=5) + factors = pool.map(lowest_factor,numbers) + + low_factor,number = max((l,f) for l,f in zip(factors,numbers)) + all_factors = prime_factors(number,low_factor) + return number,all_factors + +if __name__ == '__main__': + print('For these numbers:') + print('\n '.join(str(p) for p in numbers)) + number, all_factors = prime_factors_of_number_with_lowest_prime_factor(numbers) + print(' The one with the largest minimum prime factor is {}:'.format(number)) + print(' All its prime factors in order are: {}'.format(all_factors)) diff --git a/Task/Parametric-polymorphism/C++/parametric-polymorphism-2.cpp b/Task/Parametric-polymorphism/C++/parametric-polymorphism-2.cpp index 29e2f031e9..2fd6f03cd6 100644 --- a/Task/Parametric-polymorphism/C++/parametric-polymorphism-2.cpp +++ b/Task/Parametric-polymorphism/C++/parametric-polymorphism-2.cpp @@ -2,6 +2,8 @@ template void tree::replace_all (T new_value) { value = new_value; - left->replace_all (new_value); - right->replace_all (new_value); + if (left != NULL) + left->replace_all (new_value); + if (right != NULL) + right->replace_all (new_value); } diff --git a/Task/Parametric-polymorphism/Groovy/parametric-polymorphism.groovy b/Task/Parametric-polymorphism/Groovy/parametric-polymorphism.groovy new file mode 100644 index 0000000000..b27d76dccb --- /dev/null +++ b/Task/Parametric-polymorphism/Groovy/parametric-polymorphism.groovy @@ -0,0 +1,17 @@ +class Tree { + T value + Tree left + Tree right + + Tree(T value = null, Tree left = null, Tree right = null) { + this.value = value + this.left = left + this.right = right + } + + void replaceAll(T value) { + this.value = value + left?.replaceAll(value) + right?.replaceAll(value) + } +} diff --git a/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust b/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust new file mode 100644 index 0000000000..c0979ba65c --- /dev/null +++ b/Task/Parametric-polymorphism/Rust/parametric-polymorphism.rust @@ -0,0 +1,42 @@ +struct TreeNode { + value: T, + left: Option>>, + right: Option>>, +} + +impl TreeNode { + fn my_map(&self, f: |t: &T| -> U) -> TreeNode { + TreeNode{value: f(&self.value), + left: + match self.left { + None => None, + Some(ref n) => Some(box() n.my_map(|n| f(n))), + }, + right: + match self.right { + None => None, + Some(ref n) => Some(box() n.my_map(|n| f(n))), + },} + } +} + +fn main() { + let root = + TreeNode{value: 3i, + left: + Some(box() TreeNode{value: 55i, + left: None, + right: None,}), + right: + Some(box() TreeNode{value: 234i, + left: + Some(box() TreeNode{value: 0i, + left: None, + right: + None,}), + right: None,}),}; + root.my_map(|x| { println!("{}" , x)}); + println!("---------------"); + let new_root = root.my_map(|x| *x as f64 * 333.333f64); + new_root.my_map(|x| { println!("{}" , x) }); +} diff --git a/Task/Parametrized-SQL-statement/00DESCRIPTION b/Task/Parametrized-SQL-statement/00DESCRIPTION index a9bc8ac98b..68ac16352d 100644 --- a/Task/Parametrized-SQL-statement/00DESCRIPTION +++ b/Task/Parametrized-SQL-statement/00DESCRIPTION @@ -1,7 +1,8 @@ -Parameterized SQL statements are an easy way to avoid [[wp:SQL injection|SQL injection]] attacks. SQL drivers and libraries will automatically "sanitize" input to parameterized SQL statements to avoid these catastrophic database attacks. +Parameterized SQL statements are an easy way to avoid [[wp:SQL injection|SQL injection]] attacks. SQL drivers and libraries will automatically "sanitize" input to parameterized SQL statements to avoid these catastrophic database attacks. Second, parameterized SQL performs better. A lot better. Using a SQL update statement like this one (spacing is optional): UPDATE players SET name = 'Smith, Steve', score = 42, active = true - WHERE jerseyNum = 99 -show how to make a parameterized SQL statement, set the parameters to the values given above, and execute the statement. + WHERE jerseyNum = 99show how to make a parameterized SQL statement, set the parameters to the values given above, and execute the statement. + +
Non-parameterized SQL is the GoTo statement of database programming. Don't do it, and make sure your coworkers don't either.
diff --git a/Task/Parametrized-SQL-statement/Go/parametrized-sql-statement.go b/Task/Parametrized-SQL-statement/Go/parametrized-sql-statement.go new file mode 100644 index 0000000000..a1f62667f5 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Go/parametrized-sql-statement.go @@ -0,0 +1,33 @@ +package main + +import ( + "database/sql" + "fmt" + + _ "github.com/mattn/go-sqlite3" +) + +func main() { + db, _ := sql.Open("sqlite3", "rc.db") + defer db.Close() + db.Exec(`create table players (name, score, active, jerseyNum)`) + db.Exec(`insert into players values ("",0,0,"99")`) + db.Exec(`insert into players values ("",0,0,"100")`) + + // Parameterized + db.Exec(`update players set name=?, score=?, active=? where jerseyNum=?`, + "Smith, Steve", 42, true, "99") + + rows, _ := db.Query("select * from players") + var ( + name string + score int + active bool + jerseyNum string + ) + for rows.Next() { + rows.Scan(&name, &score, &active, &jerseyNum) + fmt.Printf("%3s %12s %3d %t\n", jerseyNum, name, score, active) + } + rows.Close() +} diff --git a/Task/Parametrized-SQL-statement/Seed7/parametrized-sql-statement.seed7 b/Task/Parametrized-SQL-statement/Seed7/parametrized-sql-statement.seed7 new file mode 100644 index 0000000000..6bf3fb0482 --- /dev/null +++ b/Task/Parametrized-SQL-statement/Seed7/parametrized-sql-statement.seed7 @@ -0,0 +1,32 @@ +$ include "seed7_05.s7i"; + include "sql_base.s7i"; + +const proc: main is func + local + var database: testDb is database.value; + var sqlStatement: statement is sqlStatement.value; + var string: name is "Smith, Steve"; + begin + testDb := openDatabase(DB_SQLITE, "test", "test", "test"); + execute(testDb, "create table players (name CHAR(32), score INTEGER, active CHAR, jerseyNum INTEGER)"); + execute(testDb, "insert into players values ('Jones, Bob',0,0,99)"); + execute(testDb, "insert into players values ('Jesten, Jim',0,0,100)"); + execute(testDb, "insert into players values ('Jello, Frank',0,0,101)"); + statement := prepare(testDb, "update players set name = ?, score = ?, active = ? \ + \where jerseyNum = ?"); + bind(statement, 1, name); + bind(statement, 2, 42); + bind(statement, 3, TRUE); + bind(statement, 4, 99); + execute(statement); + statement := prepare(testDb, "select * from players"); + execute(statement); + while fetch(statement) do + writeln(column(statement, 1, string) <& " " <& + column(statement, 2, integer) <& " " <& + column(statement, 3, boolean) <& " " <& + column(statement, 4, integer)); + end while; + execute(testDb, "drop table players"); + close(testDb); + end func; diff --git a/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg b/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg new file mode 100644 index 0000000000..099cffc8ab --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/ALGOL-68/parsing-rpn-calculator-algorithm.alg @@ -0,0 +1,143 @@ +# RPN Expression evaluator - handles numbers and + - * / ^ # +# the right-hand operand for ^ is converted to an integer # + +# expression terminator # +CHAR end of expression character = REPR 12; + +# evaluates the specified rpn expression # +PROC evaluate = ( STRING rpn expression )VOID: +BEGIN + + [ 256 ]REAL stack; + INT stack pos := 0; + + # pops an element off the stack # + PROC pop = REAL: + BEGIN + stack pos -:= 1; + stack[ stack pos + 1 ] + END; # pop # + + INT rpn pos := LWB rpn expression; + + # evaluate tokens from the expression until we get the end of expression # + WHILE + + # get the next token from the string # + + STRING token type; + REAL value; + + # skip spaces # + WHILE rpn expression[ rpn pos ] = " " + DO + rpn pos +:= 1 + OD; + + # handle the token # + IF rpn expression[ rpn pos ] = end of expression character + THEN + # no more tokens # + FALSE + + ELSE + # have a token # + + IF rpn expression[ rpn pos ] >= "0" + AND rpn expression[ rpn pos ] <= "9" + THEN + # have a number # + + # find where the nmumber is in the expression # + INT number start = rpn pos; + WHILE ( rpn expression[ rpn pos ] >= "0" + AND rpn expression[ rpn pos ] <= "9" + ) + OR rpn expression[ rpn pos ] = "." + DO + rpn pos +:= 1 + OD; + + # read the number from the expression # + FILE number f; + associate( number f + , LOC STRING := rpn expression[ number start : rpn pos - 1 ] + ); + get( number f, ( value ) ); + close( number f ); + + token type := "number" + + ELSE + # must be an operator # + CHAR op = rpn expression[ rpn pos ]; + rpn pos +:= 1; + + REAL arg1 := pop; + REAL arg2 := pop; + token type := op; + + value := IF op = "+" + THEN + # add the top two stack elements # + arg1 + arg2 + ELIF op = "-" + THEN + # subtract the top two stack elements # + arg2 - arg1 + ELIF op = "*" + THEN + # multiply the top two stack elements # + arg2 * arg1 + ELIF op = "/" + THEN + # divide the top two stack elements # + arg2 / arg1 + ELIF op = "^" + THEN + # raise op2 to the power of op1 # + arg2 ^ ENTIER arg1 + ELSE + # unknown operator # + print( ( "Unknown operator: """ + op + """", newline ) ); + 0 + FI + + FI; + + TRUE + FI + DO + # push the new value on the stack and show the new stack # + + stack[ stack pos +:= 1 ] := value; + + print( ( ( token type + " " )[ 1 : 8 ] ) ); + FOR element FROM LWB stack TO stack pos + DO + print( ( " ", fixed( stack[ element ], 8, 4 ) ) ) + OD; + print( ( newline ) ) + + OD; + + print( ( "Result is: ", fixed( stack[ stack pos ], 12, 8 ), newline ) ) + +END; # evaluate # + +main: ( + + # get the RPN expresson from the user # + + STRING rpn expression; + + print( ( "Enter expression: " ) ); + read( ( rpn expression, newline ) ); + + # add a space to terminate the final token and an expression terminator # + rpn expression +:= " " + end of expression character; + + # execute the expression # + evaluate( rpn expression ) + +) diff --git a/Task/Parsing-RPN-calculator-algorithm/Julia/parsing-rpn-calculator-algorithm.julia b/Task/Parsing-RPN-calculator-algorithm/Julia/parsing-rpn-calculator-algorithm.julia new file mode 100644 index 0000000000..ad9e88966c --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/Julia/parsing-rpn-calculator-algorithm.julia @@ -0,0 +1,16 @@ +function rpn(s) + stack = Any[] + for op in map(eval, map(parse, split(s))) + if isa(op, Function) + arg2 = pop!(stack) + arg1 = pop!(stack) + push!(stack, op(arg1, arg2)) + else + push!(stack, op) + end + println("$op: ", join(stack, ", ")) + end + length(stack) != 1 && error("invalid RPN expression $s") + return stack[1] +end +rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +") diff --git a/Task/Parsing-RPN-calculator-algorithm/VBA/parsing-rpn-calculator-algorithm.vba b/Task/Parsing-RPN-calculator-algorithm/VBA/parsing-rpn-calculator-algorithm.vba new file mode 100644 index 0000000000..2e73890a3f --- /dev/null +++ b/Task/Parsing-RPN-calculator-algorithm/VBA/parsing-rpn-calculator-algorithm.vba @@ -0,0 +1,86 @@ +Global stack$ + +Function RPN(expr$) +Debug.Print "Expression:" +Debug.Print expr$ +Debug.Print "Input", "Operation", "Stack after" + +stack$ = "" +token$ = "#" +i = 1 +token$ = Split(expr$)(i - 1) 'split is base 0 +token2$ = " " + token$ + " " + +Do + Debug.Print "Token "; i; ": "; token$, + 'operation + If InStr("+-*/^", token$) <> 0 Then + Debug.Print "operate", + op2$ = pop$() + op1$ = pop$() + If op1$ = "" Then + Debug.Print "Error: stack empty for "; i; "-th token: "; token$ + End + End If + + op1 = Val(op1$) + op2 = Val(op2$) + + Select Case token$ + Case "+" + res = CDbl(op1) + CDbl(op2) + Case "-" + res = CDbl(op1) - CDbl(op2) + Case "*" + res = CDbl(op1) * CDbl(op2) + Case "/" + res = CDbl(op1) / CDbl(op2) + Case "^" + res = CDbl(op1) ^ CDbl(op2) + End Select + + Call push2(str$(res)) + 'default:number + Else + Debug.Print "push", + Call push2(token$) + End If + Debug.Print "Stack: "; reverse$(stack$) + i = i + 1 + If i > Len(Join(Split(expr, " "), "")) Then + token$ = "" + Else + token$ = Split(expr$)(i - 1) 'base 0 + token2$ = " " + token$ + " " + End If +Loop Until token$ = "" + +Debug.Print +Debug.Print "Result:"; pop$() +'extra$ = pop$() +If stack <> "" Then + Debug.Print "Error: extra things on a stack: "; stack$ +End If +End +End Function + +'--------------------------------------- +Function reverse$(s$) + reverse$ = "" + token$ = "#" + While token$ <> "" + i = i + 1 + token$ = Split(s$, "|")(i - 1) 'split is base 0 + reverse$ = token$ & " " & reverse$ + Wend +End Function +'--------------------------------------- +Sub push2(s$) + stack$ = s$ + "|" + stack$ 'stack +End Sub + +Function pop$() + 'it does return empty on empty stack + pop$ = Split(stack$, "|")(0) + stack$ = Mid$(stack$, InStr(stack$, "|") + 1) +End Function 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 index 37591ad73d..7c84bde096 100644 --- 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 @@ -1,10 +1,10 @@ import std.stdio, std.string, std.array, std.algorithm; -void rpmToInfix(in string str) { +void rpmToInfix(in string str) @safe { static struct Exp { int p; string e; } immutable P = (in Exp pair, in int prec) pure => pair.p < prec ? format("( %s )", pair.e) : pair.e; - immutable F = (in string[] s...) pure nothrow => s.join(" "); + immutable F = (in string[] s...) pure nothrow => s.join(' '); writefln("=================\n%s", str); Exp[] stack; diff --git a/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java new file mode 100644 index 0000000000..52fcd3111d --- /dev/null +++ b/Task/Parsing-RPN-to-infix-conversion/Java/parsing-rpn-to-infix-conversion.java @@ -0,0 +1,62 @@ +public class PostfixToInfix { + + public static void main(String[] args) { + for (String e : new String[]{"3 4 2 * 1 5 - 2 3 ^ ^ / +", + "1 2 + 3 4 + ^ 5 6 + ^"}) { + System.out.printf("Postfix : %s%n", e); + System.out.printf("Infix : %s%n", postfixToInfix(e)); + System.out.println(); + } + } + + static String postfixToInfix(final String postfix) { + + class Expression { + final static String ops = "-+/*^"; + + String op, ex; + int prec = 3; + + Expression(String e) { + ex = e; + } + + Expression(String e1, String e2, String o) { + ex = String.format("%s %s %s", e1, o, e2); + op = o; + prec = ops.indexOf(o) / 2; + } + + @Override + public String toString() { + return ex; + } + } + + Stack expr = new Stack<>(); + + for (String token : postfix.split("\\s")) { + char c = token.charAt(0); + int idx = Expression.ops.indexOf(c); + if (idx != -1 && token.length() == 1) { + + Expression r = expr.pop(); + Expression l = expr.pop(); + + int opPrec = idx / 2; + + if (l.prec < opPrec || (l.prec == opPrec && c == '^')) + l.ex = '(' + l.ex + ')'; + + if (r.prec < opPrec || (r.prec == opPrec && c != '^')) + r.ex = '(' + r.ex + ')'; + + expr.push(new Expression(l.ex, r.ex, token)); + } else { + expr.push(new Expression(token)); + } + System.out.printf("%s -> %s%n", token, expr); + } + return expr.peek().ex; + } +} diff --git a/Task/Parsing-RPN-to-infix-conversion/REXX/parsing-rpn-to-infix-conversion.rexx b/Task/Parsing-RPN-to-infix-conversion/REXX/parsing-rpn-to-infix-conversion.rexx index 1dfa62eacd..a8be90e2d6 100644 --- a/Task/Parsing-RPN-to-infix-conversion/REXX/parsing-rpn-to-infix-conversion.rexx +++ b/Task/Parsing-RPN-to-infix-conversion/REXX/parsing-rpn-to-infix-conversion.rexx @@ -9,28 +9,29 @@ say "infix: " toInfix( "1 2 + 3 4 + ^ 5 6 + ^" ) /* [↓] Deutsch.*/ say "infix: " toInfix( "Mond Sterne Schlamm + * Feur Suppe * ^" ) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────────────────────────────────────────*/ -pop: pop=#; #=#-1; return @.pop -push: #=#+1; @.#=arg(1); return +pop: pop=#; #=#-1; return @.pop +push: #=#+1; @.#=arg(1); return /*──────────────────────────────────────────────────────────────────────*/ -stack2str: $=; do j=1 for #; _ = @.j; y=left(_,1) - if pos(' ',_)==0 then _ = '{'strip(substr(_,2))"}" - else _ = substr(_,2) - $=$ '{'strip(y _)"}" +stack2str: $=; do j=1 for #; _ = @.j; y=left(_,1) + if pos(' ', _)==0 then _ = '{'strip(substr(_, 2))"}" + else _ = substr(_, 2) + $=$ '{'strip(y _)"}" end /*j*/ return space($) /*──────────────────────────────────────────────────────────────────────*/ -toInfix: parse arg rpn; say copies('─',80-1); say 'RPN: ' space(rpn) +toInfix: parse arg rpn; say copies('─',80-1); say 'RPN: ' space(rpn) - do N=1 to words(RPN); ?=word(RPN,N) /*process each of the RPN tokens.*/ - if pos(?,oS)==0 then call push '¥' ? /*when in doubt, add a Yen to it.*/ - else do; g=pop(); gp=left(g,1); g=substr(g,2) - h=pop(); hp=left(h,1); h=substr(h,2) - tp=substr(oP,pos(?,oS),1);ta=substr(oA,pos(?,oS),1) - if hp (reverse y ++ x, [], "")) $ last final - f (out,st,_) t | isOp t = + 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, + | t == "(" = (out, "(":st, t) + | t == ")" = (reverse (takeWhile (/="(") st) ++ out, tail $ dropWhile (/="(") st, t) - | True = (t:out, st, t) + | otherwise = (t:out, st, t) where testOp x = isOp x && (leftAssoc t && prec t == prec x || prec t < prec x) 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 index a0ccb8d491..08381d8565 100644 --- 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 @@ -1,6 +1,7 @@ {-# LANGUAGE LambdaCase #-} import Control.Applicative import Control.Lens +import Control.Monad import Control.Monad.Error import Control.Monad.State import System.Console.Readline @@ -60,13 +61,11 @@ 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 +--Run StateT 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 +toRPN xs = evalStateT process ([],[]) + where process = mapM_ processToken xs + >> get >>= \(a,b) -> (reverse a++) <$> (mapM toOut b) toOut :: StackElem -> RPNComp OutToken toOut (StOp o) = return $ OutOp o toOut Paren = throwError "Unmatched left parenthesis" diff --git a/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java new file mode 100644 index 0000000000..52ff0e667b --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/Java/parsing-shunting-yard-algorithm.java @@ -0,0 +1,46 @@ +import java.util.Stack; + +public class ShuntingYard { + + public static void main(String[] args) { + String infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; + System.out.printf("infix: %s%n", infix); + System.out.printf("postfix: %s%n", infixToPostfix(infix)); + } + + static String infixToPostfix(String infix) { + final String ops = "-+/*^"; + StringBuilder sb = new StringBuilder(); + Stack s = new Stack<>(); + + for (String token : infix.split("\\s")) { + char c = token.charAt(0); + int idx = ops.indexOf(c); + if (idx != -1 && token.length() == 1) { + if (s.isEmpty()) + s.push(idx); + else { + while (!s.isEmpty()) { + int prec2 = s.peek() / 2; + int prec1 = idx / 2; + if (prec2 > prec1 || (prec2 == prec1 && c != '^')) + sb.append(ops.charAt(s.pop())).append(' '); + else break; + } + s.push(idx); + } + } else if (c == '(') { + s.push(-2); + } else if (c == ')') { + while (s.peek() != -2) + sb.append(ops.charAt(s.pop())).append(' '); + s.pop(); + } else { + sb.append(token).append(' '); + } + } + while (!s.isEmpty()) + sb.append(ops.charAt(s.pop())).append(' '); + return sb.toString(); + } +} diff --git a/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js b/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js new file mode 100644 index 0000000000..70dab5c0c5 --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/JavaScript/parsing-shunting-yard-algorithm.js @@ -0,0 +1,71 @@ +function Stack() { + this.dataStore = []; + this.top = 0; + this.push = push; + this.pop = pop; + this.peek = peek; + this.length = length; +} + +function push(element) { + this.dataStore[this.top++] = element; +} + +function pop() { + return this.dataStore[--this.top]; +} + +function peek() { + return this.dataStore[this.top-1]; +} + +function length() { + return this.top; +} + +var infix = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"; +infix = infix.replace(/\s+/g, ''); // remove spaces, so infix[i]!=" " + +var s = new Stack(); +var ops = "-+/*^"; +var precedence = {"^":4, "*":3, "/":3, "+":2, "-":2}; +var associativity = {"^":"Right", "*":"Left", "/":"Left", "+":"Left", "-":"Left"}; +var token; +var postfix = ""; +var o1, o2; + +for (var i = 0; i < infix.length; i++) { + token = infix[i]; + if (token > "0" && token < "9") { // if token is operand (here limited to 0 <= x <= 9) + postfix += token + " "; + } + else if (ops.indexOf(token) != -1) { // if token is an operator + o1 = token; + o2 = s.peek(); + while (ops.indexOf(o2)!=-1 && ( // while operator token, o2, on top of the stack + // and o1 is left-associative and its precedence is less than or equal to that of o2 + (associativity[o1] == "Left" && (precedence[o1] <= precedence[o2]) ) || + // the algorithm on wikipedia says: or o1 precedence < o2 precedence, but I think it should be + // or o1 is right-associative and its precedence is less than that of o2 + (associativity[o1] == "Right" && (precedence[o1] < precedence[o2])) + )){ + postfix += o2 + " "; // add o2 to output queue + s.pop(); // pop o2 of the stack + o2 = s.peek(); // next round + } + s.push(o1); // push o1 onto the stack + } + else if (token == "(") { // if token is left parenthesis + s.push(token); // then push it onto the stack + } + else if (token == ")") { // if token is right parenthesis + while (s.peek() != "("){ // until token at top is ( + postfix += s.pop() + " "; + } + s.pop(); // pop (, but not onto the output queue + } +} +while (s.length()>0){ + postfix += s.pop() + " "; +} +print(postfix); diff --git a/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl b/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl index 2b67840cce..a6048b9159 100644 --- a/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl +++ b/Task/Parsing-Shunting-yard-algorithm/Perl/parsing-shunting-yard-algorithm.pl @@ -1,51 +1,49 @@ -use 5.010; -use strict; -use warnings; - my %prec = ( - '^' => 4, - '*' => 3, - '/' => 3, - '+' => 2, - '-' => 2, - '(' => 1); + '^' => 4, + '*' => 3, + '/' => 3, + '+' => 2, + '-' => 2, + '(' => 1 +); my %assoc = ( - '^' => 'right', - '*' => 'left', - '/' => 'left', - '+' => 'left', - '-' => 'left'); + '^' => 'right', + '*' => 'left', + '/' => 'left', + '+' => 'left', + '-' => 'left' +); sub shunting_yard { - my @inp = split ' ', $_[0]; - my @ops; - my @res; + my @inp = split ' ', $_[0]; + my @ops; + my @res; - my $report = sub { printf "%25s %-7s %10s %s\n", "@res", "@ops", $_[0], "@inp" }; - my $shift = sub { $report->( "shift @_"); push @ops, @_ }; - my $reduce = sub { $report->("reduce @_"); push @res, @_ }; + my $report = sub { printf "%25s %-7s %10s %s\n", "@res", "@ops", $_[0], "@inp" }; + my $shift = sub { $report->("shift @_"); push @ops, @_ }; + my $reduce = sub { $report->("reduce @_"); push @res, @_ }; - while( @inp ) { - given( shift @inp ) { - when ( /\d/ ) { $reduce->($_) } - when ( '(' ) { $shift->($_) } - when ( ')' ) { while( @ops and "(" ne (my $x = pop @ops) ) { $reduce->( $x ) } } - default { - my $newprec = $prec{$_}; - while( @ops ) { - my $oldprec = $prec{$ops[-1]}; - last if $newprec > $oldprec; - last if $newprec == $oldprec and $assoc{$_} eq 'right'; - $reduce->( pop @ops ); - } - $shift->( $_ ); - } - } - } + while (@inp) { + my $token = shift @inp; + if ( $token =~ /\d/ ) { $reduce->($token) } + elsif ( $token eq '(' ) { $shift->($token) } + elsif ( $token eq ')' ) { + while ( @ops and "(" ne ( my $x = pop @ops ) ) { $reduce->($x) } + } else { + my $newprec = $prec{$token}; + while (@ops) { + my $oldprec = $prec{ $ops[-1] }; + last if $newprec > $oldprec; + last if $newprec == $oldprec and $assoc{$token} eq 'right'; + $reduce->( pop @ops ); + } + $shift->($token); + } + } $reduce->( pop @ops ) while @ops; @res; } local $, = " "; -say shunting_yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3' ; +print shunting_yard '3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3'; diff --git a/Task/Parsing-Shunting-yard-algorithm/VBA/parsing-shunting-yard-algorithm.vba b/Task/Parsing-Shunting-yard-algorithm/VBA/parsing-shunting-yard-algorithm.vba new file mode 100644 index 0000000000..17bc606a9e --- /dev/null +++ b/Task/Parsing-Shunting-yard-algorithm/VBA/parsing-shunting-yard-algorithm.vba @@ -0,0 +1,110 @@ +Option Explicit +Option Base 1 + +Function ShuntingYard(strInfix As String) As String +Dim i As Long, j As Long, token As String, tokenArray() As String +Dim stack() As Variant, queue() As Variant, discard As String +Dim op1 As String, op2 As String + +Debug.Print strInfix + +' Get tokens +tokenArray = Split(strInfix) + +' Initialize array (removed later) +ReDim stack(1) +ReDim queue(1) + +' Loop over tokens +Do While 1 + i = i + 1 + If i - 1 > UBound(tokenArray) Then + Exit Do + Else + token = tokenArray(i - 1) 'i-1 due to Split returning a Base 0 + End If + If token = "" Then: Exit Do + + ' Print + Debug.Print i, token, Join(stack, ","), Join(queue, ",") + ' If-loop over tokens (either brackets, operators, or numbers) + If token = "(" Then + stack = push(token, stack) + ElseIf token = ")" Then + While Peek(stack) <> "(" + queue = push(pop(stack), queue) + Wend + discard = pop(stack) 'discard "(" + ElseIf isOperator(token) Then + op1 = token + Do While (isOperator(Peek(stack))) +' Debug.Print Peek(stack) + op2 = Peek(stack) + If op2 <> "^" And precedence(op1) = precedence(op2) Then + '"^" is the only right-associative operator + queue = push(pop(stack), queue) + ElseIf precedence(op1$) < precedence(op2$) Then + queue = push(pop(stack), queue) + Else + Exit Do + End If + Loop + stack = push(op1, stack) + Else 'number + 'actually, wrong operator could end up here, like say % + 'If the token is a number, then add it to the output queue. + queue = push(CStr(token), queue) + End If +Loop + +While stack(1) <> "" + If Peek(stack) = "(" Then Debug.Print "no matching ')'": End + queue = push(pop(stack), queue) +Wend + +' Print final output +ShuntingYard = Join(queue, " ") +Debug.Print "Output:" +Debug.Print ShuntingYard +End Function + +'------------------------------------------ +Function isOperator(op As String) As Boolean + isOperator = InStr("+-*/^", op) <> 0 And Len(op$) = 1 +End Function + +Function precedence(op As String) As Integer + If isOperator(op$) Then + precedence = 1 _ + - (InStr("+-*/^", op$) <> 0) _ + - (InStr("*/^", op$) <> 0) _ + - (InStr("^", op$) <> 0) + End If +End Function + +'------------------------------------------ +Function push(str, stack) As Variant +Dim out() As Variant, i As Long +If Not IsEmpty(stack(1)) Then + out = stack + ReDim Preserve out(1 To UBound(stack) + 1) + out(UBound(out)) = str +Else + ReDim out(1 To 1) + out(1) = str +End If +push = out +End Function + +Function pop(stack) +pop = stack(UBound(stack)) +If UBound(stack) > 1 Then + ReDim Preserve stack(1 To UBound(stack) - 1) +Else + stack(1) = "" +End If +End Function + +Function Peek(stack) + Peek = stack(UBound(stack)) +End Function diff --git a/Task/Partial-function-application/Bracmat/partial-function-application.bracmat b/Task/Partial-function-application/Bracmat/partial-function-application.bracmat new file mode 100644 index 0000000000..d16d671c67 --- /dev/null +++ b/Task/Partial-function-application/Bracmat/partial-function-application.bracmat @@ -0,0 +1,27 @@ +( ( fs + = + . '$!arg:?arg + & + ' ( first r + . :?r + & whl + ' ( !arg:%?first ?arg + & !r ($arg)$!first:?r + ) + & !r + ) + ) +& ( partial + = + . !arg:(?f.?g) + & /('(x./('(y.($x)$($y)))$!g))$!f + ) +& (f1=.2*!arg) +& (f2=.!arg^2) +& partial$(fs.f1):(=?fsf1) +& partial$(fs.f2):(=?fsf2) +& out$(fsf1$(0 1 2 3)) +& out$(fsf2$(0 1 2 3)) +& out$(fsf1$(2 4 6 8)) +& out$(fsf2$(2 4 6 8)) +); diff --git a/Task/Partial-function-application/Common-Lisp/partial-function-application.lisp b/Task/Partial-function-application/Common-Lisp/partial-function-application.lisp index 2a7119565d..36cb271547 100644 --- a/Task/Partial-function-application/Common-Lisp/partial-function-application.lisp +++ b/Task/Partial-function-application/Common-Lisp/partial-function-application.lisp @@ -1,12 +1,20 @@ -(defun fs (f s) (mapcar f s)) -(defun f1 (i) (* i 2)) -(defun f2 (i) (expt i 2)) +(defun fs (f s) + (mapcar f s)) +(defun f1 (i) + (* i 2)) +(defun f2 (i) + (expt i 2)) (defun partial (func &rest args1) - (lambda (&rest args2) (apply func (append args1 args2)))) -(defvar fsf1 (partial #'fs #'f1)) -(defvar fsf2 (partial #'fs #'f2)) + (lambda (&rest args2) + (apply func (append args1 args2)))) + +(setf (symbol-function 'fsf1) (partial #'fs #'f1)) +(setf (symbol-function 'fsf2) (partial #'fs #'f2)) (dolist (seq '((0 1 2 3) (2 4 6 8))) - (format t "~%seq: ~A~% fsf1 seq: ~A~% fsf2 seq: ~A" - seq (funcall fsf1 seq) (funcall fsf2 seq))) + (format t + "~%seq: ~A~% fsf1 seq: ~A~% fsf2 seq: ~A" + seq + (fsf1 seq) + (fsf2 seq))) diff --git a/Task/Partial-function-application/Go/partial-function-application.go b/Task/Partial-function-application/Go/partial-function-application.go new file mode 100644 index 0000000000..0020aebe17 --- /dev/null +++ b/Task/Partial-function-application/Go/partial-function-application.go @@ -0,0 +1,55 @@ +package main + +import "fmt" + +// Using a method bound to a function type: + +// fn is a simple function taking an integer and returning another. +type fn func(int) int + +// fs applies fn to each argument returning all results. +func (f fn) fs(s ...int) (r []int) { + for _, i := range s { + r = append(r, f(i)) + } + return r +} + +// Two simple functions for demonstration. +func f1(i int) int { return i * 2 } +func f2(i int) int { return i * i } + +// Another way: + +// addn returns a function that adds n to a sequence of numbers +func addn(n int) func(...int) []int { + return func(s ...int) []int { + var r []int + for _, i := range s { + r = append(r, n+i) + } + return r + } +} + +func main() { + // Turning a method into a function bound to it's reciever: + fsf1 := fn(f1).fs + fsf2 := fn(f2).fs + // Or using a function that returns a function: + fsf3 := addn(100) + + s := []int{0, 1, 2, 3} + fmt.Println("For s =", s) + fmt.Println(" fsf1:", fsf1(s...)) // Called with a slice + fmt.Println(" fsf2:", fsf2(0, 1, 2, 3)) // ... or with individual arguments + fmt.Println(" fsf3:", fsf3(0, 1, 2, 3)) + fmt.Println(" fsf2(fsf1):", fsf2(fsf1(s...)...)) + + s = []int{2, 4, 6, 8} + fmt.Println("For s =", s) + fmt.Println(" fsf1:", fsf1(2, 4, 6, 8)) + fmt.Println(" fsf2:", fsf2(s...)) + fmt.Println(" fsf3:", fsf3(s...)) + fmt.Println(" fsf3(fsf1):", fsf3(fsf1(s...)...)) +} diff --git a/Task/Partial-function-application/Lua/partial-function-application.lua b/Task/Partial-function-application/Lua/partial-function-application.lua new file mode 100644 index 0000000000..8ab0834f7f --- /dev/null +++ b/Task/Partial-function-application/Lua/partial-function-application.lua @@ -0,0 +1,30 @@ +function map(f, ...) + local t = {} + for k, v in ipairs(...) do + t[#t+1] = f(v) + end + return t +end + +function timestwo(n) + return n * 2 +end + +function squared(n) + return n ^ 2 +end + +function partial(f, ...) + local args = ... + return function(...) + return f(args, ...) + end +end + +timestwo_s = partial(map, timestwo) +squared_s = partial(map, squared) + +print(table.concat(timestwo_s{0, 1, 2, 3}, ', ')) +print(table.concat(squared_s{0, 1, 2, 3}, ', ')) +print(table.concat(timestwo_s{2, 4, 6, 8}, ', ')) +print(table.concat(squared_s{2, 4, 6, 8}, ', ')) diff --git a/Task/Partial-function-application/Scala/partial-function-application.scala b/Task/Partial-function-application/Scala/partial-function-application.scala index 9cbb2d66d6..92ad84cfaf 100644 --- a/Task/Partial-function-application/Scala/partial-function-application.scala +++ b/Task/Partial-function-application/Scala/partial-function-application.scala @@ -1,11 +1,10 @@ -def fs(f:Int=>Int, s:List[Int])=s map f -def f1(x:Int)=x*2 -def f2(x:Int)=x*x - -def fsf1=fs(f1,_:List[Int]) -def fsf2=fs(f2,_:List[Int]) +def fs[X](f:X=>X)(s:Seq[X]) = s map f +def f1(x:Int) = x * 2 +def f2(x:Int) = x * x -println(fsf1(List(0,1,2,3))) -println(fsf1(List(2,4,6,8))) -println(fsf2(List(0,1,2,3))) -println(fsf2(List(2,4,6,8))) +def fsf[X](f:X=>X) = fs(f) _ +val fsf1 = fsf(f1) // or without the fsf intermediary: val fsf1 = fs(f1) _ +val fsf2 = fsf(f2) // or without the fsf intermediary: val fsf2 = fs(f2) _ + +assert(fsf1(List(0,1,2,3)) == List(0,2,4,6)) +assert(fsf2(List(0,1,2,3)) == List(0,1,4,9)) diff --git a/Task/Pascals-triangle-Puzzle/00DESCRIPTION b/Task/Pascals-triangle-Puzzle/00DESCRIPTION index f139af2c12..e8ade29ece 100644 --- a/Task/Pascals-triangle-Puzzle/00DESCRIPTION +++ b/Task/Pascals-triangle-Puzzle/00DESCRIPTION @@ -7,6 +7,7 @@ This puzzle involves a [http://xunor.free.fr/en/riddles/auto/pyramidnb.php Pasca [ X][11][ Y][ 4][ Z]
Each brick of the pyramid is the sum of the two bricks situated below it.
-Of the three missing numbers at the base of the pyramid, the middle one is the sum of the other two (that is, Y = X + Z). +Of the three missing numbers at the base of the pyramid, +the middle one is the sum of the other two (that is, Y = X + Z). Write a program to find a solution to this puzzle. diff --git a/Task/Pascals-triangle-Puzzle/Curry/pascals-triangle-puzzle.curry b/Task/Pascals-triangle-Puzzle/Curry/pascals-triangle-puzzle.curry new file mode 100644 index 0000000000..82ed4113e1 --- /dev/null +++ b/Task/Pascals-triangle-Puzzle/Curry/pascals-triangle-puzzle.curry @@ -0,0 +1,25 @@ +import CLPFD +import Constraint (allC, andC) +import Findall (findall) +import List (init, last) + + +solve :: [[Int]] -> Success +solve body@([n]:rest) = + domain (concat body) 1 n + & andC (zipWith atop body rest) + & labeling [] (concat body) + where + xs `atop` ys = andC $ zipWith3 tri xs (init ys) (tail ys) + +tri :: Int -> Int -> Int -> Success +tri x y z = x =# y +# z + +test (x,y,z) | tri y x z = + [ [151] + , [ _, _] + , [40, _, _] + , [ _, _, _, _] + , [ x, 11, y, 4, z] + ] +main = findall $ solve . test diff --git a/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d b/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d index c3b4c1bd5e..03f0bcb43c 100644 --- a/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d +++ b/Task/Pascals-triangle-Puzzle/D/pascals-triangle-puzzle.d @@ -1,45 +1,38 @@ import std.stdio, std.algorithm; -void iterate(bool doPrint=true)(double[] v, double[] diff) -/*pure nothrow*/ { +void iterate(bool doPrint=true)(double[] v, double[] diff) @safe { static ref T E(T)(T[] x, in size_t row, in size_t col) - pure nothrow { + pure nothrow @safe @nogc { return x[row * (row + 1) / 2 + col]; } double tot = 0.0; do { - // enforce boundary conditions + // Enforce boundary conditions. E(v, 0, 0) = 151; E(v, 2, 0) = 40; E(v, 4, 1) = 11; E(v, 4, 3) = 4; - // calculate difference from equilibrium + // Calculate difference from equilibrium. foreach (immutable i; 1 .. 5) { foreach (immutable j; 0 .. i + 1) { E(diff, i, j) = 0; if (j < i) - E(diff, i, j) += E(v, i - 1, j) - - E(v, i, j + 1) - - E(v, i, j); + E(diff, i, j) += E(v, i - 1, j) - E(v, i, j + 1) - E(v, i, j); if (j) - E(diff, i, j) += E(v, i - 1, j - 1) - - E(v, i, j - 1) - - E(v, i, j); + E(diff, i, j) += E(v, i - 1, j - 1) - E(v, i, j - 1) - E(v, i, j); } } foreach (immutable i; 1 .. 4) foreach (immutable j; 0 .. i) - E(diff, i, j) += E(v, i + 1, j) + - E(v, i + 1, j + 1) - - E(v, i, j); + E(diff, i, j) += E(v, i + 1, j) + E(v, i + 1, j + 1) - E(v, i, j); E(diff, 4, 2) += E(v, 4, 0) + E(v, 4, 4) - E(v, 4, 2); - // do feedback, check if we are close enough - // 4: scale down the feedback to avoid oscillations + // Do feedback, check if we are close enough. + // 4: scale down the feedback to avoid oscillations. v[] += diff[] / 4; tot = diff.map!q{ a ^^ 2 }.sum; @@ -53,18 +46,16 @@ void iterate(bool doPrint=true)(double[] v, double[] diff) } void main() { - static void show(in double[] x) nothrow { + static void show(in double[] x) nothrow @nogc { int idx; foreach (immutable i; 0 .. 5) foreach (immutable j; 0 .. i+1) { - printf("%4d%c", cast(int)(0.5 + x[idx]), - j < i ? ' ' : '\n'); + printf("%4d%c", cast(int)(0.5 + x[idx]), j < i ? ' ' : '\n'); idx++; } } - double[15] v = 0.0; - double[15] diff = 0.0; + double[15] v = 0.0, diff = 0.0; iterate(v, diff); show(v); } diff --git a/Task/Pascals-triangle-Puzzle/Ruby/pascals-triangle-puzzle.rb b/Task/Pascals-triangle-Puzzle/Ruby/pascals-triangle-puzzle.rb index cedcb37129..13e18823a5 100644 --- a/Task/Pascals-triangle-Puzzle/Ruby/pascals-triangle-puzzle.rb +++ b/Task/Pascals-triangle-Puzzle/Ruby/pascals-triangle-puzzle.rb @@ -7,7 +7,8 @@ pyramid = [ [nil,nil,nil,nil], ["x", 11,"y", 4,"z"] ] -p pyramid +pyramid.each{|row| p row} + equations = [[1,-1,1,0]] # y = x + z def parse_equation(str) @@ -16,10 +17,10 @@ def parse_equation(str) eqn[3] = rhs.to_i for term in lhs.split("+") case term - when "x": eqn[0] += 1 - when "y": eqn[1] += 1 - when "z": eqn[2] += 1 - else eqn[3] -= term.to_i + when "x" then eqn[0] += 1 + when "y" then eqn[1] += 1 + when "z" then eqn[2] += 1 + else eqn[3] -= term.to_i end end eqn @@ -28,7 +29,7 @@ end -2.downto(-5) do |row| pyramid[row].each_index do |col| val = pyramid[row][col] - sum = "%s+%s" % [pyramid[row+1][col].to_s, pyramid[row+1][col+1].to_s] + sum = "%s+%s" % [pyramid[row+1][col], pyramid[row+1][col+1]] if val.nil? pyramid[row][col] = sum else @@ -42,12 +43,13 @@ reduced = convert_to(reduced_row_echelon_form(equations), :to_i) for eqn in reduced if eqn[0] + eqn[1] + eqn[2] != 1 fail "no unique solution! #{equations.inspect} ==> #{reduced.inspect}" - elsif eqn[0] == 1: x = eqn[3] - elsif eqn[1] == 1: y = eqn[3] - elsif eqn[2] == 1: z = eqn[3] + elsif eqn[0] == 1 then x = eqn[3] + elsif eqn[1] == 1 then y = eqn[3] + elsif eqn[2] == 1 then z = eqn[3] end end +puts puts "x == #{x}" puts "y == #{y}" puts "z == #{z}" @@ -56,4 +58,5 @@ answer = [] for row in pyramid answer << row.collect {|cell| eval cell.to_s} end -p answer +puts +answer.each{|row| p row} diff --git a/Task/Pascals-triangle/00DESCRIPTION b/Task/Pascals-triangle/00DESCRIPTION index fff12d4078..c36db2c9ce 100644 --- a/Task/Pascals-triangle/00DESCRIPTION +++ b/Task/Pascals-triangle/00DESCRIPTION @@ -1,4 +1,5 @@ -[[wp:Pascal's triangle|Pascal's triangle]] is an arithmetic and geometric figure first imagined by [[wp:Blaise Pascal|Blaise Pascal]]. Its first few rows look like this: +[[wp:Pascal's triangle|Pascal's triangle]] is an arithmetic and geometric figure first imagined by [[wp:Blaise Pascal|Blaise Pascal]]. +Its first few rows look like this: 1 1 1 1 2 1 diff --git a/Task/Pascals-triangle/AWK/pascals-triangle.awk b/Task/Pascals-triangle/AWK/pascals-triangle.awk index de7b2ae6ca..24e103468e 100644 --- a/Task/Pascals-triangle/AWK/pascals-triangle.awk +++ b/Task/Pascals-triangle/AWK/pascals-triangle.awk @@ -1,7 +1 @@ $ awk 'BEGIN{for(i=0;i<6;i++){c=1;r=c;for(j=0;j) of Natural; + + function Length(R: Row) return Positive; + + function First_Row(Max_Length: Positive) return Row; + + function Next_Row(R: Row) return Row; + +end Pascal; diff --git a/Task/Pascals-triangle/Ada/pascals-triangle-2.ada b/Task/Pascals-triangle/Ada/pascals-triangle-2.ada new file mode 100644 index 0000000000..39ec85a362 --- /dev/null +++ b/Task/Pascals-triangle/Ada/pascals-triangle-2.ada @@ -0,0 +1,26 @@ +package body Pascal is + + function First_Row(Max_Length: Positive) return Row is + R: Row(0 .. Max_Length) := (0 | 1 => 1, others => 0); + begin + return R; + end First_Row; + + function Next_Row(R: Row) return Row is + S: Row(R'Range); + begin + S(0) := Length(R)+1; + S(Length(S)) := 1; + for J in reverse 2 .. Length(R) loop + S(J) := R(J)+R(J-1); + end loop; + S(1) := 1; + return S; + end Next_Row; + + function Length(R: Row) return Positive is + begin + return R(0); + end Length; + +end Pascal; diff --git a/Task/Pascals-triangle/Ada/pascals-triangle-3.ada b/Task/Pascals-triangle/Ada/pascals-triangle-3.ada new file mode 100644 index 0000000000..59f9ca89b3 --- /dev/null +++ b/Task/Pascals-triangle/Ada/pascals-triangle-3.ada @@ -0,0 +1,18 @@ +with Ada.Text_IO, Ada.Integer_Text_IO, Ada.Command_Line, Pascal; use Pascal; + +procedure Triangle is + + Number_Of_Rows: Positive := Integer'Value(Ada.Command_Line.Argument(1)); + Row: Pascal.Row := First_Row(Number_Of_Rows); + +begin + loop + -- print one row + for J in 1 .. Length(Row) loop + Ada.Integer_Text_IO.Put(Row(J), 5); + end loop; + Ada.Text_IO.New_Line; + exit when Length(Row) >= Number_Of_Rows; + Row := Next_Row(Row); + end loop; +end Triangle; diff --git a/Task/Pascals-triangle/Ada/pascals-triangle.ada b/Task/Pascals-triangle/Ada/pascals-triangle.ada deleted file mode 100644 index 0ffc83667a..0000000000 --- a/Task/Pascals-triangle/Ada/pascals-triangle.ada +++ /dev/null @@ -1,34 +0,0 @@ -with Ada.Integer_Text_Io; use Ada.Integer_Text_Io; -with Ada.Text_Io; use Ada.Text_Io; - -procedure Pascals_Triangle is - type Row is array(Positive range <>) of Integer; - type Row_Access is access Row; - type Triangle is array(Positive range <>) of Row_Access; - function General_Triangle(Depth : Positive) return Triangle is - Result : Triangle(1..Depth); - begin - for I in Result'range loop - Result(I) := new Row(1..I); - for J in 1..I loop - if J = Result(I)'First or else J = Result(I)'Last then - Result(I)(J) := 1; - else - Result(I)(J) := Result(I - 1)(J - 1) + Result(I - 1)(J); - end if; - end loop; - end loop; - return Result; - end General_Triangle; - procedure Print(Item : Triangle) is - begin - for I in Item'range loop - for J in 1..I loop - Put(Item => Item(I)(J), Width => 3); - end loop; - New_Line; - end loop; - end Print; -begin - Print(General_Triangle(7)); -end Pascals_Triangle; diff --git a/Task/Pascals-triangle/C++/pascals-triangle.cpp b/Task/Pascals-triangle/C++/pascals-triangle.cpp index 3b81d11cae..2c1c53fc44 100644 --- a/Task/Pascals-triangle/C++/pascals-triangle.cpp +++ b/Task/Pascals-triangle/C++/pascals-triangle.cpp @@ -1,26 +1,80 @@ #include #include -#include -#include +#include +using namespace std; +void Pascal_Triangle(int size) { -void genPyrN(int rows) { - if (rows < 0) return; - // save the last row here - std::vector last(1, 1); - std::cout << last[0] << std::endl; + int a[100][100]; + int i, j; - for (int i = 1; i <= rows; i++) { - // work on the next row - std::vector thisRow; - thisRow.reserve(i+1); - thisRow.push_back(last.front()); // beginning of row - std::transform(last.begin(), last.end()-1, last.begin()+1, std::back_inserter(thisRow), std::plus()); // middle of row - thisRow.push_back(last.back()); // end of row + //first row and first coloumn has the same value=1 + for (i = 1; i <= size; i++) { + a[i][1] = a[1][i] = 1; + } + + //Generate the full Triangle + for (i = 2; i <= size; i++) { + for (j = 2; j <= size - i; j++) { + if (a[i - 1][j] == 0 || a[i][j - 1] == 0) { + break; + } + a[i][j] = a[i - 1][j] + a[i][j - 1]; + } + } + + /* + 1 1 1 1 + 1 2 3 + 1 3 + 1 + + first print as above format--> + + for (i = 1; i < size; i++) { + for (j = 1; j < size; j++) { + if (a[i][j] == 0) { + break; + } + printf("%8d",a[i][j]); + } + cout<<"\n\n"; + }*/ + + // standard Pascal Triangle Format + + int row,space; + for (i = 1; i < size; i++) { + space=row=i; + j=1; + + while(space<=size+(size-i)+1){ + cout<<" "; + space++; + } + + while(j<=i){ + if (a[row][j] == 0){ + break; + } + + if(j==1){ + printf("%d",a[row--][j++]); + } + else + printf("%6d",a[row--][j++]); + } + cout<<"\n\n"; + } + +} + +int main() +{ + //freopen("out.txt","w",stdout); + + int size; + cin>>size; + Pascal_Triangle(size); +} - for (int j = 0; j <= i; j++) - std::cout << thisRow[j] << " "; - std::cout << std::endl; - - last.swap(thisRow); - } } diff --git a/Task/Pascals-triangle/Clojure/pascals-triangle-4.clj b/Task/Pascals-triangle/Clojure/pascals-triangle-4.clj new file mode 100644 index 0000000000..83fbfb3686 --- /dev/null +++ b/Task/Pascals-triangle/Clojure/pascals-triangle-4.clj @@ -0,0 +1,5 @@ +(def pascal + (iterate #(concat [1] + (map + % (rest %)) + [1]) + [1])) diff --git a/Task/Pascals-triangle/Clojure/pascals-triangle-5.clj b/Task/Pascals-triangle/Clojure/pascals-triangle-5.clj new file mode 100644 index 0000000000..5e7fb464ea --- /dev/null +++ b/Task/Pascals-triangle/Clojure/pascals-triangle-5.clj @@ -0,0 +1 @@ +(take 10 pascal) ; returns a list of the first 10 pascal rows diff --git a/Task/Pascals-triangle/Clojure/pascals-triangle-6.clj b/Task/Pascals-triangle/Clojure/pascals-triangle-6.clj new file mode 100644 index 0000000000..77dc5f8b23 --- /dev/null +++ b/Task/Pascals-triangle/Clojure/pascals-triangle-6.clj @@ -0,0 +1 @@ +(nth pascal 10) ;returns the nth row diff --git a/Task/Pascals-triangle/K/pascals-triangle.k b/Task/Pascals-triangle/K/pascals-triangle.k index 61e91a77fb..f805474ed5 100644 --- a/Task/Pascals-triangle/K/pascals-triangle.k +++ b/Task/Pascals-triangle/K/pascals-triangle.k @@ -1,4 +1,4 @@ - pascal:{(x-1){+':0,x,0}\1} + pascal:{(x-1){1_ +':0,x,0}\1} pascal 6 (1 diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 index 83b2981248..a372200df4 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-1.pl6 @@ -1,7 +1,3 @@ -multi pascal (1) { [1] } -multi pascal (Int $n where 2..*) { - my @rows = pascal $n - 1; - @rows, [0, @rows[*-1][] Z+ @rows[*-1][], 0 )]; -} +sub pascal { [1], { [0, @^p Z+ @^p, 0] } ... * } -say .perl for pascal 10; +.say for pascal[^10]; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 index 2ce8abccb1..e4268d40ac 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-2.pl6 @@ -1,8 +1,3 @@ -sub pascal ($n where $n >= 1) { - # Prints out $n rows of Pascal's triangle. - say my @last = 1; - for 1 .. $n - 1 -> $row { - my @this = map { @last[$_] + @last[$_ + 1] }, 0 .. $row - 2; - say @last = 1, @this, 1; - } -} +constant Pascal = [1], { [0, @^p Z+ @^p, 0] } ... *; + +.say for Pascal[^10]; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 index cab239edde..93051a4eb5 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-3.pl6 @@ -1,3 +1,7 @@ -sub pascal { [1], -> @p { [0, @p Z+ @p, 0] } ... * } +multi pascal (1) { [1] } +multi pascal (Int $n where 2..*) { + my @rows = pascal $n - 1; + @rows, [0, @rows[*-1][] Z+ @rows[*-1][], 0 )]; +} -.say for pascal[^10]; +.say for pascal 10; diff --git a/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 b/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 index 7f464d8c7a..06777c0c75 100644 --- a/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 +++ b/Task/Pascals-triangle/Perl-6/pascals-triangle-4.pl6 @@ -1,3 +1,9 @@ -constant Pascal = [1], -> @p { [0, @p Z+ @p, 0] } ... *; +sub pascal ($n where $n >= 1) { + say my @last = 1; + for 1 .. $n - 1 -> $row { + @last = 1, map({ @last[$_] + @last[$_ + 1] }, 0 .. $row - 2), 1; + say @last; + } +} -.say for Pascal[^10]; +pascal 10; diff --git a/Task/Pascals-triangle/Perl/pascals-triangle-1.pl b/Task/Pascals-triangle/Perl/pascals-triangle-1.pl index c5eefc362b..f0a2f9ee6b 100644 --- a/Task/Pascals-triangle/Perl/pascals-triangle-1.pl +++ b/Task/Pascals-triangle/Perl/pascals-triangle-1.pl @@ -1,13 +1,7 @@ sub pascal -# Prints out $n rows of Pascal's triangle. It returns undef for -# failure and 1 for success. - {my $n = shift; - $n < 1 and return undef; - print "1\n"; - $n == 1 and return 1; - my @last = (1); - foreach my $row (1 .. $n - 1) - {my @this = map {$last[$_] + $last[$_ + 1]} 0 .. $row - 2; - @last = (1, @this, 1); - print join(' ', @last), "\n";} - return 1;} + my $rows = shift; + my @next = (1); + for my $n (1 .. $rows) { + print "@next\n"; + @next = (1, (map $next[$_]+$next[$_+1], 0 .. $n-2), 1); + } diff --git a/Task/Pascals-triangle/Perl/pascals-triangle-2.pl b/Task/Pascals-triangle/Perl/pascals-triangle-2.pl index d9b21064c3..6b246b9d2a 100644 --- a/Task/Pascals-triangle/Perl/pascals-triangle-2.pl +++ b/Task/Pascals-triangle/Perl/pascals-triangle-2.pl @@ -1,3 +1,7 @@ -use bignum; -sub pascal { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 } -print "@{[map -+-$_, pascal $_]}\n" for 0..22; +use ntheory qw/binomial/; +sub pascal { + my $rows = shift; + for my $n (0 .. $rows-1) { + print join(" ", map { binomial($n,$_) } 0 .. $n), "\n"; + } +} diff --git a/Task/Pascals-triangle/Perl/pascals-triangle-3.pl b/Task/Pascals-triangle/Perl/pascals-triangle-3.pl new file mode 100644 index 0000000000..4e33564dbc --- /dev/null +++ b/Task/Pascals-triangle/Perl/pascals-triangle-3.pl @@ -0,0 +1,3 @@ +use bignum; +sub pascal_line { $_[0] ? unpack "A(A6)*", 1000001**$_[0] : 1 } +sub pascal { print "@{[map -+-$_, pascal_line $_]}\n" for 0..$_[0]-1 } diff --git a/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb b/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb index 235aa70da1..e13fea3a8b 100644 --- a/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb +++ b/Task/Pascals-triangle/Ruby/pascals-triangle-1.rb @@ -1,27 +1,10 @@ -def pascal(n = 1) - - return if n < 1 - - # set up a new array of arrays with the first value - p = [[1]] - - # for n - 1 number of times, - (n - 1).times do |i| - - # inject a new array starting with [1] - p << p[i].inject([1]) do |result, elem| - - # if we've reached the end, tack on a 1. - # else, tack on current elem + previous elem - if p[i].length == result.length - result << 1 - else - result << elem + p[i][result.length] - end - end +def pascal(n) + raise ArgumentError, "must be positive." if n < 1 + yield ar = [1] + (n-1).times do + ar.unshift(0).push(0) # tack a zero on both ends + yield ar = ar.each_cons(2).map{|a, b| a + b } end - - # and return the triangle. - p - end + +pascal(8){|row| puts row.join(" ").center(20)} diff --git a/Task/Pascals-triangle/Ruby/pascals-triangle-2.rb b/Task/Pascals-triangle/Ruby/pascals-triangle-2.rb index cdaf7791be..5622eff704 100644 --- a/Task/Pascals-triangle/Ruby/pascals-triangle-2.rb +++ b/Task/Pascals-triangle/Ruby/pascals-triangle-2.rb @@ -1,3 +1,5 @@ -def next_row row ; ([0] + row).zip(row + [0]).collect {|l,r| l + r }; end +def next_row(row) ([0] + row).zip(row + [0]).collect {|l,r| l + r } end -def pascal n ; ([nil] * n).inject([1]) {|x,y| y = next_row x } ; end +def pascal(n) n.times.inject([1]) {|x,_| next_row x } end + +8.times{|i| p pascal(i)} diff --git a/Task/Pattern-matching/Erlang/pattern-matching.erl b/Task/Pattern-matching/Erlang/pattern-matching.erl new file mode 100644 index 0000000000..f6287273fd --- /dev/null +++ b/Task/Pattern-matching/Erlang/pattern-matching.erl @@ -0,0 +1,39 @@ +-module(rbtree). +-export([insert/3, find/2]). + +% Node structure: { Key, Value, Color, Smaller, Bigger } + +find(_, nil) -> + not_found; +find(Key, { Key, Value, _, _, _ }) -> + { found, { Key, Value } }; +find(Key, { Key1, _, _, Left, _ }) when Key < Key1 -> + find(Key, Left); +find(Key, { Key1, _, _, _, Right }) when Key > Key1 -> + find(Key, Right). + +insert(Key, Value, Tree) -> + make_black(ins(Key, Value, Tree)). + +ins(Key, Value, nil) -> + { Key, Value, r, nil, nil }; +ins(Key, Value, { Key, _, Color, Left, Right }) -> + { Key, Value, Color, Left, Right }; +ins(Key, Value, { Ky, Vy, Cy, Ly, Ry }) when Key < Ky -> + balance({ Ky, Vy, Cy, ins(Key, Value, Ly), Ry }); +ins(Key, Value, { Ky, Vy, Cy, Ly, Ry }) when Key > Ky -> + balance({ Ky, Vy, Cy, Ly, ins(Key, Value, Ry) }). + +make_black({ Key, Value, _, Left, Right }) -> + { Key, Value, b, Left, Right }. + +balance({ Kx, Vx, b, Lx, { Ky, Vy, r, Ly, { Kz, Vz, r, Lz, Rz } } }) -> + { Ky, Vy, r, { Kx, Vx, b, Lx, Ly }, { Kz, Vz, b, Lz, Rz } }; +balance({ Kx, Vx, b, Lx, { Ky, Vy, r, { Kz, Vz, r, Lz, Rz }, Ry } }) -> + { Kz, Vz, r, { Kx, Vx, b, Lx, Lz }, { Ky, Vy, b, Rz, Ry } }; +balance({ Kx, Vx, b, { Ky, Vy, r, { Kz, Vz, r, Lz, Rz }, Ry }, Rx }) -> + { Ky, Vy, r, { Kz, Vz, b, Lz, Rz }, { Kx, Vx, b, Ry, Rx } }; +balance({ Kx, Vx, b, { Ky, Vy, r, Ly, { Kz, Vz, r, Lz, Rz } }, Rx }) -> + { Kz, Vz, r, { Ky, Vy, b, Ly, Lz }, { Kx, Vx, b, Rz, Rx } }; +balance(T) -> + T. diff --git a/Task/Percentage-difference-between-images/Haskell/percentage-difference-between-images.hs b/Task/Percentage-difference-between-images/Haskell/percentage-difference-between-images.hs new file mode 100644 index 0000000000..601dd08995 --- /dev/null +++ b/Task/Percentage-difference-between-images/Haskell/percentage-difference-between-images.hs @@ -0,0 +1,26 @@ +import Bitmap +import Bitmap.Netpbm +import Bitmap.RGB + +import Control.Monad +import Control.Monad.ST +import System.Environment (getArgs) + +main = do + [path1, path2] <- getArgs + image1 <- readNetpbm path1 + image2 <- readNetpbm path2 + diff <- stToIO $ imageDiff image1 image2 + putStrLn $ "Difference: " ++ show (100 * diff) ++ "%" + +imageDiff :: Image s RGB -> Image s RGB -> ST s Double +imageDiff image1 image2 = do + i1 <- getPixels image1 + i2 <- getPixels image2 + unless (length i1 == length i2) $ + fail "imageDiff: Images are of different sizes" + return $ + toEnum (sum $ zipWith minus i1 i2) / + toEnum (3 * 255 * length i1) + where (RGB (r1, g1, b1)) `minus` (RGB (r2, g2, b2)) = + abs (r1 - r2) + abs (g1 - g2) + abs (b1 - b2) diff --git a/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java b/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java index a0c62adad9..13ec00741b 100644 --- a/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java +++ b/Task/Percentage-difference-between-images/Java/percentage-difference-between-images.java @@ -26,10 +26,10 @@ public class ImgDiffPercent System.exit(1); } long diff = 0; - for (int i = 0; i < height1; i++) { - for (int j = 0; j < width1; j++) { - int rgb1 = img1.getRGB(i, j); - int rgb2 = img2.getRGB(i, j); + for (int y = 0; y < height1; y++) { + for (int x = 0; x < width1; x++) { + int rgb1 = img1.getRGB(x, y); + int rgb2 = img2.getRGB(x, y); int r1 = (rgb1 >> 16) & 0xff; int g1 = (rgb1 >> 8) & 0xff; int b1 = (rgb1 ) & 0xff; diff --git a/Task/Perfect-numbers/00DESCRIPTION b/Task/Perfect-numbers/00DESCRIPTION index 2f0e3b668f..95d3e11c75 100644 --- a/Task/Perfect-numbers/00DESCRIPTION +++ b/Task/Perfect-numbers/00DESCRIPTION @@ -1,9 +1,15 @@ Write a function which says whether a number is perfect. -[[wp:Perfect_numbers|A perfect number]] is a positive integer that is the sum of its proper positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself). +[[wp:Perfect_numbers|A perfect number]] is a positive integer that is +the sum of its proper positive divisors excluding the number itself. +Equivalently, a perfect number is a number that is half the sum +of all of its positive divisors (including itself). -Note: The faster [[Lucas-Lehmer test]] is used to find primes of the form 2''n''-1, all ''known'' perfect numbers can be derived from these primes using the formula (2''n'' - 1) × 2''n'' - 1. It is not known if there are any odd perfect numbers. +Note: The faster [[Lucas-Lehmer test]] is used to find primes of the form 2''n''-1, all ''known'' perfect numbers can be derived from these primes +using the formula (2''n'' - 1) × 2''n'' - 1. +It is not known if there are any odd perfect numbers (any that exist are larger than 102000). '''See also''' * [[Rational Arithmetic]] -*[[oeis:A000396|Perfect numbers on OEIS]] +* [[oeis:A000396|Perfect numbers on OEIS]] +* [http://www.oddperfect.org/ Odd Perfect] showing the current status of bounds on odd perfect numbers. diff --git a/Task/Perfect-numbers/Clojure/perfect-numbers-1.clj b/Task/Perfect-numbers/Clojure/perfect-numbers-1.clj index 98ebb804cf..bfe32abd87 100644 --- a/Task/Perfect-numbers/Clojure/perfect-numbers-1.clj +++ b/Task/Perfect-numbers/Clojure/perfect-numbers-1.clj @@ -1,8 +1,9 @@ (defn proper-divisors [n] (if (< n 4) - '(1) - (cons 1 (filter #(zero? (rem n %)) (range 2 (inc (quot n 2)))))) -) + [1] + (->> (range 2 (inc (quot n 2))) + (filter #(zero? (rem n %))) + (cons 1)))) + (defn perfect? [n] - (== (reduce + (proper-divisors n)) n) -) + (= (reduce + (proper-divisors n)) n)) diff --git a/Task/Perfect-numbers/Clojure/perfect-numbers-2.clj b/Task/Perfect-numbers/Clojure/perfect-numbers-2.clj index bef650e943..2d4d5fa340 100644 --- a/Task/Perfect-numbers/Clojure/perfect-numbers-2.clj +++ b/Task/Perfect-numbers/Clojure/perfect-numbers-2.clj @@ -1,2 +1,4 @@ (defn perfect? [n] - (= n (reduce + (for [i (range 1 n) :when (= 0 (mod n i))] i)))) + (->> (for [i (range 1 n)] :when (zero? (rem n i))] i) + (reduce +) + (= n))) diff --git a/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e b/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e new file mode 100644 index 0000000000..aa0d2b2ec6 --- /dev/null +++ b/Task/Perfect-numbers/Eiffel/perfect-numbers-1.e @@ -0,0 +1,24 @@ +class + PERFECT_NUMBERS +feature + perfect(n:INTEGER):BOOLEAN + require + n_positive: n>0 + local + sum, i: INTEGER + do + from + i:=1 + until + i=n + loop + if n\\i=0 then + sum:=sum+i + end + i:= i+1 + end + if sum= n then + RESULT:= TRUE + end + end +end diff --git a/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e b/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e new file mode 100644 index 0000000000..36573e74bf --- /dev/null +++ b/Task/Perfect-numbers/Eiffel/perfect-numbers-2.e @@ -0,0 +1,20 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + create perfect + io.put_string ("%N 6 is perfect...%T") + io.put_boolean (perfect.perfect (6)) + io.put_string ("%N77 is perfect...%T") + io.put_boolean (perfect.perfect (77)) + io.put_string ("%N496 is perfect...%T") + io.put_boolean (perfect.perfect (496)) + + end + perfect: PERFECT_NUMBERS +end diff --git a/Task/Perfect-numbers/Elixir/perfect-numbers.elixir b/Task/Perfect-numbers/Elixir/perfect-numbers.elixir new file mode 100644 index 0000000000..b33fae77f7 --- /dev/null +++ b/Task/Perfect-numbers/Elixir/perfect-numbers.elixir @@ -0,0 +1,3 @@ +def is_perfect(x) do + [1 | lc x inlist :lists.seq(2, div(n, 2)), rem(n, x) == 0, do: x] |> :lists.sum() == n +end diff --git a/Task/Perfect-numbers/J/perfect-numbers-1.j b/Task/Perfect-numbers/J/perfect-numbers-1.j index 4f461b21e9..6e5d3739a3 100644 --- a/Task/Perfect-numbers/J/perfect-numbers-1.j +++ b/Task/Perfect-numbers/J/perfect-numbers-1.j @@ -1 +1 @@ -is_perfect=: = [: +/ ((0=]|[)i.) # i. +is_perfect=: +: = >:@#.~/.~&.q:@(6>.<.) diff --git a/Task/Perfect-numbers/J/perfect-numbers-2.j b/Task/Perfect-numbers/J/perfect-numbers-2.j index 137e2095cd..b07512de3b 100644 --- a/Task/Perfect-numbers/J/perfect-numbers-2.j +++ b/Task/Perfect-numbers/J/perfect-numbers-2.j @@ -1,14 +1,15 @@ is_perfect 33550336 1 - }.I. is_perfect"0 i. 10000 + I. is_perfect i. 100000 6 28 496 8128 ] zero_through_twentynine =. i. 3 10 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 25 26 27 28 29 - is_pos_int=: 0&< *. ]=>. - (is_perfect"0 *. is_pos_int) zero_through_twentynine + is_perfect zero_through_twentynine 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 + is_perfect 191561942608236107294793378084303638130997321548169216x +1 diff --git a/Task/Perfect-numbers/MATLAB/perfect-numbers-1.m b/Task/Perfect-numbers/MATLAB/perfect-numbers-1.m new file mode 100644 index 0000000000..baf9a30335 --- /dev/null +++ b/Task/Perfect-numbers/MATLAB/perfect-numbers-1.m @@ -0,0 +1,9 @@ +function perf = isPerfect(n) + total = 0; + for k = 1:n-1 + if ~mod(n, k) + total = total+k; + end + end + perf = total == n; +end diff --git a/Task/Perfect-numbers/MATLAB/perfect-numbers-2.m b/Task/Perfect-numbers/MATLAB/perfect-numbers-2.m new file mode 100644 index 0000000000..f06786c880 --- /dev/null +++ b/Task/Perfect-numbers/MATLAB/perfect-numbers-2.m @@ -0,0 +1,20 @@ +function perf = isPerfect(n) + if n < 2 + perf = false; + else + total = 1; + k = 2; + quot = n; + while k < quot && total <= n + if ~mod(n, k) + total = total+k; + quot = n/k; + if quot ~= k + total = total+quot; + end + end + k = k+1; + end + perf = total == n; + end +end diff --git a/Task/Perfect-numbers/Perl/perfect-numbers-3.pl b/Task/Perfect-numbers/Perl/perfect-numbers-3.pl new file mode 100644 index 0000000000..c733f088d4 --- /dev/null +++ b/Task/Perfect-numbers/Perl/perfect-numbers-3.pl @@ -0,0 +1,2 @@ +use ntheory qw/divisor_sum/; +sub is_perfect { my $n = shift; divisor_sum($n) == 2*$n; } diff --git a/Task/Perfect-numbers/Perl/perfect-numbers-4.pl b/Task/Perfect-numbers/Perl/perfect-numbers-4.pl new file mode 100644 index 0000000000..a5a8609c30 --- /dev/null +++ b/Task/Perfect-numbers/Perl/perfect-numbers-4.pl @@ -0,0 +1,4 @@ +use ntheory qw/divisor_sum/; +for (1..33550336) { + print "$_\n" if divisor_sum($_) == 2*$_; +} diff --git a/Task/Perfect-numbers/Perl/perfect-numbers-5.pl b/Task/Perfect-numbers/Perl/perfect-numbers-5.pl new file mode 100644 index 0000000000..d00e0c13dc --- /dev/null +++ b/Task/Perfect-numbers/Perl/perfect-numbers-5.pl @@ -0,0 +1,6 @@ +use ntheory qw/forprimes is_prime/; +use bigint; +forprimes { + my $n = 2**$_ - 1; + print "$_\t", $n * 2**($_-1),"\n" if is_prime($n); +} 2, 4500; diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx index 018040601d..d3938f435f 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-1.rexx @@ -1,13 +1,12 @@ /*REXX version of the ooRexx pgm (code was modified for Classic REXX).*/ - - do i=1 to 10000 /*statement changed: LOOP ──► DO*/ - if perfectNumber(i) then say i "is a perfect number" + 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*/ +perfectNumber: procedure; parse arg n /*statements changed: ROUTINE,USE*/ sum=0 - do i=1 to n%2 /*statement changed: LOOP ──► DO*/ + 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 be1bebcc8b..665fefe500 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-2.rexx @@ -3,17 +3,15 @@ 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. */ -call time 'R' do i=low to high /*process the single # or range. */ - if perfect(i) then say i 'is a perfect number.' + if perfect(i) then say i 'is a perfect number.' end /*i*/ -say 'and took' format(time('E'),,2) "seconds." exit -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! */ +perfect: procedure; parse arg n /*get the number to be tested. */ +sum=0 /*the sum of the factors so far. */ + do i=1 for n-1 /*starting at 1, find all factors*/ + if n//i==0 then sum=sum+i /*I is a factor of N, so add it.*/ + end /*i*/ +return sum=n /*if the sum matches N, perfect! */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx index 58c7ea19f6..0c086e0f96 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-3.rexx @@ -7,14 +7,14 @@ 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.' + 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. */ +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*/ + 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.*/ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx index 7824170d86..13ff32c004 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-4.rexx @@ -7,22 +7,21 @@ 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.' + 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. */ +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 + /*[↓] perfect #s digitalRoot = 1.*/ + do until y<10 /*find the digital root of Y. */ + parse var y r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end 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.*/ +if r\==1 then return 0 /*Digital root ¬1? Then ¬perfect.*/ s=1 /*the first factor of X. */ - do j=2 while j*j<=x /*starting at 2, find factors ≤√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.*/ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx index bffbfb59c6..0281c09285 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-5.rexx @@ -2,28 +2,28 @@ 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 low//2 then low=low+1 /*if LOW is odd, bump it by one.*/ if high=='' then high=low /*if no HIGH, then assume LOW. */ w=length(high) /*use W for formatting 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.' + do i=low to high by 2 /*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.*/ +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 + do until y<10 /*find the digital root of Y. */ + parse var y r 2; do k=2 for length(y)-1; r=r+substr(y,k,1); end 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*/ + 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.*/ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx index e3512adad1..bb53706bc6 100644 --- a/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx +++ b/Task/Perfect-numbers/REXX/perfect-numbers-6.rexx @@ -2,17 +2,17 @@ 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 low//2 then low=low+1 /*if LOW is odd, bump it by one.*/ if high=='' then high=low /*if no HIGH, then assume LOW. */ w=length(high) /*use W for formatting 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.' + do i=low to high by 2 /*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.*/ +isPerfect: procedure expose @.; parse arg x /*get the # to be tested.*/ /*Lucas-Lehmer know that perfect */ /* numbers can be expressed as: */ /* [2**n - 1] * [2** (n-1) ] */ diff --git a/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx b/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx new file mode 100644 index 0000000000..3da41e0bcc --- /dev/null +++ b/Task/Perfect-numbers/REXX/perfect-numbers-7.rexx @@ -0,0 +1,46 @@ +/*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.*/ +low=low+low//2 /*if LOW is odd, bump it by one.*/ +if high=='' then high=low /*if no HIGH, then assume LOW. */ +w=length(high) /*use W for formatting output. */ +numeric digits max(9,w+2) /*ensure enough digits to handle#*/ +@. =0; @.1=2; !.=2; _=' 6' /*highest magic # and its index.*/ +!._=22; !.16=12; !.28=8; !.36=20; !.56=20; !.76=20; !.96=20 + /* [↑] "Lucas' numbers, 1891. */ + do i=low to high by 0 /*process the single # or range. */ + if isPerfect(i) then say right(i,w) 'is a perfect number.' + i=i+!.? /*use a fast advance for DO loop.*/ + end /*i*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────ISPERFECT subroutine────────────────*/ +isPerfect: procedure expose @. !. ? /*expose (make global) some vars.*/ +parse arg x 1 y '' -2 ? /*#, another copy, and last digit*/ +if x==6 then return 1 /*handle special case of six. */ +if !.?==2 then return 0 /*test last 2digs: François Lucas*/ + /*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/Ruby/perfect-numbers-5.rb b/Task/Perfect-numbers/Ruby/perfect-numbers-5.rb new file mode 100644 index 0000000000..fc6ce211a7 --- /dev/null +++ b/Task/Perfect-numbers/Ruby/perfect-numbers-5.rb @@ -0,0 +1,24 @@ +require "prime" + +def mersenne_prime_pow?(p) + # Lucas-Lehmer test; expects prime as argument + return true if p == 2 + m_p = ( 1 << p ) - 1 + s = 4 + (p-2).times{ s = (s**2 - 2) % m_p } + s == 0 +end + +@perfect_numerator = Prime.each.lazy.select{|p| mersenne_prime_pow?(p)}.map{|p| 2**(p-1)*(2**p-1)} +@perfects = @perfect_numerator.take(1).to_a + +def perfect?(num) + @perfects << @perfect_numerator.next until @perfects.last >= num + @perfects.include? num +end + +# demo +p (1..10000).select{|num| perfect?(num)} +t1 = Time.now +p perfect?(13164036458569648337239753460458722910223472318386943117783728128) +p Time.now - t1 diff --git a/Task/Perfect-numbers/Scala/perfect-numbers.scala b/Task/Perfect-numbers/Scala/perfect-numbers-1.scala similarity index 100% rename from Task/Perfect-numbers/Scala/perfect-numbers.scala rename to Task/Perfect-numbers/Scala/perfect-numbers-1.scala diff --git a/Task/Perfect-numbers/Scala/perfect-numbers-2.scala b/Task/Perfect-numbers/Scala/perfect-numbers-2.scala new file mode 100644 index 0000000000..10aa752a33 --- /dev/null +++ b/Task/Perfect-numbers/Scala/perfect-numbers-2.scala @@ -0,0 +1,2 @@ +def perfect(n: Int) = + (for (x <- 2 to n/2 if n % x == 0) yield x).sum + 1 == n diff --git a/Task/Permutation-test/00DESCRIPTION b/Task/Permutation-test/00DESCRIPTION index 0f048f9d01..32d86ea998 100644 --- a/Task/Permutation-test/00DESCRIPTION +++ b/Task/Permutation-test/00DESCRIPTION @@ -1,9 +1,11 @@ A new medical treatment was tested on a population of n + m volunteers, with each volunteer randomly assigned either to a group of -n treatment subjects, or to a group of m control subjects. Members of -the treatment group were given the treatment, and members of the -control group were given a placebo. The effect of the treatment or -placebo on each volunteer was measured and reported in this table. +n treatment subjects, or to a group of m control subjects. + +Members of the treatment group were given the treatment, +and members of the control group were given a placebo. +The effect of the treatment or placebo on each volunteer +was measured and reported in this table. {| style="text-align: left; width: 50%;" border="4" cellpadding="2" cellspacing="2" |+ Table of experimental results diff --git a/Task/Permutation-test/D/permutation-test-1.d b/Task/Permutation-test/D/permutation-test-1.d index c50aed753e..c10ea0ac37 100644 --- a/Task/Permutation-test/D/permutation-test-1.d +++ b/Task/Permutation-test/D/permutation-test-1.d @@ -1,9 +1,8 @@ import std.stdio, std.algorithm, std.array, combinations3; -auto permutationTest(T)(in T[] a, in T[] b) /*pure nothrow*/ { +auto permutationTest(T)(in T[] a, in T[] b) pure nothrow @safe { immutable tObs = a.sum; - //auto combs = combinations!false(a ~ b, a.length); // Not a Range. - const combs = combinations(a ~ b, a.length).array; // Slow. + auto combs = combinations!false(a ~ b, a.length); immutable under = combs.count!(perm => perm.sum <= tObs); return under * 100.0 / combs.length; } diff --git a/Task/Permutation-test/D/permutation-test-2.d b/Task/Permutation-test/D/permutation-test-2.d index cd2ba69e52..c6daf2675c 100644 --- a/Task/Permutation-test/D/permutation-test-2.d +++ b/Task/Permutation-test/D/permutation-test-2.d @@ -1,12 +1,12 @@ -import std.stdio, std.algorithm, std.range; +void main() @safe { + import std.stdio, std.algorithm, std.range; -void main() { immutable treatment = [85, 88, 75, 66, 25, 29, 83, 39, 97]; immutable control = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98]; immutable both = treatment ~ control; immutable sTreat = treatment.sum; - T pick(T)(in size_t at, in size_t remain, in T accu) pure nothrow { + T pick(T)(in size_t at, in size_t remain, in T accu) pure nothrow @safe @nogc { if (remain == 0) return accu > sTreat; diff --git a/Task/Permutation-test/REXX/permutation-test.rexx b/Task/Permutation-test/REXX/permutation-test.rexx index 0be5c7145f..457bf88cc6 100644 --- a/Task/Permutation-test/REXX/permutation-test.rexx +++ b/Task/Permutation-test/REXX/permutation-test.rexx @@ -1,30 +1,30 @@ /*REXX program does a permutation test on N + M subjects (volunteers):*/ -/* ↑ ↑ */ -/* │ │ */ -/* │ └─────control population*/ -/* └────────treatment population*/ + /* ↑ ↑ */ + /* │ │ */ + /* │ └─────control population*/ + /* └────────treatment population*/ n=9 data=85 88 75 66 25 29 83 39 97 68 41 10 49 16 65 32 92 28 98 w=words(data); m=w-n -say 'volunteer population given treatment:' right(n,length(w)) -say ' control population given a placebo:' right(m,length(w)) +say 'volunteer population given treatment:' right(n,length(w)) +say ' control population given a placebo:' right(m,length(w)) say -say 'treatment population efficacy % (percentages):' subword(data,1,n) -say ' control population placebo % (percentages):' subword(data,n+1) +say 'treatment population efficacy % (percentages):' subword(data,1,n) +say ' control population placebo % (percentages):' subword(data,n+1) say - do v= 0 for w ; #.v=word(data,v+1) ; end -treat=0; do i= 0 to n-1 ; treat=treat+#.i ; end -total=1; do j=19 to m+1 by -1 ; total=total*j ; end - do k= 9 to 1 by -1 ; total=total/k ; end -gt=pick(n+m, n, 0) + do v= 0 for w ; #.v=word(data,v+1) ; end +treat=0; do i= 0 to n-1 ; treat=treat+#.i ; end +total=1; do j=19 to m+1 by -1 ; total=total*j ; end + do k= 9 to 1 by -1 ; total=total/k ; end +gt=picker(n+m, n, 0) le=total-gt -say "<= " format(100*le/total,,3)'%' le /*show 3 decimal places.*/ -say " > " format(100*gt/total,,3)'%' gt +say "<= " format(100*le/total,,3)'%' le /*show 3 decimal places.*/ +say " > " format(100*gt/total,,3)'%' gt exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────PICK subroutine─────────────────────*/ -pick: procedure expose #. treat; parse arg it,rest,eff +/*──────────────────────────────────PICKER subroutine───────────────────*/ +picker: procedure expose #. treat; parse arg it,rest,eff if rest==0 then return eff>treat -if it>rest then q=pick(it-1, rest, eff) +if it>rest then q=picker(it-1, rest, eff) else q=0 itP=it-1 -return pick(itP, rest-1, eff+#.itP) + q +return picker(itP, rest-1, eff+#.itP) + q diff --git a/Task/Permutation-test/Ruby/permutation-test.rb b/Task/Permutation-test/Ruby/permutation-test.rb new file mode 100644 index 0000000000..69fcbf997f --- /dev/null +++ b/Task/Permutation-test/Ruby/permutation-test.rb @@ -0,0 +1,20 @@ +def statistic(ab, a) + sumab, suma = ab.inject(:+).to_f, a.inject(:+).to_f + suma / a.size - (sumab - suma) / (ab.size - a.size) +end + +def permutationTest(a, b) + ab = a + b + tobs = statistic(ab, a) + under = count = 0 + ab.combination(a.size) do |perm| + under += 1 if statistic(ab, perm) <= tobs + count += 1 + end + under * 100.0 / count +end + +treatmentGroup = [85, 88, 75, 66, 25, 29, 83, 39, 97] +controlGroup = [68, 41, 10, 49, 16, 65, 32, 92, 28, 98] +under = permutationTest(treatmentGroup, controlGroup) +puts "under=%.2f%%, over=%.2f%%" % [under, 100 - under] diff --git a/Task/Permutations-Derangements/00DESCRIPTION b/Task/Permutations-Derangements/00DESCRIPTION index ba81150663..0862dc11d3 100644 --- a/Task/Permutations-Derangements/00DESCRIPTION +++ b/Task/Permutations-Derangements/00DESCRIPTION @@ -2,7 +2,8 @@ A [http://mathworld.wolfram.com/Derangement.html derangement] is a permutation o For example, the only two derangements of the three items (0, 1, 2) are (1, 2, 0), and (2, 0, 1). -The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. There are various ways to [[wp:Derangement#Counting_derangements|calculate]] !''n''. +The number of derangements of ''n'' distinct items is known as the subfactorial of ''n'', sometimes written as !''n''. +There are various ways to [[wp:Derangement#Counting_derangements|calculate]] !''n''. ;Task The task is to: diff --git a/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements.bbc b/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements.bbc new file mode 100644 index 0000000000..6579260bdb --- /dev/null +++ b/Task/Permutations-Derangements/BBC-BASIC/permutations-derangements.bbc @@ -0,0 +1,75 @@ + PRINT"Derangements for the numbers 0,1,2,3 are:" + Count% = FN_Derangement_Generate(4,TRUE) + + PRINT'"Table of n, counted derangements, calculated derangements :" + + FOR I% = 0 TO 9 + PRINT I%, FN_Derangement_Generate(I%,FALSE), FN_SubFactorial(I%) + NEXT + + PRINT'"There is no long int in BBC BASIC!" + PRINT"!20 = ";FN_SubFactorial(20) + + END + + DEF FN_Derangement_Generate(N%, fPrintOut) + LOCAL A%(), O%(), C%, D%, I%, J% + IF N% = 0 THEN = 1 + DIM A%(N%-1), O%(N%-1) + FOR I% = 0 TO N%-1 : A%(I%) = I% : NEXT + O%() = A%() + FOR I% = 0 TO FN_Factorial(DIM(A%(),1)+1)-1 + PROC_NextPermutation(A%()) + D% = TRUE + FOR J%=0 TO N%-1 + IF A%(J%) = O%(J%) THEN D% = FALSE + NEXT + IF D% THEN + C% += 1 + IF fPrintOut THEN + FOR K% = 0 TO N%-1 + PRINT ;A%(K%);" "; + NEXT + PRINT + ENDIF + ENDIF + NEXT + = C% + + DEF PROC_NextPermutation(A%()) + LOCAL first, last, elementcount, pos + elementcount = DIM(A%(),1) + IF elementcount < 1 THEN ENDPROC + pos = elementcount-1 + WHILE A%(pos) >= A%(pos+1) + pos -= 1 + IF pos < 0 THEN + PROC_Permutation_Reverse(A%(), 0, elementcount) + ENDPROC + ENDIF + ENDWHILE + last = elementcount + WHILE A%(last) <= A%(pos) + last -= 1 + ENDWHILE + SWAP A%(pos), A%(last) + PROC_Permutation_Reverse(A%(), pos+1, elementcount) + ENDPROC + + DEF PROC_Permutation_Reverse(A%(), firstindex, lastindex) + LOCAL first, last + first = firstindex + last = lastindex + WHILE first < last + SWAP A%(first), A%(last) + first += 1 + last -= 1 + ENDWHILE + ENDPROC + + DEF FN_Factorial(N) : IF (N = 1) OR (N = 0) THEN =1 ELSE = N * FN_Factorial(N-1) + + DEF FN_SubFactorial(N) : IF N=0 THEN =1 ELSE =N*FN_SubFactorial(N-1)+-1^N + + REM Or you could use: + REM DEF FN_SubFactorial(N) : IF N<1 THEN =1 ELSE =(N-1)*(FN_SubFactorial(N-1)+FN_SubFactorial(N-2)) diff --git a/Task/Permutations-Derangements/Bracmat/permutations-derangements.bracmat b/Task/Permutations-Derangements/Bracmat/permutations-derangements.bracmat new file mode 100644 index 0000000000..bc39e8fa40 --- /dev/null +++ b/Task/Permutations-Derangements/Bracmat/permutations-derangements.bracmat @@ -0,0 +1,52 @@ +( ( calculated-!n + = memo answ + . (memo==) + & ( !arg:0&1 + | !arg:1&0 + | !(memo.):? (!arg.?answ) ?&!answ + | (!arg+-1) + * (calculated-!n$(!arg+-1)+calculated-!n$(!arg+-2)) + : ?answ + & (!arg.!answ) !(memo.):?(memo.) + & !answ + ) + ) +& ( counted-!n + = p P h H A Z L + . !arg:(%?p ?P.?H.?L) + & !H + : ?A + (%@?h:~!p) + (?Z&counted-!n$(!P.!A !Z.!h !L)) + | !arg:(..?L) + & 1+!count:?count + & (!count.!L) !D:?D + & ~ + ) +& out$"Derangements of 1 2 3 4" +& :?D +& 0:?count +& ( counted-!n$(4 3 2 1.4 3 2 1.) + | out$!D + ) +& ( pad + = len w + . @(!arg:? [?len) + & @(" ":? [!len ?w) + & !w !arg + ) +& :?K +& -1:?N +& out$(str$(N pad$List pad$Calc)) +& whl + ' ( !N+1:<10:?N + & ( 0:?count + & :?D + & counted-!n$(!K.!K.) + | out$(str$(!N pad$!count pad$(calculated-!n$!N))) + ) + & !N !K:?K + ) +& out$("!20 =" calculated-!n$20) +& lst$calculated-!n +) diff --git a/Task/Permutations-Derangements/D/permutations-derangements-1.d b/Task/Permutations-Derangements/D/permutations-derangements-1.d index 7dd0481a71..b55c8781ad 100644 --- a/Task/Permutations-Derangements/D/permutations-derangements-1.d +++ b/Task/Permutations-Derangements/D/permutations-derangements-1.d @@ -1,22 +1,23 @@ -import std.stdio, std.algorithm, std.typecons, std.conv, std.range; +import std.stdio, std.algorithm, std.typecons, std.conv, + std.range, std.traits; -T factorial(T)(in T n) pure nothrow { +T factorial(T)(in T n) pure nothrow @safe @nogc { Unqual!T result = 1; foreach (immutable i; 2 .. n + 1) result *= i; return result; } -T subfact(T)(in T n) pure nothrow { +T subfact(T)(in T n) pure nothrow @safe @nogc { if (0 <= n && n <= 2) return n != 1; return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } auto derangements(in size_t n, in bool countOnly=false) -pure /*nothrow*/ { +pure nothrow @safe { size_t[] seq = n.iota.array; - auto ori = seq.idup; // Not nothrow. + auto ori = seq.idup; size_t[][] all; size_t cnt = n == 0; @@ -44,14 +45,14 @@ pure /*nothrow*/ { if (countOnly) cnt++; else - all ~= seq.dup; // Not nothrow. + all ~= seq.dup; } } return tuple(all, cnt); } -void main() { +void main() @safe { "Derangements for n = 4:".writeln; foreach (const d; 4.derangements[0]) d.writeln; diff --git a/Task/Permutations-Derangements/D/permutations-derangements-2.d b/Task/Permutations-Derangements/D/permutations-derangements-2.d index 165868b0f3..4bf91961ac 100644 --- a/Task/Permutations-Derangements/D/permutations-derangements-2.d +++ b/Task/Permutations-Derangements/D/permutations-derangements-2.d @@ -13,10 +13,10 @@ T subfact(T)(in T n) pure nothrow { return (n - 1) * (subfact(n - 1) + subfact(n - 2)); } -auto derangementsR(in size_t n, in bool countOnly=false) -pure /*nothrow*/ { +auto derangementsR(in size_t n, in bool countOnly=false) pure +/*nothrow*/ { auto seq = n.iota.array; - immutable ori = seq.idup; // Not nothrow. + immutable ori = seq.idup; const(size_t[])[] res; size_t cnt; diff --git a/Task/Permutations-Derangements/Groovy/permutations-derangements-1.groovy b/Task/Permutations-Derangements/Groovy/permutations-derangements-1.groovy index b5c0ba81e0..21a41b8020 100644 --- a/Task/Permutations-Derangements/Groovy/permutations-derangements-1.groovy +++ b/Task/Permutations-Derangements/Groovy/permutations-derangements-1.groovy @@ -4,6 +4,6 @@ subfact = { BigInteger n -> (n == 0) ? 1 : (n == 1) ? 0 : ((n-1) * (subfact(n-1) def derangement = { List l -> def d = [] - l.eachPermutation { p -> if ([p,l].transpose().every{ it[0] != it[1] }) d << p } + if (l) l.eachPermutation { p -> if ([p,l].transpose().every{ pp, ll -> pp != ll }) d << p } d } diff --git a/Task/Permutations-Derangements/PureBasic/permutations-derangements-2.purebasic b/Task/Permutations-Derangements/PureBasic/permutations-derangements-2.purebasic index 73b5f67e78..a5d995d713 100644 --- a/Task/Permutations-Derangements/PureBasic/permutations-derangements-2.purebasic +++ b/Task/Permutations-Derangements/PureBasic/permutations-derangements-2.purebasic @@ -1,57 +1,51 @@ -Procedure.i deranged(depth,lenn,array d(1),show) -Protected count.l,tmp,i - if (depth = lenn) - if (show) - ; for i = 0 to lenn-1:so(chr(d(i) + 'a')):next - for i = 0 to lenn-1:Debug chr(d(i) + 'a'):next - ; cw("") - Debug "" - endif - ProcedureReturn 1 - endif +Procedure.i deranged(depth, lenn, Array d(1), show) + Protected count, tmp, i + If depth = lenn + If show + For i = 0 To lenn - 1: Print(Chr(d(i) + 'a')): Next + PrintN("") + EndIf + ProcedureReturn 1 + EndIf - for i = lenn - 1 to depth step -1 - if i = d(depth) :continue:endif + For i = lenn - 1 To depth Step -1 + If i = d(depth): Continue: EndIf - tmp = d(i): d(i) = d(depth): d(depth) = tmp - count + deranged(depth + 1, lenn, d(), show) - tmp = d(i): d(i) = d(depth): d(depth) = tmp - next + tmp = d(i): d(i) = d(depth): d(depth) = tmp + count + deranged(depth + 1, lenn, d(), show) + tmp = d(i): d(i) = d(depth): d(depth) = tmp + Next -ProcedureReturn count + ProcedureReturn count EndProcedure Procedure.q sub_fact(n) -if n=0:ProcedureReturn 1:endif -if n=1:ProcedureReturn 0:endif -ProcedureReturn (sub_fact(n-1)+sub_fact(n-2))*(n-1) + If n = 0: ProcedureReturn 1: EndIf + If n = 1: ProcedureReturn 0: EndIf + ProcedureReturn (sub_fact(n - 1) + sub_fact(n - 2)) * (n - 1) EndProcedure -Procedure.i gen_n(n,show) -Protected r.i -global dim a(1024) -for i=0 to n-1:a(i)=i:next -ProcedureReturn deranged(0, n, a(), show) +Procedure.i gen_n(n, show) + Protected r.i + Dim a(1024) + For i = 0 To n - 1: a(i) = i: Next + ProcedureReturn deranged(0, n, a(), show) EndProcedure - ; cw("Deranged Four:") - Debug "Deranged Four:" - gen_n(4, 1) - ; cw("") - Debug "" +If OpenConsole() + PrintN("Deranged Four:") + gen_n(4, 1) - ; cw("Compare list vs calc:") - Debug "Compare list vs calc:" - for i = 0 to 9 - ; cw(str(i)+" "+str(gen_n(i, 0))+" "+str(sub_fact(i))) - Debug str(i)+" "+str(gen_n(i, 0))+" "+str(sub_fact(i)) - next - ; cw("") - Debug "" + PrintN(#CRLF$ + "Compare list vs calc:") + For i = 0 To 9 + PrintN(Str(i) + ":" + #TAB$ + Str(gen_n(i, 0)) + #TAB$ + Str(sub_fact(i))) + Next - ; cw("further calc:") - Debug "further calc:" - for i = 10 to 20 - ; cw(str(i)+" "+str(sub_fact(i))) - Debug str(i)+" "+str(sub_fact(i)) - next + PrintN(#CRLF$ + "further calc:") + For i = 10 To 20 + PrintN(Str(i) + ": " + Str(sub_fact(i))) + Next + + Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input() + CloseConsole() +EndIf diff --git a/Task/Permutations-Derangements/REXX/permutations-derangements.rexx b/Task/Permutations-Derangements/REXX/permutations-derangements.rexx index 7d28817bc0..7868f0cc15 100644 --- a/Task/Permutations-Derangements/REXX/permutations-derangements.rexx +++ b/Task/Permutations-Derangements/REXX/permutations-derangements.rexx @@ -37,7 +37,7 @@ return # do j=i+1 while j a - b != 1}) + +def subfactorial(n: Long): Long = n match { + case 0 => 1 + case 1 => 0 + case _ => (n - 1) * (subfactorial(n - 1) + subfactorial(n - 2)) +} + +println(s"Derangements for n = 4") +println(derangements(4) mkString "\n") + +println("\n%2s%10s%10s".format("n", "derange", "subfact")) +(0 to 9).foreach(n => println("%2d%10d%10d".format(n, derangements(n).size, subfactorial(n)))) +(10 to 20).foreach(n => println(f"$n%2d${subfactorial(n)}%20d")) diff --git a/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp index 04c019c948..d51f677e4b 100644 --- a/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp +++ b/Task/Permutations-by-swapping/C++/permutations-by-swapping.cpp @@ -1,167 +1,121 @@ /* - 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 +The following code generates the permutations of the first 4 natural numbers. +The permutations are displayed in lexical order, smallest to largest, with appropriate signs */ -#include -#include -using namespace std; +#include +#include -//Function to calculate the factorial of a number -long int fact(int size) +//factorial function +long +fact(int size) { int i; - long int temp =1; + long tmp = 1; - if (size<=1) - { + if(size<=1) return 1; - } else - { - for(i=size;i>0;i--) - temp*=i; - } - - return temp; - + for(i = size;i > 0;i--) + tmp *= i; + return tmp; } -//Function to display the permutations. -void Permutations(int N) +//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; + //indicates sign + short sign = 1; - //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]; + //Tracks when to change sign. + unsigned short change_sign = 0; - //Index for Index_Nos_ptr - int *Element_Num = new int[N]; - + //loop variables + short i = 0,j = 0,k = 0; - //Initialization - for(i=0;i0) - { - - Loops--; - - cout<<"Perm: ["; - for(i=0;i 0){ + std::cout << "Perm: ["; + for(i = 0;i < N;i++){ //Print from MSD to LSD - cout<<" "<<*(Index_Nos_ptr[i] + Element_Num[i]); - + std::cout << " " << *(Index_Nos_ptr[i] + Element_Num[i]); + //Decrement the repetition count for each digit - Digit_Rep_Local[i]--; - - //If repetition count has reached 0... - if(Digit_Rep_Local[i] <=0 ) - { - + if(--Digit_Rep_Local[i] <= 0){ //Refill the repitition factor Digit_Rep_Local[i] = Digit_Rep_Master[i]; - - //And the index to access the required digit is also 0... - if(Element_Num[i] <=0 && i!=0) - { - - //Reset the index - Element_Num[i] = N-i-1; - - //Update the numbers held un Index_Nos_ptr[] - for(j=0,k=0;j<=N-i;j++) - { - //Exclude the preceeding digit(from the previous array) already printed. - if(j!=Element_Num[i-1]) - { + //And the index to access the required digit is also 0... + if(Element_Num[i] <= 0 && i != 0){ + //Reset the index + Element_Num[i] = N-i-1; + + //Update the numbers held in Index_Nos_ptr[] + for(j = 0,k = 0;j <= N-i;j++){ + //Exclude the preceeding digit (from the previous array) already printed. + if(j != Element_Num[i-1]){ *(Index_Nos_ptr[i]+k)= *(Index_Nos_ptr[i-1]+j); k++; } } - } - //If the index is not 0... - else - { + }else //Decrement the index value so as to print the appropriate digit //in the same array Element_Num[i]--; - - }//end of if-else - - }//end of if() - - }//end of for() - - //Print the sign. - cout<<"] Sign: "< 0) - { - Toggle_Flag_Change_Condition--; + } } - else - { + std::cout<<"] Sign: "<< sign <<"\n"; + + if(!(change_sign-- > 0)){ //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() + sign = -sign; -}//end of Permutations() + change_sign = 1; + } -int main() + } + +} + +int +main() { - Permutations(4); - getch(); + 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 10ed3ad817..5926326d8a 100644 --- a/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d +++ b/Task/Permutations-by-swapping/D/permutations-by-swapping-1.d @@ -4,7 +4,7 @@ struct Spermutations(bool doCopy=true) { private immutable uint n; alias TResult = Tuple!(int[], int); - int opApply(in int delegate(in ref TResult) dg) { + int opApply(in int delegate(in ref TResult) nothrow dg) nothrow { int result; int sign = 1; @@ -18,18 +18,16 @@ struct Spermutations(bool doCopy=true) { if (result) goto END; - while (p.canFind!q{ a[1] }) { + while (p.any!q{ a[1] }) { // Failed to use std.algorithm here, too much complex. auto largest = Int2(-100, -100); int i1 = -1; - foreach (immutable i, immutable pi; p) { - if (pi[1]) { + foreach (immutable i, immutable pi; p) + if (pi[1]) if (pi[0] > largest[0]) { i1 = i; largest = pi; } - } - } immutable n1 = largest[0], d1 = largest[1]; 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 27b651a200..8cef033155 100644 --- a/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d +++ b/Task/Permutations-by-swapping/D/permutations-by-swapping-2.d @@ -1,30 +1,33 @@ import std.algorithm, std.array, std.typecons, std.range; -auto sPermutations(in int n) /*pure nothrow*/ { - static int[][] sPermu(in int items) /*pure nothrow*/ { +auto sPermutations(in uint n) pure nothrow @safe { + static immutable(int[])[] inner(in int items) pure nothrow @safe { if (items <= 0) return [[]]; typeof(return) r; - foreach (immutable i, item; sPermu(items - 1)) { - //r.put((i % 2 ? iota(cast(int)item.length, -1, -1) : + foreach (immutable i, immutable item; inner(items - 1)) { + //r.put((i % 2 ? iota(item.length.signed, -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..$]; + // .map!(i => item[0 .. i] ~ (items - 1) ~ item[i .. $])); + immutable f = (in size_t i) pure nothrow @safe => + item[0 .. i] ~ (items - 1) ~ item[i .. $]; r ~= (i % 2) ? - iota(cast(int)item.length, -1, -1).map!f.array : + //iota(item.length.signed, -1, -1).map!f.array : + iota(item.length + 1).retro.map!f.array : iota(item.length + 1).map!f.array; } return r; } - return sPermu(n).zip([1, -1].cycle); + return inner(n).zip([1, -1].cycle); } void main() { import std.stdio; - foreach (immutable n; [3, 4]) { - writefln("\nPermutations and sign of %d items", n); - foreach (const tp; n.sPermutations) - writefln("Perm: %s Sign: %2d", tp[]); + foreach (immutable n; [2, 3, 4]) { + writefln("Permutations and sign of %d items:", n); + foreach (immutable tp; n.sPermutations) + writefln(" %s Sign: %2d", tp[]); + writeln; } } diff --git a/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs b/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs index f5913a4a54..b41b838184 100644 --- a/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs +++ b/Task/Permutations-by-swapping/Haskell/permutations-by-swapping.hs @@ -1,14 +1,10 @@ -insertEverywhere :: a -> [a] -> [[a]] -insertEverywhere x [] = [[x]] -insertEverywhere x l@(y:ys) = (x:l) : map (y:) (insertEverywhere x ys) - -s_perm :: [a] -> [[a]] -s_perm = foldl aux [[]] - where aux items x = do (f, item) <- zip (cycle [reverse, id]) items - f (insertEverywhere x item) - s_permutations :: [a] -> [([a], Int)] -s_permutations = flip zip (cycle [1, -1]) . s_perm +s_permutations = flip zip (cycle [1, -1]) . (foldl aux [[]]) + where aux items x = do + (f,item) <- zip (cycle [reverse,id]) items + f (insertEv x item) + insertEv x [] = [[x]] + insertEv x l@(y:ys) = (x:l) : map (y:) $ insertEv x ys main :: IO () main = do diff --git a/Task/Permutations-by-swapping/Icon/permutations-by-swapping.icon b/Task/Permutations-by-swapping/Icon/permutations-by-swapping.icon new file mode 100644 index 0000000000..b9b6dee145 --- /dev/null +++ b/Task/Permutations-by-swapping/Icon/permutations-by-swapping.icon @@ -0,0 +1,30 @@ +procedure main(A) + every write("Permutations of length ",n := !A) do + every p := permute(n) do write("\t",showList(p[1])," -> ",right(p[2],2)) +end + +procedure permute(n) + items := [[]] + every (j := 1 to n, new_items := []) do { + every item := items[i := 1 to *items] do { + if *item = 0 then put(new_items, [j]) + else if i%2 = 0 then + every k := 1 to *item+1 do { + new_item := item[1:k] ||| [j] ||| item[k:0] + put(new_items, new_item) + } + else + every k := *item+1 to 1 by -1 do { + new_item := item[1:k] ||| [j] ||| item[k:0] + put(new_items, new_item) + } + } + items := new_items + } + suspend (i := 0, [!items, if (i+:=1)%2 = 0 then 1 else -1]) +end + +procedure showList(A) + every (s := "[") ||:= image(!A)||", " + return s[1:-2]||"]" +end diff --git a/Task/Permutations-by-swapping/PicoLisp/permutations-by-swapping.l b/Task/Permutations-by-swapping/PicoLisp/permutations-by-swapping.l new file mode 100644 index 0000000000..1636cad5aa --- /dev/null +++ b/Task/Permutations-by-swapping/PicoLisp/permutations-by-swapping.l @@ -0,0 +1,42 @@ +(let + (N 4 + L + (mapcar + '((I) (list I 0)) + (range 1 N) ) ) + (for I L + (printsp (car I)) ) + (prinl) + (while + # find the lagest mobile integer + (setq + X + (maxi + '((I) (car (get L (car I)))) + (extract + '((I J) + (let? Y + (get + L + ((if (=0 (cadr I)) dec inc) J) ) + (when (> (car I) (car Y)) + (list J (cadr I)) ) ) ) + L + (range 1 N) ) ) + Y (get L (car X)) ) + # swap integer and adjacent int it is looking at + (xchg + (nth L (car X)) + (nth + L + ((if (=0 (cadr X)) dec inc) (car X)) ) ) + # reverse direction of all ints large than our + (for I L + (when (< (car Y) (car I)) + (set (cdr I) + (if (=0 (cadr I)) 1 0) ) ) ) + # print current positions + (for I L + (printsp (car I)) ) + (prinl) ) ) +(bye) diff --git a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx index 6e9dc53c17..880fbdf3be 100644 --- a/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx +++ b/Task/Permutations-by-swapping/REXX/permutations-by-swapping.rexx @@ -1,37 +1,37 @@ /*REXX pgm generates all permutations of N different objects by swapping*/ -parse arg things bunch inbetween names /*get optional C.L. args*/ -if things=='' | things==',' then things=4 /*use the default? */ -if bunch =='' | bunch ==',' then bunch =things /* " " " */ - /* ┌────────────────────────────────────────────────────────────────┐ - │ things (optional) defaults to 4. │ - │ bunch (optional) defaults to THINGS. │ - │ inbetween (optional) defaults to a [null]. │ - │ names (optional) defaults to digits (and letters). │ - └────────────────────────────────────────────────────────────────┘ */ +parse arg things bunch inbetween names /*get optional arguments from CL.*/ +things=p(things 4) /*use the default for THINGS ? */ +bunch =p(bunch things) /* " " " " BUNCH ? */ + /*╔════════════════════════════════════════════════════════════════╗ + ║ things (optional) defaults to 4. ║ + ║ bunch (optional) defaults to THINGS. ║ + ║ inbetween (optional) defaults to a [null]. ║ + ║ names (optional) defaults to digits (and letters). ║ + ╚════════════════════════════════════════════════════════════════╝*/ upper inbetween; if inbetween=='NONE' | inbetween="NULL" then inbetween= call permSets things, bunch, inbetween, names exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────! {factorial} subroutine────────────*/ -!: procedure; parse arg x; !=1; do j=2 to x; !=!*j; end; return ! +/*──────────────────────────────────one─liner subrlutines───────────────*/ +!: procedure; !=1; do j=2 to arg(1); !=!*j; end; return ! +p: return word(arg(1), 1) /*pick the first word from a list*/ /*──────────────────────────────────GETONE subroutine───────────────────*/ -getOne: if length(z)==y then return substr(z,arg(1),1) - else return sep||word(translate(z,,','),arg(1) ) -/*──────────────────────────────────P subroutine (Pick one)─────────────*/ -p: return word(arg(1),1) +getOne: if length(z)==y then return substr(z,arg(1),1) + else return sep||word(translate(z,,','), arg(1)) /*──────────────────────────────────PERMSETS subroutine─────────────────*/ permSets: procedure; parse arg x,y,between,uSyms /*X things Y at a time.*/ -sep=; !.=0 /*X can't be > length(@0abcs). */ -@abc = 'abcdefghijklmnopqrstuvwxyz'; parse upper var @abc @abcU -@abcS= @abcU || @abc; @0abcS=123456789 || @abcS -z= +sep=; !.=0 /*X can't be > length(@0abcs). */ +@abc = 'abcdefghijklmnopqrstuvwxyz'; parse upper var @abc @abcU +@abcS= @abcU || @abc; @0abcS=123456789 || @abcS +z= /*set Z to a null value. */ do i=1 for x /*build a list of (perm) symbols.*/ _=p(word(uSyms,i) p(substr(@0abcS,i,1) k)) /*get or gen a symbol.*/ - if length(_)\==1 then sep=',' /*if not 1st char, then use sep. */ + if length(_)\==1 then sep=',' /*if not 1st char, then use SEP. */ z=z || sep || _ /*append it to the symbol list. */ end /*i*/ - -if sep\=='' then z=strip(z,'L', ",") -!.z=1; #=1; times=!(x)%!(x-y); q=z; s=1; w=max(length(z),length('permute')) +#=1 +if sep\=='' then z=strip(z, 'L', ",") /*strip leading commas from Z. */ +!.z=1; q=z; s=1; times=!(x)%!(x-y) /*calculate TIMES using factorial*/ +w=max(length(z),length('permute')) /*maximum width of Z and PERMUTE.*/ say center('permutations for ' x ' with ' y "at a time",60,'═') say say 'permutation' center("permute",w,'─') 'sign' diff --git a/Task/Permutations/D/permutations-2.d b/Task/Permutations/D/permutations-2.d index 0735f6e9c0..10d5f46b41 100644 --- a/Task/Permutations/D/permutations-2.d +++ b/Task/Permutations/D/permutations-2.d @@ -6,41 +6,46 @@ struct Permutations(bool doCopy=true, T) if (isMutable!T) { private uint[31] indexes; private ulong tot; - this (in T[] items) pure /*nothrow*/ + this (T[] items) pure nothrow @safe @nogc in { - static enum string L = text(indexes.length); // impure + static enum string L = indexes.length.text; assert(items.length >= 0 && items.length <= indexes.length, "Permutations: items.length must be >= 0 && < " ~ L); } body { - static ulong factorial(in uint n) pure nothrow { + static ulong factorial(in size_t n) pure nothrow @safe @nogc { ulong result = 1; - foreach (i; 2 .. n + 1) + foreach (immutable i; 2 .. n + 1) result *= i; return result; } this.num = items.length; - this.items = items.dup; - foreach (i; 0 .. cast(typeof(indexes[0]))this.num) + this.items = items; + foreach (immutable i; 0 .. cast(typeof(indexes[0]))this.num) this.indexes[i] = i; this.tot = factorial(this.num); } - @property T[] front() pure nothrow { + @property T[] front() pure nothrow @safe { static if (doCopy) { - //return items.dup; // Not nothrow. - auto items2 = new T[items.length]; - items2[] = items[]; - return items2; + return items.dup; } else return items; } - @property bool empty() const pure nothrow { + @property bool empty() const pure nothrow @safe @nogc { return tot == 0; } - void popFront() pure nothrow { + @property size_t length() const pure nothrow @safe @nogc { + // Not cached to keep the function pure. + typeof(return) result = 1; + foreach (immutable x; 1 .. items.length + 1) + result *= x; + return result; + } + + void popFront() pure nothrow @safe @nogc { tot--; if (tot > 0) { size_t j = num - 2; @@ -66,8 +71,8 @@ struct Permutations(bool doCopy=true, T) if (isMutable!T) { } Permutations!(doCopy,T) permutations(bool doCopy=true, T) - (in T[] items) -pure /*nothrow*/ if (isMutable!T) { + (T[] items) +pure nothrow if (isMutable!T) { return Permutations!(doCopy, T)(items); } diff --git a/Task/Permutations/D/permutations-3.d b/Task/Permutations/D/permutations-3.d index a799b7c060..496fbb2453 100644 --- a/Task/Permutations/D/permutations-3.d +++ b/Task/Permutations/D/permutations-3.d @@ -1,8 +1,8 @@ -import std.stdio, std.algorithm; - void main() { + import std.stdio, std.algorithm; + auto items = [1, 2, 3]; do - writeln(items); - while (items.nextPermutation()); + items.writeln; + while (items.nextPermutation); } diff --git a/Task/Permutations/Eiffel/permutations.e b/Task/Permutations/Eiffel/permutations.e new file mode 100644 index 0000000000..f944ecd054 --- /dev/null +++ b/Task/Permutations/Eiffel/permutations.e @@ -0,0 +1,34 @@ +permute(a: ARRAY[INTEGER]; k: INTEGER) + require + ar_not_void: a.count>=1 + k_valid_index: k>0 + local + i,t: INTEGER + do + if k=a.count then + across a as ar loop io.put_string (ar.item.out) end + io.put_string ("%N") + else + from + i:= k + until + i> a.count + loop + t:= a[k] + a[k]:= a[i] + a[i]:= t + permute(a,k+1) + t:= a[k] + a[k]:= a[i] + a[i]:= t + i:= i+1 + end + end +make + do + test:= << 2,5,1>> + permute(test, 1) + end + test: ARRAY[INTEGER] + +end diff --git a/Task/Permutations/Lua/permutations.lua b/Task/Permutations/Lua/permutations-1.lua similarity index 100% rename from Task/Permutations/Lua/permutations.lua rename to Task/Permutations/Lua/permutations-1.lua diff --git a/Task/Permutations/Lua/permutations-2.lua b/Task/Permutations/Lua/permutations-2.lua new file mode 100644 index 0000000000..53800262fd --- /dev/null +++ b/Task/Permutations/Lua/permutations-2.lua @@ -0,0 +1,31 @@ +-- Iterative version +function ipermutations(a,b) + if a==0 then return end + local taken = {} local slots = {} + for i=1,a do slots[i]=0 end + for i=1,b do taken[i]=false end + local index = 1 + while index > 0 do repeat + repeat slots[index] = slots[index] + 1 + until slots[index] > b or not taken[slots[index]] + if slots[index] > b then + slots[index] = 0 + index = index - 1 + if index > 0 then + taken[slots[index]] = false + end + break + else + taken[slots[index]] = true + end + if index == a then + for i=1,a do io.write(slots[i]) io.write(" ") end + io.write("\n") + taken[slots[index]] = false + break + end + index = index + 1 + until true end +end + +ipermutations(3, 3) diff --git a/Task/Permutations/Perl/permutations-1.pl b/Task/Permutations/Perl/permutations-1.pl new file mode 100644 index 0000000000..d55ec91345 --- /dev/null +++ b/Task/Permutations/Perl/permutations-1.pl @@ -0,0 +1,5 @@ +use ntheory qw/forperm/; +my @tasks = (qw/party sleep study/); +forperm { + print "@tasks[@_]\n"; +} scalar(@tasks); diff --git a/Task/Permutations/Perl/permutations-2.pl b/Task/Permutations/Perl/permutations-2.pl new file mode 100644 index 0000000000..929d45cf29 --- /dev/null +++ b/Task/Permutations/Perl/permutations-2.pl @@ -0,0 +1,7 @@ +sub permutation { + my ($perm,@set) = @_; + print "$perm\n" || return unless (@set); + permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0..$#set); +} +my @input = (qw/a 2 c 4/); +permutation('',@input); diff --git a/Task/Permutations/Perl/permutations.pl b/Task/Permutations/Perl/permutations.pl deleted file mode 100644 index f8b8ea4319..0000000000 --- a/Task/Permutations/Perl/permutations.pl +++ /dev/null @@ -1,8 +0,0 @@ -# quick and dirty recursion -sub permutation(){ - my ($perm,@set) = @_; - print "$perm\n" || return unless (@set); - &permutation($perm.$set[$_],@set[0..$_-1],@set[$_+1..$#set]) foreach (0..$#set); -} -@input = (a,2,c,4); -&permutation('',@input); diff --git a/Task/Permutations/REXX/permutations-1.rexx b/Task/Permutations/REXX/permutations-1.rexx index 32dd4842db..22429954f1 100644 --- a/Task/Permutations/REXX/permutations-1.rexx +++ b/Task/Permutations/REXX/permutations-1.rexx @@ -16,16 +16,15 @@ permSets: procedure; parse arg x,y,between,uSyms /*X things Y at a time.*/ 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. */ + if length(_)\==1 then sep='_' /*if not 1st char, then use sep.*/ $.k=_ /*append it to the symbol list. */ - end + end /*k*/ if between=='' then between=sep /*use the appropriate separator. */ -list='$. @. between x y' -call .permset 1 +call .permset 1 /*start with the first permuation*/ return /*──────────────────────────────────.PERMSET subroutine─────────────────*/ -.permset: procedure expose (list); parse arg ? +.permset: procedure expose $. @. between x y; 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*/ diff --git a/Task/Permutations/SAS/permutations.sas b/Task/Permutations/SAS/permutations.sas index 5d0ae588b2..2b0439cbbd 100644 --- a/Task/Permutations/SAS/permutations.sas +++ b/Task/Permutations/SAS/permutations.sas @@ -1,42 +1,42 @@ /* Store permutations in a SAS dataset. Translation of Fortran 77 */ data perm; -n=6; -array a{6} p1-p6; -do i=1 to n; -a(i)=i; -end; + n=6; + array a{6} p1-p6; + do i=1 to n; + a(i)=i; + end; L1: -output; -link L2; -if next then goto L1; -stop; + output; + link L2; + if next then goto L1; + stop; L2: -next=0; -i=n-1; + next=0; + i=n-1; L10: -if a(i) len then + i := len; + result := 0; + repeat {Work backwards} + x := 10*a[i] + result*i; + result := x div (2*i - 1); + a[i] := x - result*(2*i - 1);//x mod (2*i - 1) + dec(i); + until i<= 0 ; +end; begin + for j := 1 to len do a[j] := 2; {Start with 2s} nines := 0; predigit := 0; {First predigit is a 0} + for j := 1 to n do begin - q := 0; - for i := len downto 1 do {Work backwards} - begin - x := 10*a[i] + q*i; - a[i] := x mod (2*i - 1); - q := x div (2*i - 1); - end; + q := OneLoop(n-j); a[1] := q mod 10; q := q div 10; if q = 9 then @@ -29,22 +42,22 @@ begin else if q = 10 then begin - write(predigit+1); - for k := 1 to nines do - write(0); {zeros} - predigit := 0; - nines := 0 + write(predigit+1); + for k := 1 to nines do + write(0); {zeros} + predigit := 0; + nines := 0 end else begin - write(predigit); - predigit := q; - if nines <> 0 then - begin - for k := 1 to nines do - write(9); - nines := 0 - end + write(predigit); + predigit := q; + if nines <> 0 then + begin + for k := 1 to nines do + write(9); + nines := 0 + end end end; writeln(predigit); diff --git a/Task/Pi/Perl/pi-1.pl b/Task/Pi/Perl/pi-1.pl index 6f874662da..f41340e39e 100644 --- a/Task/Pi/Perl/pi-1.pl +++ b/Task/Pi/Perl/pi-1.pl @@ -1,44 +1,41 @@ -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 pistream { + my $digits = shift; + my(@out, @a); + my($b, $c, $d, $e, $f, $g, $i, $d4, $d3, $d2, $d1); + my $outi = 0; + + $digits++; + $b = $d = $e = $g = $i = 0; + $f = 10000; + $c = 14 * (int($digits/4)+2); + @a = (20000000) x $c; + print "3."; + while (($b = $c -= 14) > 0 && $i < $digits) { + $d = $e = $d % $f; + while (--$b > 0) { + $d = $d * $b + $a[$b]; + $g = ($b << 1) - 1; + $a[$b] = ($d % $g) * $f; + $d = int($d / $g); } + $d4 = $e + int($d/$f); + if ($d4 > 9999) { + $d4 -= 10000; + $out[$i-1]++; + for ($b = $i-1; $out[$b] == 1; $b--) { + $out[$b] = 0; + $out[$b-1]++; + } + } + $d3 = int($d4/10); + $d2 = int($d3/10); + $d1 = int($d2/10); + $out[$i++] = $d1; + $out[$i++] = $d2-$d1*10; + $out[$i++] = $d3-$d2*10; + $out[$i++] = $d4-$d3*10; + print join "", @out[$i-15 .. $i-15+3] if $i >= 16; + } + # We've closed the spigot. Print the remainder without rounding. + print join "", @out[$i-15+4 .. $digits-2], "\n"; } - -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 index e70eb209e5..3dc1945690 100644 --- a/Task/Pi/Perl/pi-2.pl +++ b/Task/Pi/Perl/pi-2.pl @@ -1,55 +1,44 @@ -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; +use bigint try=>"GMP"; +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->()); + } + } + } } -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; - } +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-3.pl b/Task/Pi/Perl/pi-3.pl new file mode 100644 index 0000000000..57b9ddf467 --- /dev/null +++ b/Task/Pi/Perl/pi-3.pl @@ -0,0 +1,54 @@ +use bigint try=>"GMP" + +# 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/Pi/Perl/pi-4.pl b/Task/Pi/Perl/pi-4.pl new file mode 100644 index 0000000000..ccbf582689 --- /dev/null +++ b/Task/Pi/Perl/pi-4.pl @@ -0,0 +1,18 @@ +use ntheory qw/Pi/; +say Pi(10000); + +use Math::Pari qw/setprecision Pi/; +setprecision(10000); +say Pi; + +use Math::MPFR; +my $pi = Math::MPFR->new(); +Math::MPFR::Rmpfr_set_prec($pi, int(10000 * 3.322)+40); +Math::MPFR::Rmpfr_const_pi($pi, 0); +say Math::MPFR::Rmpfr_get_str($pi, 10, 10000, 0); + +use Math::BigFloat try=>"GMP"; # Slow without Math::BigInt::GMP installed +say Math::BigFloat::bpi(10000); # For over ~2k digits, slower than AGM + +use Math::Big qw/pi/; # Very slow +say pi(10000); diff --git a/Task/Pi/Racket/pi-1.rkt b/Task/Pi/Racket/pi-1.rkt new file mode 100644 index 0000000000..7427e6e837 --- /dev/null +++ b/Task/Pi/Racket/pi-1.rkt @@ -0,0 +1,19 @@ +#lang racket +(require racket/generator) + +(define pidig + (generator () + (let loop ([q 1] [r 0] [t 1] [k 1] [n 3] [l 3]) + (if (< (- (+ r (* 4 q)) t) (* n t)) + (begin (yield n) + (loop (* q 10) (* 10 (- r (* n t))) t k + (- (quotient (* 10 (+ (* 3 q) r)) t) (* 10 n)) + l)) + (loop (* q k) (* (+ (* 2 q) r) l) (* t l) (+ 1 k) + (quotient (+ (* (+ 2 (* 7 k)) q) (* r l)) (* t l)) + (+ l 2)))))) + +(for ([i (in-naturals)]) + (display (pidig)) + (when (zero? i) (display "." )) + (when (zero? (modulo i 80)) (newline))) diff --git a/Task/Pi/Racket/pi-2.rkt b/Task/Pi/Racket/pi-2.rkt new file mode 100644 index 0000000000..10779b682b --- /dev/null +++ b/Task/Pi/Racket/pi-2.rkt @@ -0,0 +1 @@ +3.14159265358979323846264338327950288419716939937510... diff --git a/Task/Pi/Racket/pi.rkt b/Task/Pi/Racket/pi.rkt deleted file mode 100644 index 231c361ab3..0000000000 --- a/Task/Pi/Racket/pi.rkt +++ /dev/null @@ -1,4 +0,0 @@ -#lang racket -(require math/bigfloat) -(bf-precision (exact-floor (/ (* 200 (log 10)) (log 2)))) -pi.bf diff --git a/Task/Pick-random-element/00META.yaml b/Task/Pick-random-element/00META.yaml index 659c8686af..fe8c9b44b7 100644 --- a/Task/Pick-random-element/00META.yaml +++ b/Task/Pick-random-element/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Randomness note: Basic language learning diff --git a/Task/Pick-random-element/ALGOL-68/pick-random-element.alg b/Task/Pick-random-element/ALGOL-68/pick-random-element.alg new file mode 100644 index 0000000000..f779a5caec --- /dev/null +++ b/Task/Pick-random-element/ALGOL-68/pick-random-element.alg @@ -0,0 +1,23 @@ +# pick a random element from an array of strings # + +OP PICKRANDOM = ( []STRING list )STRING: +BEGIN + + INT number of elements = ( UPB list - LWB list ) + 1; + INT random element = + ENTIER ( next random * ( number of elements ) ); + + list[ LWB list + random element ] +END; # PICKRANDOM # +# can define additional operators for other types of array # + + +main: ( + + []STRING days = ( "Sunday", "Monday", "Tuesday", "Wednesday" + , "Thursday", "Friday", "Saturday" + ); + + print( ( PICKRANDOM days, newline ) ) + +) diff --git a/Task/Pick-random-element/C-sharp/pick-random-element.cs b/Task/Pick-random-element/C-sharp/pick-random-element.cs new file mode 100644 index 0000000000..9a41ed24eb --- /dev/null +++ b/Task/Pick-random-element/C-sharp/pick-random-element.cs @@ -0,0 +1,11 @@ +using System; +using System.Collections.Generic; + +class RandomElementPicker { + static void Main() { + var list = new List(new[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}); + var rng = new Random(); + var randomElement = list[rng.Next(list.Count)]; + Console.WriteLine("I picked element {0}", randomElement); + } +} diff --git a/Task/Pick-random-element/Elixir/pick-random-element.elixir b/Task/Pick-random-element/Elixir/pick-random-element.elixir new file mode 100644 index 0000000000..2b1d1b66f0 --- /dev/null +++ b/Task/Pick-random-element/Elixir/pick-random-element.elixir @@ -0,0 +1,11 @@ +defmodule Random do + def init() do + :random.seed(:erlang.now()) + end + def pick_element(list) do + Enum.at(list, :random.uniform(Enum.count(list)) - 1) + end +end + +Random.init() +IO.puts Random.pick_element(1..20) diff --git a/Task/Pick-random-element/Erlang/pick-random-element.erl b/Task/Pick-random-element/Erlang/pick-random-element.erl index 6f53d5062f..4917e70998 100644 --- a/Task/Pick-random-element/Erlang/pick-random-element.erl +++ b/Task/Pick-random-element/Erlang/pick-random-element.erl @@ -4,5 +4,5 @@ main() -> List =[1,2,3,4,5], - index = random:uniform(length(List)), - lists:nth(index,List). + Index = random:uniform(length(List)), + lists:nth(Index,List). diff --git a/Task/Pick-random-element/Falcon/pick-random-element.falcon b/Task/Pick-random-element/Falcon/pick-random-element.falcon new file mode 100644 index 0000000000..16addee385 --- /dev/null +++ b/Task/Pick-random-element/Falcon/pick-random-element.falcon @@ -0,0 +1,2 @@ +lst = [1, 3, 5, 8, 10] +> randomPick(lst) diff --git a/Task/Pick-random-element/Haskell/pick-random-element-3.hs b/Task/Pick-random-element/Haskell/pick-random-element-3.hs new file mode 100644 index 0000000000..d2fe54c046 --- /dev/null +++ b/Task/Pick-random-element/Haskell/pick-random-element-3.hs @@ -0,0 +1,3 @@ +import Test.QuickCheck (generate, elements) + +x <- (generate . elements) [1, 2, 3] diff --git a/Task/Pick-random-element/Maxima/pick-random-element.maxima b/Task/Pick-random-element/Maxima/pick-random-element.maxima new file mode 100644 index 0000000000..806fda4680 --- /dev/null +++ b/Task/Pick-random-element/Maxima/pick-random-element.maxima @@ -0,0 +1,4 @@ +random_element(l):= part(l, 1+random(length(l))); +/* (%i1) random_element(['a, 'b, 'c]); + (%o1) c +*/ diff --git a/Task/Pick-random-element/Prolog/pick-random-element.pro b/Task/Pick-random-element/Prolog/pick-random-element.pro new file mode 100644 index 0000000000..49f3b55652 --- /dev/null +++ b/Task/Pick-random-element/Prolog/pick-random-element.pro @@ -0,0 +1,2 @@ +?- random_member(M, [a, b, c, d, e, f, g, h, i, j]). +M = i. diff --git a/Task/Pick-random-element/Scala/pick-random-element.scala b/Task/Pick-random-element/Scala/pick-random-element.scala new file mode 100644 index 0000000000..ffcd1f96a7 --- /dev/null +++ b/Task/Pick-random-element/Scala/pick-random-element.scala @@ -0,0 +1,3 @@ +val a = (1 to 10).toList + +println(scala.util.Random.shuffle(a).head) diff --git a/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk b/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk index edfc79ef74..865fab047a 100644 --- a/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk +++ b/Task/Pig-the-dice-game-Player/AutoHotkey/pig-the-dice-game-player.ahk @@ -67,7 +67,6 @@ Practical(TurnSum, SumMe, SumOpp, N=72) { Return Roll := SumOpp > N or SumMe > N or TurnSum < 21+(SumOpp-SumMe)/8 } ; Optimal play per http://cs.gettysburg.edu/~tneller/nsf/pig/pig.pdf -; Requires additional file from [[Pig the dice game/Player/AutoHotkey]] Optimal(TurnSum, SumMe, SumOpp) { Global Optimal Roll := Optimal[SumMe,TurnSum,SumOpp+1] diff --git a/Task/Pig-the-dice-game-Player/REXX/pig-the-dice-game-player.rexx b/Task/Pig-the-dice-game-Player/REXX/pig-the-dice-game-player.rexx index 83cf5fa485..de88bbc62a 100644 --- a/Task/Pig-the-dice-game-Player/REXX/pig-the-dice-game-player.rexx +++ b/Task/Pig-the-dice-game-Player/REXX/pig-the-dice-game-player.rexx @@ -1,54 +1,60 @@ -/*REXX program plays pig (the dice game) with at least one human player.*/ +/*REXX program plays pig the dice game (any # of CBLFs and/or silicons).*/ signal on syntax; signal on novalue /*handle REXX program errors. */ -sw=80-1 /*the LINESIZE bif would be nicer*/ +sw=linesize()-1 /*get the width of the terminal. */ parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments.*/ + /*names with blanks should use _ */ if _\=='' then call err 'too many arguments were specified: ' _ -@nhp = 'number of human players' ; hp = scrutinize( hp, @nhp ,0, 0) -@ncp = 'number of computer players'; cp = scrutinize( cp, @ncp ,0, 0) -@sn2w = 'score needed to win' ; win = scrutinize(win, @sn2w ,1,100) -@nsid = 'number of sides in die' ; die = scrutinize(die, @nsid ,2, 6) +@nhp = 'number of human players' ; hp =scrutinize( hp,@nhp , 0, 0, 0) +@ncp = 'number of computer players'; cp =scrutinize( cp,@ncp , 0, 0, 2) +@sn2w = 'score needed to win' ; win=scrutinize(win,@sn2w, 1,1e6,60) +@nsid = 'number of sides in die' ; die=scrutinize(die,@nsid, 2,999, 6) if hp==0 & cp==0 then cp=2 /*if both counts are zero, 2 HALs*/ if hp==1 & cp==0 then cp=1 /*if one human, then use 1 HAL.*/ +name.= /*nullify all names (to a blank).*/ L=0 /*maximum length of a player name*/ do i=1 for hp+cp /*get the player's names, maybe. */ if i>hp then @='HAL_'i"_the_computer" /*use this for default.*/ else @='player_'i /* " " " " */ name.i = translate( word( strip( word(names,i)) @, 1),,'_') L=max(L, length(name.i)) /*use L for nice name formatting.*/ - end /*i*/ /*underscores are changed─�blanks*/ + end /*i*/ /*underscores are changed─►blanks*/ hpn=hp; if hpn==0 then hpn='no' /*use normal English for display.*/ cpn=cp; if cpn==0 then cpn="no" /* " " " " " */ -say 'Pig (the dice game) is being played with' +say 'Pig (the dice game) is being played with:' /*introduction to pig.*/ if cpn\==0 then say right(cpn,9) 'computer player's(cp) if hpn\==0 then say right(hpn,9) 'human player's(hp) say 'and the' @sn2w "is: " win ' (or greater).' -!.=; dieNames='ace duece trey square nickle boxcar' /*die face names.*/ +!.=; dieNames='ace deuce trey square nickle boxcar' /*die face names.*/ /*note: snake eyes is for 2 aces.*/ - do i=1 for 6; !.i=' ['word(dieNames,i)"] "; end /*i*/ +!w=0; do i=1 for die; !.i=' ['word(dieNames,i)"]" + !w=max(!w, length(!.i)) /*!w ──► maximum length die name.*/ + end /*i*/ s.=0 /*set all player's scores to zero*/ +!w=!w+length(die)+3 /*pad the die number and die name*/ @=copies('─',9) /*an eyecatcher (for prompting). */ -@jra='just rolled a '; @ati=', and the inning' /*nice literals to have.*/ +@jra='just rolled a '; @ati='and the inning' /*nice literals to have.*/ /*──────────────────────────────────────────────────let's play some pig.*/ do game=1; in.=0 /*set each inning's score to zero*/ say; say copies('█',sw) /*display a fence for da eyeballs*/ - do k=1 for hp+cp /*display the scores (as a recap)*/ - say 'The score for' left(name.k,L) "is " right(s.k,length(win))'.' - end /*k*/ + do k=1 for hp+cp /*display the scores (as a recap)*/ + say 'The score for ' left(name.k,L) " is " right(s.k,length(win))'.' + end /*k*/ say copies('█',sw) /*display a fence for da eyeballs*/ do j=1 for hp+cp /*let each player roll their dice*/ say; say copies('─',sw); /*display a fence for da eyeballs*/ - it=word('You It', 1 + (j>hp)) /*pronoun choice: You or It */ - say name.j', your total score (so far) in this pig game is:' s.j"." + it=name.j + say it', your total score (so far) in this pig game is: ' s.j"." - do until stopped /*keep prompting/rolling 'til not*/ - r=random(1,die); !=space(r !.r) /*for color, use a die-face name.*/ - in.j=in.j+r + do until stopped /*keep prompting/rolling 'til not*/ + r=random(1,die) /*get a random die face (number).*/ + !=left(space(r !.r','), !w) /*for color, use a die-face name.*/ + in.j=in.j+r /*add die-face number to inning. */ if r==1 then do; say it @jra ! || @ati "is a bust."; leave; end - say it @jra ! || @ati "total is:" in.j + say it @jra ! || @ati "total is: " in.j stopped=what2do(j) /*determine|ask to stop rolling.*/ if j>hp & stopped then say ' and' name.j "elected to stop rolling." end /*until stopped*/ @@ -63,27 +69,29 @@ 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?*/ /*──────────────────────────────────SCRUTINIZE subroutine───────────────*/ -scrutinize: parse arg ?,what,minimum /*? is the number, or maybe not. */ -if ?=='' | ?==',' then return arg(4) +scrutinize: parse arg ?,what,min,max /*? is the number, or maybe not. */ +if ?=='' | ?==',' then return arg(5) if \datatype(?,'N') then call err what "isn't numeric: " ?; ?=?/1 if \datatype(?,'W') then call err what "isn't an integer: " ? -if ?==0 & minimum>0 then call err what "can't be zero." -if ?0 then call err what "can't be zero." +if ?0 then call err what "can't be zero." +if ?>max & max\==0 then call err what "can't be greater than" max': ' ? return ? /*──────────────────────────────────what2do subroutine──────────────────*/ what2do: parse arg who /*"who" is a human or a computer.*/ -if (j>hp & r+in.j>=win) then return 1 /*an easy choice for HAL.*/ -if (j>hp & in.j>=win%4) then return 1 /*a simple stategy for HAL.*/ -if j>hp then return 0 /*HAL says, keep truckin'! */ +if j>hp & s.j+in.j>=win then return 1 /*an easy choice for HAL.*/ +if j>hp & in.j>=win%4 then return 1 /*a simple stategy for HAL.*/ +if j>hp then return 0 /*HAL says, keep truckin'! */ say @ name.who', what do you want to do? (a QUIT will stop the game),' say @ 'press ENTER to roll again, or anything else to STOP rolling.' pull action; action=space(action) /*remove any superfluous blanks. */ if \abbrev('QUIT',action,1) then return action\=='' say; say; say; say center(' quitting. ',sw,'─'); say; say; say; exit /*───────────────────────────────error handling subroutines and others.─*/ -err: say; say; say center(' error! ',max(40,linesize()%2),"*"); say - do j=1 for arg(); say arg(j); say; end; say; exit 13 +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) +novalue: syntax: call err 'REXX program' condition('C') "error", + ,condition('D'),'REXX source statement (line' sigl"):", + ,sourceline(sigl) diff --git a/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e new file mode 100644 index 0000000000..37fafe3b6e --- /dev/null +++ b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-1.e @@ -0,0 +1,51 @@ +class + PLAYER +create + set_name +feature + set_name(n:STRING) + do + name := n.twin + set_points(0) + end + + strategy(cur_points:INTEGER) + local + current_points, thrown:INTEGER + do + io.put_string ("You currently have " +points.out+". %NDo you want to save your points? Press y or n.%N") + io.read_line + if io.last_string.same_string ("y") then + set_points(cur_points) + else + io.put_string ("Then throw again.%N") + thrown:=throw_dice + if thrown= 1 then + io.put_string("You loose your points%N") + else + strategy(cur_points+thrown) + end + end + + end + set_points (value:INTEGER) + require + value_not_neg: value >= 0 + do + points := points + value + end + + random: V_RANDOM + -- Random sequence. + once + create Result + end + throw_dice: INTEGER + do + random.forth + Result := random.bounded_item (1, 6) + end + + name: STRING + points: INTEGER +end diff --git a/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e new file mode 100644 index 0000000000..8aca1e9a6d --- /dev/null +++ b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-2.e @@ -0,0 +1,45 @@ +class + PIG_THE_DICE + +feature + play + local + points, i: INTEGER + do + io.put_string("Welcome to the game.%N") + initiate_players + from + + until + winner/=void + loop + across player as p loop + points:=p.item.throw_dice + io.put_string ("%N" + p.item.name +" you throwed " + points.out + ".%N") + if points =1 then + io.put_string ("You loose your points.%N") + else + p.item.strategy(points) + end + if p.item.points >=100 then + winner := p.item + io.put_string ("%NThe winner is " + winner.name.out + ".%N") + end + end + end + end + + initiate_players + local + p1,p2: PLAYER + do + create player.make (1, 2) + create p1.set_name ("Player1") + player.put (p1, 1) + create p2.set_name ("Player2") + player.put (p2, 2) + end + + player: V_ARRAY[PLAYER] + winner: PLAYER +end diff --git a/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e new file mode 100644 index 0000000000..100fc57401 --- /dev/null +++ b/Task/Pig-the-dice-game/Eiffel/pig-the-dice-game-3.e @@ -0,0 +1,16 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature {NONE} -- Initialization + make + local + do + create pig + pig.initiate_players + pig.play + end + pig: PIG_THE_DICE +end diff --git a/Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml b/Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml new file mode 100644 index 0000000000..188c97a5f3 --- /dev/null +++ b/Task/Pig-the-dice-game/OCaml/pig-the-dice-game.ocaml @@ -0,0 +1,52 @@ +class player (name_init : string) = + object + val name = name_init + val mutable total = 0 + val mutable turn_score = 0 + method get_name = name + method get_score = total + method end_turn = total <- total + turn_score; + turn_score <- 0; + method has_won = total >= 100; + method rolled roll = match roll with + 1 -> turn_score <- 0; + |_ -> turn_score <- turn_score + roll; + end;; + +let print_seperator () = + print_endline "#####";; + +let rec one_turn p1 p2 = + Printf.printf "What do you want to do %s?\n" p1#get_name; + print_endline " 1)Roll the dice?"; + print_endline " 2)Or end your turn?"; + let choice = read_int () in + if choice = 1 then + begin + let roll = 1 + Random.int 6 in + Printf.printf "Rolled a %d\n" roll; + p1#rolled roll; + match roll with + 1 -> print_seperator (); + one_turn p2 p1 + |_ -> one_turn p1 p2 + end + else if choice = 2 then + begin + p1#end_turn; + match p1#has_won with + false -> Printf.printf "%s's score is now %d\n" p1#get_name p1#get_score; + print_seperator(); + one_turn p2 p1; + |true -> Printf.printf "Congratulations %s! You've won\n" p1#get_name + end + else + begin + print_endline "That's not a choice! Make a real one!"; + one_turn p1 p2 + end;; + +Random.self_init (); +let p1 = new player "Steven" +and p2 = new player "John" in +one_turn p1 p2;; diff --git a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx index e1fc9c5554..14f1ba4dac 100644 --- a/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx +++ b/Task/Pig-the-dice-game/REXX/pig-the-dice-game.rexx @@ -1,6 +1,6 @@ /*REXX program plays pig the dice game (any # of CBLFs and/or silicons).*/ signal on syntax; signal on novalue /*handle REXX program errors. */ -sw=80-1 /*the LINESIZE bif would be nicer*/ +sw=linesize()-1 /*get the width of the terminal. */ parse arg hp cp win die _ . '(' names ")" /*obtain optional arguments.*/ /*names with blanks should use _ */ if _\=='' then call err 'too many arguments were specified: ' _ diff --git a/Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb b/Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb index d6557cf47c..772abb80ed 100644 --- a/Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb +++ b/Task/Pig-the-dice-game/Ruby/pig-the-dice-game.rb @@ -2,35 +2,42 @@ class PigGame Player = Struct.new(:name, :safescore, :score) do def bust!() self.score = safescore end def stay!() self.safescore = score end - def roll!(die_sides) rand(1..die_sides) end - def wants_to_roll? - print("#{name} (#{safescore}, #{score})", ": Roll? (Y) ") - ['Y','y',''].include?(gets.chomp) - end + def to_s() "#{name} (#{safescore}, #{score})" end end - def bust?(roll) roll==1 ? (puts("Busted!",'') || true) : false end + def initialize(names, maxscore=100, die_sides=6) + rotation = names.map {|name| Player.new(name,0,0) } - def play(names, maxscore=100, die_sides=6) - rotation = names.map {|name| Player.new(name,0,0) }.cycle - - while player = rotation.next + rotation.cycle do |player| loop do - if player.wants_to_roll? - puts "Rolled: #{roll=player.roll!(die_sides)}" - if bust?( roll ) - player.bust! && break + if wants_to_roll?(player) + puts "Rolled: #{roll=roll_dice(die_sides)}" + if bust?(roll) + puts "Busted!",'' + player.bust! + break else player.score += roll - return player if player.score >= maxscore + if player.score >= maxscore + puts player.name + " wins!" + return + end end else - player.stay! && puts("Staying with #{player.safescore}!", '') + player.stay! + puts "Staying with #{player.safescore}!", '' break end end end end + + def roll_dice(die_sides) rand(1..die_sides) end + def bust?(roll) roll==1 end + def wants_to_roll?(player) + print "#{player}: Roll? (Y) " + ['Y','y',''].include?(gets.chomp) + end end -print PigGame.new.play( %w|Samuel Elizabeth| ).name, " wins!" +PigGame.new( %w|Samuel Elizabeth| ) diff --git a/Task/Pinstripe-Display/C-sharp/pinstripe-display.cs b/Task/Pinstripe-Display/C-sharp/pinstripe-display.cs new file mode 100644 index 0000000000..3f39ac1492 --- /dev/null +++ b/Task/Pinstripe-Display/C-sharp/pinstripe-display.cs @@ -0,0 +1,29 @@ +using System.Drawing; + +public class Pinstripe +{ + static void Main(string[] args) + { + var pinstripe = MakePinstripeImage(1366, 768); + pinstripe.Save("pinstripe.png"); + } + + public static Bitmap MakePinstripeImage(int width, int height) + { + var image = new Bitmap(width, height); + var quarterHeight = height / 4; + + for (var y = 0; y < height; y++) + { + var stripeWidth = (y / quarterHeight) + 1; + + for (var x = 0; x < width; x++) + { + var color = ((x / stripeWidth) % 2) == 0 ? Color.White : Color.Black; + image.SetPixel(x, y, color); + } + } + + return image; + } +} diff --git a/Task/Pinstripe-Display/Java/pinstripe-display.java b/Task/Pinstripe-Display/Java/pinstripe-display.java new file mode 100644 index 0000000000..d6c55d8c05 --- /dev/null +++ b/Task/Pinstripe-Display/Java/pinstripe-display.java @@ -0,0 +1,38 @@ +import java.awt.*; +import javax.swing.*; + +public class PinstripeDisplay extends JPanel { + + final int bands = 4; + + public PinstripeDisplay() { + setPreferredSize(new Dimension(900, 600)); + } + + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + int h = getHeight(); + for (int b = 1; b <= bands; b++) { + for (int x = 0, colIndex = 0; x < getWidth(); x += b, colIndex++) { + g.setColor(colIndex % 2 == 0 ? Color.white : Color.black); + g.fillRect(x, (b - 1) * (h / bands), x + b, b * (h / bands)); + } + } + } + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + JFrame f = new JFrame(); + f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + f.setTitle("PinstripeDisplay"); + f.add(new PinstripeDisplay(), BorderLayout.CENTER); + f.pack(); + f.setLocationRelativeTo(null); + f.setVisible(true); + } + }); + } +} diff --git a/Task/Playing-cards/00DESCRIPTION b/Task/Playing-cards/00DESCRIPTION index 68ed7a0c44..fff7a1bbe9 100644 --- a/Task/Playing-cards/00DESCRIPTION +++ b/Task/Playing-cards/00DESCRIPTION @@ -1 +1,7 @@ -Create a data structure and the associated methods to define and manipulate a deck of [[wp:Playing-cards#Anglo-American-French|playing cards]]. The deck should contain 52 unique cards. The methods must include the ability to make a new deck, shuffle (randomize) the deck, deal from the deck, and print the current contents of a deck. Each card must have a pip value and a suit value which constitute the unique value of the card. +Create a data structure and the associated methods to define and manipulate a deck of [[wp:Playing-cards#Anglo-American-French|playing cards]]. + +The deck should contain 52 unique cards. + +The methods must include the ability to make a new deck, shuffle (randomize) the deck, deal from the deck, and print the current contents of a deck. + +Each card must have a pip value and a suit value which constitute the unique value of the card. diff --git a/Task/Playing-cards/00META.yaml b/Task/Playing-cards/00META.yaml index a2413d963b..940aa7be0b 100644 --- a/Task/Playing-cards/00META.yaml +++ b/Task/Playing-cards/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Cards note: Games diff --git a/Task/Playing-cards/D/playing-cards-1.d b/Task/Playing-cards/D/playing-cards-1.d index ec4282dede..bcbba50beb 100644 --- a/Task/Playing-cards/D/playing-cards-1.d +++ b/Task/Playing-cards/D/playing-cards-1.d @@ -6,25 +6,24 @@ enum Pip {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, enum Suit {Diamonds, Spades, Hearts, Clubs} alias Card = Tuple!(Pip, Suit); -Card[] newDeck() /*pure nothrow*/ { - return cartesianProduct([EnumMembers!Pip], [EnumMembers!Suit]) - .array; +auto newDeck() pure nothrow @safe { + return cartesianProduct([EnumMembers!Pip], [EnumMembers!Suit]); } alias shuffleDeck = randomShuffle; -Card dealCard(ref Card[] deck) pure nothrow { +Card dealCard(ref Card[] deck) pure nothrow @safe @nogc { immutable card = deck.back; deck.popBack; return card; } -void show(in Card[] deck) { +void show(in Card[] deck) @safe { writefln("Deck:\n%(%s\n%)\n", deck); } -void main() { - auto d = newDeck; +void main() /*@safe*/ { + auto d = newDeck.array; d.show; d.shuffleDeck; while (!d.empty) diff --git a/Task/Playing-cards/Go/playing-cards-1.go b/Task/Playing-cards/Go/playing-cards-1.go new file mode 100644 index 0000000000..cd98195257 --- /dev/null +++ b/Task/Playing-cards/Go/playing-cards-1.go @@ -0,0 +1,174 @@ +package cards + +import ( + "math/rand" +) + +// A Suit represents one of the four standard suites. +type Suit uint8 + +// The four standard suites. +const ( + Spade Suit = 3 + Heart Suit = 2 + Diamond Suit = 1 + Club Suit = 0 +) + +func (s Suit) String() string { + const suites = "CDHS" // or "♣♢♡♠" + return suites[s : s+1] +} + +// Rank is the rank or pip value of a card from Ace==1 to King==13. +type Rank uint8 + +// The ranks from Ace to King. +const ( + Ace Rank = 1 + Two Rank = 2 + Three Rank = 3 + Four Rank = 4 + Five Rank = 5 + Six Rank = 6 + Seven Rank = 7 + Eight Rank = 8 + Nine Rank = 9 + Ten Rank = 10 + Jack Rank = 11 + Queen Rank = 12 + King Rank = 13 +) + +func (r Rank) String() string { + const ranks = "A23456789TJQK" + return ranks[r-1 : r] +} + +// A Card represets a specific playing card. +// It's an encoded representation of Rank and Suit +// with a valid range of [0,51]. +type Card uint8 + +// NewCard returns the Card representation for the specified rank and suit. +func NewCard(r Rank, s Suit) Card { + return Card(13*uint8(s) + uint8(r-1)) +} + +// RankSuit returns the rank and suit of the card. +func (c Card) RankSuit() (Rank, Suit) { + return Rank(c%13 + 1), Suit(c / 13) +} + +// Rank returns the rank of the card. +func (c Card) Rank() Rank { + return Rank(c%13 + 1) +} + +// Suit returns the suit of the card. +func (c Card) Suit() Suit { + return Suit(c / 13) +} + +func (c Card) String() string { + return c.Rank().String() + c.Suit().String() +} + +// A Deck represents a set of zero or more cards in a specific order. +type Deck []Card + +// NewDeck returns a regular 52 deck of cards in A-K order. +func NewDeck() Deck { + d := make(Deck, 52) + for i := range d { + d[i] = Card(i) + } + return d +} + +// String returns a string representation of the cards in the deck with +// a newline ('\n') separating the cards into groups of thirteen. +func (d Deck) String() string { + s := "" + for i, c := range d { + switch { + case i == 0: // do nothing + case i%13 == 0: + s += "\n" + default: + s += " " + } + s += c.String() + } + return s +} + +// Shuffle randomises the order of the cards in the deck. +func (d Deck) Shuffle() { + for i := range d { + j := rand.Intn(i + 1) + d[i], d[j] = d[j], d[i] + } +} + +// Contains returns true if the specified card is withing the deck. +func (d Deck) Contains(tc Card) bool { + for _, c := range d { + if c == tc { + return true + } + } + return false +} + +// AddDeck adds the specified deck(s) to this one at the end/bottom. +func (d *Deck) AddDeck(decks ...Deck) { + for _, o := range decks { + *d = append(*d, o...) + } +} + +// AddCard adds the specified card to this deck at the end/bottom. +func (d *Deck) AddCard(c Card) { + *d = append(*d, c) +} + +// Draw removes the selected number of cards from the top of the deck, +// returning them as a new deck. +func (d *Deck) Draw(n int) Deck { + old := *d + *d = old[n:] + return old[:n:n] +} + +// DrawCard draws a single card off the top of the deck, +// removing it from the deck. +// It returns false if there are no cards in the deck. +func (d *Deck) DrawCard() (Card, bool) { + if len(*d) == 0 { + return 0, false + } + old := *d + *d = old[1:] + return old[0], true +} + +// Deal deals out cards from the deck one at a time to multiple players. +// The initial hands (decks) of each player are provided as arguments and the +// modified hands are returned. The initial hands can be empty or nil. +// E.g. Deal(7, nil, nil, nil) deals out seven cards to three players +// each starting with no cards. +// If there are insufficient cards in the deck the hands are partially dealt and +// the boolean return is set to false (true otherwise). +func (d *Deck) Deal(cards int, hands ...Deck) ([]Deck, bool) { + for i := 0; i < cards; i++ { + for j := range hands { + if len(*d) == 0 { + return hands, false + } + hands[j] = append(hands[j], (*d)[0]) + *d = (*d)[1:] + } + } + return hands, true +} diff --git a/Task/Playing-cards/Go/playing-cards-2.go b/Task/Playing-cards/Go/playing-cards-2.go new file mode 100644 index 0000000000..1ac6e301bb --- /dev/null +++ b/Task/Playing-cards/Go/playing-cards-2.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + "whatever/path/was/used/cards" +) + +func main() { + // We do not call rand.Seed() in order for the results to be repeatable. + //rand.Seed(time.Now().UnixNano()) + d := cards.NewDeck() + fmt.Println("fresh deck") + fmt.Println(d) + + d.Shuffle() + fmt.Println("\nshuffled") + fmt.Println(d) + + h := d.Draw(5) + fmt.Println("\n5 cards drawn") + fmt.Println(h) + + fmt.Println("\nrank, suit values of cards in drawn:") + fmt.Println("Card Rank Suit") + for _, c := range h { + fmt.Printf("%v : %v=%2[2]d %v=%2[3]d\n", c, c.Rank(), c.Suit()) + } + + ans := h.Contains(cards.NewCard(cards.Queen, cards.Spade)) + fmt.Println("Drawn cards include the Queen of Spades?", ans) + ans = h.Contains(cards.NewCard(cards.Jack, cards.Spade)) + fmt.Println("Drawn cards include the Jack of Spades?", ans) + + p, _ := d.Deal(7, nil, nil) + fmt.Println("\nDealing 7 cards to two players") + fmt.Println("Player1:", p[0]) + fmt.Println("Player2:", p[1]) + + fmt.Println("\n", len(d), " cards left in deck") + fmt.Println(d) + + d.AddDeck(h, p[0], p[0]) + fmt.Println("\nReturning the cards to the deck") + fmt.Println(d) +} diff --git a/Task/Playing-cards/Go/playing-cards.go b/Task/Playing-cards/Go/playing-cards.go deleted file mode 100644 index 8bd964f184..0000000000 --- a/Task/Playing-cards/Go/playing-cards.go +++ /dev/null @@ -1,125 +0,0 @@ -package main - -import ( - "fmt" - "math/rand" - "time" -) - -func main() { - rand.Seed(time.Now().UnixNano()) - d := newDeck() - fmt.Println("fresh deck") - fmt.Println(d) - - d.shuffle() - fmt.Println("\nshuffled") - fmt.Println(d) - - h := d.deal(5) - fmt.Println("\n5 cards delt") - fmt.Println(h) - - fmt.Println("\npip, suit values of cards in hand:") - fmt.Println("pip suit") - for _, c := range h { - fmt.Printf("%3d %3d\n", c.pip(), c.suit()) - } - fmt.Print("\n", len(d), " cards left in deck\n") - fmt.Println(d) -} - -// card type. (deck type defined later) -// valid range is 0..51. this facilititates computations. -type card int - -// zero-based pip/suit functions. useful for computations. -// (or maybe just reference for computations, since they are trivial) -func (c card) pip0() int { - return int(c % 13) -} - -func (c card) suit0() int { - return int(c / 13) -} - -func (c card) pipSuit0() (int, int) { - return int(c % 13), int(c / 13) -} - -// one-base pip/suit functions. meaningful for output. -// ("pip" does really mean the identifying number of spots on the card) -func (c card) pip() int { - return int(c%13) + 1 -} - -func (c card) suit() int { - return int(c/13) + 1 -} - -func (c card) pipSuit() (int, int) { - return int(c%13) + 1, int(c/13) + 1 -} - -// string representation -const pipS = "A23456789TJQK" -const suitS = "CDHS" - -func (c card) String() string { - px, sx := c.pipSuit0() - return pipS[px:px+1] + suitS[sx:sx+1] -} - -// deck type -type deck []card - -// "constructor" returns pointer to new deck object -func newDeck() deck { - d := make(deck, 52) - for i := range d { - /lang> - -Example (first 4 cards of a shuffled deck): - d[i] = card(i) - } - return d -} - -// string representation: 13 cards to a line, up to four lines. -// lines separated with newline character. empty deck is empty string. -func (d deck) String() string { - if len(d) == 0 { - return "" - } - r := d[0].String() - for i, c := range d[1:] { - if i%13 == 12 { - r += "\n" - } else { - r += " " - } - r += c.String() - } - return r -} - -// shuffle in place (although using extra memory) -func (d deck) shuffle() { - d2 := make(deck, len(d)) - copy(d2, d) - for i, s := range rand.Perm(len(d)) { - d[i] = d2[s] - } -} - -// return requested number of cards as new deck object. -// the deck being delt from (the method reciever) is resliced. -func (d *deck) deal(n int) deck { - if n > len(*d) { - return nil - } - r := make(deck, n) - copy(r, *d) - *d = (*d)[n:] - return r -} diff --git a/Task/Playing-cards/Rust/playing-cards.rust b/Task/Playing-cards/Rust/playing-cards.rust new file mode 100644 index 0000000000..b64fe3aa27 --- /dev/null +++ b/Task/Playing-cards/Rust/playing-cards.rust @@ -0,0 +1,125 @@ +use std::fmt; +use std::rand::{task_rng, Rng}; + +#[deriving(Clone)] +enum Pip { + Ace, + Two, + Three, + Four, + Five, + Six, + Seven, + Eight, + Nine, + Ten, + Jack, + Queen, + King +} + +impl fmt::Show for Pip { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let name = match *self { + Ace => "Ace", + Two => "Two", + Three => "Three", + Four => "Four", + Five => "Five", + Six => "Six", + Seven => "Seven", + Eight => "Eight", + Nine => "Nine", + Ten => "Ten", + Jack => "Jack", + Queen => "Queen", + King => "King" + }; + + write!(f, "{}", name) + } +} + +#[deriving(Clone)] +enum Suit { + Spades, + Hearts, + Diamonds, + Clubs +} + +impl fmt::Show for Suit { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let name = match *self { + Spades => "Spades", + Hearts => "Hearts", + Diamonds => "Diamonds", + Clubs => "Clubs" + }; + + write!(f, "{}", name) + } +} + +#[deriving(Clone)] +struct Card { + pip: Pip, + suit: Suit +} + +impl Card { + fn new(pip: Pip, suit: Suit) -> Card { + Card {pip: pip, suit: suit} + } +} + +impl fmt::Show for Card { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{} of {}", self.pip, self.suit) + } +} + +#[deriving(Clone)] +struct Deck(Vec); + +impl Deck { + fn new() -> Deck { + let mut cards:Vec = Vec::with_capacity(52); + for suit in [Spades, Hearts, Diamonds, Clubs].iter() { + for pip in [Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King].iter() { + cards.push(Card::new(*pip, *suit)); + } + } + Deck(cards) + } + + fn deal(&mut self) -> Option { + let &Deck(ref mut cards) = self; + cards.pop() + } + + fn shuffle(&mut self) { + let &Deck(ref mut cards) = self; + let mut rng = task_rng(); + + rng.shuffle(cards.as_mut_slice()); + } +} + +impl fmt::Show for Deck { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + let &Deck(ref cards) = self; + + let mut text = String::new(); + let mut i = 0; + for card in cards.iter() { + text.push_str(format!("{}", card).as_slice()); + i += 1; + if i < cards.capacity() { + text.push_str("\n"); + } + } + + write!(f, "{}", text) + } +} diff --git a/Task/Plot-coordinate-pairs/Clojure/plot-coordinate-pairs.clj b/Task/Plot-coordinate-pairs/Clojure/plot-coordinate-pairs.clj new file mode 100644 index 0000000000..3d8a6536f7 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Clojure/plot-coordinate-pairs.clj @@ -0,0 +1,4 @@ +(use '(incanter core stats charts)) +(def x (range 0 10)) +(def y '(2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0)) +(view (xy-plot x y)) diff --git a/Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs.py b/Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-1.py similarity index 100% rename from Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs.py rename to Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-1.py diff --git a/Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-2.py b/Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-2.py new file mode 100644 index 0000000000..bcda5d4c11 --- /dev/null +++ b/Task/Plot-coordinate-pairs/Python/plot-coordinate-pairs-2.py @@ -0,0 +1,28 @@ +from visual import * +from visual.graph import * + +plot1 = gdisplay( title='VPython Plot-Demo', + xtitle='x', + ytitle='y (click and drag mouse to see coordinates)', + foreground=color.black, + background=color.white, + x=0, y=0, + width=400, height=400, + xmin=0, xmax=10, + ymin=0, ymax=200 ) + +f1 = gdots(color=color.red) # create plot-object + +f1.plot(pos= (0, 2.7), color=color.blue ) # add a single point +f1.plot(pos=[(1, 2.8), # add a list of points + (2, 31.4), + (3, 38.1), + (4, 58.0), + (5, 76.2), + (6, 100.5), + (7, 130.0), + (8, 149.3), + (9, 180.0) ] + ) +label(display=plot1.display, text="Look here", + pos=(6,100.5), xoffset=30,yoffset=-20 ) diff --git a/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala b/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala index 0181890a91..5214229915 100644 --- a/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala +++ b/Task/Plot-coordinate-pairs/Scala/plot-coordinate-pairs.scala @@ -10,7 +10,7 @@ object PlotCoordPairs extends scala.swing.SimpleSwingApplication { val (prefSizeX, prefSizeY) = (720, 480) - lazy val ui = new Panel { + private def ui = new Panel { import math._ val xmax = { @@ -103,5 +103,4 @@ object PlotCoordPairs extends scala.swing.SimpleSwingApplication { title = "Rosetta Code >>> Task: Plot coordinate pairs | Language: Scala" contents = ui } - } diff --git a/Task/Pointers-and-references/Perl/pointers-and-references-1.pl b/Task/Pointers-and-references/Perl/pointers-and-references-1.pl index 6ecd1e98be..f69dcf8929 100644 --- a/Task/Pointers-and-references/Perl/pointers-and-references-1.pl +++ b/Task/Pointers-and-references/Perl/pointers-and-references-1.pl @@ -1,7 +1,7 @@ # start with some var definitions - my $scalar = 'a string'; - my @array = ('an', 'array'); - my %hash = ( firstkey => 'a', secondkey => 'hash' ); + my $scalar = 'aa'; + my @array = ('bb', 'cc'); + my %hash = ( dd => 'DD', ee => 'EE' ); # make references my $scalarref = \$scalar; diff --git a/Task/Pointers-and-references/Perl/pointers-and-references-2.pl b/Task/Pointers-and-references/Perl/pointers-and-references-2.pl index 36ab87ea77..a4b237ea45 100644 --- a/Task/Pointers-and-references/Perl/pointers-and-references-2.pl +++ b/Task/Pointers-and-references/Perl/pointers-and-references-2.pl @@ -1,9 +1,10 @@ - # printing the value - print ${$scalar}; - print $arrayref->[1]; # this would print "array" - print $hashref->{'secondkey'}; # this would print "hash" + # accessing the value + print $$scalarref; # 'aa' + print @$arrayref; # 'bbcc' + print $arrayref->[1]; # 'cc' + print $hashref->{ee}; # 'EE' # changing the value - ${$scalar} = 'a new string'; # would change $scalar as well - $arrayref->[0] = 'an altered'; # would change the first value of @array as well - $hashref->{'firstkey'} = 'a good'; # would change the value of the firstkey name value pair in %hash + $$scalarref = 'a new string'; # changes $scalar + $arrayref->[0] = 'foo'; # changes the first value of @array + $hashref->{'dd'} = 'bar'; # changes the value with key 'dd' in %hash diff --git a/Task/Polymorphic-copy/Ada/polymorphic-copy.ada b/Task/Polymorphic-copy/Ada/polymorphic-copy.ada index 3ff1d6ae7f..44368327b0 100644 --- a/Task/Polymorphic-copy/Ada/polymorphic-copy.ada +++ b/Task/Polymorphic-copy/Ada/polymorphic-copy.ada @@ -3,6 +3,7 @@ with Ada.Text_IO; use Ada.Text_IO; procedure Test_Polymorphic_Copy is package Base is type T is tagged null record; + type T_ptr is access all T'Class; function Name (X : T) return String; end Base; use Base; @@ -21,6 +22,12 @@ procedure Test_Polymorphic_Copy is Put_Line ("Copied " & Duplicate.Name); -- Check the copy end Copier; + -- The function knows nothing about S and creates a copy on the heap + function Clone (X : T'Class) return T_ptr is + begin + return new T'Class(X); + end Copier; + package Derived is type S is new T with null record; overriding function Name (X : S) return String; @@ -36,7 +43,11 @@ procedure Test_Polymorphic_Copy is Object_1 : T; Object_2 : S; + Object_3 : T_ptr := Clone(T); + Object_4 : T_ptr := Clone(S); begin Copier (Object_1); Copier (Object_2); + Put_Line ("Cloned " & Object_3.all.Name); + Put_Line ("Cloned " & Object_4.all.Name); end Test_Polymorphic_Copy; diff --git a/Task/Polymorphic-copy/D/polymorphic-copy-2.d b/Task/Polymorphic-copy/D/polymorphic-copy-2.d index ec6cfb1d9d..94f49fa357 100644 --- a/Task/Polymorphic-copy/D/polymorphic-copy-2.d +++ b/Task/Polymorphic-copy/D/polymorphic-copy-2.d @@ -20,7 +20,7 @@ class S : T { } override string toString() { - return "I'm the instance of S p: " ~ cast(string)str; + return "I'm the instance of S p: " ~ str.idup; } override T duplicate() { return new S(this); } @@ -41,6 +41,6 @@ void main () { T copy = orig.duplicate(); orig.custom('Y'); - writeln(orig); - writeln(copy); // Should have 'X' at the beginning. + orig.writeln; + copy.writeln; // Should have 'X' at the beginning. } diff --git a/Task/Polymorphic-copy/Groovy/polymorphic-copy-1.groovy b/Task/Polymorphic-copy/Groovy/polymorphic-copy-1.groovy new file mode 100644 index 0000000000..81ec1ba9da --- /dev/null +++ b/Task/Polymorphic-copy/Groovy/polymorphic-copy-1.groovy @@ -0,0 +1,14 @@ +class T implements Cloneable { + String property + String name() { 'T' } + T copy() { + try { super.clone() } + catch(CloneNotSupportedException e) { null } + } + @Override + boolean equals(that) { this.name() == that?.name() && this.property == that?.property } +} + +class S extends T { + @Override String name() { 'S' } +} diff --git a/Task/Polymorphic-copy/Groovy/polymorphic-copy-2.groovy b/Task/Polymorphic-copy/Groovy/polymorphic-copy-2.groovy new file mode 100644 index 0000000000..b61977c7b4 --- /dev/null +++ b/Task/Polymorphic-copy/Groovy/polymorphic-copy-2.groovy @@ -0,0 +1,14 @@ +T obj1 = new T(property: 'whatever') +S obj2 = new S(property: 'meh') + +def objA = obj1.copy() +def objB = obj2.copy() + +assert objA.class == T +assert objA == obj1 && ! objA.is(obj1) // same values, not same instance + +assert objB.class == S +assert objB == obj2 && ! objB.is(obj2) // same values, not same instance + +println "objA:: name: ${objA.name()}, property: ${objA.property}" +println "objB:: name: ${objB.name()}, property: ${objB.property}" diff --git a/Task/Polymorphism/AutoHotkey/polymorphism.ahk b/Task/Polymorphism/AutoHotkey/polymorphism.ahk new file mode 100644 index 0000000000..0ff9e1214d --- /dev/null +++ b/Task/Polymorphism/AutoHotkey/polymorphism.ahk @@ -0,0 +1,73 @@ +MyPoint := new Point(1, 8) +MyPoint.Print() +MyCircle := new Circle(4, 7, 9) +MyCircle2 := MyCircle.Copy() +MyCircle.SetX(2) ;Assignment method +MyCircle.y := 3 ;Direct assignment +MyCircle.Print() +MyCircle2.Print() +MyCircle.SetX(100), MyCircle.SetY(1000), MyCircle.r := 10000 +MsgBox, % MyCircle.__Class + . "`n`nx:`t" MyCircle.GetX() + . "`ny:`t" MyCircle.y + . "`nr:`t" MyCircle.GetR() +return + +class Point +{ + Copy() + { + return this.Clone() + } + GetX() + { + return this.x + } + GetY() + { + return this.y + } + __New(x, y) + { + this.x := x + this.y := y + } + Print() + { + MsgBox, % this.__Class + . "`n`nx:`t" this.x + . "`ny:`t" this.y + } + SetX(aValue) + { + this.x := aValue + } + SetY(aValue) + { + this.y := aValue + } +} + +class Circle extends Point +{ + GetR() + { + return this.r + } + __New(x, y, r) + { + this.r := r + base.__New(x, y) + } + Print() + { + MsgBox, % this.__Class + . "`n`nx:`t" this.x + . "`ny:`t" this.y + . "`nr:`t" this.r + } + SetR(aValue) + { + this.r := aValue + } +} diff --git a/Task/Polymorphism/Ruby/polymorphism-1.rb b/Task/Polymorphism/Ruby/polymorphism-1.rb new file mode 100644 index 0000000000..16524d762f --- /dev/null +++ b/Task/Polymorphism/Ruby/polymorphism-1.rb @@ -0,0 +1,23 @@ +class Point + attr_accessor :x,:y + def initialize(x=0, y=0) + self.x = x + self.y = y + end + def to_s + "Point at #{x},#{y}" + end +end + +# When defining Circle class as the sub-class of the Point class: +class Circle < Point + attr_accessor :r + def initialize(x=0, y=0, r=0) + self.x = x + self.y = y + self.r = r + end + def to_s + "Circle at #{x},#{y} with radius #{r}" + end +end diff --git a/Task/Polymorphism/Ruby/polymorphism-2.rb b/Task/Polymorphism/Ruby/polymorphism-2.rb new file mode 100644 index 0000000000..3688a9a1a3 --- /dev/null +++ b/Task/Polymorphism/Ruby/polymorphism-2.rb @@ -0,0 +1,15 @@ +# create a point +puts Point.new # => Point at 0,0 +p = Point.new(1, 2) +puts p # => Point at 1,2 +puts p.x # => 1 +p.y += 1 +puts p # => Point at 1,3 + +# create a circle +c = Circle.new(4,5,6) +# copy it +d = c.dup +d.r = 7.5 +puts c # => Circle at 4,5 with radius 6 +puts d # => Circle at 4,5 with radius 7.5 diff --git a/Task/Polymorphism/Ruby/polymorphism.rb b/Task/Polymorphism/Ruby/polymorphism.rb deleted file mode 100644 index f15255194d..0000000000 --- a/Task/Polymorphism/Ruby/polymorphism.rb +++ /dev/null @@ -1,22 +0,0 @@ -class Point - attr_accessor :x,:y - def initialize(x=0,y=0) - self.x=x - self.y=y - end - def to_s - "Point at #{x},#{y}" - end -end - -class Circle - attr_accessor :x,:y,:r - def initialize(x=0,y=0,r=0) - self.x=x - self.y=y - self.r=r - end - def to_s - "Circle at #{x},#{y} with radius #{r}" - end -end diff --git a/Task/Polymorphism/Tcl/polymorphism.tcl b/Task/Polymorphism/Tcl/polymorphism.tcl index 3afb6906a5..26c64aef4b 100644 --- a/Task/Polymorphism/Tcl/polymorphism.tcl +++ b/Task/Polymorphism/Tcl/polymorphism.tcl @@ -42,7 +42,7 @@ oo::class create Circle { } # No destructors: unneeded by these classes -set p [Point new 1.0 2.0] +set p [Point new 1.0 2.0] set c [Circle new 3.0 4.0 5.0] set cCopy [$c copy] puts "$p is at ([$p x],[$p y])" diff --git a/Task/Polynomial-long-division/00DESCRIPTION b/Task/Polynomial-long-division/00DESCRIPTION index 765b9809e7..9e9313ea86 100644 --- a/Task/Polynomial-long-division/00DESCRIPTION +++ b/Task/Polynomial-long-division/00DESCRIPTION @@ -1,7 +1,7 @@ {{Wikipedia}} :In algebra, [[wp:Polynomial long division|polynomial long division]] is an algorithm for dividing a polynomial by another polynomial of the same or lower degree. -Let us suppose a polynomial is represented by a vector, x (i.e., an ordered collection of [[wp:Coefficient|coefficients]]) so that the ith element keeps the coefficient of x^i, and the multiplication by a monomial is a ''shift'' of the vector's elements "towards right" (injecting zeros from left) followed by a multiplication of each element by the coefficient of the monomial. +Let us suppose a polynomial is represented by a vector, x (i.e., an ordered collection of [[wp:Coefficient|coefficients]]) so that the ith element keeps the coefficient of x^i, and the multiplication by a monomial is a ''shift'' of the vector's elements "towards right" (injecting ones from left) followed by a multiplication of each element by the coefficient of the monomial. Then a pseudocode for the polynomial long division using the conventions described above could be: diff --git a/Task/Polynomial-long-division/D/polynomial-long-division.d b/Task/Polynomial-long-division/D/polynomial-long-division.d index ef236f3c11..2795da600c 100644 --- a/Task/Polynomial-long-division/D/polynomial-long-division.d +++ b/Task/Polynomial-long-division/D/polynomial-long-division.d @@ -1,14 +1,14 @@ -import std.stdio, std.range, std.algorithm, std.typecons, std.array; +import std.stdio, std.range, std.algorithm, std.typecons, std.conv; Tuple!(double[], double[]) polyDiv(in double[] inN, in double[] inD) -pure /*nothrow*/ { +nothrow pure @safe { // Code smell: a function that does two things. - static int trimAndDegree(T)(ref T[] poly) nothrow pure { + static int trimAndDegree(T)(ref T[] poly) nothrow pure @safe @nogc { poly = poly.retro.find!q{ a != b }(0.0).retro; - return (cast(int)poly.length) - 1; + return poly.length.signed - 1; } - double[] N = inN.dup; // Not nothrow. + auto N = inN.dup; const(double)[] D = inD; const dD = trimAndDegree(D); auto dN = trimAndDegree(N); @@ -30,9 +30,9 @@ pure /*nothrow*/ { } -int trimAndDegree1(T)(ref T[] poly) nothrow pure { +int trimAndDegree1(T)(ref T[] poly) nothrow pure @safe @nogc { poly.length -= poly.retro.countUntil!q{ a != 0 }; - return (cast(int)poly.length) - 1; + return poly.length.signed - 1; } void main() { diff --git a/Task/Polynomial-long-division/Ruby/polynomial-long-division-1.rb b/Task/Polynomial-long-division/Ruby/polynomial-long-division-1.rb index e90dbe238c..a6a5438df2 100644 --- a/Task/Polynomial-long-division/Ruby/polynomial-long-division-1.rb +++ b/Task/Polynomial-long-division/Ruby/polynomial-long-division-1.rb @@ -18,8 +18,8 @@ def polynomial_long_division(numerator, denominator) end def degree(ary) - idx = ary.rindex {|x| x.nonzero?} - idx.nil? ? -1 : idx + idx = ary.rindex(&:nonzero?) + idx ? idx : -1 end def shift_right(ary, n) @@ -37,10 +37,10 @@ end f = [-42, 0, -12, 1] g = [-3, 1, 0, 0] q, r = polynomial_long_division(f, g) -p [f, g, q, r] -# => [[-42, 0, -12, 1], [-3, 1, 0, 0], [-27, -9, 1, 0, 0], [-123, 0, 0, 0, 0]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [-42, 0, -12, 1] / [-3, 1, 0, 0] => [-27, -9, 1, 0] remainder [-123, 0, 0, 0] g = [-3, 1, 1, 0] q, r = polynomial_long_division(f, g) -p [f, g, q, r] -# => [[-42, 0, -12, 1], [-3, 1, 0, 0], [-13, 1, 0, 0, 0], [-81, 16, 0, 0, 0]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [-42, 0, -12, 1] / [-3, 1, 1, 0] => [-13, 1, 0, 0] remainder [-81, 16, 0, 0] diff --git a/Task/Polynomial-long-division/Ruby/polynomial-long-division-2.rb b/Task/Polynomial-long-division/Ruby/polynomial-long-division-2.rb index f88e6c16b4..36a0a0fc4a 100644 --- a/Task/Polynomial-long-division/Ruby/polynomial-long-division-2.rb +++ b/Task/Polynomial-long-division/Ruby/polynomial-long-division-2.rb @@ -59,10 +59,10 @@ end f = [1, -12, 0, -42] g = [1, -3] q, r = polynomial_division(f, g) -p [f, g, q, r] -# => [[1, -12, 0, -42], [1, -3], [1, -9, -27], [-123]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [1, -12, 0, -42] / [1, -3] => [1, -9, -27] remainder [-123] g = [1, 1, -3] q, r = polynomial_division(f, g) -p [f, g, q, r] -# => [[1, -12, 0, -42], [1, 1, -3], [1, -13], [16, -81]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [1, -12, 0, -42] / [1, 1, -3] => [1, -13] remainder [16, -81] diff --git a/Task/Polynomial-long-division/Ruby/polynomial-long-division-3.rb b/Task/Polynomial-long-division/Ruby/polynomial-long-division-3.rb index 7288433dd0..799c4b9684 100644 --- a/Task/Polynomial-long-division/Ruby/polynomial-long-division-3.rb +++ b/Task/Polynomial-long-division/Ruby/polynomial-long-division-3.rb @@ -1,15 +1,14 @@ -def tcl_polynomial_division(f, g) +def polynomial_division(f, g) if g.length == 0 or (g.length == 1 and g[0] == 0) raise ArgumentError, "denominator is zero" end return [[0], f] if f.length < g.length - q = [] - n, d = f.dup, g - while n.length >= d.length - q << Float(n[0]) / d[0] - n[0, d.length].zip(d).each_with_index do |pair, i| - n[i] = Float(pair[0]) - q[-1] * pair[1] + q, n = [], f.dup + while n.length >= g.length + q << Float(n[0]) / g[0] + n[0, g.length].zip(g).each_with_index do |pair, i| + n[i] = pair[0] - q[-1] * pair[1] end n.shift end @@ -21,10 +20,10 @@ end f = [1, -12, 0, -42] g = [1, -3] q, r = polynomial_division(f, g) -p [f, g, q, r] -# => [[1, -12, 0, -42], [1, -3], [1, -9, -27], [-123]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [1, -12, 0, -42] / [1, -3] => [1.0, -9.0, -27.0] remainder [-123.0] g = [1, 1, -3] q, r = polynomial_division(f, g) -p [f, g, q, r] -# => [[1, -12, 0, -42], [1, 1, -3], [1, -13], [16, -81]] +puts "#{f} / #{g} => #{q} remainder #{r}" +# => [1, -12, 0, -42] / [1, 1, -3] => [1.0, -13.0] remainder [16.0, -81.0] diff --git a/Task/Polynomial-regression/HicEst/polynomial-regression.hicest b/Task/Polynomial-regression/HicEst/polynomial-regression.hicest new file mode 100644 index 0000000000..e31c893157 --- /dev/null +++ b/Task/Polynomial-regression/HicEst/polynomial-regression.hicest @@ -0,0 +1,15 @@ +REAL :: n=10, x(n), y(n), m=3, p(m) + + x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) + y = (1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) + + p = 2 ! initial guess for the polynom's coefficients + + SOLVE(NUL=Theory()-y(nr), Unknown=p, DataIdx=nr, Iters=iterations) + + WRITE(ClipBoard, Name) p, iterations + +FUNCTION Theory() + ! called by the solver of the SOLVE function. All variables are global + Theory = p(1)*x(nr)^2 + p(2)*x(nr) + p(3) + END diff --git a/Task/Polynomial-regression/Julia/polynomial-regression.julia b/Task/Polynomial-regression/Julia/polynomial-regression.julia new file mode 100644 index 0000000000..b397000990 --- /dev/null +++ b/Task/Polynomial-regression/Julia/polynomial-regression.julia @@ -0,0 +1,4 @@ +function polyfit(x, y, n) + A = [ float(x[i])^p for i = 1:length(x), p = 0:n ] + A \ y +end diff --git a/Task/Polynomial-regression/R/polynomial-regression.r b/Task/Polynomial-regression/R/polynomial-regression.r new file mode 100644 index 0000000000..2a646e259f --- /dev/null +++ b/Task/Polynomial-regression/R/polynomial-regression.r @@ -0,0 +1,3 @@ +x <- c(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10) +y <- c(1, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321) +coef(lm(y ~ x + I(x^2))) diff --git a/Task/Power-set/00DESCRIPTION b/Task/Power-set/00DESCRIPTION index d64acaec6e..484da56a4a 100644 --- a/Task/Power-set/00DESCRIPTION +++ b/Task/Power-set/00DESCRIPTION @@ -1,6 +1,20 @@ -A [[set]] is a collection (container) of certain values, without any particular order, and no repeated values. It corresponds with a finite set in mathematics. A set can be implemented as an associative array (partial mapping) in which the value of each key-value pair is ignored. +{{omit from|GUISS}} +A [[set]] is a collection (container) of certain values, +without any particular order, and no repeated values. +It corresponds with a finite set in mathematics. +A set can be implemented as an associative array (partial mapping) +in which the value of each key-value pair is ignored. -Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
+Given a set S, the [[wp:Power_set|power set]] (or powerset) of S, written P(S), or 2S, is the set of all subsets of S.
'''Task : ''' By using a library or built-in set type, or by defining a set type with necessary operations, write a function with a set S as input that yields the power set 2S of S. For example, the power set of {1,2,3,4} is {{}, {1}, {2}, {1,2}, {3}, {1,3}, {2,3}, {1,2,3}, {4}, {1,4}, {2,4}, {1,2,4}, {3,4}, {1,3,4}, {2,3,4}, {1,2,3,4}}. + +For a set which contains n elements, the corresponding power set has 2n elements, including the edge cases of [[wp:Empty_set|empty set]].
+ +The power set of the empty set is the set which contains itself (20 = 1):
+\mathcal{P}(\varnothing) = { \varnothing }
+And the power set of the set which contains only the empty set, has two subsets, the empty set and the set which contains the empty set (21 = 2):
+\mathcal{P}({\varnothing}) = { \varnothing, { \varnothing } }
+ +'''Extra credit: ''' Demonstrate that your language supports these last two powersets. diff --git a/Task/Power-set/Ada/power-set.ada b/Task/Power-set/Ada/power-set.ada index 428cb3091b..8552023ac0 100644 --- a/Task/Power-set/Ada/power-set.ada +++ b/Task/Power-set/Ada/power-set.ada @@ -1,84 +1,42 @@ -with Ada.Text_IO; use Ada.Text_IO; +with Ada.Text_IO, Ada.Command_Line; procedure Power_Set is - type Universe is (A,B,C,D,E); - -- The type Set are subsets of Universe - type Set is array (Universe) of Boolean; - Empty : constant Set := (others => False); - function Cardinality (X : Set) return Natural is - N : Natural := 0; + type List is array (Positive range <>) of Positive; + Empty: List(1 .. 0); + + procedure Print_All_Subsets(Set: List; Printable: List:= Empty) is + + procedure Print_Set(Items: List) is + First: Boolean := True; + begin + Ada.Text_IO.Put("{ "); + for Item of Items loop + if First then + First := False; -- no comma needed + else + Ada.Text_IO.Put(", "); -- comma, to separate the items + end if; + Ada.Text_IO.Put(Ada.Command_Line.Argument(Item)); + end loop; + Ada.Text_IO.Put_Line(" }"); + end Print_Set; + + Tail: List := Set(Set'First+1 .. Set'Last); + begin - for I in X'Range loop - if X (I) then - N := N + 1; - end if; - end loop; - return N; - end Cardinality; - function Element (X : Set; Position : Positive) return Universe is - N : Natural := 0; - begin - for I in X'Range loop - if X (I) then - N := N + 1; - if N = Position then - return I; - end if; - end if; - end loop; - raise Constraint_Error; - end Element; - procedure Put (X : Set) is - Empty : Boolean := True; - begin - for I in X'Range loop - if X (I) then - if Empty then - Empty := False; - Put (Universe'Image (I)); - else - Put ("," & Universe'Image (I)); - end if; - end if; - end loop; - if Empty then - Put ("empty"); + if Set = Empty then + Print_Set(Printable); + else + Print_All_Subsets(Tail, Printable & Set(Set'First)); + Print_All_Subsets(Tail, Printable); end if; - end Put; + end Print_All_Subsets; - -- Set_Of_Set are sets of subsets of Universe - type Set_Of_Sets is array (Positive range <>) of Set; - - function Power (X : Set) return Set_Of_Sets is - Length : constant Natural := Cardinality (X); - Index : array (1..Length) of Integer := (others => 0); - Result : Set_Of_Sets (1..2**Length) := (others => Empty); - begin - for N in Result'Range loop - for I in 1..Length loop -- Index determines the sample N - exit when Index (I) = 0; - Result (N) (Element (X, Index (I))) := True; - end loop; - Next : for I in 1..Length loop -- Computing the index of the following sample - if Index (I) < Length then - Index (I) := Index (I) + 1; - if I = 1 or else Index (I - 1) > Index (I) then - for J in reverse 2..I loop - Index (J - 1) := Index (J) + 1; - end loop; - exit Next; - end if; - end if; - end loop Next; - end loop; - return Result; - end Power; - - P : Set_Of_Sets := Power ((A|C|E => True, others => False)); + Set: List(1 .. Ada.Command_Line.Argument_Count); begin - for I in P'Range loop - New_Line; - Put (P (I)); + for I in Set'Range loop -- initialize set + Set(I) := I; end loop; + Print_All_Subsets(Set); -- do the work end Power_Set; diff --git a/Task/Power-set/Clojure/power-set-2.clj b/Task/Power-set/Clojure/power-set-2.clj index 3b1bdac390..093f1f627a 100644 --- a/Task/Power-set/Clojure/power-set-2.clj +++ b/Task/Power-set/Clojure/power-set-2.clj @@ -1,7 +1,9 @@ -(defn powerset - [coll] +(defn powerset [coll] (reduce (fn [a x] - (set (concat a (map #(set (concat #{x} %)) a)))) + (->> a + (map #(set (concat #{x} %))) + (concat a) + set)) #{#{}} coll)) (powerset #{1 2 3}) diff --git a/Task/Power-set/D/power-set-1.d b/Task/Power-set/D/power-set-1.d index cbfaeabc35..cb3417dd44 100644 --- a/Task/Power-set/D/power-set-1.d +++ b/Task/Power-set/D/power-set-1.d @@ -1,4 +1,4 @@ -T[][] powerSet(T)(in T[] s) pure nothrow { +T[][] powerSet(T)(in T[] s) pure nothrow @safe { auto r = new typeof(return)(1, 0); foreach (e; s) { typeof(return) rs; @@ -11,5 +11,6 @@ T[][] powerSet(T)(in T[] s) pure nothrow { 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 index 15761ed49e..1215f156ac 100644 --- a/Task/Power-set/D/power-set-2.d +++ b/Task/Power-set/D/power-set-2.d @@ -1,23 +1,32 @@ -auto powerSet(T)(T[] xs) pure nothrow { - auto output = new T[xs.length]; - immutable size_t len = 1U << xs.length; - - struct Result { +auto powerSet(T)(T[] xs) pure nothrow @safe { + static struct Result { + T[] xsLocal, output; + size_t len; 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 { + this(T[] xs_) pure nothrow @safe { + this.xsLocal = xs_; + this.output.length = xs_.length; + this.len = 1U << xs_.length; + } + + @property empty() const pure nothrow @safe { + return bits == len; + } + + void popFront() pure nothrow @safe { bits++; } + @property save() pure nothrow @safe { return this; } + + T[] front() pure nothrow @safe { size_t pos = 0; - foreach (immutable size_t i; 0 .. xs.length) + foreach (immutable size_t i; 0 .. xsLocal.length) if (bits & (1 << i)) - output[pos++] = xs[i]; + output[pos++] = xsLocal[i]; return output[0 .. pos]; } } - return Result(); + return Result(xs); } version (power_set2_main) { diff --git a/Task/Power-set/Go/power-set.go b/Task/Power-set/Go/power-set.go index 81bae2ce43..6ee8e0fc46 100644 --- a/Task/Power-set/Go/power-set.go +++ b/Task/Power-set/Go/power-set.go @@ -1,108 +1,117 @@ package main import ( - "fmt" - "strconv" + "bytes" + "fmt" + "strconv" ) // types needed to implement general purpose sets are element and set // element is an interface, allowing different kinds of elements to be // implemented and stored in sets. -type element interface { - // an element must be distinguishable from other elements to satisfy - // the mathematical definition of a set. a.eq(b) must give the same - // result as b.eq(a). - eq(element) bool - // String result is used only for printable output. Given a, b where - // a.eq(b), it is not required that a.String() == b.String(). - String() string +type elem interface { + // an element must be distinguishable from other elements to satisfy + // the mathematical definition of a set. a.eq(b) must give the same + // result as b.eq(a). + Eq(elem) bool + // String result is used only for printable output. Given a, b where + // a.eq(b), it is not required that a.String() == b.String(). + fmt.Stringer } // integer type satisfying element interface -type intEle int +type Int int -func (i intEle) eq(e element) bool { - if j, ok := e.(intEle); ok { - return i == j - } - return false +func (i Int) Eq(e elem) bool { + j, ok := e.(Int) + return ok && i == j } -func (i intEle) String() string { - return strconv.Itoa(int(i)) +func (i Int) String() string { + return strconv.Itoa(int(i)) } -// set type implemented as a simple list. methods will be added to -// make it satisfy the element interface, allowing sets of sets. -type set []element +// a set is a slice of elem's. methods are added to implement +// the element interface, to allow nesting. +type set []elem // uniqueness of elements can be ensured by using add method -func (s *set) addEle(e element) { - if !s.hasEle(e) { - *s = append(*s, e) - } +func (s *set) add(e elem) { + if !s.has(e) { + *s = append(*s, e) + } } -func (s *set) hasEle(e element) bool { - for _, ex := range *s { - if e.eq(ex) { - return true - } - } - return false +func (s *set) has(e elem) bool { + for _, ex := range *s { + if e.Eq(ex) { + return true + } + } + return false } -// method to satify element interface -func (s set) eq(e element) bool { - t, ok := e.(set) - if !ok { - return false - } - if len(s) != len(t) { - return false - } - for _, se := range s { - if !t.hasEle(se) { - return false - } - } - return true +// elem.Eq +func (s set) Eq(e elem) bool { + t, ok := e.(set) + if !ok { + return false + } + if len(s) != len(t) { + return false + } + for _, se := range s { + if !t.has(se) { + return false + } + } + return true } -// method to satify element interface +// elem.String func (s set) String() string { - r := "{" - for _, e := range s { - if len(r) > 1 { - r += " " - } - r += fmt.Sprint(e) - } - return r + "}" + if len(s) == 0 { + return "∅" + } + var buf bytes.Buffer + buf.WriteRune('{') + for i, e := range s { + if i > 0 { + buf.WriteRune(',') + } + buf.WriteString(e.String()) + } + buf.WriteRune('}') + return buf.String() } // method required for task func (s set) powerSet() set { - r := set{set{}} - for _, es := range s { - var u set - for _, er := range r { - u = append(u, append(er.(set), es)) - } - r = append(r, u...) - } - return r + r := set{set{}} + for _, es := range s { + var u set + for _, er := range r { + u = append(u, append(er.(set), es)) + } + r = append(r, u...) + } + return r } func main() { - var s set - for _, i := range []intEle{1, 2, 2, 3, 4, 4, 4} { - s.addEle(i) - } - fmt.Println(s) - fmt.Println("length =", len(s)) - ps := s.powerSet() - fmt.Println(ps) - fmt.Println("length =", len(ps)) + var s set + for _, i := range []Int{1, 2, 2, 3, 4, 4, 4} { + s.add(i) + } + fmt.Println(" s:", s, "length:", len(s)) + ps := s.powerSet() + fmt.Println(" 𝑷(s):", ps, "length:", len(ps)) + + var empty set + fmt.Println(" empty:", empty, "len:", len(empty)) + ps = empty.powerSet() + fmt.Println(" 𝑷(∅):", ps, "len:", len(ps)) + ps = ps.powerSet() + fmt.Println("𝑷(𝑷(∅)):", ps, "len:", len(ps)) } diff --git a/Task/Power-set/Java/power-set-3.java b/Task/Power-set/Java/power-set-3.java index 5efb15a167..662f137272 100644 --- a/Task/Power-set/Java/power-set-3.java +++ b/Task/Power-set/Java/power-set-3.java @@ -2,9 +2,9 @@ public static > LinkedList> BinPow LinkedList A){ LinkedList> ans= new LinkedList>(); int ansSize = (int)Math.pow(2, A.size()); - for(Integer i= 0;i< ansSize;++i){ - String bin= Integer.toString(i, 2); //convert to binary - while(bin.length() < A.size())bin = "0" + bin; //pad with 0's + for(int i= 0;i< ansSize;++i){ + String bin= Integer.toBinaryString(i); //convert to binary + while(bin.length() < A.size()) bin = "0" + bin; //pad with 0's LinkedList thisComb = new LinkedList(); //place to put one combination for(int j= 0;j< A.size();++j){ if(bin.charAt(j) == '1')thisComb.add(A.get(j)); diff --git a/Task/Power-set/Perl/power-set-7.pl b/Task/Power-set/Perl/power-set-7.pl new file mode 100644 index 0000000000..a7e912522e --- /dev/null +++ b/Task/Power-set/Perl/power-set-7.pl @@ -0,0 +1,21 @@ +use strict; +use warnings; +sub powerset(&@) { + my $callback = shift; + my $bitmask = ''; + my $bytes = @_/8; + { + my @indices = grep vec($bitmask, $_, 1), 0..$#_; + $callback->( @_[@indices] ); + ++vec($bitmask, $_, 8) and last for 0 .. $bytes; + redo if @indices != @_; + } +} + +print "powerset of empty set:\n"; +powerset { print "[@_]\n" }; +print "powerset of set {1,2,3,4}:\n"; +powerset { print "[@_]\n" } 1..4; +my $i = 0; +powerset { ++$i } 1..9; +print "The powerset of a nine element set contains $i elements.\n"; diff --git a/Task/Power-set/Ruby/power-set.rb b/Task/Power-set/Ruby/power-set.rb index b480e23622..9276428bb6 100644 --- a/Task/Power-set/Ruby/power-set.rb +++ b/Task/Power-set/Ruby/power-set.rb @@ -1,5 +1,6 @@ # Based on http://johncarrino.net/blog/2006/08/11/powerset-in-ruby/ -# See the link if you want a shorter version. This was intended to show the reader how the method works. +# See the link if you want a shorter version. +This was intended to show the reader how the method works. class Array # Adds a power_set method to every array, i.e.: [1, 2].power_set def power_set diff --git a/Task/Power-set/SAS/power-set-1.sas b/Task/Power-set/SAS/power-set-1.sas new file mode 100644 index 0000000000..8acbef9def --- /dev/null +++ b/Task/Power-set/SAS/power-set-1.sas @@ -0,0 +1,53 @@ +options mprint mlogic symbolgen source source2; + +%macro SubSets (FieldCount = ); +data _NULL_; + Fields = &FieldCount; + SubSets = 2**Fields; + call symput ("NumSubSets", SubSets); +run; + +%put &NumSubSets; + +data inital; + %do j = 1 %to &FieldCount; + F&j. = 1; + %end; +run; + +data SubSets; + set inital; + RowCount =_n_; + call symput("SetCount",RowCount); +run; + +%put SetCount ; + +%do %while (&SetCount < &NumSubSets); + +data loop; + %do j=1 %to &FieldCount; + if rand('GAUSSIAN') > rand('GAUSSIAN') then F&j. = 1; + %end; + +data SubSets_ ; +set SubSets loop; +run; + +proc sort data=SubSets_ nodupkey; + by F1 - F&FieldCount.; +run; + +data Subsets; + set SubSets_; + RowCount =_n_; +run; + +proc sql noprint; + select max(RowCount) into :SetCount + from SubSets; +quit; +run; + +%end; +%Mend SubSets; diff --git a/Task/Power-set/SAS/power-set-2.sas b/Task/Power-set/SAS/power-set-2.sas new file mode 100644 index 0000000000..75d4965007 --- /dev/null +++ b/Task/Power-set/SAS/power-set-2.sas @@ -0,0 +1 @@ +%SubSets(FieldCount = 5); diff --git a/Task/Power-set/Scala/power-set-1.scala b/Task/Power-set/Scala/power-set-1.scala new file mode 100644 index 0000000000..d7614cd41f --- /dev/null +++ b/Task/Power-set/Scala/power-set-1.scala @@ -0,0 +1,9 @@ +import scala.compat.Platform.currentTime + +object Powerset extends App { + def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el)} + + assert(powerset(Set(1, 2, 3, 4)) == Set(Set.empty, Set(1), Set(2), Set(3), Set(4), Set(1, 2), Set(1, 3), Set(1, 4), + Set(2, 3), Set(2, 4), Set(3, 4), Set(1, 2, 3), Set(1, 3, 4), Set(1, 2, 4), Set(2, 3, 4), Set(1, 2, 3, 4))) + println(s"Successfully completed without errors. [total ${currentTime - executionStart} ms]") +} diff --git a/Task/Power-set/Scala/power-set-2.scala b/Task/Power-set/Scala/power-set-2.scala new file mode 100644 index 0000000000..d7ab2b60cf --- /dev/null +++ b/Task/Power-set/Scala/power-set-2.scala @@ -0,0 +1 @@ +def powerset[A](s: Set[A]) = (0 to s.size).map(s.toSeq.combinations(_)).reduce(_ ++ _).map(_.toSet) diff --git a/Task/Power-set/Scala/power-set.scala b/Task/Power-set/Scala/power-set.scala deleted file mode 100644 index a2ecb2a4a2..0000000000 --- a/Task/Power-set/Scala/power-set.scala +++ /dev/null @@ -1 +0,0 @@ -def powerset[A](s: Set[A]) = s.foldLeft(Set(Set.empty[A])) { case (ss, el) => ss ++ ss.map(_ + el) } diff --git a/Task/Power-set/Scheme/power-set-3.ss b/Task/Power-set/Scheme/power-set-3.ss index 21be5907d4..3ddad930f9 100644 --- a/Task/Power-set/Scheme/power-set-3.ss +++ b/Task/Power-set/Scheme/power-set-3.ss @@ -1,7 +1,5 @@ -(1 2) -(1 3) -(1) -(2 3) -(2) -(3) -() +(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/Price-fraction/Clojure/price-fraction.clj b/Task/Price-fraction/Clojure/price-fraction.clj new file mode 100644 index 0000000000..8a766b0bda --- /dev/null +++ b/Task/Price-fraction/Clojure/price-fraction.clj @@ -0,0 +1,4 @@ +(def values [10 18 26 32 38 44 50 54 58 62 66 70 74 78 82 86 90 94 98 100]) + +(defn price [v] + (format "%.2f" (double (/ (values (int (/ (- (* v 100) 1) 5))) 100)))) diff --git a/Task/Price-fraction/Factor/price-fraction.factor b/Task/Price-fraction/Factor/price-fraction.factor new file mode 100644 index 0000000000..2abc667614 --- /dev/null +++ b/Task/Price-fraction/Factor/price-fraction.factor @@ -0,0 +1,25 @@ +CONSTANT: dispensary-data { +{ 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 } } + +: price-fraction ( n -- n ) dispensary-data [ first over >= ] find 2nip second ; + +{ 0 0.5 0.65 0.66 1 } [ price-fraction ] map diff --git a/Task/Price-fraction/K/price-fraction.k b/Task/Price-fraction/K/price-fraction.k new file mode 100644 index 0000000000..68bf835d28 --- /dev/null +++ b/Task/Price-fraction/K/price-fraction.k @@ -0,0 +1,4 @@ +le:- 0.96 0.91 0.86 0.81 0.76 0.71 0.66 0.61 0.56 0.51 0.46 0.41 0.36 0.31 0.26 0.21 0.16 0.11 0.06 0.0 +out: 1.00 0.98 0.94 0.90 0.86 0.82 0.78 0.74 0.70 0.66 0.62 0.58 0.54 0.50 0.44 0.38 0.32 0.26 0.18 0.1 + +pf:{out@_bin[le;-x]}' diff --git a/Task/Price-fraction/Rust/price-fraction.rust b/Task/Price-fraction/Rust/price-fraction.rust new file mode 100644 index 0000000000..42af7ff761 --- /dev/null +++ b/Task/Price-fraction/Rust/price-fraction.rust @@ -0,0 +1,36 @@ +fn fix_price(n: f64) -> f64 { + let ranges: Vec<(f64, f64, f64)> = vec![ + (0.00, 0.06, 0.10), + (0.06, 0.11, 0.18), + (0.11, 0.16, 0.26), + (0.16, 0.21, 0.32), + (0.21, 0.26, 0.38), + (0.26, 0.31, 0.44), + (0.31, 0.36, 0.50), + (0.36, 0.41, 0.54), + (0.41, 0.46, 0.58), + (0.46, 0.51, 0.62), + (0.51, 0.56, 0.66), + (0.56, 0.61, 0.70), + (0.61, 0.66, 0.74), + (0.66, 0.71, 0.78), + (0.71, 0.76, 0.82), + (0.76, 0.81, 0.86), + (0.81, 0.86, 0.90), + (0.86, 0.91, 0.94), + (0.91, 0.96, 0.98), + (0.96, 1.01, 1.00) + ]; + for &(b, e, a) in ranges.iter() { + if n >= b && n < e { return a; } + } + 1.00 +} + +fn main() { + let mut n: f64 = 0.04; + while n <= 1.01 { + println!("{} => {}", n, fix_price(n)); + n += 0.05; + } +} diff --git a/Task/Primality-by-trial-division/00DESCRIPTION b/Task/Primality-by-trial-division/00DESCRIPTION index 26ee5e3b86..f0af36a7ef 100644 --- a/Task/Primality-by-trial-division/00DESCRIPTION +++ b/Task/Primality-by-trial-division/00DESCRIPTION @@ -1,5 +1,6 @@ Write a boolean function that tells whether a given integer is prime. Remember that 1 and all non-positive numbers are not prime. -Use trial division. Even numbers over two may be eliminated right away. A loop from 3 to √n will suffice, but other loops are allowed. +Use trial division. Even numbers over two may be eliminated right away. +A loop from 3 to √n will suffice, but other loops are allowed. -* Related tasks: [[Sieve of Eratosthenes]], [[Prime decomposition]], [[AKS test for primes]]. +* Related tasks: [[Sequence of primes by Trial Division]], [[Sieve of Eratosthenes]], [[Prime decomposition]], [[AKS test for primes]]. diff --git a/Task/Primality-by-trial-division/Ada/primality-by-trial-division.ada b/Task/Primality-by-trial-division/Ada/primality-by-trial-division-1.ada similarity index 100% rename from Task/Primality-by-trial-division/Ada/primality-by-trial-division.ada rename to Task/Primality-by-trial-division/Ada/primality-by-trial-division-1.ada diff --git a/Task/Primality-by-trial-division/Ada/primality-by-trial-division-2.ada b/Task/Primality-by-trial-division/Ada/primality-by-trial-division-2.ada new file mode 100644 index 0000000000..137404c1f1 --- /dev/null +++ b/Task/Primality-by-trial-division/Ada/primality-by-trial-division-2.ada @@ -0,0 +1,13 @@ +with Prime_Numbers; + +procedure Test_Prime is + + package Integer_Numbers is new + Prime_Numbers (Natural, 0, 1, 2); + use Integer_Numbers; + +begin + if Is_Prime(12) or (not Is_Prime(13)) then + raise Program_Error with "Test_Prime failed!"; + end if; +end Test_Prime; diff --git a/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp new file mode 100644 index 0000000000..55b2ea2dcc --- /dev/null +++ b/Task/Primality-by-trial-division/Common-Lisp/primality-by-trial-division.lisp @@ -0,0 +1,6 @@ +(defun primep (n) + "Is N prime?" + (and (> n 1) + (or (= n 2) (oddp n)) + (loop for i from 3 to (isqrt n) by 2 + never (zerop (rem n i))))) diff --git a/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-1.l b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-1.l new file mode 100644 index 0000000000..b0fa8f46c9 --- /dev/null +++ b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-1.l @@ -0,0 +1,5 @@ +(defun prime (a) + (not (or (< a 2) + (loop for x from 2 to (sqrt a) + when (zerop (% a x)) + return t)))) diff --git a/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-2.l b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-2.l new file mode 100644 index 0000000000..0bccc0e503 --- /dev/null +++ b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-2.l @@ -0,0 +1,4 @@ +(defun prime2 (a) + (and (> a 1) + (loop for x from 2 to (sqrt a) + never (zerop (% a x))))) diff --git a/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-3.l b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-3.l new file mode 100644 index 0000000000..b29ffbee0d --- /dev/null +++ b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-3.l @@ -0,0 +1,5 @@ +(defun prime3 (a) + (and (> a 1) + (or (= a 2) (oddp a)) + (loop for x from 3 to (sqrt a) by 2 + never (zerop (% a x))))) diff --git a/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-4.l b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-4.l new file mode 100644 index 0000000000..8d88a027d0 --- /dev/null +++ b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-4.l @@ -0,0 +1,3 @@ +(defun prime4 (a) + (not (or (< a 2) + (some (lambda (x) (zerop (% a x))) (number-sequence 2 (sqrt a)))))) diff --git a/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-5.l b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-5.l new file mode 100644 index 0000000000..0c9671c55c --- /dev/null +++ b/Task/Primality-by-trial-division/Emacs-Lisp/primality-by-trial-division-5.l @@ -0,0 +1,4 @@ +(defun prime5 (a) + (not (or (< a 2) + (and (/= a 2) (evenp a)) + (some (lambda (x) (zerop (% a x))) (number-sequence 3 (sqrt a) 2))))) diff --git a/Task/Primality-by-trial-division/Forth/primality-by-trial-division.fth b/Task/Primality-by-trial-division/Forth/primality-by-trial-division.fth index 2224952fd1..cfccdffa01 100644 --- a/Task/Primality-by-trial-division/Forth/primality-by-trial-division.fth +++ b/Task/Primality-by-trial-division/Forth/primality-by-trial-division.fth @@ -1,4 +1,4 @@ -: prime? ( n -- ? ) +: prime? ( n -- f ) dup 2 < if drop false else dup 2 = if drop true else dup 1 and 0= if drop false 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 c474ce6cfb..8fb34a2b14 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,10 +1,11 @@ -func isPrime(p int) bool { - if p < 2 { return false } - if p == 2 { return true } - if p % 2 == 0 { return false } - - for i := 3; i*i < p; i += 2 { - if p % i == 0 { return false } +func IsPrime(num uint64) bool { + if num < 2 { return false } + if num == 2 { return true } + if num%2 == 0 { return false } + max := uint64(math.Sqrt(float64(num))) + var i uint64 + for i = 3; i <= max; i += 2 { + if num%i == 0 { return false } } return true } 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 cd891fe793..f8507c2768 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).mod n) (2:[3,5..floor.sqrt(fromIntegral n+1)]) +isPrime n = n==2 || n>2 && all ((> 0).rem 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 50ba20e5e0..a30a416982 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 || (n `mod` f /= 0 && r)) True factors +noDivsBy factors n = foldr (\f r-> f*f>n || ((rem n 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/Mathematica/primality-by-trial-division.math b/Task/Primality-by-trial-division/Mathematica/primality-by-trial-division.math index 2885b1cdf8..c7a22665e8 100644 --- a/Task/Primality-by-trial-division/Mathematica/primality-by-trial-division.math +++ b/Task/Primality-by-trial-division/Mathematica/primality-by-trial-division.math @@ -1,9 +1,5 @@ -IsPrime[n_Integer] := - Module[{k = 2}, - If[n <= 1, Return False]; - If[n == 2, Return True]; - While[k <= Sqrt[n], - If[Mod[n, k] == 0, Return[False], k++] - ]; - Return[True] - ] +IsPrime[n_Integer] := Block[{}, + If[n <= 1, Return[False]]; + If[n == 2, Return[True]]; If[Mod[n, 2] == 0, Return[False]]; + For[k = 3, k <= Sqrt[n], k += 2, If[Mod[n, k] == 0, Return[False]]]; + Return[True]] diff --git a/Task/Primality-by-trial-division/Oz/primality-by-trial-division.oz b/Task/Primality-by-trial-division/Oz/primality-by-trial-division.oz new file mode 100644 index 0000000000..1042196fc3 --- /dev/null +++ b/Task/Primality-by-trial-division/Oz/primality-by-trial-division.oz @@ -0,0 +1,12 @@ + fun {Prime N} + local IPrime in + fun {IPrime N Acc} + if N < Acc*Acc then true + elseif (N mod Acc) == 0 then false + else {IPrime N Acc+1} + end + end + if N < 2 then false + else {IPrime N 2} end + end + end diff --git a/Task/Primality-by-trial-division/Pascal/primality-by-trial-division.pascal b/Task/Primality-by-trial-division/Pascal/primality-by-trial-division-1.pascal similarity index 100% rename from Task/Primality-by-trial-division/Pascal/primality-by-trial-division.pascal rename to Task/Primality-by-trial-division/Pascal/primality-by-trial-division-1.pascal diff --git a/Task/Primality-by-trial-division/Pascal/primality-by-trial-division-2.pascal b/Task/Primality-by-trial-division/Pascal/primality-by-trial-division-2.pascal new file mode 100644 index 0000000000..0d49bf783f --- /dev/null +++ b/Task/Primality-by-trial-division/Pascal/primality-by-trial-division-2.pascal @@ -0,0 +1,14 @@ +program TestTrialDiv; +{$IFDEF FPC} + {$MODE DELPHI}{$Smartlink ON} +{$ELSE} + {$APPLICATION CONSOLE}// for Delphi +{$ENDIF} +uses + primtrial; +{ Test and display primes 0 .. 50 } +begin + repeat + write(actPrime,' '); + until nextPrime > 50; +end. diff --git a/Task/Primality-by-trial-division/Perl/primality-by-trial-division-2.pl b/Task/Primality-by-trial-division/Perl/primality-by-trial-division-2.pl index 7cd1a31460..2c7a28b5aa 100644 --- a/Task/Primality-by-trial-division/Perl/primality-by-trial-division-2.pl +++ b/Task/Primality-by-trial-division/Perl/primality-by-trial-division-2.pl @@ -1,6 +1,13 @@ sub isprime { - ('1' x shift) !~ /^1?$|^(11+?)\1+$/ + my $n = shift; + return ($n >= 2) if $n < 4; + return unless $n % 2 && $n % 3; + my $sqrtn = int(sqrt($n)); + for (my $i = 5; $i <= $sqrtn; $i += 6) { + return unless $n % $i && $n % ($i+2); + } + 1; } - -# A quick test -print join(', ', grep(isprime($_), 0..39)), "\n"; +my $s = 0; +$s += !!isprime($_) for 1..100000; +print "Pi(100,000) = $s\n"; diff --git a/Task/Primality-by-trial-division/Perl/primality-by-trial-division-3.pl b/Task/Primality-by-trial-division/Perl/primality-by-trial-division-3.pl new file mode 100644 index 0000000000..37e87cc69b --- /dev/null +++ b/Task/Primality-by-trial-division/Perl/primality-by-trial-division-3.pl @@ -0,0 +1,4 @@ +sub isprime { + ('1' x shift) !~ /^1?$|^(11+?)\1+$/ +} +print join(', ', grep(isprime($_), 0..39)), "\n"; diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx index a4b723eaea..0b693ddaca 100644 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx +++ b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-1.rexx @@ -1,24 +1,22 @@ /*REXX program tests for primality using (kinda smartish) trial division*/ -parse arg n . /*let user choose how many, maybe*/ -if n=='' then n=10000 /*if not, then assume the default*/ +parse arg n .; if n=='' then n=10000 /*let user choose the upper limit*/ +tell=(n>0); n=abs(n) /*display primes only if N > 0 */ p=0 /*a count of primes (so far). */ do j=-57 to n /*start in the cellar and work up*/ - if \isprime(j) then iterate /*if not prime, keep looking. */ + if \isPrime(j) then iterate /*if not prime, keep looking. */ p=p+1 /*bump the jelly bean counter. */ - if j<99 then say right(j,20) 'is prime.' /*Just show wee primes.*/ + if tell then say right(j,20) 'is prime.' /*maybe show the prime.*/ end /*j*/ say -say "There are" p "primes up to" n '(inclusive).' +say "There are " p " primes up to " n ' (inclusive).' exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────ISPRIME subroutine──────────────────*/ -isprime: procedure; parse arg x /*get the number in question*/ -if \datatype(x,'W') then return 0 /*X not an integer? ¬prime.*/ +isPrime: procedure; parse arg x /*get the number in question*/ if wordpos(x,'2 3 5 7')\==0 then return 1 /*is number a teacher's pet?*/ if x<2 | x//2==0 | x//3==0 then return 0 /*weed out the riff-raff. */ - do k=5 by 6 until k*k > x /*skips odd multiples of 3. */ - if x//k==0 | x//(k+2)==0 then return 0 /*do a pair of divides (mod)*/ - end /*k*/ - /*Note: // is modulus. */ + do k=5 by 6 until k*k>x /*skips odd multiples of 3. */ + if x//k==0 | x//(k+2)==0 then return 0 /*a pair of divides. ___*/ + end /*k*/ /*divide up through the √ x.*/ + /*Note: // is remainder.*/ return 1 /*done dividing, it's prime.*/ diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx index 3e24e6bc59..fae0b627cf 100644 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx +++ b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-2.rexx @@ -1,26 +1,23 @@ /*REXX program tests for primality using (kinda smartish) trial division*/ -parse arg n . /*let user choose how many, maybe*/ -if n=='' then n=10000 /*if not, then assume the default*/ +parse arg n .; if n=='' then n=10000 /*let user choose the upper limit*/ +tell=(n>0); n=abs(n) /*display primes only if N > 0 */ p=0 /*a count of primes (so far). */ do j=-57 to n /*start in the cellar and work up*/ - if \isprime(j) then iterate /*if not prime, then keep looking*/ + if \isPrime(j) then iterate /*if not prime, then keep looking*/ p=p+1 /*bump the jelly bean counter. */ - if j<99 then say right(j,20) 'is prime.' /*Just show wee primes.*/ + if tell then say right(j,20) 'is prime.' /*maybe show the prime.*/ end /*j*/ - -say; say "There are" p "primes up to" n '(inclusive).' +say +say "There are " p " primes up to " n ' (inclusive).' exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────ISPRIME subroutine──────────────────*/ -isprime: procedure; parse arg x /*get integer to be investigated.*/ -if \datatype(x,'W') then return 0 /*X isn't an integer? Not prime.*/ -if x<11 then return wordpos(x,'2 3 5 7')\==0 /*is it a wee prime? */ -if x//2==0 then return 0 /*eliminate the evens. */ +isPrime: procedure; parse arg x /*get integer to be investigated.*/ +if x<11 then return wordpos(x,'2 3 5 7')\==0 /*is it a wee prime?*/ +if x//2==0 then return 0 /*eliminate all the even numbers.*/ if x//3==0 then return 0 /* ··· and eliminate the triples.*/ - /*right dig test: faster than //.*/ - do k=5 by 6 until k*k > x /*this skips odd multiples of 3. */ - if x // k == 0 then return 0 /*perform a divide (modulus), */ - if x // (k+2) == 0 then return 0 /* ··· and the next umpty one. */ - end /*k*/ - /*Note: // is modulus. */ -return 1 /*did all divisions, it's prime. *// + + do k=5 by 6 until k*k>x /*this skips odd multiples of 3. */ + if x//k ==0 then return 0 /*perform a divide (modulus), */ + if x//(k+2)==0 then return 0 /* ··· and the next umpty one. */ + end /*k*/ /*Note: REXX // is remainder*/ +return 1 /*did all divisions, it's prime. */ diff --git a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx index 7d83817a20..55ba3e170c 100644 --- a/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx +++ b/Task/Primality-by-trial-division/REXX/primality-by-trial-division-3.rexx @@ -1,28 +1,24 @@ /*REXX program tests for primality using (kinda smartish) trial division*/ -parse arg n . /*let user choose how many, maybe*/ -if n=='' then n=10000 /*if not, then assume the default*/ +parse arg n .; if n=='' then n=10000 /*let user choose the upper limit*/ +tell=(n>0); n=abs(n) /*display primes only if N > 0 */ p=0 /*a count of primes (so far). */ do j=-57 to n /*start in the cellar and work up*/ - if \isprime(j) then iterate /*if not prime, then keep looking*/ + if \isPrime(j) then iterate /*if not prime, then keep looking*/ p=p+1 /*bump the jelly bean counter. */ - if j<99 then say right(j,20) 'is prime.' /*Just show wee primes.*/ + if tell then say right(j,20) 'is prime.' /*maybe show the prime.*/ end /*j*/ - -say; say "There are" p "primes up to" n '(inclusive).' +say +say "There are " p " primes up to " n ' (inclusive).' exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────ISPRIME subroutine──────────────────*/ -isprime: procedure; parse arg x /*get integer to be investigated.*/ -if \datatype(x,'W') then return 0 /*X isn't an integer? Not prime.*/ -if x<107 then do /*test for (low) special cases. */ - _='2 3 5 7 11 13 17 19 23 29 31 37 41 43 47', /*list of ··*/ - '53 59 61 67 71 73 79 83 89 97 101 103' /*wee primes*/ - return wordpos(x,_)\==0 /*is it a wee prime? ··· or not?*/ - end +isPrime: procedure; parse arg x /*get integer to be investigated.*/ +if x<107 then return wordpos(x, '2 3 5 7', /*test for some low primes*/ + '11 13 17 19 23 29 31 37 41 43 47 53', /*list of ··*/ + '59 61 67 71 73 79 83 89 97 101 103')\==0 /*loo primes*/ -if x// 2 ==0 then return 0 /*eliminate the evens. */ +if x// 2 ==0 then return 0 /*eliminate all the even numbers.*/ if x// 3 ==0 then return 0 /* ··· and eliminate the triples.*/ -if right(x,1) == 5 then return 0 /* ··· and eliminate the nickels.*/ +if right(x,1) ==5 then return 0 /* ··· and eliminate the nickels.*/ if x// 7 ==0 then return 0 /* ··· and eliminate the luckies.*/ if x//11 ==0 then return 0 if x//13 ==0 then return 0 @@ -47,10 +43,9 @@ if x//89 ==0 then return 0 if x//97 ==0 then return 0 if x//101==0 then return 0 if x//103==0 then return 0 - /*Note: // is modulus. */ - do k=107 by 6 while k*k<=x /*this skips odd multiples of 3. */ - if x // k == 0 then return 0 /*perform a divide (modulus), */ - if x // (k+2) == 0 then return 0 /* ··· and the next umpty one. */ - end /*k*/ - + /*Note: REXX // is remainder*/ + do k=107 by 6 while k*k<=x /*this skips odd multiples of 3. */ + if x//k ==0 then return 0 /*perform a divide (modulus), */ + if x//(k+2)==0 then return 0 /* ··· and the next also. ___ */ + end /*k*/ /*divide up through the √ x. */ return 1 /*after all that, ··· it's prime.*/ diff --git a/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust b/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust new file mode 100644 index 0000000000..e2496cc94a --- /dev/null +++ b/Task/Primality-by-trial-division/Rust/primality-by-trial-division.rust @@ -0,0 +1,16 @@ +fn is_prime(n: u64) -> bool { + if n == 2 { return true; } + if n % 2 == 0 || n < 3 { return false; } + for i in range(3u64, ((n as f64).sqrt() as u64) + 1) { + if n % i == 0 { return false; } + } + true +} + +fn main() { + for i in range(1u64, 30u64) { + if is_prime(i) { + println!("{} is prime!", i); + } + } +} diff --git a/Task/Prime-decomposition/00DESCRIPTION b/Task/Prime-decomposition/00DESCRIPTION index 277bde1d04..5c796a1614 100644 --- a/Task/Prime-decomposition/00DESCRIPTION +++ b/Task/Prime-decomposition/00DESCRIPTION @@ -1,6 +1,13 @@ -The prime decomposition of a number is defined as a list of prime numbers which when all multiplied together, are equal to that number. Example: 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} +{{omit from|GUISS}} +The prime decomposition of a number is defined as a list of prime numbers +which when all multiplied together, are equal to that number. -Write a function which returns an [[array]] or [[Collections|collection]] which contains the prime decomposition of a given number, n, greater than 1. If your language does not have an isPrime-like function available, you may assume that you have a function which determines whether a number is prime (note its name before your code). +Example: 12 = 2 × 2 × 3, so its prime decomposition is {2, 2, 3} + +Write a function which returns an [[array]] or [[Collections|collection]] which contains the prime decomposition of a given number, n, greater than 1. +If your language does not have an isPrime-like function available, +you may assume that you have a function which determines +whether a number is prime (note its name before your code). If you would like to test code from this task, you may use code from [[Primality by Trial Division|trial division]] or the [[Sieve of Eratosthenes]]. diff --git a/Task/Prime-decomposition/AWK/prime-decomposition.awk b/Task/Prime-decomposition/AWK/prime-decomposition.awk index d6321e48ef..befd4ba5bd 100644 --- a/Task/Prime-decomposition/AWK/prime-decomposition.awk +++ b/Task/Prime-decomposition/AWK/prime-decomposition.awk @@ -1,3 +1,4 @@ +# Usage: awk -f primefac.awk function pfac(n, r, f){ r = ""; f = 2 while (f <= n) { diff --git a/Task/Prime-decomposition/Ada/prime-decomposition-1.ada b/Task/Prime-decomposition/Ada/prime-decomposition-1.ada index 7ade825047..c2a22ba8f5 100644 --- a/Task/Prime-decomposition/Ada/prime-decomposition-1.ada +++ b/Task/Prime-decomposition/Ada/prime-decomposition-1.ada @@ -4,10 +4,12 @@ generic One : Number; Two : Number; with function "+" (X, Y : Number) return Number is <>; + with function "*" (X, Y : Number) return Number is <>; with function "/" (X, Y : Number) return Number is <>; with function "mod" (X, Y : Number) return Number is <>; - with function ">=" (X, Y : Number) return Boolean is <>; + with function ">" (X, Y : Number) return Boolean is <>; package Prime_Numbers is type Number_List is array (Positive range <>) of Number; function Decompose (N : Number) return Number_List; + function Is_Prime (N : Number) return Boolean; end Prime_Numbers; diff --git a/Task/Prime-decomposition/Ada/prime-decomposition-2.ada b/Task/Prime-decomposition/Ada/prime-decomposition-2.ada index abac72ffac..afc6b0ea56 100644 --- a/Task/Prime-decomposition/Ada/prime-decomposition-2.ada +++ b/Task/Prime-decomposition/Ada/prime-decomposition-2.ada @@ -1,30 +1,31 @@ package body Prime_Numbers is - function Decompose (N : Number) return Number_List is - Size : Natural := 0; - M : Number := N; - K : Number := Two; + -- auxiliary (internal) functions + function First_Factor (N : Number; Start : Number) return Number is + K : Number := Start; begin - -- Estimation of the result length from above - while M >= Two loop - M := (M + One) / Two; - Size := Size + 1; + while ((N mod K) /= Zero) and then (N > (K*K)) loop + K := K + One; end loop; - M := N; - -- Filling the result with prime numbers - declare - Result : Number_List (1..Size); - Index : Positive := 1; - begin - while N >= K loop -- Divisors loop - while Zero = (M mod K) loop -- While divides - Result (Index) := K; - Index := Index + 1; - M := M / K; - end loop; - K := K + One; - end loop; - return Result (1..Index - 1); - end; + if (N mod K) = Zero then + return K; + else + return N; + end if; + end First_Factor; + + function Decompose (N : Number; Start : Number) return Number_List is + F: Number := First_Factor(N, Start); + M: Number := N / F; + begin + if M = One then -- F is the last factor + return (1 => F); + else + return F & Decompose(M, Start); + end if; end Decompose; + -- functions visible from the outside + function Decompose (N : Number) return Number_List is (Decompose(N, Two)); + function Is_Prime (N : Number) return Boolean is + (N > One and then First_Factor(N, Two)=N); end Prime_Numbers; diff --git a/Task/Prime-decomposition/D/prime-decomposition.d b/Task/Prime-decomposition/D/prime-decomposition.d index f4409c3fa5..d597f0fa04 100644 --- a/Task/Prime-decomposition/D/prime-decomposition.d +++ b/Task/Prime-decomposition/D/prime-decomposition.d @@ -1,6 +1,6 @@ import std.stdio, std.bigint, std.algorithm, std.traits, std.range; -Unqual!T[] decompose(T)(in T number) pure /*nothrow*/ +Unqual!T[] decompose(T)(in T number) pure nothrow in { assert(number > 1); } body { diff --git a/Task/Prime-decomposition/Eiffel/prime-decomposition.e b/Task/Prime-decomposition/Eiffel/prime-decomposition.e new file mode 100644 index 0000000000..d523b57238 --- /dev/null +++ b/Task/Prime-decomposition/Eiffel/prime-decomposition.e @@ -0,0 +1,37 @@ +class + PRIME_DECOMPOSITION +feature + factor(p: INTEGER): ARRAY[INTEGER] + require + p_positive: p>0 + local + div,i: INTEGER + next:INTEGER + rest: INTEGER + d: ARRAY[INTEGER] + do + create d.make_empty + if p= 1 then + d.force (1, 1) + Result:= d + end + div:= 2 + next:= 3 + rest:=p + from + i:=1 + until rest=1 + loop + from + until rest\\div/=0 + loop + d.force( div, i) + rest := (rest/div).floor + i:= i+1 + end + div := next + next:= next+2 + end + Result:= d + end +end diff --git a/Task/Prime-decomposition/Haskell/prime-decomposition-1.hs b/Task/Prime-decomposition/Haskell/prime-decomposition-1.hs index 0b3cc204c9..627b0ba6cd 100644 --- a/Task/Prime-decomposition/Haskell/prime-decomposition-1.hs +++ b/Task/Prime-decomposition/Haskell/prime-decomposition-1.hs @@ -1,3 +1,3 @@ -factorize_ n | n > 1 = concat [divs n p | p <- [2..n], isPrime p] +factorize n = concat [divs n p | p <- [2..n], isPrime p] where divs n p = if rem n p==0 then p:divs (quot n p) p else [] diff --git a/Task/Prime-decomposition/Haskell/prime-decomposition-2.hs b/Task/Prime-decomposition/Haskell/prime-decomposition-2.hs index d9b52d9cf0..239fcff53c 100644 --- a/Task/Prime-decomposition/Haskell/prime-decomposition-2.hs +++ b/Task/Prime-decomposition/Haskell/prime-decomposition-2.hs @@ -1,8 +1,6 @@ -factorize n | n > 1 = go n primesList +factorize n = divs n primesList where - go n ds@(d:t) - | d*d > n = [n] - | r == 0 = d : go q ds - | otherwise = go n t - where - (q,r) = quotRem n d + divs n ds@(d:t) | d*d > n = [n | n > 1] + | r == 0 = d : divs q ds + | otherwise = divs n t + where (q,r) = quotRem n d diff --git a/Task/Prime-decomposition/J/prime-decomposition-2.j b/Task/Prime-decomposition/J/prime-decomposition-2.j index d3cc242e45..3628feb42f 100644 --- a/Task/Prime-decomposition/J/prime-decomposition-2.j +++ b/Task/Prime-decomposition/J/prime-decomposition-2.j @@ -1,9 +1,2 @@ -q: 3684 + q: 3684 2 2 3 307 - - _1+2^128x -340282366920938463463374607431768211455 - q: _1+2^128x -3 5 17 257 641 65537 274177 6700417 67280421310721 - */ q: _1+2^128x -340282366920938463463374607431768211455 diff --git a/Task/Prime-decomposition/J/prime-decomposition-3.j b/Task/Prime-decomposition/J/prime-decomposition-3.j new file mode 100644 index 0000000000..5318dd93d0 --- /dev/null +++ b/Task/Prime-decomposition/J/prime-decomposition-3.j @@ -0,0 +1,6 @@ + _1+2^128x +340282366920938463463374607431768211455 + q: _1+2^128x +3 5 17 257 641 65537 274177 6700417 67280421310721 + */ q: _1+2^128x +340282366920938463463374607431768211455 diff --git a/Task/Prime-decomposition/PL-I/prime-decomposition.pli b/Task/Prime-decomposition/PL-I/prime-decomposition.pli index a7b3dc6fe7..72c75aef97 100644 --- a/Task/Prime-decomposition/PL-I/prime-decomposition.pli +++ b/Task/Prime-decomposition/PL-I/prime-decomposition.pli @@ -2,16 +2,13 @@ test: procedure options (main, reorder); declare (n, i) fixed binary (31); get list (n); - put edit ( n, '[' ) (x(1), a); - restart: if is_prime(n) then do; put edit (trim(n), ']' ) (x(1), a); stop; end; - do i = n/2 to 2 by -1; if is_prime(i) then if (mod(n, i) = 0) then @@ -23,7 +20,6 @@ restart: end; put edit ( ' ]' ) (a); - is_prime: procedure (n) options (reorder) returns (bit(1)); declare n fixed binary (31); declare i fixed binary (31); diff --git a/Task/Prime-decomposition/Perl/prime-decomposition.pl b/Task/Prime-decomposition/Perl/prime-decomposition-1.pl similarity index 100% rename from Task/Prime-decomposition/Perl/prime-decomposition.pl rename to Task/Prime-decomposition/Perl/prime-decomposition-1.pl diff --git a/Task/Prime-decomposition/Perl/prime-decomposition-2.pl b/Task/Prime-decomposition/Perl/prime-decomposition-2.pl new file mode 100644 index 0000000000..8fd9a40319 --- /dev/null +++ b/Task/Prime-decomposition/Perl/prime-decomposition-2.pl @@ -0,0 +1,14 @@ +sub prime_factors { + my($n, $p, @out) = (shift, 3); + return if $n < 1; + while (!($n&1)) { $n >>= 1; push @out, 2; } + while ($n > 1 && $p*$p <= $n) { + while ( ($n % $p) == 0) { + $n /= $p; + push @out, $p; + } + $p += 2; + } + push @out, $n if $n > 1; + @out; +} diff --git a/Task/Prime-decomposition/Perl/prime-decomposition-3.pl b/Task/Prime-decomposition/Perl/prime-decomposition-3.pl new file mode 100644 index 0000000000..85864043f5 --- /dev/null +++ b/Task/Prime-decomposition/Perl/prime-decomposition-3.pl @@ -0,0 +1,7 @@ +use ntheory qw/factor forprimes/; +use bigint; + +forprimes { + my $p = 2 ** $_ - 1; + print "2**$_-1: ", join(" ", factor($p)), "\n"; +} 100, 150; diff --git a/Task/Prime-decomposition/Perl/prime-decomposition-4.pl b/Task/Prime-decomposition/Perl/prime-decomposition-4.pl new file mode 100644 index 0000000000..820cd6bb5a --- /dev/null +++ b/Task/Prime-decomposition/Perl/prime-decomposition-4.pl @@ -0,0 +1,13 @@ +use Math::Pari qw/:int factorint isprime/; + +# Convert Math::Pari's format into simple vector +sub factor { + my ($pn,$pc) = @{Math::Pari::factorint(shift)}; + map { ($pn->[$_]) x $pc->[$_] } 0 .. $#$pn; +} + +for (100 .. 150) { + next unless isprime($_); + my $p = 2 ** $_ - 1; + print "2^$_-1: ", join(" ", factor($p)), "\n"; +} diff --git a/Task/Prime-decomposition/Python/prime-decomposition-2.py b/Task/Prime-decomposition/Python/prime-decomposition-2.py index 8175901839..07546c659d 100644 --- a/Task/Prime-decomposition/Python/prime-decomposition-2.py +++ b/Task/Prime-decomposition/Python/prime-decomposition-2.py @@ -5,19 +5,14 @@ except NameError: long = int def fac(n): - step = lambda x: 1 + x*4 - (x//2)*2 + step = lambda x: 1 + (x<<2) - ((x>>1)<<1) maxq = long(floor(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 + return q <= maxq and [q] + fac(n//q) or [n] if __name__ == '__main__': import time diff --git a/Task/Prime-decomposition/Scala/prime-decomposition-1.scala b/Task/Prime-decomposition/Scala/prime-decomposition-1.scala index 16472f5de5..69c9d3e95b 100644 --- a/Task/Prime-decomposition/Scala/prime-decomposition-1.scala +++ b/Task/Prime-decomposition/Scala/prime-decomposition-1.scala @@ -31,10 +31,10 @@ object PrimeFactors extends App { val datum = System.nanoTime val result = factorize(nMersenne) - val mSec = ((System.nanoTime - datum) / 1.e+6).round + val mSec = ((System.nanoTime - datum) / 1.0e+6).round def decStr = { if (lit.length > 30) f"(M has ${lit.length}%3d dec)" else "" } - def sPrime = { if (result.isEmpty) " is a Mersenne prime number." else "" } + def sPrime = { if (result.isEmpty) " is a 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/Priority-queue/C-sharp/priority-queue.cs b/Task/Priority-queue/C-sharp/priority-queue.cs new file mode 100644 index 0000000000..d5891700fd --- /dev/null +++ b/Task/Priority-queue/C-sharp/priority-queue.cs @@ -0,0 +1,60 @@ +using System; + +namespace PriorityQueue +{ + class Program + { + static void Main(string[] args) + { + PriorityQueue PQ = new PriorityQueue(); + PQ.push(3, "Clear drains"); + PQ.push(4, "Feed cat"); + PQ.push(5, "Make tea"); + PQ.push(1, "Solve RC tasks"); + PQ.push(2, "Tax return"); + + while (!PQ.Empty) + { + var Val = PQ.pop(); + Console.WriteLine(Val[0] + " : " + Val[1]); + } + Console.ReadKey(); + } + } + + class PriorityQueue + { + private System.Collections.SortedList PseudoQueue; + + public bool Empty + { + get + { + return PseudoQueue.Count == 0; + } + } + + public PriorityQueue() + { + PseudoQueue = new System.Collections.SortedList(); + } + + public void push(object Priority, object Value) + { + PseudoQueue.Add(Priority, Value); + } + + public object[] pop() + { + object[] ReturnValue = { null, null }; + if (PseudoQueue.Count > 0) + { + ReturnValue[0] = PseudoQueue.GetKey(0); + ReturnValue[1] = PseudoQueue.GetByIndex(0); + + PseudoQueue.RemoveAt(0); + } + return ReturnValue; + } + } +} diff --git a/Task/Priority-queue/Clojure/priority-queue.clj b/Task/Priority-queue/Clojure/priority-queue.clj new file mode 100644 index 0000000000..b5f8e5ceac --- /dev/null +++ b/Task/Priority-queue/Clojure/priority-queue.clj @@ -0,0 +1,19 @@ +user=> (use 'clojure.data.priority-map) + +; priority-map can be used as a priority queue +user=> (def p (priority-map "Clear drains" 3, "Feed cat" 4, "Make tea" 5, "Solve RC tasks" 1)) +#'user/p +user=> p +{"Solve RC tasks" 1, "Clear drains" 3, "Feed cat" 4, "Make tea" 5} + +; You can use assoc or conj to add items +user=> (assoc p "Tax return" 2) +{"Solve RC tasks" 1, "Tax return" 2, "Clear drains" 3, "Feed cat" 4, "Make tea" 5} + +; peek to get first item, pop to give you back the priority-map with the first item removed +user=> (peek p) +["Solve RC tasks" 1] + +; Merge priority-maps together +user=> (into p [["Wax Car" 4]["Paint Fence" 1]["Sand Floor" 3]]) +{"Solve RC tasks" 1, "Paint Fence" 1, "Clear drains" 3, "Sand Floor" 3, "Wax Car" 4, "Feed cat" 4, "Make tea" 5} diff --git a/Task/Priority-queue/Lua/priority-queue-1.lua b/Task/Priority-queue/Lua/priority-queue-1.lua new file mode 100644 index 0000000000..b76bc16b05 --- /dev/null +++ b/Task/Priority-queue/Lua/priority-queue-1.lua @@ -0,0 +1,50 @@ +PriorityQueue = { + __index = { + put = function(self, p, v) + local q = self[p] + if not q then + q = {first = 1, last = 0} + self[p] = q + end + q.last = q.last + 1 + q[q.last] = v + end, + pop = function(self) + for p, q in pairs(self) do + if q.first <= q.last then + local v = q[q.first] + q[q.first] = nil + q.first = q.first + 1 + return p, v + else + self[p] = nil + end + end + end + }, + __call = function(cls) + return setmetatable({}, cls) + end +} + +setmetatable(PriorityQueue, PriorityQueue) + +-- Usage: +pq = PriorityQueue() + +tasks = { + {3, 'Clear drains'}, + {4, 'Feed cat'}, + {5, 'Make tea'}, + {1, 'Solve RC tasks'}, + {2, 'Tax return'} +} + +for _, task in ipairs(tasks) do + print(string.format("Putting: %d - %s", unpack(task))) + pq:put(unpack(task)) +end + +for prio, task in pq.pop, pq do + print(string.format("Popped: %d - %s", prio, task)) +end diff --git a/Task/Priority-queue/Lua/priority-queue-2.lua b/Task/Priority-queue/Lua/priority-queue-2.lua new file mode 100644 index 0000000000..25d4f4705f --- /dev/null +++ b/Task/Priority-queue/Lua/priority-queue-2.lua @@ -0,0 +1,40 @@ +-- Use socket.gettime() for benchmark measurements +-- since it has millisecond precision on most systems +local socket = require("socket") + +n = 10000000 -- number of tasks added (10^7) +m = 1000 -- number different priorities + +local pq = PriorityQueue() + +print(string.format("Adding %d tasks with random priority 1-%d ...", n, m)) +start = socket.gettime() + +for i = 1, n do + pq:put(math.random(m), i) +end + +print(string.format("Elapsed: %.3f ms.", (socket.gettime() - start) * 1000)) + +print("Retrieving all tasks in order...") +start = socket.gettime() + +local pp = 0 +local pv = 0 + +for i = 1, n do + local p, task = pq:pop() + + -- check that tasks are popped in ascending priority + assert(p >= pp) + + if pp == p then + -- check that tasks within one priority maintain the insertion order + assert(task > pt) + end + + pp = p + pt = task +end + +print(string.format("Elapsed: %.3f ms.", (socket.gettime() - start) * 1000)) diff --git a/Task/Priority-queue/Objective-C/priority-queue.m b/Task/Priority-queue/Objective-C/priority-queue.m index b0f8056041..8b01659258 100644 --- a/Task/Priority-queue/Objective-C/priority-queue.m +++ b/Task/Priority-queue/Objective-C/priority-queue.m @@ -14,12 +14,12 @@ CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) { int priority; NSString *name; } -- (id)initWithPriority:(int)p andName:(NSString *)n; +- (instancetype)initWithPriority:(int)p andName:(NSString *)n; - (NSComparisonResult)compare:(Task *)other; @end @implementation Task -- (id)initWithPriority:(int)p andName:(NSString *)n { +- (instancetype)initWithPriority:(int)p andName:(NSString *)n { if ((self = [super init])) { priority = p; name = [n copy]; diff --git a/Task/Priority-queue/Ruby/priority-queue.rb b/Task/Priority-queue/Ruby/priority-queue.rb index 7617624fb1..df1c660604 100644 --- a/Task/Priority-queue/Ruby/priority-queue.rb +++ b/Task/Priority-queue/Ruby/priority-queue.rb @@ -1,7 +1,8 @@ class PriorityQueueNaive - def initialize - @q = Hash.new { |h, k| h[k] = []} - @priorities = [] + def initialize(data=nil) + @q = Hash.new {|h, k| h[k] = []} + data.each {|priority, item| @q[priority] << item} if data + @priorities = @q.keys.sort end def push(priority, item) @@ -20,7 +21,7 @@ class PriorityQueueNaive end def peek - if not empty? + unless empty? @q[@priorities[0]][0] end end @@ -29,6 +30,25 @@ class PriorityQueueNaive @priorities.empty? end + def each + @q.each do |priority, items| + items.each {|item| yield priority, item} + end + end + + def dup + @q.each_with_object(self.class.new) do |(priority, items), obj| + items.each {|item| obj.push(priority, item)} + end + end + + def merge(other) + raise TypeError unless self.class == other.class + pq = dup + other.each {|priority, item| pq.push(priority, item)} + pq # return a new object + end + def inspect @q.inspect end @@ -49,3 +69,14 @@ test.each {|pr, str| pq.push(pr, str) } until pq.empty? puts pq.pop end + +puts +test2 = test.shift(3) +p pq1 = PriorityQueueNaive.new(test) +p pq2 = PriorityQueueNaive.new(test2) +p pq3 = pq1.merge(pq2) +puts "peek : #{pq3.peek}" +until pq3.empty? + puts pq3.pop +end +puts "peek : #{pq3.peek}" diff --git a/Task/Probabilistic-choice/D/probabilistic-choice-2.d b/Task/Probabilistic-choice/D/probabilistic-choice-2.d index e56c9e76e0..2439a28e71 100644 --- a/Task/Probabilistic-choice/D/probabilistic-choice-2.d +++ b/Task/Probabilistic-choice/D/probabilistic-choice-2.d @@ -12,11 +12,8 @@ void main() { double[pr.length] counts = 0.0; auto rnd = Xorshift(unpredictableSeed); - foreach (immutable _; 0 .. nTrials) { - immutable rnd01 = rnd.front / double(rnd.max); - rnd.popFront; - counts[cumulatives[].countUntil!(c => c >= rnd01)]++; - } + foreach (immutable _; 0 .. nTrials) + counts[cumulatives[].countUntil!(c => c >= rnd.uniform01)]++; writeln("Item Target prob Attained prob"); foreach (name, p, co; zip(items, pr, counts[])) diff --git a/Task/Probabilistic-choice/Erlang/probabilistic-choice.erl b/Task/Probabilistic-choice/Erlang/probabilistic-choice.erl new file mode 100644 index 0000000000..56694e9c05 --- /dev/null +++ b/Task/Probabilistic-choice/Erlang/probabilistic-choice.erl @@ -0,0 +1,31 @@ +-module(probabilistic_choice). + +-export([test/0]). + +-define(TRIES, 1000000). + +test() -> + Probs = + [{aleph,1/5}, + {beth,1/6}, + {gimel,1/7}, + {daleth,1/8}, + {he,1/9}, + {waw,1/10}, + {zayin,1/11}, + {heth,1759/27720}], + random:seed(now()), + Trials = + [get_choice(Probs,random:uniform()) || _ <- lists:seq(1,?TRIES)], + [{Glyph,Expected,(length([Glyph || Glyph_ <- Trials, Glyph_ == Glyph])/?TRIES)} + || {Glyph,Expected} <- Probs]. + +get_choice([{Glyph,_}],_) -> + Glyph; +get_choice([{Glyph,Prob}|T],Ran) -> + case (Ran < Prob) of + true -> + Glyph; + false -> + get_choice(T,Ran - Prob) + end. diff --git a/Task/Probabilistic-choice/MATLAB/probabilistic-choice-1.m b/Task/Probabilistic-choice/MATLAB/probabilistic-choice-1.m new file mode 100644 index 0000000000..5edb87c056 --- /dev/null +++ b/Task/Probabilistic-choice/MATLAB/probabilistic-choice-1.m @@ -0,0 +1,11 @@ +function probChoice + choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'}; + w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]; + R = randsample(length(w), 1e6, true, w); + T = tabulate(R); + fprintf('Value\tCount\tPercent\tGoal\n') + for k = 1:size(T, 1) + fprintf('%6s\t%.f\t%.2f%%\t%.2f%%\n', ... + choices{k}, T(k, 2), T(k, 3), 100*w(k)) + end +end diff --git a/Task/Probabilistic-choice/MATLAB/probabilistic-choice-2.m b/Task/Probabilistic-choice/MATLAB/probabilistic-choice-2.m new file mode 100644 index 0000000000..c8554b9772 --- /dev/null +++ b/Task/Probabilistic-choice/MATLAB/probabilistic-choice-2.m @@ -0,0 +1,17 @@ +function probChoice + choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'}; + w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720]; + nSamp = 1e6; + nChoice = length(w); + R = rand(nSamp, 1); + wCS = cumsum(w); + results = zeros(1, nChoice); + fprintf('Value\tCount\tPercent\tGoal\n') + for k = 1:nChoice + choiceKIdxs = R < wCS(k); + R(choiceKIdxs) = k; + results(k) = sum(choiceKIdxs); + fprintf('%6s\t%.f\t%.2f%%\t%.2f%%\n', ... + choices{k}, results(k), 100*results(k)/nSamp, 100*w(k)) + end +end diff --git a/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 b/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 index f624efec45..2ad4eab39f 100644 --- a/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 +++ b/Task/Probabilistic-choice/Perl-6/probabilistic-choice.pl6 @@ -1,19 +1,21 @@ constant TRIALS = 1e4; -my %ps = Z=> 1 «/« (5 .. 11); -%ps = 1 - [+] values %ps; +my @event = ; -my %results; +my @P = 1 «/« (5 .. 11), 1759/27720; +my @cP = [\+] @P; + +my @results; for ^TRIALS { - %results{.key}++ given - first { .value > state $ = rand }, - state % = %ps.keys Z=> [\+] %ps.values; + @results[ + first { @cP[$_] > state $ = rand }, ^@P; + ]++; } -say 'Event Occurred Expected Difference'; -for sort *.value, %results { - my ($occurred, $expected) = .value/TRIALS, %ps{.key}; - printf "%-6s %f %f %f\n", - .key, $occurred, $expected, +say 'Event Occurred Expected Difference'; +for ^@results { + my ($occurred, $expected) = @results[$_], @P[$_]*TRIALS; + printf "%-9s%8.0f%9.1f%12.1f\n", + @event[$_], $occurred, $expected, abs( $occurred - $expected ); } diff --git a/Task/Probabilistic-choice/Scala/probabilistic-choice.scala b/Task/Probabilistic-choice/Scala/probabilistic-choice.scala new file mode 100644 index 0000000000..a225ccd658 --- /dev/null +++ b/Task/Probabilistic-choice/Scala/probabilistic-choice.scala @@ -0,0 +1,64 @@ +object ProbabilisticChoice extends App { + import scala.collection.mutable.LinkedHashMap + + def weightedProb[A](prob: LinkedHashMap[A,Double]): A = { + require(prob.forall{case (_, p) => p > 0 && p < 1}) + assume(prob.values.sum == 1) + def weighted(todo: Iterator[(A,Double)], rand: Double, accum: Double = 0): A = todo.next match { + case (s, i) if rand < (accum + i) => s + case (_, i) => weighted(todo, rand, accum + i) + } + weighted(prob.toIterator, scala.util.Random.nextDouble) + } + + def weightedFreq[A](freq: LinkedHashMap[A,Int]): A = { + require(freq.forall{case (_, f) => f >= 0}) + require(freq.values.sum > 0) + def weighted(todo: Iterator[(A,Int)], rand: Int, accum: Int = 0): A = todo.next match { + case (s, i) if rand < (accum + i) => s + case (_, i) => weighted(todo, rand, accum + i) + } + weighted(freq.toIterator, scala.util.Random.nextInt(freq.values.sum)) + } + + // Tests: + + val probabilities = LinkedHashMap( + 'aleph -> 1.0/5, + 'beth -> 1.0/6, + 'gimel -> 1.0/7, + 'daleth -> 1.0/8, + 'he -> 1.0/9, + 'waw -> 1.0/10, + 'zayin -> 1.0/11, + 'heth -> 1759.0/27720 + ) + + val frequencies = LinkedHashMap( + 'aleph -> 200, + 'beth -> 167, + 'gimel -> 143, + 'daleth -> 125, + 'he -> 111, + 'waw -> 100, + 'zayin -> 91, + 'heth -> 63 + ) + + def check[A](original: LinkedHashMap[A,Double], results: Seq[A]) { + val freq = results.groupBy(x => x).mapValues(_.size.toDouble/results.size) + original.foreach{case (k, v) => + val a = v/original.values.sum + val b = freq(k) + val c = if (Math.abs(a - b) < 0.001) "ok" else "**" + println(f"$k%10s $a%.4f $b%.4f $c") + } + println(" "*10 + f" ${1}%.4f ${freq.values.sum}%.4f") + } + + println("Checking weighted probabilities:") + check(probabilities, for (i <- 1 to 1000000) yield weightedProb(probabilities)) + println + println("Checking weighted frequencies:") + check(frequencies.map{case (a, b) => a -> b.toDouble}, for (i <- 1 to 1000000) yield weightedFreq(frequencies)) +} diff --git a/Task/Probabilistic-choice/Scheme/probabilistic-choice.ss b/Task/Probabilistic-choice/Scheme/probabilistic-choice.ss new file mode 100644 index 0000000000..9c99b63713 --- /dev/null +++ b/Task/Probabilistic-choice/Scheme/probabilistic-choice.ss @@ -0,0 +1,45 @@ +(use-modules (ice-9 format)) + +(define (random-choice probs) + (define choice (random 1.0)) + (define (helper val prob-lis) + (let ((nval (- val (cadar prob-lis)))) + (if + (< nval 0) + (caar prob-lis) + (helper nval (cdr prob-lis))))) + (helper choice probs)) + +(define (add-result result delta table) + (cond + ((null? table) (list (list result delta))) + ((eq? (caar table) result) + (cons (list result (+ (cadar table) delta)) (cdr table))) + (#t (cons (car table) (add-result result delta (cdr table)))))) + +(define (choices trials probs) + (define (helper trial-num freq-table) + (if + (= trial-num trials) + freq-table + (helper + (+ trial-num 1) + (add-result (random-choice probs) (/ 1 trials) freq-table)))) + (helper 0 '())) + +(define (format-results probs results) + (for-each + (lambda (x) + (format + #t + "~10a~10,5f~10,5f~%" + (car x) + (cadr x) + (cadr (assoc (car x) results)))) + probs)) + +(define probs + '((aleph 1/5) (beth 1/6) (gimel 1/7) (daleth 1/8) + (he 1/9) (waw 1/10) (zayin 1/11) (heth 1759/27720))) + +(format-results probs (choices 1000000 probs)) diff --git a/Task/Problem-of-Apollonius/D/problem-of-apollonius.d b/Task/Problem-of-Apollonius/D/problem-of-apollonius.d index e53867e718..74c0218395 100644 --- a/Task/Problem-of-Apollonius/D/problem-of-apollonius.d +++ b/Task/Problem-of-Apollonius/D/problem-of-apollonius.d @@ -17,52 +17,52 @@ Params: Returns: The Circle that is tangent to c1, c2 and c3. */ -pure nothrow Circle -solveApollonius(in Circle c1, in Circle c2, in Circle c3, - in Tangent t1, in Tangent t2, in Tangent t3) { - alias immutable(double) imd; - imd s1 = (t1 == Tangent.externally) ? 1.0 : -1.0; - imd s2 = (t2 == Tangent.externally) ? 1.0 : -1.0; - imd s3 = (t3 == Tangent.externally) ? 1.0 : -1.0; +Circle solveApollonius(in Circle c1, in Circle c2, in Circle c3, + in Tangent t1, in Tangent t2, in Tangent t3) +pure nothrow @safe @nogc { + alias Imd = immutable(double); + Imd s1 = (t1 == Tangent.externally) ? 1.0 : -1.0; + Imd s2 = (t2 == Tangent.externally) ? 1.0 : -1.0; + Imd s3 = (t3 == Tangent.externally) ? 1.0 : -1.0; - imd v11 = 2 * c2.x - 2 * c1.x; - imd v12 = 2 * c2.y - 2 * c1.y; - imd v13 = c1.x ^^ 2 - c2.x ^^ 2 + + Imd v11 = 2 * c2.x - 2 * c1.x; + Imd v12 = 2 * c2.y - 2 * c1.y; + Imd v13 = c1.x ^^ 2 - c2.x ^^ 2 + c1.y ^^ 2 - c2.y ^^ 2 - c1.r ^^ 2 + c2.r ^^ 2; - imd v14 = 2 * s2 * c2.r - 2 * s1 * c1.r; + Imd v14 = 2 * s2 * c2.r - 2 * s1 * c1.r; - imd v21 = 2 * c3.x - 2 * c2.x; - imd v22 = 2 * c3.y - 2 * c2.y; - imd v23 = c2.x ^^ 2 - c3.x ^^ 2 + + Imd v21 = 2 * c3.x - 2 * c2.x; + Imd v22 = 2 * c3.y - 2 * c2.y; + Imd v23 = c2.x ^^ 2 - c3.x ^^ 2 + c2.y ^^ 2 - c3.y ^^ 2 - c2.r ^^ 2 + c3.r ^^ 2; - imd v24 = 2 * s3 * c3.r - 2 * s2 * c2.r; + Imd v24 = 2 * s3 * c3.r - 2 * s2 * c2.r; - imd w12 = v12 / v11; - imd w13 = v13 / v11; - imd w14 = v14 / v11; + Imd w12 = v12 / v11; + Imd w13 = v13 / v11; + Imd w14 = v14 / v11; - imd w22 = v22 / v21 - w12; - imd w23 = v23 / v21 - w13; - imd w24 = v24 / v21 - w14; + Imd w22 = v22 / v21 - w12; + Imd w23 = v23 / v21 - w13; + Imd w24 = v24 / v21 - w14; - imd P = -w23 / w22; - imd Q = w24 / w22; - imd M = -w12 * P - w13; - imd N = w14 - w12 * Q; + Imd P = -w23 / w22; + Imd Q = w24 / w22; + Imd M = -w12 * P - w13; + Imd N = w14 - w12 * Q; - imd a = N * N + Q ^^ 2 - 1; - imd b = 2 * M * N - 2 * N * c1.x + + Imd a = N * N + Q ^^ 2 - 1; + Imd b = 2 * M * N - 2 * N * c1.x + 2 * P * Q - 2 * Q * c1.y + 2 * s1 * c1.r; - imd c = c1.x ^^ 2 + M ^^ 2 - 2 * M * c1.x + + Imd c = c1.x ^^ 2 + M ^^ 2 - 2 * M * c1.x + P ^^ 2 + c1.y ^^ 2 - 2 * P * c1.y - c1.r ^^ 2; // find a root of a quadratic equation. // This requires the circle centers not to be e.g. colinear - imd D = b ^^ 2 - 4 * a * c; - imd rs = (-b - sqrt(D)) / (2 * a); + Imd D = b ^^ 2 - 4 * a * c; + Imd rs = (-b - D.sqrt) / (2 * a); return Circle(M + N * rs, P + Q * rs, rs); } @@ -72,9 +72,9 @@ void main() { immutable c2 = Circle(4.0, 0.0, 1.0); immutable c3 = Circle(2.0, 4.0, 2.0); - alias Tangent.externally te; - writeln(solveApollonius(c1, c2, c3, te, te, te)); + alias Te = Tangent.externally; + solveApollonius(c1, c2, c3, Te, Te, Te).writeln; - alias Tangent.internally ti; - writeln(solveApollonius(c1, c2, c3, ti, ti, ti)); + alias Ti = Tangent.internally; + solveApollonius(c1, c2, c3, Ti, Ti, Ti).writeln; } diff --git a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx index 42eecf76a6..498a8b52bb 100644 --- a/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx +++ b/Task/Problem-of-Apollonius/REXX/problem-of-apollonius.rexx @@ -1,15 +1,15 @@ -/*REXX program to solve the problem of Apollonius, named after the */ -/* Greek, Apollonius of Perga [Pergaeus] (circa 262 BC ──► 190 BC).*/ -w=20; numeric digits w-5 /*width used to display numbers. */ -c1.x=0; c1.y=0; c1.r=1 -c2.x=4; c2.y=0; c2.r=1 -c3.x=2; c3.y=4; c3.r=2 -call tell 'external tangent:', solveApollonius( 1, 1, 1) -call tell 'internal tangent:', solveApollonius(-1,-1,-1) +/*REXX program to solve the problem of Apollonius, named after the Greek*/ +/*────────── Apollonius of Perga [Pergæus] (circa 262 BC ──► 190 BC).*/ +w=20; numeric digits w-5 /*width used to display numbers. */ + c1.x=0; c1.y=0; c1.r=1 + c2.x=4; c2.y=0; c2.r=1 + c3.x=2; c3.y=4; c3.r=2 +call tell 'external tangent:', solveApollonius( 1, 1, 1) +call tell 'internal tangent:', solveApollonius(-1, -1, -1) exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SOLVEAPOLLONIUS subroutine──────────*/ -/*───────────────────this code should be covered with a very think tarp.*/ -solveApollonius: arg s1,s2,s3 /*internal or external tangent ? */ +/*───────────────────this code should be covered with a very thick tarp.*/ +solveApollonius: parse arg s1,s2,s3 /*internal or external tangent ? */ numeric digits digits()*3 /*reduce rounding: use triple dig*/ x1=c1.x; x2=c2.x; x3=c3.x y1=c1.y; y2=c2.y; y3=c3.y diff --git a/Task/Program-name/Mercury/program-name.mercury b/Task/Program-name/Mercury/program-name.mercury new file mode 100644 index 0000000000..5f00d2a30a --- /dev/null +++ b/Task/Program-name/Mercury/program-name.mercury @@ -0,0 +1,16 @@ +:- module program_name. +:- interface. + +:- import_module io. +:- pred main(io::di, io::uo) is det. + +:- implementation. + +main(!IO) :- + % The first argument is used as the program name if it is not otherwise + % available. (We could also have used the predicate io.progname_base/4 + % if we did not want path preceding the program name.) + io.progname("", ProgName, !IO), + io.print_line(ProgName, !IO). + +:- end_module program_name. diff --git a/Task/Program-name/Oberon-2/program-name.oberon-2 b/Task/Program-name/Oberon-2/program-name.oberon-2 new file mode 100644 index 0000000000..bf2b7663d5 --- /dev/null +++ b/Task/Program-name/Oberon-2/program-name.oberon-2 @@ -0,0 +1,7 @@ +MODULE ProgramName; +IMPORT + NPCT:Args, + Out; +BEGIN + Out.Object("Program name: " + Args.Get(0));Out.Ln +END ProgramName. diff --git a/Task/Program-name/Perl/program-name.pl b/Task/Program-name/Perl/program-name-1.pl similarity index 100% rename from Task/Program-name/Perl/program-name.pl rename to Task/Program-name/Perl/program-name-1.pl diff --git a/Task/Program-name/Perl/program-name-2.pl b/Task/Program-name/Perl/program-name-2.pl new file mode 100644 index 0000000000..1059d34557 --- /dev/null +++ b/Task/Program-name/Perl/program-name-2.pl @@ -0,0 +1,2 @@ +use FindBin; +print "Program name $FindBin::Script\n"; diff --git a/Task/Program-name/Ruby/program-name.rb b/Task/Program-name/Ruby/program-name.rb index ffe047413e..41ccadb088 100644 --- a/Task/Program-name/Ruby/program-name.rb +++ b/Task/Program-name/Ruby/program-name.rb @@ -1,4 +1,4 @@ #!/usr/bin/env ruby -puts "Path: #{$0}" +puts "Path: #{$PROGRAM_NAME}" # or puts "Path: #{$0}" puts "Name: #{File.basename $0}" diff --git a/Task/Program-name/Scala/program-name.scala b/Task/Program-name/Scala/program-name.scala new file mode 100644 index 0000000000..337c8e0b8a --- /dev/null +++ b/Task/Program-name/Scala/program-name.scala @@ -0,0 +1,5 @@ +object ScriptName extends App { + println(s"Program of instantiated object: ${this.getClass.getName}") + // Not recommended, due various implementations + println(s"Program via enviroment: ${System.getProperty("sun.java.command")}") +} diff --git a/Task/Program-name/TXR/program-name.txr b/Task/Program-name/TXR/program-name.txr index e869d07d59..63d2b6dbdb 100644 --- a/Task/Program-name/TXR/program-name.txr +++ b/Task/Program-name/TXR/program-name.txr @@ -1,2 +1,2 @@ -#!/usr/local/bin/txr +#!/usr/local/bin/txr -B @(bind my-name @*self-path*) diff --git a/Task/Program-termination/00DESCRIPTION b/Task/Program-termination/00DESCRIPTION index d657dcb630..3689e92664 100644 --- a/Task/Program-termination/00DESCRIPTION +++ b/Task/Program-termination/00DESCRIPTION @@ -1,3 +1,4 @@ -Show the syntax for a complete stoppage of a program inside a [[Conditional Structures|conditional]]. This includes all [[threads]]/[[processes]] which are part of your program. +Show the syntax for a complete stoppage of a program inside a [[Conditional Structures|conditional]]. +This includes all [[threads]]/[[processes]] which are part of your program. Explain the cleanup (or lack thereof) caused by the termination (allocated memory, database connections, open files, object finalizers/destructors, run-on-exit hooks, etc.). Unless otherwise described, no special cleanup outside that provided by the operating system is provided. diff --git a/Task/Program-termination/00META.yaml b/Task/Program-termination/00META.yaml index 659c8686af..3548159ac8 100644 --- a/Task/Program-termination/00META.yaml +++ b/Task/Program-termination/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: Basic language learning diff --git a/Task/Program-termination/AWK/program-termination.awk b/Task/Program-termination/AWK/program-termination-1.awk similarity index 100% rename from Task/Program-termination/AWK/program-termination.awk rename to Task/Program-termination/AWK/program-termination-1.awk diff --git a/Task/Program-termination/AWK/program-termination-2.awk b/Task/Program-termination/AWK/program-termination-2.awk new file mode 100644 index 0000000000..536788e335 --- /dev/null +++ b/Task/Program-termination/AWK/program-termination-2.awk @@ -0,0 +1,9 @@ +# usage: awk -f exittest.awk input.txt +BEGIN { print "# Exit-Test" } + +#/s.*t/ { print "!", NR, $0; next } #1: List all matches + /s.*t/ { print "!", NR, $0; problem=1; exit} #2: Abort after first match + { print " ", NR, $0} + +END { if(problem) {print "!! Problem !!"; exit 2} } +END { print "# Lines read:", NR } diff --git a/Task/Program-termination/D/program-termination-1.d b/Task/Program-termination/D/program-termination-1.d new file mode 100644 index 0000000000..f565bda1cd --- /dev/null +++ b/Task/Program-termination/D/program-termination-1.d @@ -0,0 +1,53 @@ +import core.stdc.stdio, core.stdc.stdlib; + +extern(C) void foo() nothrow { + "foo at exit".puts; +} + +extern(C) void bar() nothrow { + "bar at exit".puts; +} + +extern(C) void spam() nothrow { + "spam at exit".puts; +} + +int baz(in int x) pure nothrow +in { + assert(x != 0); +} body { + if (x < 0) + return 10; + if (x > 0) + return 20; + + // x can't be 0. + + // In release mode this becomes a halt, and it's sometimes + // necessary. If you remove this the compiler gives: + // Error: function test.notInfinite no return exp; + // or assert(0); at end of function + assert(false); +} + +// This generates an error, that is not meant to be caught. +// Objects are not guaranteed to be finalized. +int empty() pure nothrow { + throw new Error(null); +} + +static ~this() { + // This module destructor is never called if + // the program calls the exit function. + import std.stdio; + "Never called".writeln; +} + +void main() { + atexit(&foo); + atexit(&bar); + atexit(&spam); + + //abort(); // Also this is allowed. Will not call foo, bar, spam. + exit(0); +} diff --git a/Task/Program-termination/D/program-termination-2.d b/Task/Program-termination/D/program-termination-2.d new file mode 100644 index 0000000000..50acc8ae33 --- /dev/null +++ b/Task/Program-termination/D/program-termination-2.d @@ -0,0 +1,21 @@ +import core.runtime, std.c.stdlib; + +static ~this() { + // This module destructor is called if + // the program calls the dexit function. + import std.stdio; + "Called on dexit".writeln; +} + +void dexit(int rc) { + // Calling dexit() should have the same effect with regard to cleanup as as reaching the end of the main program. + Runtime.terminate(); + exit(rc); +} + +int main() { + if(true) { + dexit(0); + } + return 0; +} diff --git a/Task/Program-termination/Emacs-Lisp/program-termination.l b/Task/Program-termination/Emacs-Lisp/program-termination.l new file mode 100644 index 0000000000..e569b603aa --- /dev/null +++ b/Task/Program-termination/Emacs-Lisp/program-termination.l @@ -0,0 +1,2 @@ +(if something + (kill-emacs)) diff --git a/Task/Program-termination/Gnuplot/program-termination.gnuplot b/Task/Program-termination/Gnuplot/program-termination.gnuplot new file mode 100644 index 0000000000..1c122a1cb6 --- /dev/null +++ b/Task/Program-termination/Gnuplot/program-termination.gnuplot @@ -0,0 +1,4 @@ +problem=1 +if (problem) { + exit gnuplot +} diff --git a/Task/Program-termination/Oberon-2/program-termination.oberon-2 b/Task/Program-termination/Oberon-2/program-termination.oberon-2 new file mode 100644 index 0000000000..882a036b17 --- /dev/null +++ b/Task/Program-termination/Oberon-2/program-termination.oberon-2 @@ -0,0 +1,3 @@ + IF problem THEN + HALT(1) + END diff --git a/Task/Program-termination/REXX/program-termination.rexx b/Task/Program-termination/REXX/program-termination.rexx index 59f08ce6d3..0fec02ca96 100644 --- a/Task/Program-termination/REXX/program-termination.rexx +++ b/Task/Program-termination/REXX/program-termination.rexx @@ -5,7 +5,7 @@ exit /*─────2nd way────────────────────────────────────────────────────────*/ -exit (expression) /*Note: the "expression" doen't need parenthesis*/ +exit (expression) /*Note: the "expression" doesn't need parentheses*/ /*"expression" is any REXX expression. */ @@ -16,7 +16,7 @@ return /*which returns to this program's invoker. If */ /*─────4th way────────────────────────────────────────────────────────*/ -return (expression) /* [See the note above concerning parenthesis.] */ +return (expression) /* [See the note above concerning parentheses.] */ /*─────5th way────────────────────────────────────────────────────────*/ diff --git a/Task/Program-termination/Ruby/program-termination-1.rb b/Task/Program-termination/Ruby/program-termination-1.rb index 5d9fe7ce00..1e69322082 100644 --- a/Task/Program-termination/Ruby/program-termination-1.rb +++ b/Task/Program-termination/Ruby/program-termination-1.rb @@ -1,3 +1,8 @@ if problem - exit(1) + exit(1) +end + +# or +if problem + abort # equivalent to exit(1) end diff --git a/Task/Program-termination/Ruby/program-termination-2.rb b/Task/Program-termination/Ruby/program-termination-2.rb index a44cbaff45..3a45ba105b 100644 --- a/Task/Program-termination/Ruby/program-termination-2.rb +++ b/Task/Program-termination/Ruby/program-termination-2.rb @@ -1,3 +1,3 @@ if problem - abort # equivalent to exit(1) + exit! # default value 1 end diff --git a/Task/Program-termination/Scala/program-termination.scala b/Task/Program-termination/Scala/program-termination.scala new file mode 100644 index 0000000000..efe95d3151 --- /dev/null +++ b/Task/Program-termination/Scala/program-termination.scala @@ -0,0 +1,6 @@ +if (problem) { + // sys.exit returns type "Nothing" + sys.exit(0) + // conventionally, error code 0 is the code for "OK", + // while anything else is an actual problem +} diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-1.d b/Task/Pythagorean-triples/D/pythagorean-triples-1.d index 80c8ac72df..38f73bbc30 100644 --- a/Task/Pythagorean-triples/D/pythagorean-triples-1.d +++ b/Task/Pythagorean-triples/D/pythagorean-triples-1.d @@ -1,17 +1,15 @@ -import std.stdio; +void main() @safe { + import std.stdio, std.range, std.algorithm, std.typecons, std.numeric; -ulong[2] tri(ulong lim, ulong a=3, ulong b=4, ulong c=5) { - immutable l = a + b + c; - if (l > lim) - return [0, 0]; - typeof(return) r = [1, lim / l]; - r[] += tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c)[]; - r[] += tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c)[]; - r[] += tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)[]; - return r; -} + enum triples = (in uint n) pure nothrow @safe /*@nogc*/ => + iota(1, n + 1) + .map!(z => iota(1, z + 1) + .map!(x => iota(x, z + 1).map!(y => tuple(x, y, z)))) + .joiner.joiner + .filter!(t => t[0] ^^ 2 + t[1] ^^ 2 == t[2] ^^ 2 && t[].only.sum <= n) + .map!(t => tuple(t[0 .. 2].gcd == 1, t[])); -void main() { - foreach (immutable p; 1 .. 8) - writeln(10 ^^ p, " ", tri(10 ^^ p)); + auto xs = triples(100); + writeln("Up to 100 there are ", xs.count, " triples, ", + xs.filter!q{ a[0] }.count, " are primitive."); } diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-2.d b/Task/Pythagorean-triples/D/pythagorean-triples-2.d index d4ef74dcc3..e055de2028 100644 --- a/Task/Pythagorean-triples/D/pythagorean-triples-2.d +++ b/Task/Pythagorean-triples/D/pythagorean-triples-2.d @@ -1,40 +1,17 @@ -import std.stdio; - -alias uint xuint; // ulong if going over 1 billion. - -__gshared xuint nTriples, nPrimitives, limit; - -void countTriples(xuint x, xuint y, xuint z) nothrow { - while (true) { - immutable xuint p = x + y + z; - if (p > limit) - return; - - nPrimitives++; - nTriples += limit / p; - - xuint t0 = x - 2 * y + 2 * z; - xuint t1 = 2 * x - y + 2 * z; - xuint t2 = t1 - y + z; - countTriples(t0, t1, t2); - - t0 += 4 * y; - t1 += 2 * y; - t2 += 4 * y; - countTriples(t0, t1, t2); - - z = t2 - 4 * x; - y = t1 - 4 * x; - x = t0 - 2 * x; - } +ulong[2] tri(ulong lim, ulong a=3, ulong b=4, ulong c=5) +pure nothrow @safe @nogc { + immutable l = a + b + c; + if (l > lim) + return [0, 0]; + typeof(return) r = [1, lim / l]; + r[] += tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c)[]; + r[] += tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c)[]; + r[] += tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c)[]; + return r; } -void main() { - foreach (p; 1 .. 9) { - limit = (cast(xuint)10) ^^ p; - nTriples = nPrimitives = 0; - countTriples(3, 4, 5); - writefln("Up to %11d: %11d triples, %9d primitives.", - limit, nTriples, nPrimitives); - } +void main() /*@safe*/ { + import std.stdio; + foreach (immutable p; 1 .. 9) + writeln(10 ^^ p, ' ', tri(10 ^^ p)); } diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-3.d b/Task/Pythagorean-triples/D/pythagorean-triples-3.d new file mode 100644 index 0000000000..545fc4c309 --- /dev/null +++ b/Task/Pythagorean-triples/D/pythagorean-triples-3.d @@ -0,0 +1,18 @@ +import std.stdio, core.simd; + +ulong2 tri(in ulong lim, in ulong a=3, in ulong b=4, in ulong c=5) +pure nothrow @safe @nogc { + immutable l = a + b + c; + if (l > lim) + return [0, 0]; + typeof(return) r = [1, lim / l]; + r += tri(lim, a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c); + r += tri(lim, a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c); + r += tri(lim, -a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c); + return r; +} + +void main() /*@safe*/ { + foreach (immutable p; 1 .. 9) + writeln(10 ^^ p, ' ', tri(10 ^^ p).array); +} diff --git a/Task/Pythagorean-triples/D/pythagorean-triples-4.d b/Task/Pythagorean-triples/D/pythagorean-triples-4.d new file mode 100644 index 0000000000..71ec4102cb --- /dev/null +++ b/Task/Pythagorean-triples/D/pythagorean-triples-4.d @@ -0,0 +1,40 @@ +import std.stdio; + +alias Xuint = uint; // ulong if going over 1 billion. + +__gshared Xuint nTriples, nPrimitives, limit; + +void countTriples(Xuint x, Xuint y, Xuint z) nothrow @nogc { + while (true) { + immutable p = x + y + z; + if (p > limit) + return; + + nPrimitives++; + nTriples += limit / p; + + auto t0 = x - 2 * y + 2 * z; + auto t1 = 2 * x - y + 2 * z; + auto t2 = t1 - y + z; + countTriples(t0, t1, t2); + + t0 += 4 * y; + t1 += 2 * y; + t2 += 4 * y; + countTriples(t0, t1, t2); + + z = t2 - 4 * x; + y = t1 - 4 * x; + x = t0 - 2 * x; + } +} + +void main() { + foreach (immutable p; 1 .. 9) { + limit = Xuint(10) ^^ p; + nTriples = nPrimitives = 0; + countTriples(3, 4, 5); + writefln("Up to %11d: %11d triples, %9d primitives.", + limit, nTriples, nPrimitives); + } +} diff --git a/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e b/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e new file mode 100644 index 0000000000..57823906ac --- /dev/null +++ b/Task/Pythagorean-triples/Eiffel/pythagorean-triples.e @@ -0,0 +1,37 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + Perimeter:= 100 + from + until + Perimeter>1000000 + loop + pyt_tri(3,4,5) + io.put_string ("There are " +total.out + " triples, below " + Perimeter.out + ". Of which " + prim.out+ " are primitives.%N") + Perimeter:= Perimeter*10 + end + end + + pyt_tri(a, b, c: INTEGER) + local + p: INTEGER + do + p:= a+b+c + if p<= Perimeter then + prim:= prim+1 + total := total + Perimeter // p + pyt_tri (a+2*(-b+c), 2*(a+c)-b, 2*(a-b+c)+c) + pyt_tri (a+2*(b+c), 2*(a+c)+b, 2*(a+b+c)+c) + pyt_tri (-a+2*(b+c), 2*(-a+c)+b, 2*(-a+b+c)+c) + end + end +Perimeter:INTEGER +prim: INTEGER +total: INTEGER +end diff --git a/Task/Pythagorean-triples/Groovy/pythagorean-triples-1.groovy b/Task/Pythagorean-triples/Groovy/pythagorean-triples-1.groovy new file mode 100644 index 0000000000..be5a0654e0 --- /dev/null +++ b/Task/Pythagorean-triples/Groovy/pythagorean-triples-1.groovy @@ -0,0 +1,36 @@ +class Triple { + BigInteger a, b, c + def getPerimeter() { this.with { a + b + c } } + boolean isValid() { this.with { a*a + b*b == c*c } } +} + +def initCounts (def n = 10) { + (n..1).collect { 10g**it }.inject ([:]) { Map map, BigInteger perimeterLimit -> + map << [(perimeterLimit): [primative: 0g, total: 0g]] + } +} + +def findPythagTriples, findChildTriples + +findPythagTriples = {Triple t = new Triple(a:3, b:4, c:5), Map counts = initCounts() -> + def p = t.perimeter + def currentCounts = counts.findAll { pLimit, tripleCounts -> p <= pLimit } + if (! currentCounts || ! t.valid) { return } + currentCounts.each { pLimit, tripleCounts -> + tripleCounts.with { primative ++; total += pLimit.intdiv(p) } + } + findChildTriples(t, currentCounts) + counts +} + +findChildTriples = { Triple t, Map counts -> + t.with { + [ + [ a - 2*b + 2*c, 2*a - b + 2*c, 2*a - 2*b + 3*c], + [ a + 2*b + 2*c, 2*a + b + 2*c, 2*a + 2*b + 3*c], + [-a + 2*b + 2*c, -2*a + b + 2*c, -2*a + 2*b + 3*c] + ]*.sort().each { aa, bb, cc -> + findPythagTriples(new Triple(a:aa, b:bb, c:cc), counts) + } + } +} diff --git a/Task/Pythagorean-triples/Groovy/pythagorean-triples-2.groovy b/Task/Pythagorean-triples/Groovy/pythagorean-triples-2.groovy new file mode 100644 index 0000000000..013d3a3a55 --- /dev/null +++ b/Task/Pythagorean-triples/Groovy/pythagorean-triples-2.groovy @@ -0,0 +1,5 @@ +printf (' LIMIT PRIMATIVE ALL\n') +findPythagTriples().sort().each { perimeterLimit, result -> + def exponent = perimeterLimit.toString().size() - 1 + printf ('a+b+c <= 10E%2d %9d %12d\n', exponent, result.primative, result.total) +} diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx index 66c3e56a6a..bba6601872 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-1.rexx @@ -1,28 +1,30 @@ /*REXX pgm counts number of Pythagorean triples that exist given a max */ /* perimeter of N, and also counts how many of them are primitives.*/ -trips=0; prims=0 +trips=0; prims=0 /*zero # of triples, primatives. */ parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ - do b=a+1 /*triangle can't be isosceles. */ - ab=a+b /*compute partial perimeter. */ - if ab>=n then iterate a /*a+b>perimeter? Try different A*/ - aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ + do b=a+1 /*triangle can't be isosceles. */ + ab=a+b /*compute partial perimeter. */ + if ab>=N then iterate a /*a+b≥perimeter? Try different A*/ + aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ - do c=b+1; cc=c*c /*3rd side: also compute c² */ - if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ - if cc>aabb then iterate b /*c² > a²+b² ? Try different B.*/ - if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ - trips=trips+1 /*eureka. */ - prims=prims+(gcd(a,b)==1) /*is this triple a primitive? */ - end /*a*/ - end /*b*/ - end /*c*/ + do c=b+1 /*3rd side: also compute c² */ + if ab+c>N then iterate a /*a+b+c > perimeter? Try diff A.*/ + cc=c*c /*compute C². */ + if cc > aabb then iterate b /*c² > a²+b² ? Try different B.*/ + if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ + trips=trips+1 /*eureka. We found a prim triple*/ + prims=prims+(gcd(a,b)==1) /*is this triple a primitive? */ + end /*a*/ + end /*b*/ + end /*c*/ say 'max perimeter =' N, /*show a single line of output. */ - left('',7) "Pythagorean triples =" trips, /*left('',0)≡7 blanks.*/ + left('',7) "Pythagorean triples =" trips, /*left('',7)≡7 blanks.*/ left('',7) 'primitives =' prims exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────GCD subroutine──────────────────────*/ -gcd: procedure; arg x,y; do until _==0; _=x//y; x=y; y=_; end; return x +gcd: procedure; parse arg x,y + do until y==0; parse value x//y y with y x; end; return x diff --git a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx index 6a6be76599..8299d48898 100644 --- a/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx +++ b/Task/Pythagorean-triples/REXX/pythagorean-triples-2.rexx @@ -1,35 +1,36 @@ /*REXX pgm counts number of Pythagorean triples that exist given a max */ /* perimeter of N, and also counts how many of them are primitives.*/ -@.=0; trips=0; prims=0 -parse arg N .; if N=='' then n=100 /*get "N". If none, then assume.*/ +@.=0; trips=0; prims=0 /*zero some REXX variables. */ +parse arg N .; if N=='' then N=100 /*get "N". If none, then assume.*/ do a=3 to N%3; aa=a*a /*limit side to 1/3 of perimeter.*/ - aEven= a//2==0 + aEven= a//2==0 /*set var to 1 if A is even.*/ - do b=a+1 by 1+aEven /*triangle can't be isosceles. */ - ab=a+b /*compute partial perimeter. */ - if ab>=n then iterate a /*a+b>perimeter? Try different A*/ - aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ + do b=a+1 by 1+aEven /*triangle can't be isosceles. */ + ab=a+b /*compute partial perimeter. */ + if ab>=N then iterate a /*a+b≥perimeter? Try different A*/ + aabb=aa+b*b /*compute sum of a² + b² (cheat)*/ - do c=b+1; cc=c*c /*3rd side: also compute c² */ - if aEven then if c//2==0 then iterate - if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ - if cc>aabb then iterate b /*c² > a²+b² ? Try different B.*/ - if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ - if @.a.b.c then iterate - trips=trips+1 /*eureka. */ - prims=prims+1 /*count this primitive triple. */ + do c=b+1 /*C is the third side of triangle*/ + if aEven then if c//2==0 then iterate + if ab+c>n then iterate a /*a+b+c > perimeter? Try diff A.*/ + cc=c*c /*compute C². */ + if cc > aabb then iterate b /*c² > a²+b² ? Try different B.*/ + if cc\==aabb then iterate /*c² ¬= a²+b² ? Try different C.*/ + if @.a.b.c then iterate /*Is this a duplicate? Try again*/ + trips=trips+1 /*eureka. We found a prim triple*/ + prims=prims+1 /*count this primitive triple. */ - do m=2; !a=a*m; !b=b*m; !c=c*m /*gen non-primitives.*/ - if !a+!b+!c>N then leave /*is this multiple a triple ? */ - trips=trips+1 /*yuppers, then we found another.*/ - if m//2 then @.!a.!b.!c=1 /*don't mark if an even multiple.*/ - end /*m*/ - end /*d*/ - end /*b*/ + do m=2; am=a*m; bm=b*m; cm=c*m /*gen non-primitives.*/ + if am+bm+cm>N then leave /*is this multiple a triple ? */ + trips=trips+1 /*yuppers, then we found another.*/ + if m//2 then @.am.bm.cm=1 /*don't mark if an even multiple.*/ + end /*m*/ + end /*d*/ + end /*b*/ end /*a*/ -say 'max perimeter =' N, /*show a single line of output. */ - left('',7) "Pythagorean triples =" trips, /*left('',0) = 7 blanks.*/ +say 'max perimeter =' N, /*show a single line of output. */ + left('',7) "Pythagorean triples =" trips, /*left('',7)≡7 blanks.*/ left('',7) 'primitives =' prims /*stick a fork in it, we're done.*/ diff --git a/Task/Pythagorean-triples/Scheme/pythagorean-triples.ss b/Task/Pythagorean-triples/Scheme/pythagorean-triples.ss new file mode 100644 index 0000000000..f0169d2e9f --- /dev/null +++ b/Task/Pythagorean-triples/Scheme/pythagorean-triples.ss @@ -0,0 +1,12 @@ +(use srfi-42) + +(define (py perim) + (define prim 0) + (values + (sum-ec + (: c perim) (: b c) (: a b) + (if (and (<= (+ a b c) perim) + (= (square c) (+ (square b) (square a))))) + (begin (when (= 1 (gcd a b)) (inc! prim))) + 1) + prim)) diff --git a/Task/QR-decomposition/D/qr-decomposition.d b/Task/QR-decomposition/D/qr-decomposition.d index 0fbf58cb71..af15b84789 100644 --- a/Task/QR-decomposition/D/qr-decomposition.d +++ b/Task/QR-decomposition/D/qr-decomposition.d @@ -2,30 +2,33 @@ import std.stdio, std.math, std.algorithm, std.traits, std.typecons, std.numeric, std.range, std.conv; 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); + T[][] elementwiseMat(T)(in T[][] A, in T B) pure nothrow { 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][]"); - } + R[r][] = mixin("row[] " ~ op ~ "B"); + return R; + } + T[][] elementwiseMat(T, U)(in T[][] A, in U[][] B) + pure nothrow if (is(Unqual!T == Unqual!U)) { + 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) { + assert(row.length == B[r].length); + R[r][] = mixin("row[] " ~ op ~ "B[r][]"); + } return R; } } -alias msum = elementwiseMat!q{ + }, - msub = elementwiseMat!q{ - }, - pmul = elementwiseMat!q{ * }, - pdiv = elementwiseMat!q{ / }; +alias mSum = elementwiseMat!q{ + }, + mSub = elementwiseMat!q{ - }, + pMul = elementwiseMat!q{ * }, + pDiv = elementwiseMat!q{ / }; bool isRectangular(T)(in T[][] mat) pure nothrow { return mat.all!(r => r.length == mat[0].length); @@ -49,7 +52,7 @@ in { Unqual!T[][] transpose(T)(in T[][] m) pure nothrow { auto r = new Unqual!T[][](m[0].length, m.length); - foreach (immutable nr, const row; m) + foreach (immutable nr, row; m) foreach (immutable nc, immutable c; row) r[nc][nr] = c; return r; @@ -59,8 +62,8 @@ T norm(T)(in T[][] m) pure nothrow { return transversal(m, 0).map!q{ a ^^ 2 }.sum.sqrt; } -T[][] makeUnitVector(T)(in size_t dim) pure nothrow { - auto result = new T[][](dim, 1); +Unqual!T[][] makeUnitVector(T)(in size_t dim) pure nothrow { + auto result = new Unqual!T[][](dim, 1); foreach (row; result) row[] = 0; result[0][0] = 1; @@ -68,8 +71,8 @@ T[][] makeUnitVector(T)(in size_t dim) pure nothrow { } /// Return a nxn identity matrix. -T[][] matId(T)(in size_t n) pure nothrow { - auto Id = new T[][](n, n); +Unqual!T[][] matId(T)(in size_t n) pure nothrow { + auto Id = new Unqual!T[][](n, n); foreach (immutable r, row; Id) { row[] = 0; row[r] = 1; @@ -77,10 +80,10 @@ T[][] matId(T)(in size_t n) pure nothrow { return Id; } -Unqual!T[][] slice2D(T)(in T[][] A, - in size_t ma, in size_t mb, - in size_t na, in size_t nb) pure nothrow { - auto B = new Unqual!T[][](mb - ma + 1, nb - na + 1); +T[][] slice2D(T)(in T[][] A, + in size_t ma, in size_t mb, + in size_t na, in size_t nb) pure nothrow { + auto B = new T[][](mb - ma + 1, nb - na + 1); foreach (immutable i, brow; B) brow[] = A[ma + i][na .. na + brow.length]; return B; @@ -93,7 +96,7 @@ size_t cols(T)(in T[][] A) pure nothrow { } T[][] mcol(T)(in T[][] A, in size_t n) pure nothrow { - return slice2D(A, 0, rows(A)-1, n, n); + return slice2D(A, 0, A.rows - 1, n, n); } T[][] matEmbed(T)(in T[][] A, in T[][] B, @@ -109,13 +112,13 @@ T[][] matEmbed(T)(in T[][] A, in T[][] B, // Main routines --------------- T[][] makeHouseholder(T)(in T[][] a) { - immutable size_t m = rows(a); - immutable T s = sgn(a[0][0]); + immutable m = a.rows; + immutable T s = a[0][0].sgn; immutable e = makeUnitVector!T(m); - immutable u = msum(a, pmul(e, norm(a) * s)); - immutable v = pdiv(u, u[0][0]); - immutable beta = 2.0 / matMul(transpose(v), v)[0][0]; - return msub(matId!T(m), pmul(matMul(v, transpose(v)), beta)); + immutable u = mSum(a, pMul(e, a.norm * s)); + immutable v = pDiv(u, u[0][0]); + immutable beta = 2.0 / v.transpose.matMul(v)[0][0]; + return mSub(matId!T(m), pMul(v.matMul(v.transpose), beta)); } Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) { @@ -124,25 +127,25 @@ Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) { auto Q = matId!T(m); // Work on n columns of A. - foreach (immutable i; 0 .. (m == n ? n-1 : n)) { + foreach (immutable i; 0 .. (m == n ? n - 1 : n)) { // Select the i-th submatrix. For i=0 this means the original // matrix A. - immutable B = slice2D(A, i, m-1, i, n-1); + immutable B = slice2D(A, i, m - 1, i, n - 1); // Take the first column of the current submatrix B. immutable x = mcol(B, 0); // Create the Householder matrix for the column and embed it // into an mxm identity. - immutable H = matEmbed(matId!T(m), makeHouseholder(x), i, i); + immutable H = matEmbed(matId!T(m), x.makeHouseholder, i, i); // The product of all H matrices from the right hand side is // the orthogonal matrix Q. - Q = matMul(Q, H); + Q = Q.matMul(H); // The product of all H matrices with A from the LHS is the // upper triangular matrix R. - A = matMul(H, A); + A = H.matMul(A); } // Return Q and R. @@ -153,7 +156,7 @@ Tuple!(T[][],"Q", T[][],"R") QRdecomposition(T)(T[][] A) { /// Solve an upper triangular system by back substitution. T[][] solveUpperTriangular(T)(in T[][] R, in T[][] b) pure nothrow { - immutable size_t n = cols(R); + immutable n = R.cols; auto x = new T[][](n, 1); foreach_reverse (immutable k; 0 .. n) { @@ -168,33 +171,32 @@ 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) pure nothrow { - const qr = QRdecomposition(A); - immutable size_t n = cols(qr.R); + const qr = A.QRdecomposition; + immutable n = qr.R.cols; return solveUpperTriangular( - slice2D(qr.R, 0, n-1, 0, n-1), - slice2D(matMul(transpose(qr.Q), b), 0, n-1, 0, 0)); + slice2D(qr.R, 0, n - 1, 0, n - 1), + slice2D(qr.Q.transpose.matMul(b), 0, n - 1, 0, 0)); } -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); +T[][] polyFit(T)(in T[][] x, in T[][] y, in size_t n) pure nothrow { + immutable size_t m = x.cols; + auto A = new T[][](m, n + 1); foreach (immutable i, row; A) foreach (immutable j, ref item; row) item = x[0][i] ^^ j; - return lsqr(A, transpose(y)); + return lsqr(A, y.transpose); } void main() { - // const (Q, R) = QRdecomposition( - const qr = QRdecomposition([[12.0, -51, 4], - [ 6.0, 167, -68], - [-4.0, 24, -41]]); - immutable string form = "[%([%(%2.3f, %)]%|,\n %)]\n"; + // immutable (Q, R) = QRdecomposition([[12.0, -51, 4], + immutable qr = QRdecomposition([[12.0, -51, 4], + [ 6.0, 167, -68], + [-4.0, 24, -41]]); + immutable form = "[%([%(%2.3f, %)]%|,\n %)]\n"; writefln(form, qr.Q); writefln(form, qr.R); immutable x = [[0.0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]; immutable y = [[1.0, 6, 17, 34, 57, 86, 121, 162, 209, 262, 321]]; - writeln(polyFit(x, y, 2)); + polyFit(x, y, 2).writeln; } diff --git a/Task/Quaternion-type/Axiom/quaternion-type.axiom b/Task/Quaternion-type/Axiom/quaternion-type.axiom new file mode 100644 index 0000000000..7392ec50dd --- /dev/null +++ b/Task/Quaternion-type/Axiom/quaternion-type.axiom @@ -0,0 +1,48 @@ +qi := quatern$Quaternion(Integer); + + Type: ((Integer,Integer,Integer,Integer) -> Quaternion(Integer)) +q := qi(1,2,3,4); + + Type: Quaternion(Integer) +q1 := qi(2,3,4,5); + + Type: Quaternion(Integer) +q2 := qi(3,4,5,6); + + Type: Quaternion(Integer) +r : Integer := 7; + + Type: Integer +sqrt norm q + + +--+ + (6) \|30 + Type: AlgebraicNumber +-q + + (7) - 1 - 2i - 3j - 4k + Type: Quaternion(Integer) +conjugate q + + (8) 1 - 2i - 3j - 4k + Type: Quaternion(Integer) +r + q + + (9) 8 + 2i + 3j + 4k + Type: Quaternion(Integer) +q1 + q2 + + (10) 5 + 7i + 9j + 11k + Type: Quaternion(Integer) +q*r + + (11) 7 + 14i + 21j + 28k + Type: Quaternion(Integer) +r*q + + (12) 7 + 14i + 21j + 28k + Type: Quaternion(Integer) +q1*q2 ~= q2*q1 + + (13) true + Type: Boolean diff --git a/Task/Quaternion-type/D/quaternion-type.d b/Task/Quaternion-type/D/quaternion-type.d index c679418f64..01f3815490 100644 --- a/Task/Quaternion-type/D/quaternion-type.d +++ b/Task/Quaternion-type/D/quaternion-type.d @@ -2,92 +2,96 @@ import std.math, std.numeric, std.traits, std.conv, std.complex; struct Quat(T) if (isFloatingPoint!T) { - alias Complex!T CT; + alias CT = Complex!T; union { - struct { T re, i, j, k; } // Default init to NaN + struct { T re, i, j, k; } // Default init to NaN. struct { CT x, y; } struct { T[4] vector; } } - string toString() const /*pure nothrow*/ { - return text(vector); + string toString() const pure /*nothrow*/ @safe { + return vector.text; } - @property T norm2() const pure nothrow { /// Norm squared + @property T norm2() const pure nothrow @safe @nogc { /// Norm squared. return re ^^ 2 + i ^^ 2 + j ^^ 2 + k ^^ 2; } - @property T abs() const pure nothrow { /// Norm + @property T abs() const pure nothrow @safe @nogc { /// Norm. return sqrt(norm2); } - @property T arg() const pure nothrow { /// Theta + @property T arg() const pure nothrow @safe @nogc { /// Theta. return acos(re / abs); // this may be incorrect... } - @property Quat!T conj() const pure nothrow { /// Conjugate + @property Quat!T conj() const pure nothrow @safe @nogc { /// Conjugate. return Quat!T(re, -i, -j, -k); } - @property Quat!T recip() const pure nothrow { /// Reciprocal + @property Quat!T recip() const pure nothrow @safe @nogc { /// Reciprocal. return Quat!T(re / norm2, -i / norm2, -j / norm2, -k / norm2); } - @property Quat!T pureim() const pure nothrow { /// Pure imagery + @property Quat!T pureim() const pure nothrow @safe @nogc { /// Pure imagery. return Quat!T(0, i, j, k); } - @property Quat!T versor() const pure nothrow { /// Unit versor + @property Quat!T versor() const pure nothrow @safe @nogc { /// Unit versor. return this / abs; } - /// Unit versor of imagery part - @property Quat!T iversor() const pure nothrow { + /// Unit versor of imagery part. + @property Quat!T iversor() const pure nothrow @safe @nogc { return pureim / pureim.abs; } - /// Assignment - Quat!T opAssign(U : T)(Quat!U z) pure nothrow { + /// Assignment. + Quat!T opAssign(U : T)(Quat!U z) pure nothrow @safe @nogc { x = z.x; y = z.y; return this; } - Quat!T opAssign(U : T)(Complex!U c) pure nothrow { + Quat!T opAssign(U : T)(Complex!U c) pure nothrow @safe @nogc { x = c; y = 0; return this; } - Quat!T opAssign(U : T)(U r) pure nothrow if (isNumeric!U) { + Quat!T opAssign(U : T)(U r) pure nothrow @safe @nogc + if (isNumeric!U) { re = r; i = 0; y = 0; return this; } - /// Test for equal, not ordered so no opCmp - bool opEquals(U : T)(Quat!U z) const pure nothrow { + /// Test for equal, not ordered so no opCmp. + bool opEquals(U : T)(Quat!U z) const pure nothrow @safe @nogc { return re == z.re && i == z.i && j == z.j && k == z.k; } - bool opEquals(U : T)(Complex!U c) const pure nothrow { + bool opEquals(U : T)(Complex!U c) const pure nothrow @safe @nogc { return re == c.re && i == c.im && j == 0 && k == 0; } - bool opEquals(U : T)(U r) const pure nothrow if (isNumeric!U) { + bool opEquals(U : T)(U r) const pure nothrow @safe @nogc + if (isNumeric!U) { return re == r && i == 0 && j == 0 && k == 0; } - /// Unary op - Quat!T opUnary(string op)() const pure nothrow if (op == "+") { + /// Unary op. + Quat!T opUnary(string op)() const pure nothrow @safe @nogc + if (op == "+") { return this; } - Quat!T opUnary(string op)() const pure nothrow if (op == "-") { + Quat!T opUnary(string op)() const pure nothrow @safe @nogc + if (op == "-") { return Quat!T(-re, -i, -j, -k); } - /// Binary op, Quaternion on left of op + /// Binary op, Quaternion on left of op. Quat!(CommonType!(T,U)) opBinary(string op, U)(Quat!U z) - const pure nothrow { + const pure nothrow @safe @nogc { alias typeof(return) C; static if (op == "+" ) { @@ -104,15 +108,16 @@ struct Quat(T) if (isFloatingPoint!T) { } } - /// Extend complex to quaternion + /// Extend complex to quaternion. Quat!(CommonType!(T,U)) opBinary(string op, U)(Complex!U c) - const pure nothrow { + const pure nothrow @safe @nogc { return opBinary!op(typeof(return)(c.re, c.im, 0, 0)); } - /// For scalar + /// For scalar. Quat!(CommonType!(T,U)) opBinary(string op, U)(U r) - const pure nothrow if (isNumeric!U) { + const pure nothrow @safe @nogc + if (isNumeric!U) { alias typeof(return) C; static if (op == "+" ) { @@ -128,23 +133,25 @@ struct Quat(T) if (isFloatingPoint!T) { } } - /// Power function + /// Power function. Quat!(CommonType!(T,U)) pow(U)(U r) - const pure nothrow if (isNumeric!U) { + const pure nothrow @safe @nogc + if (isNumeric!U) { return (abs^^r) * exp(r * iversor * arg); } /// Handle binary op if Quaternion on right of op and left is /// not quaternion. Quat!(CommonType!(T,U)) opBinaryRight(string op, U)(Complex!U c) - const pure nothrow { + const pure nothrow @safe @nogc { alias typeof(return) C; auto w = C(c.re, c.im, 0, 0); return w.opBinary!(op)(this); } Quat!(CommonType!(T,U)) opBinaryRight(string op, U)(U r) - const pure nothrow if (isNumeric!U) { + const pure nothrow @safe @nogc + if (isNumeric!U) { alias typeof(return) C; static if (op == "+" || op == "*") { @@ -159,20 +166,23 @@ struct Quat(T) if (isFloatingPoint!T) { } -HT exp(HT)(HT z) pure nothrow if (is(HT T == Quat!T)) { +HT exp(HT)(HT z) pure nothrow @safe @nogc +if (is(HT T == Quat!T)) { immutable inorm = z.pureim.abs; return std.math.exp(z.re) * (cos(inorm) + z.iversor * sin(inorm)); } -HT log(HT)(HT z) pure nothrow if (is(HT T == Quat!T)) { +HT log(HT)(HT z) pure nothrow @safe @nogc +if (is(HT T == Quat!T)) { return std.math.log(z.abs) + z.iversor * acos(z.re / z.abs); } -void main() { // Demo code +void main() @safe { // Demo code. import std.stdio; - alias Quat!real QR; - immutable real r = 7; + + alias QR = Quat!real; + enum real r = 7.0; immutable QR q = QR(2, 3, 4, 5), q1 = QR(2, 3, 4, 5), @@ -207,7 +217,7 @@ void main() { // Demo code writeln(" log(q): ", log(q)); writeln(" exp(log(q)): ", exp(log(q))); writeln(" log(exp(q)): ", log(exp(q))); - immutable s = log(exp(q)); + immutable s = q.exp.log; writeln("9.5 let s = log(exp(q)): ", s); writeln(" exp(s): ", exp(s)); writeln(" log(s): ", log(s)); diff --git a/Task/Quaternion-type/Julia/quaternion-type-1.julia b/Task/Quaternion-type/Julia/quaternion-type-1.julia index 34e0abd8d4..8bf86002d4 100644 --- a/Task/Quaternion-type/Julia/quaternion-type-1.julia +++ b/Task/Quaternion-type/Julia/quaternion-type-1.julia @@ -1,4 +1,4 @@ -import Base: convert, promote_rule, show, real, imag, conj, abs, abs2, inv, +, -, /, * +import Base: convert, promote_rule, show, conj, abs, +, -, * immutable Quaternion{T<:Real} <: Number q0::T @@ -25,18 +25,11 @@ function show(io::IO, z::Quaternion) print(io, z.q0, pm(z.q1), "i", pm(z.q2), "j", pm(z.q3), "k") end -real(z::Quaternion) = z.q0 -imag(z::Quaternion) = z.q1 - conj(z::Quaternion) = Quaternion(z.q0, -z.q1, -z.q2, -z.q3) abs(z::Quaternion) = sqrt(z.q0*z.q0 + z.q1*z.q1 + z.q2*z.q2 + z.q3*z.q3) -abs2(z::Quaternion) = z.q0*z.q0 + z.q1*z.q1 + z.q2*z.q2 + z.q3*z.q3 -inv(z::Quaternion) = conj(z)/abs2(z) (-)(z::Quaternion) = Quaternion(-z.q0, -z.q1, -z.q2, -z.q3) -(/)(z::Quaternion, x::Real) = Quaternion(z.q0/x, z.q1/x, z.q2/x, z.q3/x) - (+)(z::Quaternion, w::Quaternion) = Quaternion(z.q0 + w.q0, z.q1 + w.q1, z.q2 + w.q2, z.q3 + w.q3) (-)(z::Quaternion, w::Quaternion) = Quaternion(z.q0 - w.q0, z.q1 - w.q1, @@ -45,4 +38,3 @@ inv(z::Quaternion) = conj(z)/abs2(z) z.q0*w.q1 + z.q1*w.q0 + z.q2*w.q3 - z.q3*w.q2, z.q0*w.q2 - z.q1*w.q3 + z.q2*w.q0 + z.q3*w.q1, z.q0*w.q3 + z.q1*w.q2 - z.q2*w.q1 + z.q3*w.q0) -(/)(z::Quaternion, w::Quaternion) = z*inv(w) diff --git a/Task/Quaternion-type/Lua/quaternion-type-2.lua b/Task/Quaternion-type/Lua/quaternion-type-2.lua index fc13bbc1fd..e3cb702487 100644 --- a/Task/Quaternion-type/Lua/quaternion-type-2.lua +++ b/Task/Quaternion-type/Lua/quaternion-type-2.lua @@ -11,7 +11,7 @@ io.write( "r*q1 = " ); Quaternion.print( r*q1 ) io.write( "q1*r = " ); Quaternion.print( q1*r ) io.write( "q1*q2 = " ); Quaternion.print( q1*q2 ) io.write( "q2*q1 = " ); Quaternion.print( q2*q1 ) -Output: +{{out}} norm(q1) = 5.4772255750517 -q1 = -1.000000 -2.000000i -3.000000j -4.000000k conj(q1) = 1.000000 -2.000000i -3.000000j -4.000000k diff --git a/Task/Queue-Definition/00DESCRIPTION b/Task/Queue-Definition/00DESCRIPTION index 7e89fbb181..f13d6e4adf 100644 --- a/Task/Queue-Definition/00DESCRIPTION +++ b/Task/Queue-Definition/00DESCRIPTION @@ -1,6 +1,7 @@ {{Data structure}} [[File:Fifo.gif|frame|right|Illustration of FIFO behavior]] -Implement a FIFO queue. Elements are added at one side and popped from the other in the order of insertion. +Implement a FIFO queue. +Elements are added at one side and popped from the other in the order of insertion. Operations: * push (aka ''enqueue'') - add element diff --git a/Task/Queue-Definition/Bracmat/queue-definition.bracmat b/Task/Queue-Definition/Bracmat/queue-definition.bracmat new file mode 100644 index 0000000000..262569a7ed --- /dev/null +++ b/Task/Queue-Definition/Bracmat/queue-definition.bracmat @@ -0,0 +1,10 @@ + ( queue + = (list=) + (enqueue=.(.!arg) !(its.list):?(its.list)) + ( dequeue + = x + . !(its.list):?(its.list) (.?x) + & !x + ) + (empty=.!(its.list):) + ) diff --git a/Task/Queue-Definition/Clojure/queue-definition.clj b/Task/Queue-Definition/Clojure/queue-definition.clj index e09687db7c..5cc5fe36bb 100644 --- a/Task/Queue-Definition/Clojure/queue-definition.clj +++ b/Task/Queue-Definition/Clojure/queue-definition.clj @@ -5,10 +5,8 @@ (swap! q conj x)) (defn dequeue [q] - (if (seq @q) - (let [x (first @q)] - (swap! q subvec 1) - x) + (if-let [[f & r] (seq @q)] + (do (reset! q r) f) (throw (IllegalStateException. "Can't pop an empty queue.")))) (defn queue-empty? [q] diff --git a/Task/Queue-Definition/CoffeeScript/queue-definition.coffee b/Task/Queue-Definition/CoffeeScript/queue-definition.coffee new file mode 100644 index 0000000000..46b538ac3c --- /dev/null +++ b/Task/Queue-Definition/CoffeeScript/queue-definition.coffee @@ -0,0 +1,38 @@ +# Implement a fifo as an array of arrays, to +# greatly amortize dequeue costs, at some expense of +# memory overhead and insertion time. The speedup +# depends on the underlying JS implementation, but +# it's significant on node.js. +Fifo = -> + max_chunk = 512 + arr = [] # array of arrays + count = 0 + + self = + enqueue: (elem) -> + if count == 0 or arr[arr.length-1].length >= max_chunk + arr.push [] + count += 1 + arr[arr.length-1].push elem + dequeue: (elem) -> + throw Error("queue is empty") if count == 0 + val = arr[0].shift() + count -= 1 + if arr[0].length == 0 + arr.shift() + val + is_empty: (elem) -> + count == 0 + +# test +do -> + max = 5000000 + q = Fifo() + for i in [1..max] + q.enqueue + number: i + + console.log q.dequeue() + while !q.is_empty() + v = q.dequeue() + console.log v diff --git a/Task/Queue-Definition/UNIX-Shell/queue-definition-1.sh b/Task/Queue-Definition/UNIX-Shell/queue-definition-1.sh new file mode 100644 index 0000000000..8390610540 --- /dev/null +++ b/Task/Queue-Definition/UNIX-Shell/queue-definition-1.sh @@ -0,0 +1,25 @@ +queue_push() { + typeset -n q=$1 + shift + q+=("$@") +} + +queue_pop() { + if queue_empty $1; then + print -u2 "queue $1 is empty" + return 1 + fi + typeset -n q=$1 + print "${q[0]}" # emit the value of the popped element + q=( "${q[@]:1}" ) # and remove the first element from the queue +} + +queue_empty() { + typeset -n q=$1 + (( ${#q[@]} == 0 )) +} + +queue_peek() { + typeset -n q=$1 + print "${q[0]}" +} diff --git a/Task/Queue-Definition/UNIX-Shell/queue-definition-2.sh b/Task/Queue-Definition/UNIX-Shell/queue-definition-2.sh new file mode 100644 index 0000000000..3fd4f6e945 --- /dev/null +++ b/Task/Queue-Definition/UNIX-Shell/queue-definition-2.sh @@ -0,0 +1,14 @@ +# any valid variable name can be used as a queue without initialization + +queue_empty foo && echo foo is empty || echo foo is not empty + +queue_push foo bar +queue_push foo baz +queue_push foo "element with spaces" + +queue_empty foo && echo foo is empty || echo foo is not empty + +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo diff --git a/Task/Queue-Usage/Bracmat/queue-usage.bracmat b/Task/Queue-Usage/Bracmat/queue-usage.bracmat new file mode 100644 index 0000000000..d56be28cc1 --- /dev/null +++ b/Task/Queue-Usage/Bracmat/queue-usage.bracmat @@ -0,0 +1,38 @@ + ( queue + = (list=) + (enqueue=.(.!arg) !(its.list):?(its.list)) + ( dequeue + = x + . !(its.list):?(its.list) (.?x) + & !x + ) + (empty=.!(its.list):) + ) +& new$queue:?Q +& ( (Q..enqueue)$1 + & (Q..enqueue)$2 + & (Q..enqueue)$3 + & out$((Q..dequeue)$) + & (Q..enqueue)$4 + & out$((Q..dequeue)$) + & out$((Q..dequeue)$) + & out + $ ( The + queue + is + ((Q..empty)$&|not) + empty + ) + & out$((Q..dequeue)$) + & out + $ ( The + queue + is + ((Q..empty)$&|not) + empty + ) + & out$((Q..dequeue)$) + & out$Success! + | out$"Attempt to dequeue failed" + ) +; diff --git a/Task/Queue-Usage/D/queue-usage-2.d b/Task/Queue-Usage/D/queue-usage-2.d index e228295fed..68fc943b21 100644 --- a/Task/Queue-Usage/D/queue-usage-2.d +++ b/Task/Queue-Usage/D/queue-usage-2.d @@ -1,62 +1,75 @@ module queue_usage2; +import std.traits: hasIndirections; + struct GrowableCircularQueue(T) { public size_t length; - private size_t head, tail; + private size_t first, last; private T[] A = [T.init]; - bool empty() const pure nothrow { + this(T[] items...) pure nothrow @safe { + foreach (x; items) + push(x); + } + + @property bool empty() const pure nothrow @safe @nogc { return length == 0; } - void push(immutable T item) pure nothrow { + @property T front() pure nothrow @safe @nogc { + assert(length != 0); + return A[first]; + } + + T opIndex(in size_t i) pure nothrow @safe @nogc { + assert(i < length); + return A[(first + i) & (A.length - 1)]; + } + + void push(T item) pure nothrow @safe { if (length >= A.length) { // Double the queue. - const old = A; - A = new T[A.length * 2]; - A[0 .. (old.length - head)] = old[head .. $]; - if (head) - A[(old.length - head) .. old.length] = old[0 .. head]; - head = 0; - tail = length; + immutable oldALen = A.length; + A.length *= 2; + if (last < first) { + A[oldALen .. oldALen + last + 1] = A[0 .. last + 1]; + static if (hasIndirections!T) + A[0 .. last + 1] = T.init; // Help for the GC. + last += oldALen; + } } - A[tail] = item; - tail = (tail + 1) & (A.length - 1); + last = (last + 1) & (A.length - 1); + A[last] = item; length++; } - T pop() pure { - import std.traits: hasIndirections; - - if (length == 0) - throw new Exception("GrowableCircularQueue is empty."); - auto saved = A[head]; + @property T pop() pure nothrow @safe @nogc { + assert(length != 0); + auto saved = A[first]; static if (hasIndirections!T) - A[head] = T.init; // Help for the GC. - head = (head + 1) & (A.length - 1); + A[first] = T.init; // Help for the GC. + first = (first + 1) & (A.length - 1); length--; return saved; } } version (queue_usage2_main) { - unittest { - auto q = new GrowableCircularQueue!int(); + void main() { + GrowableCircularQueue!int q; q.push(10); q.push(20); q.push(30); - assert(q.pop() == 10); - assert(q.pop() == 20); - assert(q.pop() == 30); - assert(q.empty()); + assert(q.pop == 10); + assert(q.pop == 20); + assert(q.pop == 30); + assert(q.empty); uint count = 0; foreach (immutable i; 1 .. 1_000) { foreach (immutable j; 0 .. i) q.push(count++); foreach (immutable j; 0 .. i) - q.pop(); + q.pop; } } - - void main() {} } diff --git a/Task/Queue-Usage/Lua/queue-usage.lua b/Task/Queue-Usage/Lua/queue-usage-1.lua similarity index 100% rename from Task/Queue-Usage/Lua/queue-usage.lua rename to Task/Queue-Usage/Lua/queue-usage-1.lua diff --git a/Task/Queue-Usage/Lua/queue-usage-2.lua b/Task/Queue-Usage/Lua/queue-usage-2.lua new file mode 100644 index 0000000000..35882a2222 --- /dev/null +++ b/Task/Queue-Usage/Lua/queue-usage-2.lua @@ -0,0 +1,16 @@ +> -- create queue: +> q = {} +> -- push: +> q[#q+1] = "first" +> q[#q+1] = "second" +> q[#q+1] = "third" +> -- pop: +> =table.remove(q, 1) +first +> =table.remove(q, 1) +second +> =table.remove(q, 1) +third +> -- empty? +> =#q == 0 +true diff --git a/Task/Queue-Usage/REXX/queue-usage.rexx b/Task/Queue-Usage/REXX/queue-usage.rexx index 61b4d4602c..08602b5f63 100644 --- a/Task/Queue-Usage/REXX/queue-usage.rexx +++ b/Task/Queue-Usage/REXX/queue-usage.rexx @@ -1,18 +1,18 @@ -/*REXX program demonstrates three queue operations: push, pop, queued. */ -say '══════════════════════════════════Pushing five values to the stack.' +/*REXX program demonstrates three queue operations: push, pop, empty. */ +say '══════════════════════════════════ Pushing five values to the stack.' do j=1 for 4 /*loop to PUSH four values. */ call push j*10 /*PUSH (aka enqueue to stack). */ say 'pushed value:' j*10 /*echo the pushed value. */ - if j\==3 then iterate /*also, insert a "null" entry. */ - call push /*PUSH (aka enqueue to stack). */ + if j\==3 then iterate /*also, insert a "null" entry. */ + call push /*PUSH (aka enqueue to stack). */ say 'pushed a "null" value.' /*echo what was pushed. */ end /*j*/ -say '══════════════════════════════════Popping all values from the stack.' +say '══════════════════════════════════ Popping all values from the stack.' do m=1 while \empty() /*EMPTY (returns TRUE if empty). */ call pop /*POP (aka dequeue from stack).*/ say m': popped value=' result /*echo the popped value. */ end /*m*/ -say '══════════════════════════════════The stack is now empty.' +say '══════════════════════════════════ The stack is now empty.' exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────subroutines/functions/operators. */ push: queue arg(1); return /*REXX QUEUE is FIFO. */ diff --git a/Task/Queue-Usage/UNIX-Shell/queue-usage.sh b/Task/Queue-Usage/UNIX-Shell/queue-usage.sh new file mode 100644 index 0000000000..3fd4f6e945 --- /dev/null +++ b/Task/Queue-Usage/UNIX-Shell/queue-usage.sh @@ -0,0 +1,14 @@ +# any valid variable name can be used as a queue without initialization + +queue_empty foo && echo foo is empty || echo foo is not empty + +queue_push foo bar +queue_push foo baz +queue_push foo "element with spaces" + +queue_empty foo && echo foo is empty || echo foo is not empty + +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo +print "peek: $(queue_peek foo)"; queue_pop foo diff --git a/Task/Quine/00DESCRIPTION b/Task/Quine/00DESCRIPTION index 26b1de7af6..031ab09d20 100644 --- a/Task/Quine/00DESCRIPTION +++ b/Task/Quine/00DESCRIPTION @@ -1,6 +1,11 @@ -A [[wp:Quine_%28computing%29|Quine]] is a self-referential program that can, without any external access, output its own source. It is named after the [[wp:Willard_Van_Orman_Quine|philosopher and logician]] who studied self-reference and quoting in natural language, as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." +A [[wp:Quine_%28computing%29|Quine]] is a self-referential program that can, +without any external access, output its own source. +It is named after the [[wp:Willard_Van_Orman_Quine|philosopher and logician]] +who studied self-reference and quoting in natural language, +as for example in the paradox "'Yields falsehood when preceded by its quotation' yields falsehood when preceded by its quotation." -"Source" has one of two meanings. It can refer to the text-based program source. For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. +"Source" has one of two meanings. It can refer to the text-based program source. +For languages in which program source is represented as a data structure, "source" may refer to the data structure: quines in these languages fall into two categories: programs which print a textual representation of themselves, or expressions which evaluate to a data structure which is equivalent to that expression. The usual way to code a Quine works similarly to this paradox: The program consists of two identical parts, once as plain code and once ''quoted'' in some way (for example, as a character string, or a literal data structure). The plain code then accesses the quoted code and prints it out twice, once unquoted and once with the proper quotation marks added. Often, the plain code and the quoted code have to be nested. diff --git a/Task/Quine/Frink/quine.frink b/Task/Quine/Frink/quine-1.frink similarity index 100% rename from Task/Quine/Frink/quine.frink rename to Task/Quine/Frink/quine-1.frink diff --git a/Task/Quine/Frink/quine-2.frink b/Task/Quine/Frink/quine-2.frink new file mode 100644 index 0000000000..d00491fd7e --- /dev/null +++ b/Task/Quine/Frink/quine-2.frink @@ -0,0 +1 @@ +1 diff --git a/Task/Quine/J/quine-1.j b/Task/Quine/J/quine-1.j new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Task/Quine/J/quine.j b/Task/Quine/J/quine-2.j similarity index 100% rename from Task/Quine/J/quine.j rename to Task/Quine/J/quine-2.j diff --git a/Task/Quine/JavaScript/quine-4.js b/Task/Quine/JavaScript/quine-4.js new file mode 100644 index 0000000000..bb3945e6e1 --- /dev/null +++ b/Task/Quine/JavaScript/quine-4.js @@ -0,0 +1 @@ +var a=function () {var b="var a="+a.toString()+"\;a()";alert(b)};a() diff --git a/Task/Quine/Mathematica/quine-4.math b/Task/Quine/Mathematica/quine-4.math new file mode 100644 index 0000000000..9b8aaa46ea --- /dev/null +++ b/Task/Quine/Mathematica/quine-4.math @@ -0,0 +1 @@ +Unevaluated[1989^1989] diff --git a/Task/Quine/Mathematica/quine-5.math b/Task/Quine/Mathematica/quine-5.math new file mode 100644 index 0000000000..587be6b4c3 --- /dev/null +++ b/Task/Quine/Mathematica/quine-5.math @@ -0,0 +1 @@ +x diff --git a/Task/Quine/Pascal/quine.pascal b/Task/Quine/Pascal/quine-1.pascal similarity index 100% rename from Task/Quine/Pascal/quine.pascal rename to Task/Quine/Pascal/quine-1.pascal diff --git a/Task/Quine/Pascal/quine-2.pascal b/Task/Quine/Pascal/quine-2.pascal new file mode 100644 index 0000000000..8f647022b2 --- /dev/null +++ b/Task/Quine/Pascal/quine-2.pascal @@ -0,0 +1 @@ +program Quine(Output);const A='program Quine(Output);const A=';B='begin writeln(A,char(39),A,char(39),char(59),char(66),char(61),char(39),B,char(39),char(59),B)end.';begin writeln(A,char(39),A,char(39),char(59),char(66),char(61),char(39),B,char(39),char(59),B)end. diff --git a/Task/Quine/Perl-6/quine.pl6 b/Task/Quine/Perl-6/quine-1.pl6 similarity index 100% rename from Task/Quine/Perl-6/quine.pl6 rename to Task/Quine/Perl-6/quine-1.pl6 diff --git a/Task/Quine/Perl-6/quine-2.pl6 b/Task/Quine/Perl-6/quine-2.pl6 new file mode 100644 index 0000000000..d931d1b127 --- /dev/null +++ b/Task/Quine/Perl-6/quine-2.pl6 @@ -0,0 +1 @@ +{.fmt($_).say}(<{.fmt($_).say}(<%s>)>) diff --git a/Task/Quine/Prolog/quine.pro b/Task/Quine/Prolog/quine-1.pro similarity index 100% rename from Task/Quine/Prolog/quine.pro rename to Task/Quine/Prolog/quine-1.pro diff --git a/Task/Quine/Prolog/quine-2.pro b/Task/Quine/Prolog/quine-2.pro new file mode 100644 index 0000000000..d9ff17b690 --- /dev/null +++ b/Task/Quine/Prolog/quine-2.pro @@ -0,0 +1 @@ +quine:-asserta(a((quine:-asserta(a(A,B)),a(C,D+E),a(D,E),numbervars(C),write(C),write(.)),A+B)),a(F,G+H),a(G,H),numbervars(F),write(F),write(.). diff --git a/Task/Quine/Python/quine-4.py b/Task/Quine/Python/quine-4.py index 1acb041803..113e4495f0 100644 --- a/Task/Quine/Python/quine-4.py +++ b/Task/Quine/Python/quine-4.py @@ -1 +1 @@ -print(__file__[:-3]) +import sys,inspect;sys.stdout.write(inspect.getsource(inspect.currentframe())) diff --git a/Task/Quine/Python/quine-5.py b/Task/Quine/Python/quine-5.py index 2a666e4872..1acb041803 100644 --- a/Task/Quine/Python/quine-5.py +++ b/Task/Quine/Python/quine-5.py @@ -1,2 +1 @@ -$ python print\(__file__\[\:-3\]\).py print(__file__[:-3]) diff --git a/Task/Quine/Python/quine-6.py b/Task/Quine/Python/quine-6.py index ef7144048b..2a666e4872 100644 --- a/Task/Quine/Python/quine-6.py +++ b/Task/Quine/Python/quine-6.py @@ -1,4 +1,2 @@ -$ cat print\(__file__\) -print(__file__) -$ python print\(__file__\) -print(__file__) +$ python print\(__file__\[\:-3\]\).py +print(__file__[:-3]) diff --git a/Task/Quine/Python/quine-7.py b/Task/Quine/Python/quine-7.py index c7c6469de7..ef7144048b 100644 --- a/Task/Quine/Python/quine-7.py +++ b/Task/Quine/Python/quine-7.py @@ -1,11 +1,4 @@ -$ cat reproducing.py - File "reproducing.py", line 1 - File "reproducing.py", line 1 - ^ -IndentationError: unexpected indent - -$ python reproducing.py - File "reproducing.py", line 1 - File "reproducing.py", line 1 - ^ -IndentationError: unexpected indent +$ cat print\(__file__\) +print(__file__) +$ python print\(__file__\) +print(__file__) diff --git a/Task/Quine/Python/quine-8.py b/Task/Quine/Python/quine-8.py new file mode 100644 index 0000000000..c7c6469de7 --- /dev/null +++ b/Task/Quine/Python/quine-8.py @@ -0,0 +1,11 @@ +$ cat reproducing.py + File "reproducing.py", line 1 + File "reproducing.py", line 1 + ^ +IndentationError: unexpected indent + +$ python reproducing.py + File "reproducing.py", line 1 + File "reproducing.py", line 1 + ^ +IndentationError: unexpected indent diff --git a/Task/Quine/Ruby/quine-4.rb b/Task/Quine/Ruby/quine-4.rb new file mode 100644 index 0000000000..bc3256f899 --- /dev/null +++ b/Task/Quine/Ruby/quine-4.rb @@ -0,0 +1,4 @@ +f = File.open __FILE__ +f.each_line do |line| + puts line +f.close diff --git a/Task/Quine/Rust/quine.rust b/Task/Quine/Rust/quine-1.rust similarity index 98% rename from Task/Quine/Rust/quine.rust rename to Task/Quine/Rust/quine-1.rust index 2cd701eaf6..88df728796 100644 --- a/Task/Quine/Rust/quine.rust +++ b/Task/Quine/Rust/quine-1.rust @@ -1,4 +1,3 @@ -// 0.9-pre compatible fn main() { let q = 34u8; diff --git a/Task/Quine/Rust/quine-2.rust b/Task/Quine/Rust/quine-2.rust new file mode 100644 index 0000000000..1c84e334c8 --- /dev/null +++ b/Task/Quine/Rust/quine-2.rust @@ -0,0 +1,8 @@ +extern crate debug; +fn main() { + let x = "extern crate debug;\nfn main() {\n let x = "; + let y = "print!(\"{}{:?};\n let y = {:?};\n {}\", x, x, y, y)\n}"; + print!("{}{:?}; + let y = {:?}; + {}", x, x, y, y) +} diff --git a/Task/Quine/Standard-ML/quine.ml b/Task/Quine/Standard-ML/quine-1.ml similarity index 100% rename from Task/Quine/Standard-ML/quine.ml rename to Task/Quine/Standard-ML/quine-1.ml diff --git a/Task/Quine/Standard-ML/quine-2.ml b/Task/Quine/Standard-ML/quine-2.ml new file mode 100644 index 0000000000..c9d9d3f699 --- /dev/null +++ b/Task/Quine/Standard-ML/quine-2.ml @@ -0,0 +1 @@ +(fn y=>(fn x=>(print(x^y^x^y)))) (implode[chr(34)])"(fn y=>(fn x=>(print(x^y^x^y)))) (implode[chr(34)])" diff --git a/Task/Quine/UNIX-Shell/quine-1.sh b/Task/Quine/UNIX-Shell/quine-1.sh index e522f749b4..e0aa9c7f0c 100644 --- a/Task/Quine/UNIX-Shell/quine-1.sh +++ b/Task/Quine/UNIX-Shell/quine-1.sh @@ -1,2 +1,2 @@ #!/bin/sh -cat -- "$0" +cat < "$0" diff --git a/Task/RIPEMD-160/00DESCRIPTION b/Task/RIPEMD-160/00DESCRIPTION index e638dc7c02..42148cc4d8 100644 --- a/Task/RIPEMD-160/00DESCRIPTION +++ b/Task/RIPEMD-160/00DESCRIPTION @@ -1,5 +1,13 @@ +{{omit from|Brlcad}} +{{omit from|GUISS}} +{{omit from|Lilypond}} +{{omit from|Openscad}} + '''RIPEMD-160''' is another hash function; it computes a 160-bit message digest. -There is a [http://homes.esat.kuleuven.be/~bosselae/ripemd160.html RIPEMD-160 home page], with test vectors and [http://www.esat.kuleuven.be/~bosselae/ripemd/rmd160.txt pseudocode for RIPEMD-160]. For padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320). +There is a [http://homes.esat.kuleuven.be/~bosselae/ripemd160.html RIPEMD-160 home page], with test vectors and [http://www.esat.kuleuven.be/~bosselae/ripemd/rmd160.txt pseudocode for RIPEMD-160]. +For padding the message, RIPEMD-160 acts like [[MD4]] (RFC 1320). -Find the RIPEMD-160 message digest of a string of [[octet]]s. Use the ASCII encoded string “Rosetta Code”. You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language. +Find the RIPEMD-160 message digest of a string of [[octet]]s. +Use the ASCII encoded string “Rosetta Code”. +You may either call an RIPEMD-160 library, or implement RIPEMD-160 in your language. diff --git a/Task/RIPEMD-160/Clojure/ripemd-160.clj b/Task/RIPEMD-160/Clojure/ripemd-160.clj new file mode 100644 index 0000000000..5d2bf950ed --- /dev/null +++ b/Task/RIPEMD-160/Clojure/ripemd-160.clj @@ -0,0 +1,2 @@ +(use 'pandect.core) +(ripemd160 "Rosetta Code") diff --git a/Task/RIPEMD-160/Go/ripemd-160.go b/Task/RIPEMD-160/Go/ripemd-160.go index 1b76aa5f3c..104eb86d9c 100644 --- a/Task/RIPEMD-160/Go/ripemd-160.go +++ b/Task/RIPEMD-160/Go/ripemd-160.go @@ -1,7 +1,7 @@ package main import ( - "code.google.com/p/go.crypto/ripemd160" + "golang.org/x/crypto/ripemd160" "fmt" ) diff --git a/Task/RIPEMD-160/Perl/ripemd-160-1.pl b/Task/RIPEMD-160/Perl/ripemd-160-1.pl new file mode 100644 index 0000000000..4b03b2b266 --- /dev/null +++ b/Task/RIPEMD-160/Perl/ripemd-160-1.pl @@ -0,0 +1,2 @@ +use Crypt::RIPEMD160; +say unpack "H*", Crypt::RIPEMD160->hash("Rosetta Code"); diff --git a/Task/RIPEMD-160/Perl/ripemd-160-2.pl b/Task/RIPEMD-160/Perl/ripemd-160-2.pl new file mode 100644 index 0000000000..5a7c2081ff --- /dev/null +++ b/Task/RIPEMD-160/Perl/ripemd-160-2.pl @@ -0,0 +1,2 @@ +use Crypt::Digest::RIPEMD160 qw/ripemd160_hex/; +say ripemd160_hex("Rosetta Code") diff --git a/Task/RIPEMD-160/PicoLisp/ripemd-160.l b/Task/RIPEMD-160/PicoLisp/ripemd-160.l new file mode 100644 index 0000000000..8f44eed5ca --- /dev/null +++ b/Task/RIPEMD-160/PicoLisp/ripemd-160.l @@ -0,0 +1,160 @@ +(de *R160-R1 . (1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + 8 5 14 2 11 7 16 4 13 1 10 6 3 15 12 9 + 4 11 15 5 10 16 9 2 3 8 1 7 14 12 6 13 + 2 10 12 11 1 9 13 5 14 4 8 16 15 6 7 3 + 5 1 6 10 8 13 3 11 15 2 4 9 12 7 16 14 .)) +(de *R160-R2 . (6 15 8 1 10 3 12 5 14 7 16 9 2 11 4 13 + 7 12 4 8 1 14 6 11 15 16 9 13 5 10 2 3 + 16 6 2 4 8 15 7 10 12 9 13 3 11 1 5 14 + 9 7 5 2 4 12 16 1 6 13 3 14 10 8 11 15 + 13 16 11 5 2 6 9 8 7 3 14 15 1 4 10 12 .)) +(de *R160-S1 . (11 14 15 12 5 8 7 9 11 13 14 15 6 7 9 8 + 7 6 8 13 11 9 7 15 7 12 15 9 11 7 13 12 + 11 13 6 7 14 9 13 15 14 8 13 6 5 12 7 5 + 11 12 14 15 14 15 9 8 9 14 5 6 8 6 5 12 + 9 15 5 11 6 8 13 12 5 12 13 14 11 8 5 6 .)) +(de *R160-S2 . (8 9 9 11 13 15 15 5 7 7 8 11 14 14 12 6 + 9 13 15 7 12 8 9 11 7 7 12 7 6 15 13 11 + 9 7 15 11 8 6 6 14 12 13 5 14 13 13 7 5 + 15 5 8 11 14 14 6 14 6 9 12 9 12 5 15 8 + 8 5 12 9 12 5 14 6 8 13 6 5 15 13 11 11 .)) + +(de mod32 (N) + (& N `(hex "FFFFFFFF")) ) + +(de not32 (N) + (x| N `(hex "FFFFFFFF")) ) + +(de add32 @ + (mod32 (pass +)) ) + +(de leftRotate (X C) + (| (mod32 (>> (- C) X)) (>> (- 32 C) X)) ) + +(de ripemd160 (Str) + (let Len (length Str) + (setq Str + (conc + (need + (- 8 (* 64 (/ (+ Len 1 8 63) 64))) + (conc + (mapcar char (chop Str)) + (cons `(hex "80")) ) + 0 ) + (make + (setq Len (* 8 Len)) + (do 8 + (link (& Len 255)) + (setq Len (>> 8 Len )) ) ) ) ) ) + (let + (H0 `(hex "67452301") + H1 `(hex "EFCDAB89") + H2 `(hex "98BADCFE") + H3 `(hex "10325476") + H4 `(hex "C3D2E1F0") ) + (while Str + (let + (A1 H0 B1 H1 C1 H2 D1 H3 E1 H4 + A2 H0 B2 H1 C2 H2 D2 H3 E2 H4 + W (make + (do 16 + (link + (apply | + (mapcar >> (0 -8 -16 -24) (cut 4 'Str)) ) ) ) ) ) + (use (Func1 Func2 Hex1 Hex2) + (for I 80 + (cond + ((>= 16 I) + (setq + Func1 '(x| B1 C1 D1) + Func2 '(x| B2 (| C2 (not32 D2))) + Hex1 0 + Hex2 `(hex "50A28BE6") ) ) + ((>= 32 I) + (setq + Func1 '(| (& B1 C1) (& (not32 B1) D1)) + Func2 '(| (& B2 D2) (& C2 (not32 D2))) + Hex1 `(hex "5A827999") + Hex2 `(hex "5C4DD124") ) ) + ((>= 48 I) + (setq + Func1 '(x| (| B1 (not32 C1)) D1) + Func2 '(x| (| B2 (not32 C2)) D2) + Hex1 `(hex "6ED9EBA1") + Hex2 `(hex "6D703EF3") ) ) + ((>= 64 I) + (setq + Func1 '(| (& B1 D1) (& C1 (not32 D1))) + Func2 '(| (& B2 C2) (& (not32 B2) D2)) + Hex1 `(hex "8F1BBCDC") + Hex2 `(hex "7A6D76E9") ) ) + (T + (setq + Func1 '(x| B1 (| C1 (not32 D1))) + Func2 '(x| B2 C2 D2) + Hex1 `(hex "A953FD4E") + Hex2 0 ) ) ) + (setq + Tmp1 + (add32 + (leftRotate + (add32 + A1 + (eval Func1) + (get W (pop '*R160-R1)) + Hex1 ) + (pop '*R160-S1) ) + E1 ) + Tmp2 + (add32 + (leftRotate + (add32 + A2 + (eval Func2) + (get W (pop '*R160-R2)) + Hex2 ) + (pop '*R160-S2) ) + E2 ) + A1 E1 + E1 D1 + D1 (leftRotate C1 10) + C1 B1 + B1 Tmp1 + + A2 E2 + E2 D2 + D2 (leftRotate C2 10) + C2 B2 + B2 Tmp2 ) ) ) + (setq + Tmp (add32 H1 C1 D2) + H1 (add32 H2 D1 E2) + H2 (add32 H3 E1 A2) + H3 (add32 H4 A1 B2) + H4 (add32 H0 B1 C2) + H0 Tmp ) ) ) + (make + (for N (list H0 H1 H2 H3 H4) + (do 4 + (link (& N 255)) + (setq N (>> 8 N)) ) ) ) ) ) + +(let Str "Rosetta Code" + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (ripemd160 Str) ) ) ) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (native + "libcrypto.so" + "RIPEMD160" + '(B . 20) + Str + (length Str) + '(NIL (20)) ) ) ) ) ) + +(bye) diff --git a/Task/RIPEMD-160/Scala/ripemd-160.scala b/Task/RIPEMD-160/Scala/ripemd-160.scala new file mode 100644 index 0000000000..4bc3cc8c01 --- /dev/null +++ b/Task/RIPEMD-160/Scala/ripemd-160.scala @@ -0,0 +1,10 @@ +import org.bouncycastle.crypto.digests.RIPEMD160Digest + +object RosettaRIPEMD160 extends App { + val (raw, messageDigest) = ("Rosetta Code".getBytes("US-ASCII"), new RIPEMD160Digest()) + messageDigest.update(raw, 0, raw.length) + val out = Array.fill[Byte](messageDigest.getDigestSize())(0) + messageDigest.doFinal(out, 0) + + assert(out.map("%02x".format(_)).mkString == "b3be159860842cebaa7174c8fff0aa9e50a5199f") +} diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--1.c b/Task/Random-number-generator--device-/C/random-number-generator--device--1.c index ad2e957ecc..fcfff87677 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--1.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--1.c @@ -1,25 +1,25 @@ -#include #include -#include +#include -int main(int argc, char **argv) +#define RANDOM_PATH "/dev/urandom" + +int main(void) { - uint32_t v; - FILE *r = fopen("/dev/urandom", "r"); - if (r == NULL) - { - perror("/dev/urandom"); - return 1; - } + unsigned char buf[4]; + unsigned long v; + FILE *fin; - size_t br = fread(&v, sizeof v, 1, r); - if (br < 1) - { - fputs("/dev/urandom: Not enough bytes\n", stderr); - return 1; - } - - printf("%" PRIu32 "\n", v); - fclose(r); - return 0; + if ((fin = fopen(RANDOM_PATH, "r")) == NULL) { + fprintf(stderr, "%s: unable to open file\n", RANDOM_PATH); + return EXIT_FAILURE; + } + if (fread(buf, 1, sizeof buf, fin) != sizeof buf) { + fprintf(stderr, "%s: not enough bytes (expected %u)\n", + RANDOM_PATH, (unsigned) sizeof buf); + return EXIT_FAILURE; + } + fclose(fin); + v = buf[0] | buf[1] << 8UL | buf[2] << 16UL | buf[3] << 24UL; + printf("%lu\n", v); + return 0; } diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--5.c b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c index 2ae9f1abac..58ad592c53 100644 --- a/Task/Random-number-generator--device-/C/random-number-generator--device--5.c +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--5.c @@ -1,11 +1 @@ -#include -#include -#include - -int main() -{ - std::random_device rd; - std::uniform_int_distribution dist; - - std::cout << "Random Number: " << dist(rd) << std::endl; -} + Math.random2(-(Math.random()),Math.random(); diff --git a/Task/Random-number-generator--device-/C/random-number-generator--device--6.c b/Task/Random-number-generator--device-/C/random-number-generator--device--6.c new file mode 100644 index 0000000000..80c3924f4f --- /dev/null +++ b/Task/Random-number-generator--device-/C/random-number-generator--device--6.c @@ -0,0 +1,10 @@ +#include +#include + +int main() +{ + std::random_device rd; + std::uniform_int_distribution dist; // long is guaranteed to be 32 bits + + std::cout << "Random Number: " << dist(rd) << std::endl; +} diff --git a/Task/Random-number-generator--device-/Fortran/random-number-generator--device-.f b/Task/Random-number-generator--device-/Fortran/random-number-generator--device-.f new file mode 100644 index 0000000000..ab8206b2bd --- /dev/null +++ b/Task/Random-number-generator--device-/Fortran/random-number-generator--device-.f @@ -0,0 +1,24 @@ +!----------------------------------------------------------------------- +! Test Linux urandom in Fortran +!----------------------------------------------------------------------- +program urandom_test + use iso_c_binding, only : c_long + implicit none + + character(len=*), parameter :: RANDOM_PATH = "/dev/urandom" + integer :: funit, ios + integer(c_long) :: buf + + open(newunit=funit, file=RANDOM_PATH, access="stream", form="UNFORMATTED", & + iostat=ios, status="old", action="read") + if ( ios /= 0 ) stop "Error opening file: "//RANDOM_PATH + + read(funit) buf + + close(funit) + + write(*,'(A,I64)') "Integer: ", buf + write(*,'(A,B64)') "Binary: ", buf + write(*,'(A,Z64)') "Hexadecimal: ", buf + +end program urandom_test diff --git a/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--1.math b/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--1.math new file mode 100644 index 0000000000..108af895a9 --- /dev/null +++ b/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--1.math @@ -0,0 +1 @@ +rand32[] := RandomInteger[{-2^31, 2^31 - 1}] diff --git a/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--2.math b/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--2.math new file mode 100644 index 0000000000..0c282e046f --- /dev/null +++ b/Task/Random-number-generator--device-/Mathematica/random-number-generator--device--2.math @@ -0,0 +1 @@ +Table[rand32[], {i, 1, 10}] diff --git a/Task/Random-number-generator--device-/Perl/random-number-generator--device--1.pl b/Task/Random-number-generator--device-/Perl/random-number-generator--device--1.pl new file mode 100644 index 0000000000..e88d801b68 --- /dev/null +++ b/Task/Random-number-generator--device-/Perl/random-number-generator--device--1.pl @@ -0,0 +1,3 @@ +use Crypt::Random::Seed; +my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom +print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values diff --git a/Task/Random-number-generator--device-/Perl/random-number-generator--device--2.pl b/Task/Random-number-generator--device-/Perl/random-number-generator--device--2.pl new file mode 100644 index 0000000000..6a71688a69 --- /dev/null +++ b/Task/Random-number-generator--device-/Perl/random-number-generator--device--2.pl @@ -0,0 +1,2 @@ +use Crypt::Random::Source qw/get_weak/; # Alternately get_strong +print unpack('L*',get_weak(4)), "\n" for 1..10; diff --git a/Task/Random-number-generator--device-/Perl/random-number-generator--device-.pl b/Task/Random-number-generator--device-/Perl/random-number-generator--device--3.pl similarity index 100% rename from Task/Random-number-generator--device-/Perl/random-number-generator--device-.pl rename to Task/Random-number-generator--device-/Perl/random-number-generator--device--3.pl diff --git a/Task/Random-number-generator--device-/UNIX-Shell/random-number-generator--device-.sh b/Task/Random-number-generator--device-/UNIX-Shell/random-number-generator--device-.sh new file mode 100644 index 0000000000..c90850446f --- /dev/null +++ b/Task/Random-number-generator--device-/UNIX-Shell/random-number-generator--device-.sh @@ -0,0 +1 @@ +od -An -N 4 -t u4 /dev/urandom diff --git a/Task/Random-number-generator--included-/Elixir/random-number-generator--included-.elixir b/Task/Random-number-generator--included-/Elixir/random-number-generator--included-.elixir new file mode 100644 index 0000000000..1feccc0afe --- /dev/null +++ b/Task/Random-number-generator--included-/Elixir/random-number-generator--included-.elixir @@ -0,0 +1,8 @@ +# Seed the RNG +:random.seed(:erlang.now()) + +# Integer in the range 1..10 +:random.uniform(10) + +# Float between 0.0 and 1.0 +:random.uniform() diff --git a/Task/Random-number-generator--included-/PL-SQL/random-number-generator--included--1.sql b/Task/Random-number-generator--included-/PL-SQL/random-number-generator--included--1.sql index 5a386aab4b..6124d06779 100644 --- a/Task/Random-number-generator--included-/PL-SQL/random-number-generator--included--1.sql +++ b/Task/Random-number-generator--included-/PL-SQL/random-number-generator--included--1.sql @@ -1,2 +1,3 @@ DBMS_RANDOM.RANDOM --produces integers in [-2^^31, 2^^31). -DBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision. +DBMS_RANDOM.VALUE --produces numbers in [0,1) with 38 digits of precision. +DBMS_RANDOM.NORMAL --produces normal distributed numbers with a mean of 0 and a variance of 1 diff --git a/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx b/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx index 17cdf94f0c..eaa4405d0f 100644 --- a/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx +++ b/Task/Random-number-generator--included-/REXX/random-number-generator--included--3.rexx @@ -2,6 +2,7 @@ * 08.09.2013 Walter Pachl * Please add the output from other REXXes * 10.09.2013 Walter Pachl added REXX/TSO +* 01.08.2014 Walter Pachl show what ooRexx supports **********************************************************************/ Parse Version v Call random ,,44 @@ -9,4 +10,6 @@ ol=v':' Do i=1 To 10 ol=ol random(1,10) End +If left(v,11)='REXX-ooRexx' Then + ol=ol random(-999999999,0) /* ooRexx supports negative limits */ Say ol diff --git a/Task/Random-numbers/00DESCRIPTION b/Task/Random-numbers/00DESCRIPTION index ac09fcdf70..863b255f4d 100644 --- a/Task/Random-numbers/00DESCRIPTION +++ b/Task/Random-numbers/00DESCRIPTION @@ -1,3 +1,13 @@ -The goal of this task is to generate a collection filled with 1000 normally distributed random (or pseudorandom) numbers with a mean of 1.0 and a [[wp:Standard_deviation|standard deviation]] of 0.5 +{{omit from|GUISS}} +{{omit from|UNIX Shell|From the shell, we simply invoke the awk solution}} -Many libraries only generate uniformly distributed random numbers. If so, use [[wp:Normal_distribution#Generating_values_from_normal_distribution|this formula]] to convert them to a normal distribution. +The goal of this task is to generate a collection filled with +1000 normally distributed random (or pseudorandom) numbers +with a mean of 1.0 and a [[wp:Standard_deviation|standard deviation]] of 0.5 + +Many libraries only generate uniformly distributed random numbers. + +If so, use [[wp:Normal_distribution#Generating_values_from_normal_distribution|this formula]] to convert them to a normal distribution. + +;See also: +* [[Standard deviation]] diff --git a/Task/Random-numbers/00META.yaml b/Task/Random-numbers/00META.yaml index b643d1dd0b..8315d112b8 100644 --- a/Task/Random-numbers/00META.yaml +++ b/Task/Random-numbers/00META.yaml @@ -1,4 +1,5 @@ --- category: - Probability and statistics +- Randomness note: Basic language learning diff --git a/Task/Random-numbers/AWK/random-numbers.awk b/Task/Random-numbers/AWK/random-numbers-1.awk similarity index 100% rename from Task/Random-numbers/AWK/random-numbers.awk rename to Task/Random-numbers/AWK/random-numbers-1.awk diff --git a/Task/Random-numbers/AWK/random-numbers-2.awk b/Task/Random-numbers/AWK/random-numbers-2.awk new file mode 100644 index 0000000000..d8ff0d49e2 --- /dev/null +++ b/Task/Random-numbers/AWK/random-numbers-2.awk @@ -0,0 +1,12 @@ +function r() { + return sqrt( -2*log( rand() ) ) * cos(6.2831853*rand() ) +} + +BEGIN { + n=1000 + for(i=0;i>> import random +>>> values = [random.gauss(1, .5) for i in range(1000)] +>>> diff --git a/Task/Random-numbers/Python/random-numbers-2.py b/Task/Random-numbers/Python/random-numbers-2.py index 13cdcd443d..0e6942982d 100644 --- a/Task/Random-numbers/Python/random-numbers-2.py +++ b/Task/Random-numbers/Python/random-numbers-2.py @@ -1,4 +1,9 @@ ->>> mean = sum(values)/1000 ->>> sdeviation = (sum((i - mean)**2 for i in values)/1000)**0.5 ->>> mean, sdeviation -(1.0127861555468178, 0.5006682783828207) +>>> def quick_check(numbers): + count = len(numbers) + mean = sum(numbers) / count + sdeviation = (sum((i - mean)**2 for i in numbers) / count)**0.5 + return mean, sdeviation + +>>> quick_check(values) +(1.0140373306786599, 0.49943411329234066) +>>> diff --git a/Task/Random-numbers/Python/random-numbers-3.py b/Task/Random-numbers/Python/random-numbers-3.py new file mode 100644 index 0000000000..180d170eb8 --- /dev/null +++ b/Task/Random-numbers/Python/random-numbers-3.py @@ -0,0 +1,4 @@ +>>> values = [ random.normalvariate(1, 0.5) for i in range(1000)] +>>> quick_check(values) +(0.990099111944864, 0.5029847005836282) +>>> diff --git a/Task/Random-numbers/REXX/random-numbers.rexx b/Task/Random-numbers/REXX/random-numbers.rexx index 7bf4ed0455..6408fe7ad5 100644 --- a/Task/Random-numbers/REXX/random-numbers.rexx +++ b/Task/Random-numbers/REXX/random-numbers.rexx @@ -1,41 +1,38 @@ -/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=½. */ -call pi /*call subroutine to define pi. */ -parse arg n seed . /*allow specification of N | seed*/ -if n=='' | n==',' then n=1000 /* N is the size of the array. */ -if seed\=='' then call random ,,seed /*use seed for repeatable RANDOM#*/ -mean=1 /*desired new mean (arith. avg.) */ +/*REXX pgm gens 1,000 normally distributed #s: mean=1, standard dev.=½.*/ +numeric digits 20 /*greater precision than 9 digits*/ +parse arg n seed . /*allow specification of N & seed*/ +if n=='' | n==',' then n=1000 /*N: is the size of the array.*/ +if seed\=='' then call random ,,seed /*SEED: for repeatable random #'s*/ +newMean=1 /*desired new mean|arithmetic avg*/ sd=1/2 /*desired new standard deviation.*/ - do g=1 for n /*generate N uniform random nums.*/ - #.g=random(0,1e5)/1e5 /*REXX gens uniform rand integers*/ - end /*g*/ - + do g=1 for n /*gen N uniform random #'s (0,1].*/ + #.g = random(1,1e5) / 1e5 /*RANDOM bif generates integers.*/ + end /*g*/ /* [↑] rand integers──►fractions*/ say ' old mean=' mean() say 'old standard deviation=' stddev() +call pi; pi2=pi+pi /*define pi and also 2*pi. */ say - do j=1 to n-1 by 2 - m=j+1 - _=sd*sqrt(-2*ln(#.j))*cos(2*pi*#.m)+mean /*use Box-Muller method*/ - #.m=sd*sqrt(-2*ln(#.j))*sin(2*pi*#.m)+mean /*rand # must be 0──�1.*/ - #.j=_ - end /*j*/ + do j=1 to n-1 by 2; m=j+1 /*step through iterations by two.*/ + _=sd * sqrt(ln(#.j) * -2) /*calculate used-twice expression*/ + #.j=_ * cos(pi2*#.m) + newMean /*utilize the Box─Muller method.*/ + #.m=_ * sin(pi2*#.m) + newMean /*random number must be: (0,1] */ + end /*j*/ say ' new mean=' mean() say 'new standard deviation=' stddev() exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────subroutines─────────────────────────*/ -mean: _=0; do k=1 for n; _=_+#.k; end; return _/n -stddev: _avg=mean(); _=0; do k=1 for n; _=_+(#.k-_avg)**2; end; return sqrt(_/n) -e: e=2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e -pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi -r2r: return arg(1)//(2*pi()) -sqrt: procedure;parse arg x; if x=0 then return 0; d=digits(); numeric digits 11; g=.sqrtGuess() - 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 -.sqrtGuess: numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 -cos: procedure; arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9); if a=pi() then return -1 - if a=pi()/2|a=2*pi() then return 0;if a=pi()/3 then return .5;if a=2*pi()/3 then return -.5;return .sincos(1,1,-1) -sin: procedure; arg x; x=r2r(x); numeric fuzz min(5,digits()-3); if abs(x)=pi() then return 0; return .sincos(x,x,1) -.sincos:parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z -ln: procedure; parse arg x,f; call e; ig=x>1.5; is=1-2*(ig\==1); ii=0; xx=x; return .ln_comp() +/*──────────────────────────────────subroutines──────────────────────────────────────────────────────────────────────*/ +mean: _=0; do k=1 for n; _=_+#.k; end; return _/n +stddev: _avg=mean(); _=0; do k=1 for n; _=_+(#.k-_avg)**2; end; return sqrt(_/n) +e: e =2.7182818284590452353602874713526624977572470936999595749669676277240766303535; return e /*digs overkill*/ +pi: pi=3.1415926535897932384626433832795028841971693993751058209749445923078164062862; return pi /* " " */ +r2r: return arg(1) // (2*pi()) /*normalize ang*/ +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits 11; numeric form; m.=11; p=d+d%4+2 + parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'E'_%2; 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 +cos: procedure; parse arg x; x=r2r(x); a=abs(x); numeric fuzz min(9,digits()-9); if a=pi then return -1; pi2=pi+pi + if a=pi*.5|a=pi2 then return 0; if a=pi/3 then return .5; if a=pi2/3 then return -.5; return .sincos(1,1,-1) +sin: procedure; parse arg x;x=r2r(x);numeric fuzz min(5,digits()-3);if abs(x)=pi then return 0;return .sincos(x,x,1) +.sincos:parse arg z,_,i; x=x*x; p=z; do k=2 by 2; _=-_*x/(k*(k+i)); z=z+_; if z=p then leave; p=z; end; return z +ln: procedure; parse arg x,f; call e; ig= x>1.5; is=1-2*(ig\==1); ii=0; xx=x; return .ln_comp() .ln_comp: do while ig&xx>1.5|\ig&xx<.5;_=e;do k=-1;iz=xx*_**-is;if k>=0&(ig&iz<1|\ig&iz>.5) then leave;_=_*_;izz=iz;end - xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end;return z+ii + xx=izz;ii=ii+is*2**k;end;x=x*e**-ii-1;z=0;_=-1;p=z;do k=1;_=-_*x;z=z+_/k;if z=p then leave;p=z;end; return z+ii diff --git a/Task/Range-expansion/00DESCRIPTION b/Task/Range-expansion/00DESCRIPTION index 933e0b8069..c2d9489c32 100644 --- a/Task/Range-expansion/00DESCRIPTION +++ b/Task/Range-expansion/00DESCRIPTION @@ -3,6 +3,7 @@ ;The task Expand the range description: : -6,-3--1,3-5,7-11,14,15,17-20 -Note that the second element above, is the '''range from minus 3 to ''minus'' 1'''. +Note that the second element above, +is the '''range from minus 3 to ''minus'' 1'''. C.f. [[Range extraction]] diff --git a/Task/Range-expansion/COBOL/range-expansion.cobol b/Task/Range-expansion/COBOL/range-expansion.cobol new file mode 100644 index 0000000000..072eeac969 --- /dev/null +++ b/Task/Range-expansion/COBOL/range-expansion.cobol @@ -0,0 +1,93 @@ + >>SOURCE FREE +IDENTIFICATION DIVISION. +PROGRAM-ID. expand-range. + +DATA DIVISION. +WORKING-STORAGE SECTION. +01 comma-pos PIC 99 COMP VALUE 1. +01 dash-pos PIC 99 COMP. +01 end-num PIC S9(3). +01 Max-Part-Len CONSTANT 10. +01 num PIC S9(3). +01 edited-num PIC -(3)9. +01 part PIC X(10). + +01 part-flag PIC X. + 88 last-part VALUE "Y". + +01 range-str PIC X(80). +01 Range-Str-Len CONSTANT 80. +01 start-pos PIC 99 COMP. +01 start-num PIC S9(3). + +PROCEDURE DIVISION. + ACCEPT range-str + + PERFORM WITH TEST AFTER UNTIL last-part + UNSTRING range-str DELIMITED BY "," INTO part WITH POINTER comma-pos + PERFORM check-if-last + + PERFORM find-range-dash + + IF dash-pos > Max-Part-Len + PERFORM display-num + ELSE + PERFORM display-range + END-IF + END-PERFORM + + DISPLAY SPACES + + GOBACK + . +check-if-last SECTION. + IF comma-pos > Range-Str-Len + SET last-part TO TRUE + END-IF + . +find-range-dash SECTION. + IF part (1:1) <> "-" + MOVE 1 TO start-pos + ELSE + MOVE 2 TO start-pos + END-IF + + MOVE 1 TO dash-pos + INSPECT part (start-pos:) TALLYING dash-pos FOR CHARACTERS BEFORE "-" + COMPUTE dash-pos = dash-pos + start-pos - 1 + . +display-num SECTION. + MOVE part TO edited-num + CALL "display-edited-num" USING CONTENT part-flag, edited-num + . +display-range SECTION. + MOVE part (1:dash-pos - 1) TO start-num + MOVE part (dash-pos + 1:) TO end-num + + PERFORM VARYING num FROM start-num BY 1 UNTIL num = end-num + MOVE num TO edited-num + CALL "display-edited-num" USING CONTENT "N", edited-num + END-PERFORM + + MOVE end-num TO edited-num + CALL "display-edited-num" USING CONTENT part-flag, edited-num + . +END PROGRAM expand-range. + + +IDENTIFICATION DIVISION. +PROGRAM-ID. display-edited-num. + +DATA DIVISION. +LINKAGE SECTION. +01 hide-comma-flag PIC X. + 88 hide-comma VALUE "Y". +01 edited-num PIC -(3)9. + +PROCEDURE DIVISION USING hide-comma-flag, edited-num. + DISPLAY FUNCTION TRIM(edited-num) NO ADVANCING + IF NOT hide-comma + DISPLAY ", " NO ADVANCING + END-IF + . +END PROGRAM display-edited-num. diff --git a/Task/Range-expansion/Haskell/range-expansion-3.hs b/Task/Range-expansion/Haskell/range-expansion-3.hs index 3f95890d05..6ad83e1bbc 100644 --- a/Task/Range-expansion/Haskell/range-expansion-3.hs +++ b/Task/Range-expansion/Haskell/range-expansion-3.hs @@ -1,16 +1,14 @@ -import Control.Monad -import Text.ParserCombinators.Parsec +import Control.Applicative (Applicative((<*>),(*>)),(<$>)) +import Text.Parsec -expandRange :: String -> [Int] -expandRange s = case parse rangeParser "" s of Right l -> l +expandRange :: String -> Maybe [Int] +expandRange = either (const Nothing) Just . parse rangeParser "" rangeParser :: Parser [Int] -rangeParser = liftM concat $ item `sepBy` char ',' - where item = do - n1 <- num - n2 <- option n1 $ char '-' >> num - return [n1 .. n2] +rangeParser = concat <$> (item `sepBy` char ',') + where item = do n1 <- num + n2 <- option n1 (char '-' *> num) + return [n1 .. n2] num :: Parser Int - num = liftM read $ liftM2 (++) - (option "" $ string "-") - (many1 digit) + num = read `dot` (++) <$> option "" (string "-") <*> many1 digit + dot = ((.).(.)) diff --git a/Task/Range-expansion/Lua/range-expansion.lua b/Task/Range-expansion/Lua/range-expansion.lua new file mode 100644 index 0000000000..1e665afb9d --- /dev/null +++ b/Task/Range-expansion/Lua/range-expansion.lua @@ -0,0 +1,28 @@ +function range(i, j) + local t = {} + for n = i, j, i values) { + var list = values.Distinct().OrderBy(_ => _).ToArray(); + var ranges = new int[0][].AsEnumerable(); + var current = 0; + for (var i = 1; ; ++i) { + if (i >= list.Length) { + ranges = ranges.Concat(new[] { new[] { i != current ? current : i - 1, i - 1 } }); + break; + } + if (list[i] == list[i - 1] + 1) + continue; + ranges = ranges.Concat(new[] { new[] { current, i - 1 } }); + current = i; + } + return string.Join(",", ranges.Select(r => string.Format(r[0] == r[1] ? "{0}" : "{0}-{1}", list[r[0]], list[r[1]]))); + } + } + + internal class Program { + private static readonly IList VALUES = new[] { + 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 + }; + + private static void Main(string[] args) { + var rangestr = VALUES.ExtractRange(); + Console.WriteLine("values: {{{0}}}", string.Join(", ", VALUES.Select(_=>_.ToString()))); + Console.WriteLine("\r\nranges = \"{0}\"", rangestr); + } + } +} diff --git a/Task/Range-extraction/C/range-extraction.c b/Task/Range-extraction/C/range-extraction.c new file mode 100644 index 0000000000..4c0fd09e59 --- /dev/null +++ b/Task/Range-extraction/C/range-extraction.c @@ -0,0 +1,36 @@ +#include +#include + +size_t rprint(char *s, int *x, int len) +{ +#define sep (a > s ? "," : "") /* use comma except before first output */ +#define ol (s ? 100 : 0) /* print only if not testing for length */ + int i, j; + char *a = s; + for (i = j = 0; i < len; i = ++j) { + for (; j < len - 1 && x[j + 1] == x[j] + 1; j++); + + if (i + 1 < j) + a += snprintf(s?a:s, ol, "%s%d-%d", sep, x[i], x[j]); + else + while (i <= j) + a += snprintf(s?a:s, ol, "%s%d", sep, x[i++]); + } + return a - s; +#undef sep +#undef ol +} + +int main() +{ + int x[] = { 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 }; + + char *s = malloc(rprint(0, x, sizeof(x) / sizeof(int)) + 1); + rprint(s, x, sizeof(x) / sizeof(int)); + printf("%s\n", s); + + return 0; +} diff --git a/Task/Range-extraction/D/range-extraction.d b/Task/Range-extraction/D/range-extraction.d index 091f2b6ebb..407c1710c5 100644 --- a/Task/Range-extraction/D/range-extraction.d +++ b/Task/Range-extraction/D/range-extraction.d @@ -15,8 +15,8 @@ in { ranges ~= [y.text]; return ranges - .map!(r => r.length > 2 ? r[0] ~ "-" ~ r.back : r.join(",")) - .join(","); + .map!(r => r.length > 2 ? r[0] ~ "-" ~ r.back : r.join(',')) + .join(','); } void main() { diff --git a/Task/Range-extraction/Eiffel/range-extraction.e b/Task/Range-extraction/Eiffel/range-extraction.e new file mode 100644 index 0000000000..341d9d47e1 --- /dev/null +++ b/Task/Range-extraction/Eiffel/range-extraction.e @@ -0,0 +1,72 @@ +class + RANGE + +create + make + +feature + make + local + extended_range: STRING + do + extended_range := "0, 1, 2, 4, 6, 7, 8, 11, 12, 14, " + + "15, 16, 17, 18, 19, 20, 21, 22, 23, 24, " + + "25, 27, 28, 29, 30, 31, 32, 33, 35, 36, " + + "37, 38, 39" + print("Extended range: " + extended_range + "%N") + print("Extracted range: " + extracted_range(extended_range) + "%N%N") + end + +feature + extracted_range(sequence: STRING): STRING + local + elements: LIST[STRING] + first, curr: STRING + subrange_size, index: INTEGER + do + sequence.replace_substring_all (", ", ",") + elements := sequence.split (',') + from + index := 2 + first := elements.at (1) + subrange_size := 0 + Result := "" + until + index > elements.count + loop + curr := elements.at (index) + if curr.to_integer - first.to_integer - subrange_size = 1 + then + subrange_size := subrange_size + 1 + else + Result.append(first) + if (subrange_size <= 1) + then + Result.append (", ") + else + Result.append (" - ") + end + if (subrange_size >= 1) + then + Result.append ((first.to_integer + subrange_size).out) + Result.append (", ") + end + + first := curr + subrange_size := 0 + end + index := index + 1 + end + Result.append(first) + if (subrange_size <= 1) + then + Result.append (", ") + else + Result.append (" - ") + end + if (subrange_size >= 1) + then + Result.append ((first.to_integer + subrange_size).out) + end + end +end diff --git a/Task/Range-extraction/Emacs-Lisp/range-extraction.l b/Task/Range-extraction/Emacs-Lisp/range-extraction.l new file mode 100644 index 0000000000..e20def1f3f --- /dev/null +++ b/Task/Range-extraction/Emacs-Lisp/range-extraction.l @@ -0,0 +1,12 @@ +(require 'gnus-range) +(defun rangext (lst) + (mapconcat (lambda (item) + (if (consp item) + (format "%d-%d" (car item) (cdr item)) + (format "%d" item))) + (gnus-compress-sequence lst) + ",")) +(rangext '(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/Range-extraction/K/range-extraction.k b/Task/Range-extraction/K/range-extraction.k new file mode 100644 index 0000000000..b76c755ed2 --- /dev/null +++ b/Task/Range-extraction/K/range-extraction.k @@ -0,0 +1,3 @@ +grp : {(&~1=0,-':x)_ x} +fmt : {:[1=#s:$x;s;(*s),:[3>#s;",";"-"],*|s]} +erng: {{x,",",y}/,//'fmt'grp x} diff --git a/Task/Range-extraction/MATLAB/range-extraction.m b/Task/Range-extraction/MATLAB/range-extraction.m index 82aa4ee919..2695ab592f 100644 --- a/Task/Range-extraction/MATLAB/range-extraction.m +++ b/Task/Range-extraction/MATLAB/range-extraction.m @@ -1,18 +1,23 @@ 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; + % 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 +end + +disp(range_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])) diff --git a/Task/Range-extraction/Objective-C/range-extraction.m b/Task/Range-extraction/Objective-C/range-extraction.m new file mode 100644 index 0000000000..3f106e0f7a --- /dev/null +++ b/Task/Range-extraction/Objective-C/range-extraction.m @@ -0,0 +1,34 @@ +#import + +NSString *extractRanges(NSArray *nums) { + NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] init]; + for (NSNumber *n in nums) { + if ([n integerValue] < 0) + @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"negative number not supported" userInfo:nil]; + [indexSet addIndex:[n unsignedIntegerValue]]; + } + NSMutableString *s = [[NSMutableString alloc] init]; + [indexSet enumerateRangesUsingBlock:^(NSRange range, BOOL *stop) { + if (s.length) + [s appendString:@","]; + if (range.length == 1) + [s appendFormat:@"%lu", range.location]; + else if (range.length == 2) + [s appendFormat:@"%lu,%lu", range.location, range.location+1]; + else + [s appendFormat:@"%lu-%lu", range.location, range.location+range.length-1]; + }]; + return s; +} + +int main() { + @autoreleasepool { + + NSLog(@"%@", extractRanges(@[@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])); + + } + return 0; +} diff --git a/Task/Range-extraction/Oz/range-extraction.oz b/Task/Range-extraction/Oz/range-extraction.oz new file mode 100644 index 0000000000..47b0006861 --- /dev/null +++ b/Task/Range-extraction/Oz/range-extraction.oz @@ -0,0 +1,47 @@ +declare + fun {Extract Xs} + {CommaSeparated + {Map {ExtractRanges Xs} RangeToString}} + end + + fun {ExtractRanges Xs} + fun {Loop Ys Start End} + case Ys + of Y|Yr andthen Y == End+1 then {Loop Yr Start Y} + [] Y|Yr then Start#End|{Loop Yr Y Y} + [] nil then [Start#End] + end + end + in + case Xs + of X|Xr then {Loop Xr X X} + [] nil then nil + end + end + + fun {RangeToString S#E} + if E-S >= 2 then + {VirtualString.toString S#"-"#E} + else + {CommaSeparated + {Map {List.number S E 1} Int.toString}} + end + end + + fun {CommaSeparated Xs} + {Flatten {Intersperse "," Xs}} + end + + fun {Intersperse Sep Xs} + case Xs of X|Y|Xr then + X|Sep|{Intersperse Sep Y|Xr} + else + Xs + end + end +in + {System.showInfo + {Extract [ 0 1 2 4 6 7 8 11 12 14 + 15 16 17 18 19 20 21 22 23 24 + 25 27 28 29 30 31 32 33 35 36 + 37 38 39 ]}} diff --git a/Task/Range-extraction/Perl/range-extraction.pl b/Task/Range-extraction/Perl/range-extraction-1.pl similarity index 100% rename from Task/Range-extraction/Perl/range-extraction.pl rename to Task/Range-extraction/Perl/range-extraction-1.pl diff --git a/Task/Range-extraction/Perl/range-extraction-2.pl b/Task/Range-extraction/Perl/range-extraction-2.pl new file mode 100644 index 0000000000..132abb78e4 --- /dev/null +++ b/Task/Range-extraction/Perl/range-extraction-2.pl @@ -0,0 +1,2 @@ +use Set::IntSpan; +sub rangext { return Set::IntSpan->new(@_) . '' } # stringized diff --git a/Task/Range-extraction/Perl/range-extraction-3.pl b/Task/Range-extraction/Perl/range-extraction-3.pl new file mode 100644 index 0000000000..655ae686ca --- /dev/null +++ b/Task/Range-extraction/Perl/range-extraction-3.pl @@ -0,0 +1,2 @@ +use Set::IntSpan::Fast; +sub rangext { return Set::IntSpan::Fast->new(@_)->as_string } diff --git a/Task/Range-extraction/REXX/range-extraction-1.rexx b/Task/Range-extraction/REXX/range-extraction-1.rexx index ad0ff81a0f..aaffa7d94a 100644 --- a/Task/Range-extraction/REXX/range-extraction-1.rexx +++ b/Task/Range-extraction/REXX/range-extraction-1.rexx @@ -1,20 +1,20 @@ /*REXX program creates a range extraction from a list of integers. */ old=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 w=words(old) /*number of integers in the list.*/ -new= /*new list (maybe with ranges). */ - do j=1 to w; x=word(old,j) /*get the Jth number in the list.*/ - new=new',' x /*append Jth number to new list.*/ - inc=1; g= /*start with an increment of one.*/ +new= /*new list, possibly with ranges.*/ + do j=1 to w; x=word(old,j) /*get the Jth number in the list.*/ + new=new',' x /*append Jth number to new list.*/ + inc=1 /*start with an increment of one.*/ do k=j+1 to w; y=word(old,k) /*get the Kth number in the list.*/ - if y\=x+inc then leave /*is this number ¬> prev by inc ?*/ + if y\=x+inc then leave /*is this number ¬> prev by inc? */ inc=inc+1; g=y /*increase range, assign g (good)*/ end /*k*/ - if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ - new=new'-'g /*indicate a range of numbers. */ - j =k-1 /*changing the J DO loop index.*/ - end /*j*/ + if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ + new=new'-'g /*indicate a range of numbers. */ + j=k-1 /*changing the J DO loop index.*/ + end /*j*/ new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ -say 'old:' old /*show the old range of numbers. */ -say 'new:' new /*display new list of numbers. */ +say 'old:' old /*show the old range of numbers. */ +say 'new:' new /* " " new list " " */ /*stick a fork in it, we're done.*/ diff --git a/Task/Range-extraction/REXX/range-extraction-2.rexx b/Task/Range-extraction/REXX/range-extraction-2.rexx index 3559e93951..ca4b8679a6 100644 --- a/Task/Range-extraction/REXX/range-extraction-2.rexx +++ b/Task/Range-extraction/REXX/range-extraction-2.rexx @@ -1,20 +1,20 @@ /*REXX program creates a range extraction from a list of integers. */ old=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 w=words(old); j=0 /*number of integers in the list.*/ -new= /*new list (maybe with ranges). */ +new= /*new list, possibly with ranges.*/ do while j prev by inc ?*/ - inc=inc+1; g=y /*increase range, assign g (good)*/ + new=new',' x /*append Jth number to new list.*/ + inc=1 /*start with an increment of one.*/ + do k=j+1 to w; y=word(old,k) /*get the Kth number in the list.*/ + if y\=x+inc then leave /*is this number ¬> prev by inc? */ + inc=inc+1; g=y /*increase range, assign g (good)*/ end /*k*/ - if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ - new=new'-'g /*indicate a range of numbers. */ - j =k-1 /*which number to examine next. */ - end /*while*/ + if k-1=j | g=x+1 then iterate /*range= 0|1? Then keep truckin'*/ + new=new'-'g /*indicate a range of numbers. */ + j=k-1 /*which number to examine next. */ + end /*while*/ new=space(substr(new, 2), 0) /*elide leading comma, all blanks*/ -say 'old:' old /*show the old range of numbers. */ -say 'new:' new /*display new list of numbers. */ +say 'old:' old /*show the old range of numbers. */ +say 'new:' new /* " " new list " " */ /*stick a fork in it, we're done.*/ diff --git a/Task/Range-extraction/Ruby/range-extraction.rb b/Task/Range-extraction/Ruby/range-extraction.rb index 804b53e2da..e406e09886 100644 --- a/Task/Range-extraction/Ruby/range-extraction.rb +++ b/Task/Range-extraction/Ruby/range-extraction.rb @@ -1,17 +1,25 @@ def range_extract(l) - sorted = l.sort - range = [] - start = sorted.first # pad the list with a big value, so that the last loop iteration will - # appended something to the range - sorted.concat([Float::MAX]).each_cons(2) do |prev,n| - if prev.succ < n - if start == prev - range << start.to_s + # append something to the range + sorted, range = l.sort.concat([Float::MAX]), [] + canidate_number = sorted.first + + # enumerate over the sorted list in pairs of current number and next by index + sorted.each_cons(2) do |current_number, next_number| + # if there is a gap between the current element and its next by index + if current_number.succ < next_number + # if current element is our first or our next by index + if canidate_number == current_number + # put the first element or next by index into our range as a string + range << canidate_number.to_s else - range << "%d%s%d" % [start, (start.succ == prev ? "," : "-"), prev] + # if current element is not the same as the first or next + # add [first or next, first or next equals current add , else -, current] + seperator = canidate_number.succ == current_number ? "," : "-" + range << "%d%s%d" % [canidate_number, seperator, current_number] end - start = n + # make the first element the next element + canidate_number = next_number end end range.join(',') diff --git a/Task/Rate-counter/Haskell/rate-counter.hs b/Task/Rate-counter/Haskell/rate-counter.hs new file mode 100644 index 0000000000..60c2d4313d --- /dev/null +++ b/Task/Rate-counter/Haskell/rate-counter.hs @@ -0,0 +1,22 @@ +import Control.Monad +import Control.Concurrent +import Data.Time + +getTime :: IO DiffTime +getTime = fmap utctDayTime getCurrentTime + +addSample :: MVar [a] -> a -> IO () +addSample q v = modifyMVar_ q (return . (v:)) + +timeit :: Int -> IO a -> IO [DiffTime] +timeit n task = do + samples <- newMVar [] + forM_ [0..n] $ \n -> do + t1 <- getTime + task + t2 <- getTime + addSample samples (t2 - t1) + + readMVar samples + +main = timeit 10 (threadDelay 1000000) diff --git a/Task/Rate-counter/Mathematica/rate-counter.math b/Task/Rate-counter/Mathematica/rate-counter.math new file mode 100644 index 0000000000..dd57f3d7e1 --- /dev/null +++ b/Task/Rate-counter/Mathematica/rate-counter.math @@ -0,0 +1,5 @@ +jobRateCounted[fn_,Y_Integer]:=First[AbsoluteTiming[Do[fn,{Y}]]/Y; +SetAttributes[jobRateCounted,HoldFirst] + +jobRatePeriod[fn_,time_]:=Block[{n=0},TimeConstrained[While[True,fn;n++]];n/time]; +SetAttributes[jobRatePeriod,HoldFirst] diff --git a/Task/Ray-casting-algorithm/C/ray-casting-algorithm.c b/Task/Ray-casting-algorithm/C/ray-casting-algorithm.c index a1009f6cba..c4e3c79bbc 100644 --- a/Task/Ray-casting-algorithm/C/ray-casting-algorithm.c +++ b/Task/Ray-casting-algorithm/C/ray-casting-algorithm.c @@ -71,12 +71,12 @@ double dist(vec x, vec y0, vec y1, double tol) int inside(vec v, polygon p, double tol) { /* should assert p->n > 1 */ - int i, k, crosses; + int i, k, crosses, intersectResult; vec *pv; double min_x, max_x, min_y, max_y; for (i = 0; i < p->n; i++) { - k = i + 1 % p->n; + k = (i + 1) % p->n; min_x = dist(v, p->v[i], p->v[k], tol); if (min_x < tol) return 0; } @@ -107,13 +107,13 @@ int inside(vec v, polygon p, double tol) for (i = 0; i < p->n; i++) { k = (i + 1) % p->n; - k = intersect(v, e, p->v[i], p->v[k], tol, 0); + intersectResult = intersect(v, e, p->v[i], p->v[k], tol, 0); /* picked a bad point, ray got too close to vertex. re-pick */ - if (!k) break; + if (!intersectResult) break; - if (k == 1) crosses++; + if (intersectResult == 1) crosses++; } if (i == p->n) break; } diff --git a/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d b/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d index 3285181152..28fb5f472e 100644 --- a/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d +++ b/Task/Ray-casting-algorithm/D/ray-casting-algorithm.d @@ -7,8 +7,9 @@ immutable struct Figure { Edge[] edges; } -bool contains(in Figure poly, in Point p) pure nothrow { - static bool raySegI(in Point p, in Edge edge) pure nothrow { +bool contains(in Figure poly, in Point p) pure nothrow @safe @nogc { + static bool raySegI(in Point p, in Edge edge) + pure nothrow @safe @nogc { enum double epsilon = 0.00001; with (edge) { if (a.y > b.y) @@ -31,7 +32,7 @@ bool contains(in Figure poly, in Point p) pure nothrow { } } - return poly.edges.count!(e => raySegI(p, e))() % 2; + return poly.edges.count!(e => raySegI(p, e)) % 2; } void main() { @@ -54,6 +55,7 @@ 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}}]} ]; + immutable Point[] testPoints = [{ 5, 5}, {5, 8}, {-10, 5}, {0, 5}, {10, 5}, {8, 5}, { 10, 10}]; diff --git a/Task/Read-a-configuration-file/00DESCRIPTION b/Task/Read-a-configuration-file/00DESCRIPTION index 5a3746b863..372a493762 100644 --- a/Task/Read-a-configuration-file/00DESCRIPTION +++ b/Task/Read-a-configuration-file/00DESCRIPTION @@ -1,4 +1,7 @@ -The task is to read a configuration file in standard configuration file, and set variables accordingly. For this task, we have a configuration file as follows: +The task is to read a configuration file in standard configuration file, +and set variables accordingly. + +For this task, we have a configuration file as follows: # This is a configuration file in standard configuration file format # diff --git a/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj b/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj new file mode 100644 index 0000000000..8d075afccc --- /dev/null +++ b/Task/Read-a-configuration-file/Clojure/read-a-configuration-file.clj @@ -0,0 +1,2 @@ +(let [cfg (read-string (slurp "config.edn"))] + (clojure.pprint/pprint cfg)) diff --git a/Task/Read-a-configuration-file/Mathematica/read-a-configuration-file.math b/Task/Read-a-configuration-file/Mathematica/read-a-configuration-file.math new file mode 100644 index 0000000000..d1ac56ca91 --- /dev/null +++ b/Task/Read-a-configuration-file/Mathematica/read-a-configuration-file.math @@ -0,0 +1,21 @@ +ClearAll[CreateVar, ImportConfig]; +CreateVar[x_, y_String: "True"] := Module[{}, + If[StringFreeQ[y, ","] + , + ToExpression[x <> "=" <> y] + , + ToExpression[x <> "={" <> StringJoin@Riffle[StringSplit[y, ","], ","] <> "}"] + ] + ] +ImportConfig[configfile_String] := Module[{data}, + (*data = ImportString[configfile, "List", "Numeric" -> False];*) + data=Import[configfile,"List","Numeric"\[Rule]False]; + + data = StringTrim /@ data; + data = Select[data, # =!= "" &]; + data = Select[data, ! StringMatchQ[#, "#" | ";" ~~ ___] &]; + data = If[! StringFreeQ[#, " "], StringSplit[#, " ", 2], {#}] & /@ data; + + CreateVar @@@ data; + ] +ImportConfig[file] diff --git a/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file.l b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file.l new file mode 100644 index 0000000000..0989e62148 --- /dev/null +++ b/Task/Read-a-configuration-file/PicoLisp/read-a-configuration-file.l @@ -0,0 +1,8 @@ +(de rdConf (File) + (in File + (while (read) + (set @ (or (pack (clip (line))) T)) ) ) ) + +(rdConf "conf.txt") +(println FULLNAME FAVOURITEFRUIT NEEDSPEELING SEEDSREMOVED OTHERFAMILY) +(bye) diff --git a/Task/Read-a-configuration-file/RapidQ/read-a-configuration-file.rapidq b/Task/Read-a-configuration-file/RapidQ/read-a-configuration-file.rapidq new file mode 100644 index 0000000000..3b26d7db41 --- /dev/null +++ b/Task/Read-a-configuration-file/RapidQ/read-a-configuration-file.rapidq @@ -0,0 +1,59 @@ +type TSettings extends QObject + FullName as string + FavouriteFruit as string + NeedSpelling as integer + SeedsRemoved as integer + OtherFamily as QStringlist + + Constructor + FullName = "" + FavouriteFruit = "" + NeedSpelling = 0 + SeedsRemoved = 0 + OtherFamily.clear + end constructor +end type + +Dim Settings as TSettings +dim ConfigList as QStringList +dim x as integer +dim StrLine as string +dim StrPara as string +dim StrData as string + +function Trim$(Expr as string) as string + Result = Rtrim$(Ltrim$(Expr)) +end function + +Sub ConfigOption(PData as string) + dim x as integer + for x = 1 to tally(PData, ",") +1 + Settings.OtherFamily.AddItems Trim$(field$(PData, "," ,x)) + next +end sub + +Function ConfigBoolean(PData as string) as integer + PData = Trim$(PData) + Result = iif(lcase$(PData)="true" or PData="1" or PData="", 1, 0) +end function + +sub ReadSettings + ConfigList.LoadFromFile("Rosetta.cfg") + ConfigList.text = REPLACESUBSTR$(ConfigList.text,"="," ") + + for x = 0 to ConfigList.ItemCount -1 + StrLine = Trim$(ConfigList.item(x)) + StrPara = Trim$(field$(StrLine," ",1)) + StrData = Trim$(lTrim$(StrLine - StrPara)) + + Select case UCase$(StrPara) + case "FULLNAME" : Settings.FullName = StrData + case "FAVOURITEFRUIT" : Settings.FavouriteFruit = StrData + case "NEEDSPEELING" : Settings.NeedSpelling = ConfigBoolean(StrData) + case "SEEDSREMOVED" : Settings.SeedsRemoved = ConfigBoolean(StrData) + case "OTHERFAMILY" : Call ConfigOption(StrData) + end select + next +end sub + +Call ReadSettings diff --git a/Task/Read-a-configuration-file/UNIX-Shell/read-a-configuration-file.sh b/Task/Read-a-configuration-file/UNIX-Shell/read-a-configuration-file.sh new file mode 100644 index 0000000000..1b950e90bc --- /dev/null +++ b/Task/Read-a-configuration-file/UNIX-Shell/read-a-configuration-file.sh @@ -0,0 +1,44 @@ +readconfig() ( + # redirect stdin to read from the given filename + exec 0<"$1" + + declare -l varname + while IFS=$' =\t' read -ra words; do + # is it a comment or blank line? + if [[ ${#words[@]} -eq 0 || ${words[0]} == ["#;"]* ]]; then + continue + fi + + # get the variable name + varname=${words[0]} + + # split all the other words by comma + value="${words[*]:1}" + oldIFS=$IFS IFS=, + values=( $value ) + IFS=$oldIFS + + # assign the other words to a "scalar" variable or array + case ${#values[@]} in + 0) printf '%s=true\n' "$varname" ;; + 1) printf '%s=%q\n' "$varname" "${values[0]}" ;; + *) n=0 + for value in "${values[@]}"; do + value=${value# } + printf '%s[%d]=%q\n' "$varname" $((n++)) "${value% }" + done + ;; + esac + done +) + +# parse the config file and evaluate the output in the current shell +source <( readconfig config.file ) + +echo "fullname = $fullname" +echo "favouritefruit = $favouritefruit" +echo "needspeeling = $needspeeling" +echo "seedsremoved = $seedsremoved" +for i in "${!otherfamily[@]}"; do + echo "otherfamily[$i] = ${otherfamily[i]}" +done diff --git a/Task/Read-a-file-line-by-line/00DESCRIPTION b/Task/Read-a-file-line-by-line/00DESCRIPTION index ba03c99b0e..f27e42992e 100644 --- a/Task/Read-a-file-line-by-line/00DESCRIPTION +++ b/Task/Read-a-file-line-by-line/00DESCRIPTION @@ -1,4 +1,12 @@ -Read a file one line at a time, as opposed to [[Read entire file|reading the entire file at once]]. +{{omit from|GUISS}} +{{omit from|Lotus 123 Macro Scripting|Reads the whole file at once}} +{{omit from|Openscad}} +{{omit from|TI-83 BASIC|No filesystem.}} +{{omit from|TI-89 BASIC|No filesystem.}} +{{omit from|Unlambda|Does not know files.}} + +Read a file one line at a time, +as opposed to [[Read entire file|reading the entire file at once]]. ;See also * [[Read a file character by character]] diff --git a/Task/Read-a-file-line-by-line/00META.yaml b/Task/Read-a-file-line-by-line/00META.yaml index 53d5156105..9d7e332fd2 100644 --- a/Task/Read-a-file-line-by-line/00META.yaml +++ b/Task/Read-a-file-line-by-line/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Simple note: File handling diff --git a/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line.awk b/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-1.awk similarity index 100% rename from Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line.awk rename to Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-1.awk diff --git a/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-2.awk b/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-2.awk new file mode 100644 index 0000000000..2ba1e4badf --- /dev/null +++ b/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-2.awk @@ -0,0 +1 @@ +awk '1' filename diff --git a/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-3.awk b/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-3.awk new file mode 100644 index 0000000000..a0ec640ea7 --- /dev/null +++ b/Task/Read-a-file-line-by-line/AWK/read-a-file-line-by-line-3.awk @@ -0,0 +1,9 @@ +# usage: awk -f readlines.awk *.txt +BEGIN { print "# Reading..." } +FNR==1 { f++; print "# File #" f, ":", FILENAME } +/^#/ { c++; next } # skip lines starting with "#", but count them +/you/ { gsub("to", "TO") } # change text in lines with "you" somewhere +/TO/ { print FNR,":",$0; next } # print with line-number + { print } # same as "print $0" +END { print "# Done with", f, "file(s), with a total of", NR, "lines." } +END { print "# Comment-lines:", c } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c index c65bf46270..d7b1e5daab 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-1.c @@ -1,35 +1,14 @@ -#include /* err */ -#include /* fopen, fgetln, fputs, fwrite */ - -/* - * Read a file line by line. - * http://rosettacode.org/wiki/Read_a_file_line_by_line - */ -int -main() +#include +#include +int main (void) { - FILE *f; - size_t len; - char *line; - - f = fopen("foobar.txt", "r"); - if (f == NULL) - err(1, "foobar.txt"); - - /* - * This loop reads each line. - * Remember that line is not a C string. - * There is no terminating '\0'. - */ - while (line = fgetln(f, &len)) { - /* - * Do something with line. - */ - fputs("LINE: ", stdout); - fwrite(line, len, 1, stdout); - } - if (!feof(f)) - err(1, "fgetln"); - - return 0; + char buf[256]; + while (fgets (buf, sizeof(buf), stdin)) { + printf("line: %s", buf); + } + if (ferror(stdin)) { + fprintf(stderr,"Oops, error reading stdin\n"); + abort(); + } + return 0; } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c index 6e36638c56..c65bf46270 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-2.c @@ -1,86 +1,5 @@ -#include /* exit, malloc, realloc, free */ -#include /* fopen, fgetc, fputs, fwrite */ - -struct line_reader { - /* All members are private. */ - FILE *f; - char *buf; - size_t siz; -}; - -/* - * Initializes a line reader _lr_ for the stream _f_. - */ -void -lr_init(struct line_reader *lr, FILE *f) -{ - lr->f = f; - lr->buf = NULL; - lr->siz = 0; -} - -/* - * Reads the next line. If successful, returns a pointer to the line, - * and sets *len to the number of characters, at least 1. The result is - * _not_ a C string; it has no terminating '\0'. The returned pointer - * remains valid until the next call to next_line() or lr_free() with - * the same _lr_. - * - * next_line() returns NULL at end of file, or if there is an error (on - * the stream, or with memory allocation). - */ -char * -next_line(struct line_reader *lr, size_t *len) -{ - size_t newsiz; - int c; - char *newbuf; - - *len = 0; /* Start with empty line. */ - for (;;) { - c = fgetc(lr->f); /* Read next character. */ - if (ferror(lr->f)) - return NULL; - - if (c == EOF) { - /* - * End of file is also end of last line, - ` * unless this last line would be empty. - */ - if (*len == 0) - return NULL; - else - return lr->buf; - } else { - /* Append c to the buffer. */ - if (*len == lr->siz) { - /* Need a bigger buffer! */ - newsiz = lr->siz + 4096; - newbuf = realloc(lr->buf, newsiz); - if (newbuf == NULL) - return NULL; - lr->buf = newbuf; - lr->siz = newsiz; - } - lr->buf[(*len)++] = c; - - /* '\n' is end of line. */ - if (c == '\n') - return lr->buf; - } - } -} - -/* - * Frees internal memory used by _lr_. - */ -void -lr_free(struct line_reader *lr) -{ - free(lr->buf); - lr->buf = NULL; - lr->siz = 0; -} +#include /* err */ +#include /* fopen, fgetln, fputs, fwrite */ /* * Read a file line by line. @@ -89,35 +8,28 @@ lr_free(struct line_reader *lr) int main() { - struct line_reader lr; FILE *f; size_t len; char *line; f = fopen("foobar.txt", "r"); - if (f == NULL) { - perror("foobar.txt"); - exit(1); - } + if (f == NULL) + err(1, "foobar.txt"); /* * This loop reads each line. * Remember that line is not a C string. * There is no terminating '\0'. */ - lr_init(&lr, f); - while (line = next_line(&lr, &len)) { + while (line = fgetln(f, &len)) { /* * Do something with line. */ fputs("LINE: ", stdout); fwrite(line, len, 1, stdout); } - if (!feof(f)) { - perror("next_line"); - exit(1); - } - lr_free(&lr); + if (!feof(f)) + err(1, "fgetln"); return 0; } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c index c6c2bacffa..6e36638c56 100644 --- a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-3.c @@ -1,75 +1,123 @@ -#include -#include -#include -#include -#include -#include -#include -#include +#include /* exit, malloc, realloc, free */ +#include /* fopen, fgetc, fputs, fwrite */ -int read_lines(const char * fname, int (*call_back)(const char*, const char*)) +struct line_reader { + /* All members are private. */ + FILE *f; + char *buf; + size_t siz; +}; + +/* + * Initializes a line reader _lr_ for the stream _f_. + */ +void +lr_init(struct line_reader *lr, FILE *f) { - int fd = open(fname, O_RDONLY); - struct stat fs; - char *buf, *buf_end; - char *begin, *end, c; - - if (fd == -1) { - err(1, "open: %s", fname); - return 0; - } - - if (fstat(fd, &fs) == -1) { - err(1, "stat: %s", fname); - return 0; - } - - /* fs.st_size could have been 0 actually */ - buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0); - if (buf == (void*) -1) { - err(1, "mmap: %s", fname); - close(fd); - return 0; - } - - buf_end = buf + fs.st_size; - - begin = end = buf; - while (1) { - if (! (*end == '\r' || *end == '\n')) { - if (++end < buf_end) continue; - } else if (1 + end < buf_end) { - /* see if we got "\r\n" or "\n\r" here */ - c = *(1 + end); - if ( (c == '\r' || c == '\n') && c != *end) - ++end; - } - - /* call the call back and check error indication. Announce - error here, because we didn't tell call_back the file name */ - if (! call_back(begin, end)) { - err(1, "[callback] %s", fname); - break; - } - - if ((begin = ++end) >= buf_end) - break; - } - - munmap(buf, fs.st_size); - close(fd); - return 1; + lr->f = f; + lr->buf = NULL; + lr->siz = 0; } -int print_line(const char* begin, const char* end) +/* + * Reads the next line. If successful, returns a pointer to the line, + * and sets *len to the number of characters, at least 1. The result is + * _not_ a C string; it has no terminating '\0'. The returned pointer + * remains valid until the next call to next_line() or lr_free() with + * the same _lr_. + * + * next_line() returns NULL at end of file, or if there is an error (on + * the stream, or with memory allocation). + */ +char * +next_line(struct line_reader *lr, size_t *len) { - if (write(fileno(stdout), begin, end - begin + 1) == -1) { - return 0; - } - return 1; + size_t newsiz; + int c; + char *newbuf; + + *len = 0; /* Start with empty line. */ + for (;;) { + c = fgetc(lr->f); /* Read next character. */ + if (ferror(lr->f)) + return NULL; + + if (c == EOF) { + /* + * End of file is also end of last line, + ` * unless this last line would be empty. + */ + if (*len == 0) + return NULL; + else + return lr->buf; + } else { + /* Append c to the buffer. */ + if (*len == lr->siz) { + /* Need a bigger buffer! */ + newsiz = lr->siz + 4096; + newbuf = realloc(lr->buf, newsiz); + if (newbuf == NULL) + return NULL; + lr->buf = newbuf; + lr->siz = newsiz; + } + lr->buf[(*len)++] = c; + + /* '\n' is end of line. */ + if (c == '\n') + return lr->buf; + } + } } -int main() +/* + * Frees internal memory used by _lr_. + */ +void +lr_free(struct line_reader *lr) { - return read_lines("test.ps", print_line) ? 0 : 1; + free(lr->buf); + lr->buf = NULL; + lr->siz = 0; +} + +/* + * Read a file line by line. + * http://rosettacode.org/wiki/Read_a_file_line_by_line + */ +int +main() +{ + struct line_reader lr; + FILE *f; + size_t len; + char *line; + + f = fopen("foobar.txt", "r"); + if (f == NULL) { + perror("foobar.txt"); + exit(1); + } + + /* + * This loop reads each line. + * Remember that line is not a C string. + * There is no terminating '\0'. + */ + lr_init(&lr, f); + while (line = next_line(&lr, &len)) { + /* + * Do something with line. + */ + fputs("LINE: ", stdout); + fwrite(line, len, 1, stdout); + } + if (!feof(f)) { + perror("next_line"); + exit(1); + } + lr_free(&lr); + + return 0; } diff --git a/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c new file mode 100644 index 0000000000..c6c2bacffa --- /dev/null +++ b/Task/Read-a-file-line-by-line/C/read-a-file-line-by-line-4.c @@ -0,0 +1,75 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +int read_lines(const char * fname, int (*call_back)(const char*, const char*)) +{ + int fd = open(fname, O_RDONLY); + struct stat fs; + char *buf, *buf_end; + char *begin, *end, c; + + if (fd == -1) { + err(1, "open: %s", fname); + return 0; + } + + if (fstat(fd, &fs) == -1) { + err(1, "stat: %s", fname); + return 0; + } + + /* fs.st_size could have been 0 actually */ + buf = mmap(0, fs.st_size, PROT_READ, MAP_SHARED, fd, 0); + if (buf == (void*) -1) { + err(1, "mmap: %s", fname); + close(fd); + return 0; + } + + buf_end = buf + fs.st_size; + + begin = end = buf; + while (1) { + if (! (*end == '\r' || *end == '\n')) { + if (++end < buf_end) continue; + } else if (1 + end < buf_end) { + /* see if we got "\r\n" or "\n\r" here */ + c = *(1 + end); + if ( (c == '\r' || c == '\n') && c != *end) + ++end; + } + + /* call the call back and check error indication. Announce + error here, because we didn't tell call_back the file name */ + if (! call_back(begin, end)) { + err(1, "[callback] %s", fname); + break; + } + + if ((begin = ++end) >= buf_end) + break; + } + + munmap(buf, fs.st_size); + close(fd); + return 1; +} + +int print_line(const char* begin, const char* end) +{ + if (write(fileno(stdout), begin, end - begin + 1) == -1) { + return 0; + } + return 1; +} + +int main() +{ + return read_lines("test.ps", print_line) ? 0 : 1; +} diff --git a/Task/Read-a-file-line-by-line/D/read-a-file-line-by-line.d b/Task/Read-a-file-line-by-line/D/read-a-file-line-by-line.d index 8bff975e97..5cf6ca519c 100644 --- a/Task/Read-a-file-line-by-line/D/read-a-file-line-by-line.d +++ b/Task/Read-a-file-line-by-line/D/read-a-file-line-by-line.d @@ -1,6 +1,6 @@ -import std.stdio; - void main() { - foreach (line; File("unixdict.txt").byLine()) - writeln(line); + import std.stdio; + + foreach (line; "read_a_file_line_by_line.d".File.byLine) + line.writeln; } diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-1.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-1.pl index f04db69760..ddb6df36d3 100644 --- a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-1.pl +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-1.pl @@ -1,6 +1,9 @@ -open(FOO, '<', 'foobar.txt') or die $!; -while () { # each line is stored in $_, with terminating newline - chomp; # chomp, short for chomp($_), removes the terminating newline +open(my $fh, '<', 'foobar.txt') + || die "Could not open file: $!"; +while (<$fh>) +{ # each line is stored in $_, with terminating newline + # chomp, short for chomp($_), removes the terminating newline + chomp; process($_); } -close(FOO); +close $fh; diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-2.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-2.pl index d5ca26a67b..6a7f9062ce 100644 --- a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-2.pl +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-2.pl @@ -1,6 +1,2 @@ -open(FOO, '<', 'foobar.txt') or die $!; -while (my $line = ) { - chomp($line); - process($line); -} -close(FOO); +open(my $fh, '< :encoding(UTF-8)', 'foobar.txt') + || die "Could not open file: $!"; diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-3.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-3.pl index b74c354302..2a372fb7b3 100644 --- a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-3.pl +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-3.pl @@ -1,4 +1,8 @@ -while (<>) { - chomp; - process($_); +open(my $fh, '<', 'foobar.txt') + || die "Could not open file: $!"; +while (my $line = <$fh>) +{ + chomp $line; + process($line); } +close $fh; diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-4.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-4.pl new file mode 100644 index 0000000000..b74c354302 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-4.pl @@ -0,0 +1,4 @@ +while (<>) { + chomp; + process($_); +} diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-5.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-5.pl new file mode 100644 index 0000000000..ede8d921e5 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-5.pl @@ -0,0 +1 @@ +perl myscript.pl 'rm -rf / |' diff --git a/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-6.pl b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-6.pl new file mode 100644 index 0000000000..c5a44a2636 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Perl/read-a-file-line-by-line-6.pl @@ -0,0 +1,7 @@ +open(my $fh, '<', 'foobar.txt') or die "$!"; +while (readline $fh) +{ ... } + +while (my $line = readline $fh) +{ ... } +close $fh; diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-1.rexx similarity index 70% rename from Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line.rexx rename to Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-1.rexx index e28b1fa354..17cf551148 100644 --- a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line.rexx +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-1.rexx @@ -1,17 +1,11 @@ /*REXX program to read and display (with count) a file, one line at a time.*/ - parse arg fileID . say 'Displaying file:' fileID -do linenumber=1 by 1 while lines(fileID)>0 /* loop construct */ + do linenumber=1 while lines(fileID)\==0 /* loop construct */ line=linein(fileID) /* read line */ say 'Line' linenumber':' line /* show line number and line */ end linenumber /* end loop and confirm which loop */ + say say 'File' fileID 'has' linenumber-1 'lines.' /*summary.*/ - - ----- -/* Or: the 'known name' short version: */ -file='foobar.txt' -do while lines(file)>0; say linein(file); end diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-2.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-2.rexx new file mode 100644 index 0000000000..4dcd1a09b4 --- /dev/null +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-2.rexx @@ -0,0 +1,2 @@ +file='foobar.txt' +do while lines(file)\==0; say linein(file); end diff --git a/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx new file mode 100644 index 0000000000..2570873c72 --- /dev/null +++ b/Task/Read-a-file-line-by-line/REXX/read-a-file-line-by-line-3.rexx @@ -0,0 +1,15 @@ +/*REXX program reads and displays (with count) a file, 1 line at a time.*/ +parse arg fileID .; if fileID=='' then exit /*No fileID? Then stop.*/ +say 'displaying file: ' fileID /*show what file is being shown. */ +call linein fileID,1,0 /*see comment in the section hdr.*/ +say /* [↓] show the file's contents.*/ + do #=1 while lines(fileID)\==0 /*loop whilst there are records. */ + x=linein(fileID); xLen=length(x) /*read a record; get its length. */ + say /*show a blank for peruseability.*/ + say 'record#=' # " length=" xLen /*show the record number & length*/ + say x /*show the content of the record.*/ + end /*#*/ +say +say 'file ' fileID " has " #-1 ' records.' /*record count summary.*/ +call lineout fileID /*close input file (most REXXes).*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Read-a-file-line-by-line/RapidQ/read-a-file-line-by-line.rapidq b/Task/Read-a-file-line-by-line/RapidQ/read-a-file-line-by-line.rapidq new file mode 100644 index 0000000000..340ae94b46 --- /dev/null +++ b/Task/Read-a-file-line-by-line/RapidQ/read-a-file-line-by-line.rapidq @@ -0,0 +1,12 @@ +$Include "Rapidq.inc" +dim file as qfilestream + +if file.open("c:\A Test.txt", fmOpenRead) then + while not File.eof + print File.readline + wend +else + print "Cannot read file" +end if + +input "Press enter to exit: ";a$ diff --git a/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust b/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust new file mode 100644 index 0000000000..a2a9b733c4 --- /dev/null +++ b/Task/Read-a-file-line-by-line/Rust/read-a-file-line-by-line.rust @@ -0,0 +1,10 @@ +use std::io::BufferedReader; +use std::io::File; + +fn main() { + let path = Path::new("file.txt"); + let mut file = BufferedReader::new(File::open(&path)); + for line in file.lines() { + println!("{}", line.unwrap()); + } +} diff --git a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-1.st b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-1.st index 77284ba4c4..3006ba9e15 100644 --- a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-1.st +++ b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-1.st @@ -1 +1 @@ -'foobar.txt' asFilename readingLinesDo:[:eachLine | eachLine printCR] +(StandardFileStream oldFileNamed: 'test.txt') contents lines do: [ :each | Transcript show: each. ] diff --git a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-2.st b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-2.st index b60cd7ad70..77284ba4c4 100644 --- a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-2.st +++ b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-2.st @@ -1,6 +1 @@ -|s| -s := 'foobar.txt' asFilename readStream. -[ s atEnd ] whileFalse:[ - s nextLine printCR. -]. -s close +'foobar.txt' asFilename readingLinesDo:[:eachLine | eachLine printCR] diff --git a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-3.st b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-3.st index 1be8439d7e..b60cd7ad70 100644 --- a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-3.st +++ b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-3.st @@ -1 +1,6 @@ -'foobar.txt' asFilename contents do:[:eachLine | eachLine printCR]. +|s| +s := 'foobar.txt' asFilename readStream. +[ s atEnd ] whileFalse:[ + s nextLine printCR. +]. +s close diff --git a/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-4.st b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-4.st new file mode 100644 index 0000000000..1be8439d7e --- /dev/null +++ b/Task/Read-a-file-line-by-line/Smalltalk/read-a-file-line-by-line-4.st @@ -0,0 +1 @@ +'foobar.txt' asFilename contents do:[:eachLine | eachLine printCR]. diff --git a/Task/Read-a-specific-line-from-a-file/ALGOL-68/read-a-specific-line-from-a-file.alg b/Task/Read-a-specific-line-from-a-file/ALGOL-68/read-a-specific-line-from-a-file.alg new file mode 100644 index 0000000000..e9fe607e6a --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/ALGOL-68/read-a-specific-line-from-a-file.alg @@ -0,0 +1,91 @@ +# reads the line with number "number" (counting from 1) # +# from the file named "file name" and returns the text of the # +# in "line". If an error occurs, the result is FALSE and a # +# message is returned in "err". If no error occurs, TRUE is # +# returned # +PROC read specific line = ( STRING file name + , INT number # line 7 # + , REF STRING line + , REF STRING err + )BOOL: +BEGIN + + FILE input file; + + line := ""; + err := ""; + + IF open( input file, file name, stand in channel ) /= 0 + THEN + # failed to open the file # + err := "Unable to open """ + file name + """"; + FALSE + + ELSE + # file opened OK # + + BOOL at eof := FALSE; + + # set the EOF handler for the file # + on logical file end( input file + , ( REF FILE f )BOOL: + BEGIN + # note that we reached EOF on the # + # latest read # + at eof := TRUE; + + # return TRUE so processing can continue # + TRUE + END + ); + + INT line number := 0; + STRING text; + + WHILE line number < number + AND NOT at eof + DO + + get( input file, ( text, newline ) ); + line number +:= 1 + + OD; + + # close the file # + close( input file ); + + # return the line or an error message depending on whether # + # we got a line with the required number or not # + IF line number = number + THEN + # got the required line # + line := text; + TRUE + ELSE + # not enough lines in the file # + err := """" + file name + """ is too short"; + FALSE + FI + + FI + +END; # read specific line # + + +main:( + # read the seventh line of this source and print it # + # (or an error message if we can't) # + + STRING line; + STRING err; + + IF read specific line( "read-specific-line.a68", 7, line, err ) + THEN + # got the line # + print( ( "line seven is: """ + line + """", newline ) ) + ELSE + # got an error # + print( ( "unable to read line: """ + err + """" ) ) + FI + +) diff --git a/Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file.c b/Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-1.c similarity index 100% rename from Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file.c rename to Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-1.c diff --git a/Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-2.c b/Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-2.c new file mode 100644 index 0000000000..91bee364da --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/C/read-a-specific-line-from-a-file-2.c @@ -0,0 +1,101 @@ +#include +#include + +#define BUF_SIZE ( 256 ) + +char *get_nth_line( FILE *f, int line_no ) +{ + char buf[ BUF_SIZE ]; + size_t curr_alloc = BUF_SIZE, curr_ofs = 0; + char *line = malloc( BUF_SIZE ); + int in_line = line_no == 1; + size_t bytes_read; + + /* Illegal to ask for a line before the first one. */ + if ( line_no < 1 ) + return NULL; + + /* Handle out-of-memory by returning NULL */ + if ( !line ) + return NULL; + + /* Scan the file looking for newlines */ + while ( line_no && + ( bytes_read = fread( buf, 1, BUF_SIZE, f ) ) > 0 ) + { + int i; + + for ( i = 0 ; i < bytes_read ; i++ ) + { + if ( in_line ) + { + if ( curr_ofs >= curr_alloc ) + { + curr_alloc <<= 1; + line = realloc( line, curr_alloc ); + + if ( !line ) /* out of memory? */ + return NULL; + } + line[ curr_ofs++ ] = buf[i]; + } + + if ( buf[i] == '\n' ) + { + line_no--; + + if ( line_no == 1 ) + in_line = 1; + + if ( line_no == 0 ) + break; + } + } + } + + /* Didn't find the line? */ + if ( line_no != 0 ) + { + free( line ); + return NULL; + } + + /* Resize allocated buffer to what's exactly needed by the string + and the terminating NUL character. Note that this code *keeps* + the terminating newline as part of the string. + */ + line = realloc( line, curr_ofs + 1 ); + + if ( !line ) /* out of memory? */ + return NULL; + + /* Add the terminating NUL. */ + line[ curr_ofs ] = '\0'; + + /* Return the line. Caller is responsible for freeing it. */ + return line; +} + + +/* Test program. Prints out the 7th line of input from stdin, if any */ +int main( int argc, char *argv[] ) +{ + char *line7 = get_nth_line( stdin, 7 ); + + if ( line7 ) + { + printf("The 7th line of input was:\n%s\n", line7 ); + free( line7 ); + } else + { + printf("Did not find the 7th line of input. Reason: "); + if ( feof( stdin ) ) + puts("End of file reached."); + else if ( ferror( stdin ) ) + puts("Error reading input."); + else + puts("Out of memory."); + } + + return 0; +} diff --git a/Task/Read-a-specific-line-from-a-file/Clojure/read-a-specific-line-from-a-file.clj b/Task/Read-a-specific-line-from-a-file/Clojure/read-a-specific-line-from-a-file.clj new file mode 100644 index 0000000000..03ae617404 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Clojure/read-a-specific-line-from-a-file.clj @@ -0,0 +1,5 @@ +(defn read-nth-line + "Read line-number from the given text file. The first line has the number 1." + [file line-number] + (with-open [rdr (clojure.java.io/reader file)] + (nth (line-seq rdr) (dec line-number)))) diff --git a/Task/Read-a-specific-line-from-a-file/Go/read-a-specific-line-from-a-file.go b/Task/Read-a-specific-line-from-a-file/Go/read-a-specific-line-from-a-file.go index 69cd4a46f1..005752144a 100644 --- a/Task/Read-a-specific-line-from-a-file/Go/read-a-specific-line-from-a-file.go +++ b/Task/Read-a-specific-line-from-a-file/Go/read-a-specific-line-from-a-file.go @@ -1,69 +1,51 @@ package main import ( - "bufio" - "errors" - "fmt" - "io" - "os" + "bufio" + "errors" + "fmt" + "io" + "os" ) func main() { - if line, err := rsl("input.txt", 7); err == nil { - fmt.Println("7th line:") - fmt.Println(line) - } else { - fmt.Println(err) - } + if line, err := rsl("input.txt", 7); err == nil { + fmt.Println("7th line:") + fmt.Println(line) + } else { + fmt.Println("rsl:", err) + } } -func rsl(fn string, n int) (r string, err error) { - if n < 1 { - return "", errors.New(fmt.Sprintf("Invalid request: line %d", n)) - } - f, err := os.Open(fn) - if err != nil { - return - } - defer f.Close() - bf := bufio.NewReader(f) - var l int - for { - line, isPrefix, err := bf.ReadLine() - if err == io.EOF { - switch l { - case 0: - return "", errors.New("Empty file.") - case 1: - return "", errors.New("Only 1 line.") - default: - return "", errors.New(fmt.Sprintf("Only %d lines", l)) - } - } - if err != nil { - return "", err - } - l++ - if l == n { - r = string(line) - for isPrefix { - line, isPrefix, err = bf.ReadLine() - if err != nil { - return "", err - } - r += string(line) - } - if r == "" { - return "", errors.New(fmt.Sprintf("Line %d empty.", n)) - } - break - } - for isPrefix { - line, isPrefix, err = bf.ReadLine() - if err != nil { - return "", err - } - } - } - return // success +func rsl(fn string, n int) (string, error) { + if n < 1 { + return "", fmt.Errorf("invalid request: line %d", n) + } + f, err := os.Open(fn) + if err != nil { + return "", err + } + defer f.Close() + bf := bufio.NewReader(f) + var line string + for lnum := 0; lnum < n; lnum++ { + line, err = bf.ReadString('\n') + if err == io.EOF { + switch lnum { + case 0: + return "", errors.New("no lines in file") + case 1: + return "", errors.New("only 1 line") + default: + return "", fmt.Errorf("only %d lines", lnum) + } + } + if err != nil { + return "", err + } + } + if line == "" { + return "", fmt.Errorf("line %d empty", n) + } + return line, nil } diff --git a/Task/Read-a-specific-line-from-a-file/Icon/read-a-specific-line-from-a-file.icon b/Task/Read-a-specific-line-from-a-file/Icon/read-a-specific-line-from-a-file.icon index 08aae12d23..1d27edd721 100644 --- a/Task/Read-a-specific-line-from-a-file/Icon/read-a-specific-line-from-a-file.icon +++ b/Task/Read-a-specific-line-from-a-file/Icon/read-a-specific-line-from-a-file.icon @@ -4,7 +4,7 @@ end procedure readline(f,n) # return n'th line of file f f := open(\f,"r") | fail # open file -every i := n & line := |read() \ n do i -:= 1 # <== here +every i := n & line := |read(f) \ n do i -:= 1 # <== here close(f) if i = 0 then return line end diff --git a/Task/Read-a-specific-line-from-a-file/Lua/read-a-specific-line-from-a-file.lua b/Task/Read-a-specific-line-from-a-file/Lua/read-a-specific-line-from-a-file.lua new file mode 100644 index 0000000000..505802f1fe --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Lua/read-a-specific-line-from-a-file.lua @@ -0,0 +1,8 @@ +iter = io.lines 'test.txt' +for i=0, 5 do + if not iter() then + error 'Not 7 lines in file' + end +end + +line = iter() diff --git a/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-1.py b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-1.py new file mode 100644 index 0000000000..bf35d3e09c --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-1.py @@ -0,0 +1,7 @@ +with open('xxx.txt') as f: + for i, line in enumerate(f): + if i == 6: + break + else: + print('Not 7 lines in file') + line = None diff --git a/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-2.py b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-2.py new file mode 100644 index 0000000000..7349f0eef7 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-2.py @@ -0,0 +1,7 @@ +from itertools import islice + +with open('xxx.txt') as f: + try: + line = next(islice(f, 6, 7)) + except StopIteration: + print('Not 7 lines in file') diff --git a/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-3.py b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-3.py new file mode 100644 index 0000000000..2cb07e48eb --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file-3.py @@ -0,0 +1 @@ +print open('xxx.txt').readlines()[:7][-1] diff --git a/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file.py b/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file.py deleted file mode 100644 index 1f6be62c40..0000000000 --- a/Task/Read-a-specific-line-from-a-file/Python/read-a-specific-line-from-a-file.py +++ /dev/null @@ -1,6 +0,0 @@ -from itertools import islice - -with open('xxx.txt') as f: - linelist = list(islice(f, 7, 8)) - assert linelist != [], 'Not 7 lines in file' - line = linelist[0] diff --git a/Task/Read-a-specific-line-from-a-file/REXX/read-a-specific-line-from-a-file.rexx b/Task/Read-a-specific-line-from-a-file/REXX/read-a-specific-line-from-a-file.rexx index 6cda11a740..5cdaff8c24 100644 --- a/Task/Read-a-specific-line-from-a-file/REXX/read-a-specific-line-from-a-file.rexx +++ b/Task/Read-a-specific-line-from-a-file/REXX/read-a-specific-line-from-a-file.rexx @@ -1,26 +1,10 @@ /*REXX program to read a specific line from a file. */ parse arg fileId n . /*get the user args: fileid n */ -if fileID=='' then fileId='JUNK.TXT' /*assume the default: JUNK.TXT */ -if n=='' then n=7 /*assume the default (n=7) */ +if fileID=='' then fileId='JUNK.TXT' /*assume fileID default: JUNK.TXT*/ +if n=='' then n=7 /*assume N default: 7 */ L=lines(fileid) /*first, see if the file exists. */ -if L ==0 then do; say 'error, fileID not found:' fileId; exit; end -if n\==1 then call linein fileId,n-1 /*second, read previous rec. to N*/ -L=lines(fileid) /* L = # lines left in the file.*/ -q=linein(fileId,n) /*read the Nth line, store in Q.*/ -qL=length(q) /*get the length of the record. */ - select - when L==0 & qL==0 then say 'line' n "not found." - when L==1 & qL==0 then say 'line' n "has a zero length." - otherwise say 'file' fileId "record" n '=' q - end /*select*/ +if L==0 then do; say 'error, fileID not found:' fileId; exit; end +q=linein(fileId, n) /*read the Nth line, store in Q.*/ +if length(q)==0 then say 'line' n "not found." + else say 'file' fileId "record" n '=' q /*stick a fork in it, we're done.*/ -/*┌────────────────────────────────────────────────────────────────────┐ - │ ─── Normally, we could just use: ─── │ - │ │ - │ q=linein(fileId,n) /*read a specific record num. */ │ - │ │ - │── but LINEIN will just return a null when a record isn't found or│ - │ when the fileID doesn't exist, or N is beyond the end-of-file.│ - │ │ - │── In the case of sparse files, the record may not exist (be null).│ - └────────────────────────────────────────────────────────────────────┘*/ diff --git a/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt b/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt index f45f9528ad..ffda92accf 100644 --- a/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt +++ b/Task/Read-a-specific-line-from-a-file/Racket/read-a-specific-line-from-a-file.rkt @@ -3,7 +3,7 @@ ;; simple, but reads the whole file (define s1 (list-ref (file->lines "some-file") 6)) -;; more efficient: read and discare n-1 lines +;; more efficient: read and discard n-1 lines (define s2 (call-with-input-file "some-file" (λ(i) (for/last ([line (in-lines i)] [n 7]) line)))) diff --git a/Task/Read-a-specific-line-from-a-file/Ruby/read-a-specific-line-from-a-file.rb b/Task/Read-a-specific-line-from-a-file/Ruby/read-a-specific-line-from-a-file.rb index 30d2ac1038..50a3a50f2c 100644 --- a/Task/Read-a-specific-line-from-a-file/Ruby/read-a-specific-line-from-a-file.rb +++ b/Task/Read-a-specific-line-from-a-file/Ruby/read-a-specific-line-from-a-file.rb @@ -1,15 +1 @@ -def getNthLine(filename, n) - line="" - File.open(filename) do |f| - n.times do |nr| - line = f.gets - if line.nil? - puts "file #{filename} does not have #{n} lines, only #{nr}" - break - end - end - end - line -end - -puts getNthLine("/etc/passwd", 7) + seventh_line = open("/etc/passwd").each_line.take(7).last diff --git a/Task/Read-a-specific-line-from-a-file/Smalltalk/read-a-specific-line-from-a-file.st b/Task/Read-a-specific-line-from-a-file/Smalltalk/read-a-specific-line-from-a-file.st new file mode 100644 index 0000000000..0ddb4b83f9 --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/Smalltalk/read-a-specific-line-from-a-file.st @@ -0,0 +1 @@ +line := (StandardFileStream oldFileNamed: 'test.txt') contents lineNumber: 7. diff --git a/Task/Read-a-specific-line-from-a-file/UNIX-Shell/read-a-specific-line-from-a-file.sh b/Task/Read-a-specific-line-from-a-file/UNIX-Shell/read-a-specific-line-from-a-file.sh new file mode 100644 index 0000000000..647fa622ad --- /dev/null +++ b/Task/Read-a-specific-line-from-a-file/UNIX-Shell/read-a-specific-line-from-a-file.sh @@ -0,0 +1,12 @@ +get_nth_line() { + local file=$1 n=$2 line + while ((n-- > 0)); do + if ! IFS= read -r line; then + echo "No such line $2 in $file" + return 1 + fi + done < "$file" + echo "$line" +} + +get_nth_line filename 7 diff --git a/Task/Read-entire-file/00DESCRIPTION b/Task/Read-entire-file/00DESCRIPTION index 8c69b9c010..178ff4474f 100644 --- a/Task/Read-entire-file/00DESCRIPTION +++ b/Task/Read-entire-file/00DESCRIPTION @@ -1,5 +1,14 @@ +{{omit from|Batch File|No way of reading entire files or putting line breaks into variables.}} +{{omit from|Brainf***}} +{{omit from|TI-83 BASIC|No filesystem.}} +{{omit from|TI-89 BASIC|No filesystem.}} +{{omit from|Unlambda|Does not know files.}} + Load the entire contents of some text file as a single string variable. If applicable, discuss: encoding selection, the possibility of memory-mapping. -Of course, one should avoid reading an entire file at once if the file is large and the task can be accomplished incrementally instead (in which case check [[File IO]]); this is for those cases where having the entire file is actually what is wanted. +Of course, one should avoid reading an entire file at once +if the file is large and the task can be accomplished incrementally instead +(in which case check [[File IO]]); +this is for those cases where having the entire file is actually what is wanted. diff --git a/Task/Read-entire-file/AWK/read-entire-file.awk b/Task/Read-entire-file/AWK/read-entire-file-1.awk similarity index 100% rename from Task/Read-entire-file/AWK/read-entire-file.awk rename to Task/Read-entire-file/AWK/read-entire-file-1.awk diff --git a/Task/Read-entire-file/AWK/read-entire-file-2.awk b/Task/Read-entire-file/AWK/read-entire-file-2.awk new file mode 100644 index 0000000000..b0938dc94f --- /dev/null +++ b/Task/Read-entire-file/AWK/read-entire-file-2.awk @@ -0,0 +1,10 @@ +#!/usr/bin/awk -f + +@include "readfile" + +BEGIN { + + str = readfile("file.txt") + print str + +} diff --git a/Task/Read-entire-file/Emacs-Lisp/read-entire-file.l b/Task/Read-entire-file/Emacs-Lisp/read-entire-file.l new file mode 100644 index 0000000000..a18343396d --- /dev/null +++ b/Task/Read-entire-file/Emacs-Lisp/read-entire-file.l @@ -0,0 +1,3 @@ +(setq my-variable (with-temp-buffer + (insert-file-contents "foo.txt") + (buffer-string))) diff --git a/Task/Read-entire-file/Go/read-entire-file-2.go b/Task/Read-entire-file/Go/read-entire-file-2.go index 61d5ce8fc6..53943e873d 100644 --- a/Task/Read-entire-file/Go/read-entire-file-2.go +++ b/Task/Read-entire-file/Go/read-entire-file-2.go @@ -1,3 +1,5 @@ +// +build !windows,!plan9,!nacl // These lack syscall.Mmap + package main import ( diff --git a/Task/Read-entire-file/M4/read-entire-file.m4 b/Task/Read-entire-file/M4/read-entire-file.m4 new file mode 100644 index 0000000000..00e74b755a --- /dev/null +++ b/Task/Read-entire-file/M4/read-entire-file.m4 @@ -0,0 +1,3 @@ +define(`foo',include(`file.txt')) +defn(`foo') +defn(`foo') diff --git a/Task/Read-entire-file/Make/read-entire-file.make b/Task/Read-entire-file/Make/read-entire-file.make new file mode 100644 index 0000000000..8f0aa0f30e --- /dev/null +++ b/Task/Read-entire-file/Make/read-entire-file.make @@ -0,0 +1 @@ +contents := $(shell cat foo.txt) diff --git a/Task/Read-entire-file/PARI-GP/read-entire-file.pari b/Task/Read-entire-file/PARI-GP/read-entire-file.pari index 21e3e3bb79..7b4d307b97 100644 --- a/Task/Read-entire-file/PARI-GP/read-entire-file.pari +++ b/Task/Read-entire-file/PARI-GP/read-entire-file.pari @@ -1 +1 @@ -text=read("file.txt"); +str = concat(apply(s->concat(s,"\n"), readstr("file.txt"))) diff --git a/Task/Read-entire-file/Perl/read-entire-file-4.pl b/Task/Read-entire-file/Perl/read-entire-file-4.pl index 30f5d8ae23..b442fc3937 100644 --- a/Task/Read-entire-file/Perl/read-entire-file-4.pl +++ b/Task/Read-entire-file/Perl/read-entire-file-4.pl @@ -1,6 +1,2 @@ -use IO::All; -$text = io($filename)->all; -$text = io($filename)->utf8->all; -@text = io($filename)->slurp; -$text < io($filename); -io($filename) > $text; +use Perl6::Slurp qw(slurp); +my $text = slurp($filename); diff --git a/Task/Read-entire-file/Perl/read-entire-file-5.pl b/Task/Read-entire-file/Perl/read-entire-file-5.pl index b3889b504a..30f5d8ae23 100644 --- a/Task/Read-entire-file/Perl/read-entire-file-5.pl +++ b/Task/Read-entire-file/Perl/read-entire-file-5.pl @@ -1 +1,6 @@ -perl -n -0777 -e 'print "file len: ".length' stuff.txt +use IO::All; +$text = io($filename)->all; +$text = io($filename)->utf8->all; +@text = io($filename)->slurp; +$text < io($filename); +io($filename) > $text; diff --git a/Task/Read-entire-file/Perl/read-entire-file-6.pl b/Task/Read-entire-file/Perl/read-entire-file-6.pl new file mode 100644 index 0000000000..b3889b504a --- /dev/null +++ b/Task/Read-entire-file/Perl/read-entire-file-6.pl @@ -0,0 +1 @@ +perl -n -0777 -e 'print "file len: ".length' stuff.txt diff --git a/Task/Read-entire-file/Perl/read-entire-file-7.pl b/Task/Read-entire-file/Perl/read-entire-file-7.pl new file mode 100644 index 0000000000..51bfc7043e --- /dev/null +++ b/Task/Read-entire-file/Perl/read-entire-file-7.pl @@ -0,0 +1,3 @@ +use File::Map 'map_file'; +map_file(my $str, "foo.txt"); +print $str; diff --git a/Task/Read-entire-file/Perl/read-entire-file-8.pl b/Task/Read-entire-file/Perl/read-entire-file-8.pl new file mode 100644 index 0000000000..786b227298 --- /dev/null +++ b/Task/Read-entire-file/Perl/read-entire-file-8.pl @@ -0,0 +1,4 @@ +use Sys::Mmap; +Sys::Mmap->new(my $str, 0, 'foo.txt') + or die "Cannot Sys::Mmap->new: $!"; +print $str; diff --git a/Task/Read-entire-file/REXX/read-entire-file.rexx b/Task/Read-entire-file/REXX/read-entire-file.rexx index a139dbb705..84e879d6d1 100644 --- a/Task/Read-entire-file/REXX/read-entire-file.rexx +++ b/Task/Read-entire-file/REXX/read-entire-file.rexx @@ -1,9 +1,8 @@ -/*REXX program to read a file and store it as a continuous char string. */ - +/*REXX program reads a file and stores it as a continuous character str.*/ iFID = 'a_file' /*name of the input file. */ -aString = - - do while lines(iFID)\==0 /*read until finished. */ - aString = aString || linein(iFID) /*append input to Astring. */ +aString = /*value of file's contents so far*/ + /* [↓] read file line-by-line. */ + do while lines(iFID) \== 0 /*read file's lines 'til finished*/ + aString = aString || linein(iFID) /*append a (file) line to aString*/ end /*while*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Read-entire-file/Rust/read-entire-file.rust b/Task/Read-entire-file/Rust/read-entire-file.rust index f73017d038..e81008b18a 100644 --- a/Task/Read-entire-file/Rust/read-entire-file.rust +++ b/Task/Read-entire-file/Rust/read-entire-file.rust @@ -1,11 +1,13 @@ -// -*- rust v0.9 -*- -use std::str; +// -*- rust v1.0-alpha -*- use std::io::File; fn main() { - let path = Path::new("hello.txt"); - let mut file = File::open(&path); + let mut file = File::open(&Path::new("somefile.txt")); - let contents = str::from_utf8_owned(file.read_to_end()); - println(contents); + // returns Vector of Bytes (Vec) + let contents = file.read_to_end().unwrap(); + + // To print the contents of the file + let filestr = String::from_utf8(contents).unwrap(); + println!("{}", filestr); } diff --git a/Task/Read-entire-file/Scala/read-entire-file.scala b/Task/Read-entire-file/Scala/read-entire-file.scala index c70fafa841..d5a30482ee 100644 --- a/Task/Read-entire-file/Scala/read-entire-file.scala +++ b/Task/Read-entire-file/Scala/read-entire-file.scala @@ -1,6 +1,6 @@ object TextFileSlurper extends App { val fileLines = try scala.io.Source.fromFile("my_file.txt", "UTF-8").mkString catch { - case e: java.io.FileNotFoundException => "" + case e: java.io.FileNotFoundException => e.getLocalizedMessage() } } diff --git a/Task/Real-constants-and-functions/PL-I/real-constants-and-functions.pli b/Task/Real-constants-and-functions/PL-I/real-constants-and-functions.pli index 0feeaa0c10..a824174a30 100644 --- a/Task/Real-constants-and-functions/PL-I/real-constants-and-functions.pli +++ b/Task/Real-constants-and-functions/PL-I/real-constants-and-functions.pli @@ -1,5 +1,5 @@ /* e not available other than by using exp(1q0).*/ -/* pi not available other than by using a trig function such as atan */ +/* pi not available other than by using a trig function such as: pi=4*atan(1) */ y = sqrt(x); y = log(x); y = log2(x); diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-1.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-1.rexx index 2f0036db4b..3a55bff9f0 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-1.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-1.rexx @@ -1,3 +1 @@ a=abs(y) /*takes the absolute value of y.*/ - -r=x**y /*only supports integer powers. */ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-2.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-2.rexx index 38feb02eeb..86514f34b2 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-2.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-2.rexx @@ -1 +1,3 @@ -ceiling: procedure; parse arg x; t=trunc(x); return t+(x>0)*(x\=t) +r=x**y /*REXX only supports integer powers.*/ + /*Y may be negative, zero, positive.*/ + /*X may be any real number. */ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx index 794b93d5b4..38feb02eeb 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-3.rexx @@ -1 +1 @@ -floor: procedure; parse arg x; t=trunc(x); return t-(x<0)-(x\=t) +ceiling: procedure; parse arg x; t=trunc(x); return t+(x>0)*(x\=t) diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx index c2e8010353..794b93d5b4 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-4.rexx @@ -1,63 +1 @@ -/*─────────────────────────────────────SQRT subroutine──────────────────*/ -sqrt: procedure /*square root subroutine. */ - /*returns the principal SQRT. */ - -r='' /*list of square roots calculated*/ - do j=1 for arg() /*process each argument specified*/ - a=arg(j) /*extract the argument specified*/ - do k=1 for words(a) /*process each number specified. */ - r=r sqrt_(word(a,k)) /*calculate sqrt, add to results.*/ - end - end -return space(r) /*return list of SQRTs calculated*/ - - -/*─────────────────────────────────────SQRT_ subroutine─────────────────*/ -sqrt_: procedure; parse arg x 1 ox -if x=0 then return 0 /*handle special case of zero. */ -if x='' then return '' /*if null, then return null. */ -if pos(',',x)\==0 then do;x=space(translate(x,,","),0);ox=x;end /*del ,*/ -if \datatype(x,'N') then return '[n/a]' /*not numberic? not applicable*/ -x=abs(x) /*just use positive value of X. */ -d=digits() /*get the current precision. */ -numeric digits 11 /*use "small" precision at first.*/ -g=sqrt_guess() /*try get a good 1st guesstimate.*/ -m.=11 /*technique uses just enough digs*/ -p=d+d%4+2 /*# of iterations (calculations).*/ - - /*Note: to insure enough accuracy*/ - /*for the result, the precsion */ - /*during the SQRT calcuations is */ - /*increased by two extra digits. */ - 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 /*each iteration, increase digits*/ - g=.5*(g+x/g) /*do the nitty-gritty calculation*/ - end /* .5* is faster than /2 */ - -numeric digits d /*restore the original precision.*/ -return (g/1)left('i',ox<0) /*normalize to old digs, complex?*/ - - -sqrt_guess: numeric form scientific /*force scientific form of number*/ -parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get X's exponent.*/ -return g*.5'E'_%2 /*1st guesstimate. */ - - -/*┌────────────────────────────────────────────────────────────────────┐ -┌─┘ √ └─┐ -│ While the above REXX code seems like it's doing a lot of extra work, │ -│ it saves a substanial amount of processing time when the precision │ -│ (DIGITs) is a lot greater than the default (9 digits). │ -│ │ -│ Indeed, when computing square roots in the hundreds (even thousands) │ -│ of digits, this technique reduces the amount of CPU processing time │ -│ by keeping the length of the computations to a minimim (due to a large │ -│ precision) while the accuracy (at the beginning) isn't important for │ -│ caculating the guesstimate (the running square root guess). │ -└─┐ √ ┌─┘ - └────────────────────────────────────────────────────────────────────┘*/ +floor: procedure; parse arg x; t=trunc(x); return t-(x<0)-(x\=t) diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx index a3feaaf2cd..391ef85d96 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-5.rexx @@ -1,16 +1,36 @@ -/*─────────────────────────────────────SQRT subroutine──────────────────*/ -sqrt: procedure; parse arg x /*a simple SQRT subroutine. */ -if x=0 then return 0 /*handle special case of zero. */ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; r= /*returns principal SQRT of args.*/ + do j=1 for arg() /*process each argument specified*/ + a=arg(j) /*extract the argument specified*/ + do k=1 for words(a) /*process each number specified. */ + r=r sqrt_(word(a,k)) /*calculate sqrt, add to results.*/ + end /*k*/ /* [↑] process each # in Nth arg*/ + end /*j*/ /* [↑] process each #s in args. */ +return r /*return list of SQRTs calculated*/ +/*──────────────────────────────────SQRT_ subroutine────────────────────*/ +sqrt_: procedure; parse arg x; if x=0 then return 0 /*handle 0*/ +if pos(',',x)\==0 then x=space(translate(x,,","),0) /*elide comma.*/ +if \datatype(x,'N') then return '[n/a]' /*not numberic? not applicable*/ +ox=x /*save the original value of X. */ +x=abs(x) /*just use positive value of X. */ d=digits() /*get the current precision. */ -numeric digits digits()+2 /*ensure extra precision. */ -g=x/4 /*try get a so-so 1st guesstimate*/ -old=0 /*set OLD guess to zero. */ - - do forever - g=.5*(g+x/g) /*do the nitty-gritty calculation*/ - if g=old then leave /*if G is the same as old, quit. */ - old=g /*save OLD for next iteration. */ - end /* .5* is faster than /2 */ - +m.=11 /*technique uses just enough digs*/ +numeric digits m. /*use "small" precision at first.*/ +numeric form /*force scientific form of number*/ +parse value format(x,2,1,,0) 'E0' with g 'E' _ . /*get X's exponent.*/ +g=g * .5'E'_ % 2 /*1st guesstimate for square root*/ +p=d + d%4 + 2 /*# of iterations (calculations).*/ + /*Note: to insure enough accuracy*/ + /*for the result, the precsion */ + /*during the SQRT calcuations is */ + /*increased by two extra digits. */ + do j=0 while p>9; m.j=p; p=p%2+1 /*compute the sizes of precision.*/ + end /*j*/ /* [↑] precisions stored in M. */ + /* [↓] da rubber meets da road. */ + do k=j+5 to 0 by -1 /*compute √ with increasing digs.*/ + numeric digits m.k /*each iteration, increase digits*/ + g=(g+x/g) * .5 /*do the nitty-gritty calculation*/ + end /*k*/ /* [↑] .5* is faster than /2 */ + /* [↓] normalize√──►original dig*/ numeric digits d /*restore the original precision.*/ -return g/1 /*normalize to old precision. */ +return (g/1)left('i',ox<0) /*normalize, add possible suffix.*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx index abb4b2d2f1..053f669bd0 100644 --- a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-6.rexx @@ -1,27 +1,13 @@ -numeric digits ddd /*sets the current precision to DDD */ -numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/ -numeric form kkk /*exponential: scientific | engineering*/ - -low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/ -big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/ - -rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/ -arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ - -mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ - - fs=format(x) /*formats X with the current DIGITS() */ - fb=format(x,bbb) /* BBB digs before decimal*/ - fa=format(x,bbb,aaa) /* AAA digs after decimal*/ - fa=format(x,,0) /* rounds X to an integer.*/ - fe=format(x,,eee) /* exponent has eee places. */ - ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ - -hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ -dd=c2d(ccc) /*converts character to decimal. */ -hh=c2x(ccc) /*converts character to hexadecimal. */ -cc=d2c(ddd) /*converts decimal to character. */ -hh=d2x(ddd) /*converts decimal to hexadecimal. */ -bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ -cc=x2c(hhh) /*converts hexadecimal to character. */ -dd=x2d(hhh) /*converts hexadecimal to decimal. */ +/*┌────────────────────────────────────────────────────────────────────┐ +┌─┘ √ └─┐ +│ While the above REXX code seems like it's doing a lot of extra work, │ +│ it saves a substantial amount of processing time when the precision │ +│ (DIGITs) is a lot greater than the default (which is nine digits). │ +│ │ +│ Indeed, when computing square roots in the hundreds (even thousands) │ +│ of digits, this technique reduces the amount of CPU processing time │ +│ by keeping the length of the computations to a minimum (due to a large │ +│ precision), while the accuracy at the beginning isn't important for │ +│ calculating the (first) guesstimate (the running square root guess). │ +└─┐ √ ┌─┘ + └────────────────────────────────────────────────────────────────────┘*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx new file mode 100644 index 0000000000..6d3d413b63 --- /dev/null +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-7.rexx @@ -0,0 +1,14 @@ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; arg x /*a simplistic SQRT subroutine.*/ +if x=0 then return 0 /*handle special case of zero. */ +d=digits() /*get the current precision (dig)*/ +numeric digits d+2 /*ensure extra precision (2 digs)*/ +g=x/4 /*try get a so-so 1st guesstimate*/ +old=0 /*set OLD guess to zero. */ + do forever /*keep at it 'til G (guess)=old.*/ + g=(g+x/g) / 2 /*do the nitty-gritty calculation*/ + if g=old then leave /*if G is the same as old, quit. */ + old=g /*save OLD for next iteration. */ + end /*forever*/ /* [↑] ···'til we run out of digs*/ +numeric digits d /*restore the original precision.*/ +return g/1 /*normalize to old precision (d).*/ diff --git a/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx new file mode 100644 index 0000000000..abb4b2d2f1 --- /dev/null +++ b/Task/Real-constants-and-functions/REXX/real-constants-and-functions-8.rexx @@ -0,0 +1,27 @@ +numeric digits ddd /*sets the current precision to DDD */ +numeric fuzz fff /*arithmetic comparisons with FFF fuzzy*/ +numeric form kkk /*exponential: scientific | engineering*/ + +low=min(a,b,c,d,e,f,g, ...) /*finds the min of specified arguments.*/ +big=min(a,b,c,d,e,f,g, ...) /*finds the max of specified arguments.*/ + +rrr=random(low,high) /*gets a random integer from LOW-->HIGH*/ +arr=random(low,high,seed) /* ... with a seed (to make repeatable)*/ + +mzp=sign(x) /*finds the sign of x (-1, 0, +1). */ + + fs=format(x) /*formats X with the current DIGITS() */ + fb=format(x,bbb) /* BBB digs before decimal*/ + fa=format(x,bbb,aaa) /* AAA digs after decimal*/ + fa=format(x,,0) /* rounds X to an integer.*/ + fe=format(x,,eee) /* exponent has eee places. */ + ft=format(x,,eee,ttt) /*if x exceeds TTT digits, force exp. */ + +hh=b2x(bbb) /*converts binary/bits to hexadecimal. */ +dd=c2d(ccc) /*converts character to decimal. */ +hh=c2x(ccc) /*converts character to hexadecimal. */ +cc=d2c(ddd) /*converts decimal to character. */ +hh=d2x(ddd) /*converts decimal to hexadecimal. */ +bb=x2b(hhh) /*converts hexadecimal to binary (bits)*/ +cc=x2c(hhh) /*converts hexadecimal to character. */ +dd=x2d(hhh) /*converts hexadecimal to decimal. */ diff --git a/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb b/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb index 8830d3a83e..d85e75a266 100644 --- a/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb +++ b/Task/Real-constants-and-functions/Ruby/real-constants-and-functions.rb @@ -1,11 +1,13 @@ -Math::E #e -Math::PI #pi -Math.sqrt(x) #square root -Math.log(x) #natural logarithm -Math.log(x, y) #logarithm base y -Math.log10(x) #base 10 logarithm -Math.exp(x) #exponential x.abs #absolute value +x.magnitude #absolute value x.floor #floor x.ceil #ceiling x ** y #power +include Math +E #e +PI #pi +sqrt(x) #square root +log(x) #natural logarithm +log(x, y) #logarithm base y +log10(x) #base 10 logarithm +exp(x) #exponential diff --git a/Task/Real-constants-and-functions/UNIX-Shell/real-constants-and-functions.sh b/Task/Real-constants-and-functions/UNIX-Shell/real-constants-and-functions.sh new file mode 100644 index 0000000000..d54c91370a --- /dev/null +++ b/Task/Real-constants-and-functions/UNIX-Shell/real-constants-and-functions.sh @@ -0,0 +1,15 @@ +echo $(( exp(1) )) # e +echo $(( acos(-1) )) # PI +x=5 +echo $(( sqrt(x) )) # square root +echo $(( log(x) )) # logarithm base e +echo $(( log2(x) )) # logarithm base 2 +echo $(( log10(x) )) # logarithm base 10 +echo $(( exp(x) )) # exponential +x=-42 +echo $(( abs(x) )) # absolute value +x=-5.5 +echo $(( floor(x) )) # floor +echo $(( ceil(x) )) # ceiling +x=10 y=3 +echo $(( pow(x,y) )) # power diff --git a/Task/Record-sound/00DESCRIPTION b/Task/Record-sound/00DESCRIPTION index 312cb2e30c..4ce6b6715e 100644 --- a/Task/Record-sound/00DESCRIPTION +++ b/Task/Record-sound/00DESCRIPTION @@ -1,3 +1,18 @@ +{{omit from|AWK}} +{{omit from|Brlcad}} +{{omit from|HTML}} +{{omit from|Logtalk}} +{{omit from|Lotus 123 Macro Scripting}} +{{omit from|Maxima}} +{{omit from|ML/I}} +{{omit from|Openscad}} +{{omit from|PARI/GP}} +{{omit from|TI-83 BASIC}} +{{omit from|TPP}} +{{omit from|zkl}} + Record a monophonic 16-bit PCM sound into either memory space, a file or array. -(This task neglects to specify the sample rate, and whether to use signed samples. The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. Therefore, these programs might not record sound in the same format.) +(This task neglects to specify the sample rate, and whether to use signed samples. +The programs in this page might use signed 16-bit or unsigned 16-bit samples, at 8000 Hz, 44100 Hz, or any other sample rate. +Therefore, these programs might not record sound in the same format.) diff --git a/Task/Record-sound/00META.yaml b/Task/Record-sound/00META.yaml new file mode 100644 index 0000000000..0485c0005f --- /dev/null +++ b/Task/Record-sound/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Temporal media +note: Sound diff --git a/Task/Record-sound/C++/record-sound.cpp b/Task/Record-sound/C++/record-sound.cpp new file mode 100644 index 0000000000..c814ddd8c9 --- /dev/null +++ b/Task/Record-sound/C++/record-sound.cpp @@ -0,0 +1,93 @@ +#include +#include +#include +#include + +#pragma comment ( lib, "winmm.lib" ) +using namespace std; + +class recorder +{ +public: + void start() + { + paused = rec = false; action = "IDLE"; + while( true ) + { + cout << endl << "==" << action << "==" << endl << endl; + cout << "1) Record" << endl << "2) Play" << endl << "3) Pause" << endl << "4) Stop" << endl << "5) Quit" << endl; + char c; cin >> c; + if( c > '0' && c < '6' ) + { + switch( c ) + { + case '1': record(); break; + case '2': play(); break; + case '3': pause(); break; + case '4': stop(); break; + case '5': stop(); return; + } + } + } + } +private: + void record() + { + if( mciExecute( "open new type waveaudio alias my_sound") ) + { + mciExecute( "record my_sound" ); + action = "RECORDING"; rec = true; + } + } + void play() + { + if( paused ) + mciExecute( "play my_sound" ); + else + if( mciExecute( "open tmp.wav alias my_sound" ) ) + mciExecute( "play my_sound" ); + + action = "PLAYING"; + paused = false; + } + void pause() + { + if( rec ) return; + mciExecute( "pause my_sound" ); + paused = true; action = "PAUSED"; + } + void stop() + { + if( rec ) + { + mciExecute( "stop my_sound" ); + mciExecute( "save my_sound tmp.wav" ); + mciExecute( "close my_sound" ); + action = "IDLE"; rec = false; + } + else + { + mciExecute( "stop my_sound" ); + mciExecute( "close my_sound" ); + action = "IDLE"; + } + } + bool mciExecute( string cmd ) + { + if( mciSendString( cmd.c_str(), NULL, 0, NULL ) ) + { + cout << "Can't do this: " << cmd << endl; + return false; + } + return true; + } + + bool paused, rec; + string action; +}; + +int main( int argc, char* argv[] ) +{ + recorder r; r.start(); + return 0; +} diff --git a/Task/Record-sound/Scala/record-sound.scala b/Task/Record-sound/Scala/record-sound.scala new file mode 100644 index 0000000000..7e411e0911 --- /dev/null +++ b/Task/Record-sound/Scala/record-sound.scala @@ -0,0 +1,51 @@ +import java.io.{File, IOException} +import javax.sound.sampled.{AudioFileFormat, AudioFormat, AudioInputStream} +import javax.sound.sampled.{AudioSystem, DataLine, LineUnavailableException, TargetDataLine} + +object SoundRecorder extends App { + // record duration, in milliseconds + final val RECORD_TIME = 60000 // 1 minute + + // path and format of the wav file + val (wavFile, fileType) = (new File("RecordAudio.wav"), AudioFileFormat.Type.WAVE) + val format = new AudioFormat(/*sampleRate =*/ 16000f, + /*sampleSizeInBits =*/ 16, + /*channels =*/ 2, + /*signed =*/ true, + /*bigEndian =*/ true) + + val info = new DataLine.Info(classOf[TargetDataLine], format) + val line: TargetDataLine = AudioSystem.getLine(info).asInstanceOf[TargetDataLine] + + // Entry to run the program + + // Creates a new thread that waits for a specified of time before stopping + new Thread(new Runnable() { + def run() { + try { + Thread.sleep(RECORD_TIME) + } catch { + case ex: InterruptedException => ex.printStackTrace() + } + finally { + line.stop() + line.close() + } + println("Finished") + } + }).start() + + //Captures the sound and record into a WAV file + try { + // checks if system supports the data line + if (AudioSystem.isLineSupported(info)) { + line.open(format) + line.start() // start capturing + println("Recording started") + AudioSystem.write(new AudioInputStream(line), fileType, wavFile) + } else println("Line not supported") + } catch { + case ex: LineUnavailableException => ex.printStackTrace() + case ioe: IOException => ioe.printStackTrace() + } +} diff --git a/Task/Reduced-row-echelon-form/00DESCRIPTION b/Task/Reduced-row-echelon-form/00DESCRIPTION index fd350e8ef6..539a1f0ad1 100644 --- a/Task/Reduced-row-echelon-form/00DESCRIPTION +++ b/Task/Reduced-row-echelon-form/00DESCRIPTION @@ -1,4 +1,11 @@ -Show how to compute the '''reduced row echelon form''' (a.k.a. '''row canonical form''') of a matrix. The matrix can be stored in any datatype that is convenient (for most languages, this will probably be a two-dimensional array). Built-in functions or this pseudocode (from Wikipedia) may be used: +{{omit from|GUISS}} +Show how to compute the '''reduced row echelon form''' +(a.k.a. '''row canonical form''') of a matrix. + +The matrix can be stored in any datatype that is convenient +(for most languages, this will probably be a two-dimensional array). + +Built-in functions or this pseudocode (from Wikipedia) may be used: '''function''' ToReducedRowEchelonForm(Matrix M) '''is''' ''lead'' := 0 ''rowCount'' := the number of rows in M diff --git a/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d b/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d index 286d6d40b3..8c4d162dee 100644 --- a/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d +++ b/Task/Reduced-row-echelon-form/D/reduced-row-echelon-form.d @@ -1,13 +1,13 @@ import std.stdio, std.algorithm, std.array, std.conv; -void toReducedRowEchelonForm(T)(T[][] M) pure nothrow { +void toReducedRowEchelonForm(T)(T[][] M) pure nothrow @nogc { if (M.empty) return; immutable nrows = M.length; immutable ncols = M[0].length; size_t lead; - foreach (r; 0 .. nrows) { + foreach (immutable r; 0 .. nrows) { if (ncols <= lead) return; { diff --git a/Task/Reduced-row-echelon-form/Icon/reduced-row-echelon-form.icon b/Task/Reduced-row-echelon-form/Icon/reduced-row-echelon-form.icon new file mode 100644 index 0000000000..f8dd82b68b --- /dev/null +++ b/Task/Reduced-row-echelon-form/Icon/reduced-row-echelon-form.icon @@ -0,0 +1,33 @@ +procedure main(A) + tM := [[ 1, 2, -1, -4], + [ 2, 3, -1,-11], + [ -2, 0, -3, 22]] + showMat(rref(tM)) +end + +procedure rref(M) + lead := 1 + rCount := *\M | stop("no Matrix?") + cCount := *(M[1]) | 0 + every r := !rCount do { + i := r + while M[i,lead] = 0 do { + if (i+:=1) > rCount then { + i := r + if cCount < (lead +:= 1) then stop("can't reduce") + } + } + M[i] :=: M[r] + if 0 ~= (m0 := M[r,lead]) then every !M[r] /:= real(m0) + every r ~= (i := !rCount) do { + every !(mr := copy(M[r])) *:= M[i,lead] + every M[i,j := !cCount] -:= mr[j] + } + lead +:= 1 + } + return M +end + +procedure showMat(M) + every r := !M do every writes(right(!r,5)||" " | "\n") +end diff --git a/Task/Reduced-row-echelon-form/Python/reduced-row-echelon-form.py b/Task/Reduced-row-echelon-form/Python/reduced-row-echelon-form.py index 65e47719ea..fcd3f1e057 100644 --- a/Task/Reduced-row-echelon-form/Python/reduced-row-echelon-form.py +++ b/Task/Reduced-row-echelon-form/Python/reduced-row-echelon-form.py @@ -16,7 +16,7 @@ def ToReducedRowEchelonForm( M): return M[i],M[r] = M[r],M[i] lv = M[r][lead] - M[r] = [ mrx / lv for mrx in M[r]] + M[r] = [ mrx / float(lv) for mrx in M[r]] for i in range(rowCount): if i != r: lv = M[i][lead] diff --git a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx index 4899769a10..ac2998b223 100644 --- a/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx +++ b/Task/Reduced-row-echelon-form/REXX/reduced-row-echelon-form.rexx @@ -1,30 +1,30 @@ -/*REXX program to perform Reduced Row Echelon Form (RREF) on a matrix. */ -cols=0 /*maximum columns in any row. */ -maxW=0 /*maximum width of any element. */ -@.= /*matrix to be constructed. */ -mat.= -mat.1 = ' 1 2 -1 -4 ' -mat.2 = ' 2 3 -1 -11 ' -mat.3 = ' -2 0 -3 22 ' +/*REXX program to perform Reduced Row Echelon Form (RREF) on a matrix).*/ +cols = 0 /*maximum columns in any row. */ +maxW = 0 /*maximum width of any element. */ + @. = /*matrix to be constructed. */ +mat. = +mat.1 = ' 1 2 -1 -4 ' /*a few extra blanks can't hurt. */ +mat.2 = ' 2 3 -1 -11 ' +mat.3 = ' -2 0 -3 22 ' - do r=1 until mat.r==''; _=mat.r /*build @.row.col from mat.n */ - do c=1 until _=''; parse var _ @.r.c _ + do r=1 until mat.r==''; _=mat.r /*build @.row.col from mat.X */ + do c=1 until _=''; parse var _ @.r.c _ maxW = max(maxW, length(@.r.c)) end /*c*/ - cols = max(cols,c) - end + cols = max(cols, c) /*remember the max number of cols*/ + end /*r*/ -rows = r - 1 /*adjust the row count. */ +rows = r - 1 /*adjust the row count (from DO).*/ maxW = maxW + 1 /*bump the max width, better view*/ -call showMat 'original matrix' /*show the original matrix. */ -! = 1 /*set the pointer to one. */ +call showMat 'original matrix' /*show the original matrix. */ + ! = 1 /*set the pointer to one. */ /*═══════════════════════════════════Reduced Row Echelon Form on matrix.*/ do r=1 for rows while cols>! /*start to do the heavy lifting. */ j=r - do while @.j.!==0; j = j+1 + do while @.j.!==0; j=j+1 if j==rows then do - j = r - ! = ! + 1; if cols==! then leave r + j=r + !=!+1; if cols==! then leave r end end /*while*/ @@ -32,35 +32,34 @@ call showMat 'original matrix' /*show the original matrix. */ parse value @.r.w @.j.w with @.j.w @.w.w end /*w*/ ?=@.r.! - do d=1 for cols while ?\=1 /*divide row J by @.r.p--unless 1*/ + do d=1 for cols while ?\=1 /*divide row J by @.r.p──unless≡1*/ @.r.d = @.r.d / ? end /*d*/ - do k=1 for rows /*sub (row K) *@.r.s from row K */ - if k==r then iterate /*skip if row k is the same as R */ - ?=@.k.! - do s=1 for cols while ?\=0 /*but not if @.r.! is 0*/ - @.k.s = @.k.s - ? * @.r.s - end /*s*/ - end /*k*/ + do k=1 for rows; ?=@.k.! /*sub (row K) *@.r.s from row K */ + if k==r | ?=0 then iterate /*skip if row k is the same as R */ + do s=1 for cols /*perform for the rest of the row*/ + @.k.s=@.k.s - ? * @.r.s + end /*s*/ + end /*k*/ !=!+1 - end /*r*/ + end /*r*/ call showMat 'matrix RREF' /*show reduced row echelon form. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOWMAT subroutine──────────────────*/ -showMat: parse arg title; say -say center(title,3+(cols+1)*maxW,'─'); say /*build a pretty title.*/ +showMat: parse arg title; say +say center(title, 3+(cols+1)*maxW, '─'); say /*build a pretty title.*/ - do r =1 for rows; _= - do c=1 for cols - if @.r.c=='' then do; say; say '*** error! ***'; say - say "matrix element isn't defined:" - say 'row' row", column" c'.'; say - exit 13 - end - _ = _ right(@.r.c,maxW) - end /*c*/ + do r=1 for rows; _= + do c=1 for cols + if @.r.c=='' then do; say; say '*** error! ***'; say + say "matrix element isn't defined:" + say 'row' row", column" c'.'; say + exit 13 + end + _=_ right(@.r.c, maxW) + end /*c*/ say _ - end /*r*/ + end /*r*/ return diff --git a/Task/Regular-expressions/00DESCRIPTION b/Task/Regular-expressions/00DESCRIPTION index 66e1e182e1..b41d5259ae 100644 --- a/Task/Regular-expressions/00DESCRIPTION +++ b/Task/Regular-expressions/00DESCRIPTION @@ -1,3 +1,8 @@ +{{omit from|BASIC}} +{{omit from|Brlcad}} +{{omit from|GUISS}} +{{omit from|PARI/GP}} + The goal of this task is * to match a string against a regular expression * to substitute part of a string using a regular expression diff --git a/Task/Regular-expressions/00META.yaml b/Task/Regular-expressions/00META.yaml index 88eb5468ca..f26b1767c4 100644 --- a/Task/Regular-expressions/00META.yaml +++ b/Task/Regular-expressions/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- Regular expressions note: Text processing diff --git a/Task/Regular-expressions/D/regular-expressions.d b/Task/Regular-expressions/D/regular-expressions.d index 1cec6ce653..84a23116c9 100644 --- a/Task/Regular-expressions/D/regular-expressions.d +++ b/Task/Regular-expressions/D/regular-expressions.d @@ -4,7 +4,7 @@ void main() { immutable s = "I am a string"; // Test. - if (!s.match(r"string$").empty) + if (s.match("string$")) "Ends with 'string'.".writeln; // Substitute. diff --git a/Task/Regular-expressions/Lua/regular-expressions.lua b/Task/Regular-expressions/Lua/regular-expressions.lua index 40f354d3b2..1c886ea97e 100644 --- a/Task/Regular-expressions/Lua/regular-expressions.lua +++ b/Task/Regular-expressions/Lua/regular-expressions.lua @@ -1,5 +1,9 @@ -str1 = "This is a string!" -str2 = "string" +test = "My name is Lua." +pattern = ".*name is (%a*).*" -print( str1:match( str2 ) ) -erg = str1:gsub( "a", "another" ); print( erg ) +if test:match(pattern) then + print("Name found.") +end + +sub, num_matches = test:gsub(pattern, "Hello, %1!") +print(sub) diff --git a/Task/Regular-expressions/MAXScript/regular-expressions.max b/Task/Regular-expressions/MAXScript/regular-expressions.max new file mode 100644 index 0000000000..287b33239a --- /dev/null +++ b/Task/Regular-expressions/MAXScript/regular-expressions.max @@ -0,0 +1,39 @@ +samples = #("Some string 123","Example text 123","string",\ + "ThisString Will Not Match","A123,333,string","123451") +samples2 = #("I am a string","Me too.") + +regex = dotnetobject "System.Text.RegularExpressions.Regex" ".*\bstring*" +regex2 = dotnetobject "System.Text.RegularExpressions.Regex" "\ba\b" + +clearlistener() + +format "Pattern is : %\n" (regex.toString()) + +for i in samples do +( + if regex.ismatch(i) then + ( + format "The string \"%\" matches the pattern\n" i + ) + else + ( + format "The string \"%\" doesn't match the pattern\n" i + ) +) + +-- replacement + +format "Pattern is : %\n" (regex2.toString()) + +for i in samples2 do +( + if regex2.ismatch(i) then + ( + local replaced = regex2.replace i "another" + format "The string \"%\" matched the pattern, so it was replaced: \"%\"\n" i replaced + ) + else + ( + format "The string \"%\" does not match the pattern\n" i + ) +) diff --git a/Task/Regular-expressions/Python/regular-expressions.py b/Task/Regular-expressions/Python/regular-expressions.py index bbcbafd373..9dbbf5cc88 100644 --- a/Task/Regular-expressions/Python/regular-expressions.py +++ b/Task/Regular-expressions/Python/regular-expressions.py @@ -2,8 +2,8 @@ import re string = "This is a string" -if re.search('string$',string): +if re.search('string$', string): print("Ends with string.") -string = re.sub(" a "," another ",string) -print string +string = re.sub(" a ", " another ", string) +print(string) diff --git a/Task/Regular-expressions/REXX/regular-expressions-1.rexx b/Task/Regular-expressions/REXX/regular-expressions-1.rexx index 977928f126..35cd21ec1f 100644 --- a/Task/Regular-expressions/REXX/regular-expressions-1.rexx +++ b/Task/Regular-expressions/REXX/regular-expressions-1.rexx @@ -1,15 +1,8 @@ /*REXX program demonstrates testing (modeled after Perl example).*/ -$string = "I am a string" - say 'The string is:' $string - x = "string" -if right($string,length(x))=x then say 'It ends with:' x - - y = "You" -if left($string,length(y))\=y then say 'It does not start with:' y - - z = "ring" -if pos(z,$string)\==0 then say 'It contains the string:' z - - z = "ring" -if wordpos(z,$string)==0 then say 'It does not contain the word:' z +$string="I am a string" + say 'The string is:' $string +x="string" ; if right($string,length(x))=x then say 'It ends with:' x +y="You" ; if left($string,length(y))\=y then say 'It does not start with:' y +z="ring" ; if pos(z,$string)\==0 then say 'It contains the string:' z +z="ring" ; if wordpos(z,$string)==0 then say 'It does not contain the word:' z /*stick a fork in it, we're done.*/ diff --git a/Task/Regular-expressions/REXX/regular-expressions-2.rexx b/Task/Regular-expressions/REXX/regular-expressions-2.rexx index 687d92034f..23402d0d44 100644 --- a/Task/Regular-expressions/REXX/regular-expressions-2.rexx +++ b/Task/Regular-expressions/REXX/regular-expressions-2.rexx @@ -2,9 +2,9 @@ $string = "I am a string" old = " a " new = " another " -say 'The original string is:' $string -say 'old word is:' old -say 'new word is:' new +say 'The original string is:' $string +say 'old word is:' old +say 'new word is:' new $string = changestr(old,$string,new) -say 'The changed string is:' $string +say 'The changed string is:' $string /*stick a fork in it, we're done.*/ diff --git a/Task/Regular-expressions/REXX/regular-expressions-3.rexx b/Task/Regular-expressions/REXX/regular-expressions-3.rexx index ed7e2c992c..1a09ff3f0d 100644 --- a/Task/Regular-expressions/REXX/regular-expressions-3.rexx +++ b/Task/Regular-expressions/REXX/regular-expressions-3.rexx @@ -3,8 +3,8 @@ $string = "I am a string" old = " a " new = " another " say 'The original string is:' $string -say 'old word is:' old -say 'new word is:' new +say 'old word is:' old +say 'new word is:' new $string2 = changestr(old,$string,new) say 'The original string is:' $string say 'The changed string is:' $string2 diff --git a/Task/Regular-expressions/REXX/regular-expressions-4.rexx b/Task/Regular-expressions/REXX/regular-expressions-4.rexx index f0f0942a69..01d797cc82 100644 --- a/Task/Regular-expressions/REXX/regular-expressions-4.rexx +++ b/Task/Regular-expressions/REXX/regular-expressions-4.rexx @@ -3,10 +3,10 @@ old = " am " new = " was " say 'The original string is:' $string -say 'old word is:' old -say 'new word is:' new +say 'old word is:' old +say 'new word is:' new -if wordpos(old,$string)\==0 then +if wordpos(old,$string)\==0 then do $string = changestr(old,$string,new) say 'I was able to find and replace ' old " with " new diff --git a/Task/Regular-expressions/UNIX-Shell/regular-expressions-1.sh b/Task/Regular-expressions/UNIX-Shell/regular-expressions-1.sh new file mode 100644 index 0000000000..86e499ba9e --- /dev/null +++ b/Task/Regular-expressions/UNIX-Shell/regular-expressions-1.sh @@ -0,0 +1,4 @@ +s="I am a string" +if [[ $s =~ str..g$ ]]; then + echo "the string ends with 'str..g'" +fi diff --git a/Task/Regular-expressions/UNIX-Shell/regular-expressions-2.sh b/Task/Regular-expressions/UNIX-Shell/regular-expressions-2.sh new file mode 100644 index 0000000000..42525a34c8 --- /dev/null +++ b/Task/Regular-expressions/UNIX-Shell/regular-expressions-2.sh @@ -0,0 +1,3 @@ +s="I am the original string" +re='o.*l' +repl="modified" diff --git a/Task/Regular-expressions/UNIX-Shell/regular-expressions-3.sh b/Task/Regular-expressions/UNIX-Shell/regular-expressions-3.sh new file mode 100644 index 0000000000..9618eadbc8 --- /dev/null +++ b/Task/Regular-expressions/UNIX-Shell/regular-expressions-3.sh @@ -0,0 +1,2 @@ +modified=${s/~(E)$re/$repl} +echo "$modified" # I am the modified string diff --git a/Task/Regular-expressions/UNIX-Shell/regular-expressions-4.sh b/Task/Regular-expressions/UNIX-Shell/regular-expressions-4.sh new file mode 100644 index 0000000000..2d27e3d75a --- /dev/null +++ b/Task/Regular-expressions/UNIX-Shell/regular-expressions-4.sh @@ -0,0 +1,5 @@ +if [[ $s =~ $re ]]; then + submatch=${BASH_REMATCH[0]} + modified="${s%%$submatch*}$repl${s#*$submatch}" + echo "$modified" # I am the modified string +fi diff --git a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-1.go b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-1.go index 1a9254f54b..642f6423f9 100644 --- a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-1.go +++ b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-1.go @@ -1,20 +1,19 @@ package main + import "fmt" func uniq(list []int) []int { - unique_set := make(map[int] bool, len(list)) - for _, x := range list { - unique_set[x] = true - } - result := make([]int, len(unique_set)) - i := 0 - for x := range unique_set { - result[i] = x - i++ - } - return result + unique_set := make(map[int]bool, len(list)) + for _, x := range list { + unique_set[x] = true + } + result := make([]int, 0, len(unique_set)) + for x := range unique_set { + result = append(result, x) + } + return result } func main() { - fmt.Println(uniq([]int {1,2,3,2,3,4})) // prints: [3 1 4 2] + fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) // prints: [3 4 1 2] (but in a semi-random order) } diff --git a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-2.go b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-2.go index 9aa3b7dffa..85a1816f79 100644 --- a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-2.go +++ b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-2.go @@ -3,21 +3,21 @@ package main import "fmt" func uniq(list []int) []int { - unique_set := make(map[int]int, len(list)) - i := 0 - for _, x := range list { - if _, there := unique_set[x]; !there { - unique_set[x] = i - i++ - } - } - result := make([]int, len(unique_set)) - for x, i := range unique_set { - result[i] = x - } - return result + unique_set := make(map[int]int, len(list)) + i := 0 + for _, x := range list { + if _, there := unique_set[x]; !there { + unique_set[x] = i + i++ + } + } + result := make([]int, len(unique_set)) + for x, i := range unique_set { + result[i] = x + } + return result } func main() { - fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) // prints: [1 2 3 4] + fmt.Println(uniq([]int{1, 2, 3, 2, 3, 4})) // prints: [1 2 3 4] } diff --git a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-3.go b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-3.go index 96c89f8e32..9366ef68c0 100644 --- a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-3.go +++ b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-3.go @@ -1,35 +1,35 @@ package main import ( - "fmt" - "math" + "fmt" + "math" ) func uniq(list []float64) []float64 { - unique_set := map[float64]int{} - i := 0 - nan := false - for _, x := range list { - if _, exists := unique_set[x]; exists { - continue - } - if math.IsNaN(x) { - if nan { - continue - } else { - nan = true - } - } - unique_set[x] = i - i++ - } - result := make([]float64, len(unique_set)) - for x, i := range unique_set { - result[i] = x - } - return result + unique_set := map[float64]int{} + i := 0 + nan := false + for _, x := range list { + if _, exists := unique_set[x]; exists { + continue + } + if math.IsNaN(x) { + if nan { + continue + } else { + nan = true + } + } + unique_set[x] = i + i++ + } + result := make([]float64, len(unique_set)) + for x, i := range unique_set { + result[i] = x + } + return result } func main() { - fmt.Println(uniq([]float64{1, 2, math.NaN(), 2, math.NaN(), 4})) + fmt.Println(uniq([]float64{1, 2, math.NaN(), 2, math.NaN(), 4})) // Prints [1 2 NaN 4] } diff --git a/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-4.go b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-4.go new file mode 100644 index 0000000000..e14f1e7c14 --- /dev/null +++ b/Task/Remove-duplicate-elements/Go/remove-duplicate-elements-4.go @@ -0,0 +1,90 @@ +package main + +import ( + "fmt" + "math" + "reflect" +) + +func uniq(x interface{}) (interface{}, bool) { + v := reflect.ValueOf(x) + if !v.IsValid() { + panic("uniq: invalid argument") + } + if k := v.Kind(); k != reflect.Array && k != reflect.Slice { + panic("uniq: argument must be an array or a slice") + } + elemType := v.Type().Elem() + intType := reflect.TypeOf(int(0)) + mapType := reflect.MapOf(elemType, intType) + m := reflect.MakeMap(mapType) + i := 0 + for j := 0; j < v.Len(); j++ { + x := v.Index(j) + if m.MapIndex(x).IsValid() { + continue + } + m.SetMapIndex(x, reflect.ValueOf(i)) + if m.MapIndex(x).IsValid() { + i++ + } + } + sliceType := reflect.SliceOf(elemType) + result := reflect.MakeSlice(sliceType, i, i) + hadNaN := false + for _, key := range m.MapKeys() { + ival := m.MapIndex(key) + if !ival.IsValid() { + hadNaN = true + } else { + result.Index(int(ival.Int())).Set(key) + } + } + + return result.Interface(), hadNaN +} + +type MyType struct { + name string + value float32 +} + +func main() { + intArray := [...]int{5, 1, 2, 3, 2, 3, 4} + intSlice := []int{5, 1, 2, 3, 2, 3, 4} + stringSlice := []string{"five", "one", "two", "three", "two", "three", "four"} + floats := []float64{1, 2, 2, 4, + math.NaN(), 2, math.NaN(), + math.Inf(1), math.Inf(1), math.Inf(-1), math.Inf(-1)} + complexes := []complex128{1, 1i, 1 + 1i, 1 + 1i, + complex(math.NaN(), 1), complex(1, math.NaN()), + complex(math.Inf(+1), 1), complex(1, math.Inf(1)), + complex(math.Inf(-1), 1), complex(1, math.Inf(1)), + } + structs := []MyType{ + {"foo", 42}, + {"foo", 2}, + {"foo", 42}, + {"bar", 42}, + {"bar", 2}, + {"fail", float32(math.NaN())}, + } + + fmt.Print("intArray: ", intArray, " → ") + fmt.Println(uniq(intArray)) + fmt.Print("intSlice: ", intSlice, " → ") + fmt.Println(uniq(intSlice)) + fmt.Print("stringSlice: ", stringSlice, " → ") + fmt.Println(uniq(stringSlice)) + fmt.Print("floats: ", floats, " → ") + fmt.Println(uniq(floats)) + fmt.Print("complexes: ", complexes, "\n → ") + fmt.Println(uniq(complexes)) + fmt.Print("structs: ", structs, " → ") + fmt.Println(uniq(structs)) + // Passing a non slice or array will compile put + // then produce a run time panic: + //a := 42 + //uniq(a) + //uniq(nil) +} diff --git a/Task/Remove-duplicate-elements/Mathematica/remove-duplicate-elements-3.math b/Task/Remove-duplicate-elements/Mathematica/remove-duplicate-elements-3.math index 3e07149f89..71498bd37d 100644 --- a/Task/Remove-duplicate-elements/Mathematica/remove-duplicate-elements-3.math +++ b/Task/Remove-duplicate-elements/Mathematica/remove-duplicate-elements-3.math @@ -1,2 +1 @@ -NoDupes[input_List] := Split[Sort[input]][[All, 1]] -NoDupes[{0, 2, 1, 4, 2, 0, 3, 1, 1, 1, 0, 3}] +Union[{0, 2, 1, 4, 2, 0, 3, 1, 1, 1, 0, 3}] diff --git a/Task/Remove-duplicate-elements/PL-I/remove-duplicate-elements.pli b/Task/Remove-duplicate-elements/PL-I/remove-duplicate-elements.pli index 19e2222efa..5eefe99bdc 100644 --- a/Task/Remove-duplicate-elements/PL-I/remove-duplicate-elements.pli +++ b/Task/Remove-duplicate-elements/PL-I/remove-duplicate-elements.pli @@ -1,7 +1,11 @@ - declare t(20) fixed initial (1, 5, 6, 2, 1, 7, - 5, 22, 4, 19, 1, 1, 6, 6, 6, 8, 9, 10, 11, 12); +*process mar(1,72); +remdup: Proc options(main); + declare t(20) fixed initial (6, 6, 1, 5, 6, 2, 1, 7, + 5, 22, 4, 19, 1, 1, 6, 8, 9, 10, 11, 12); declare (i, j, k, n, e) fixed; + put skip list ('Input:'); + put edit ((t(k) do k = 1 to hbound(t))) (skip,20(f(3))); n = hbound(t,1); i = 0; outer: @@ -15,4 +19,5 @@ outer: end; put skip list ('Unique elements are:'); - put edit ((t(k) do k = 1 to i)) (skip, f(11)); + put edit ((t(k) do k = 1 to i)) (skip,20(f(3))); +end; diff --git a/Task/Remove-duplicate-elements/Prolog/remove-duplicate-elements-3.pro b/Task/Remove-duplicate-elements/Prolog/remove-duplicate-elements-3.pro index 39f13f8285..a47fddc08c 100644 --- a/Task/Remove-duplicate-elements/Prolog/remove-duplicate-elements-3.pro +++ b/Task/Remove-duplicate-elements/Prolog/remove-duplicate-elements-3.pro @@ -1,5 +1,5 @@ member1(X,[H|_]) :- X==H,!. -member1(X,[_|T]) :- member1_(X,T). +member1(X,[_|T]) :- member1(X,T). distinct([],[]). distinct([H|T],C) :- member1(H,T),!, distinct(T,C). diff --git a/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-2.py b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-2.py index d05d59cd9e..344fe615b8 100644 --- a/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-2.py +++ b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-2.py @@ -1,3 +1,7 @@ -import itertools items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] -unique = [k for k,g in itertools.groupby(sorted(items))] +unique = [] +helperset = set() +for x in items: + if x not in helperset: + unique.append(x) + helperset.add(x) diff --git a/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-3.py b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-3.py index bcda68e080..d05d59cd9e 100644 --- a/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-3.py +++ b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-3.py @@ -1,5 +1,3 @@ +import itertools items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] -unique = [] -for x in items: - if x not in unique: - unique.append(x) +unique = [k for k,g in itertools.groupby(sorted(items))] diff --git a/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-4.py b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-4.py new file mode 100644 index 0000000000..bcda68e080 --- /dev/null +++ b/Task/Remove-duplicate-elements/Python/remove-duplicate-elements-4.py @@ -0,0 +1,5 @@ +items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd'] +unique = [] +for x in items: + if x not in unique: + unique.append(x) diff --git a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-1.rb b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-1.rb new file mode 100644 index 0000000000..42251ae97a --- /dev/null +++ b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-1.rb @@ -0,0 +1,2 @@ +ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'] +p ary.uniq # => [1, 2, "redundant", [1, 2, 3]] diff --git a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-2.rb b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-2.rb new file mode 100644 index 0000000000..fa868e8ead --- /dev/null +++ b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-2.rb @@ -0,0 +1,26 @@ +class Array + # used Hash + def uniq1 + each_with_object({}) {|elem, h| h[elem] = true}.keys + end + # sort (requires comparable) + def uniq2 + sorted = sort + pre = sorted.first + sorted.each_with_object([pre]){|elem, uniq| uniq << (pre = elem) if elem != pre} + end + # go through the list + def uniq3 + each_with_object([]) {|elem, uniq| uniq << elem unless uniq.include?(elem)} + end +end + +ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'] +p ary.uniq1 #=> [1, 2, "redundant", [1, 2, 3]] +p ary.uniq2 rescue nil # Error (not comparable) +p ary.uniq3 #=> [1, 2, "redundant", [1, 2, 3]] + +ary = [1,2,3,7,6,5,2,3,4,5,6,1,1,1] +p ary.uniq1 #=> [1, 2, 3, 7, 6, 5, 4] +p ary.uniq2 #=> [1, 2, 3, 4, 5, 6, 7] +p ary.uniq3 #=> [1, 2, 3, 7, 6, 5, 4] diff --git a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb new file mode 100644 index 0000000000..58a0709b89 --- /dev/null +++ b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements-3.rb @@ -0,0 +1,15 @@ +def unique(array) + pure = Array.new + for i in array + flag = false + for j in pure + flag = true if j==i + end + pure << i unless flag + end + return pure +end + + +unique ["hi","hey","hello","hi","hey","heyo"] # => ["hi", "hey", "hello", "heyo"] +unique [1,2,3,4,1,2,3,5,1,2,3,4,5] # => [1,2,3,4,5] diff --git a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements.rb b/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements.rb deleted file mode 100644 index 00e06623e6..0000000000 --- a/Task/Remove-duplicate-elements/Ruby/remove-duplicate-elements.rb +++ /dev/null @@ -1,3 +0,0 @@ -ary = [1,1,2,1,'redundant',[1,2,3],[1,2,3],'redundant'] -uniq_ary = ary.uniq -# => [1, 2, "redundant", [1, 2, 3]] diff --git a/Task/Remove-lines-from-a-file/Frink/remove-lines-from-a-file.frink b/Task/Remove-lines-from-a-file/Frink/remove-lines-from-a-file.frink new file mode 100644 index 0000000000..c1415b6411 --- /dev/null +++ b/Task/Remove-lines-from-a-file/Frink/remove-lines-from-a-file.frink @@ -0,0 +1,12 @@ +removeLines[filename, start, len] := +{ + lines = array[lines["file:$filename"]] + modified = lines.removeLen[start-1, len] + if modified != len + println["Was only able to remove $modified lines due to end-of-file."] + + w = new Writer[filename] + for line = lines + w.println[line] + w.close[] +} diff --git a/Task/Remove-lines-from-a-file/J/remove-lines-from-a-file-1.j b/Task/Remove-lines-from-a-file/J/remove-lines-from-a-file-1.j index c673219a01..8b3061228b 100644 --- a/Task/Remove-lines-from-a-file/J/remove-lines-from-a-file-1.j +++ b/Task/Remove-lines-from-a-file/J/remove-lines-from-a-file-1.j @@ -1,6 +1,6 @@ -removeLines=:4 :0 +removeLines=: 4 :0 'count start'=. x file=. boxxopen y - lines=. <;.2]1!:1 file - (;lines {~ <<< (start-1)+i.count) 1!:2 file + lines=. <;.2 fread file + (;lines {~ <<< (start-1)+i.count) fwrite file ) diff --git a/Task/Remove-lines-from-a-file/Mathematica/remove-lines-from-a-file.math b/Task/Remove-lines-from-a-file/Mathematica/remove-lines-from-a-file.math new file mode 100644 index 0000000000..6b1f719a5e --- /dev/null +++ b/Task/Remove-lines-from-a-file/Mathematica/remove-lines-from-a-file.math @@ -0,0 +1,10 @@ +f[doc_String, start_Integer, n_Integer] := Module[{p, newdoc}, + p = Import[doc, "List"]; + If[start + n - 1 <= Length@p, + p = Drop[p, {start, start + n - 1}]; + newdoc = FileNameJoin[{DirectoryName[doc], FileBaseName[doc] <> "_removed.txt"}]; + Export[newdoc, p, "List"]; + , + Print["Too few lines in document. Operation aborted."] + ] + ] diff --git a/Task/Remove-lines-from-a-file/Scala/remove-lines-from-a-file.scala b/Task/Remove-lines-from-a-file/Scala/remove-lines-from-a-file.scala new file mode 100644 index 0000000000..01ec1b1ada --- /dev/null +++ b/Task/Remove-lines-from-a-file/Scala/remove-lines-from-a-file.scala @@ -0,0 +1,18 @@ +object RemoveLinesFromAFile extends App { + args match { + case Array(filename, start, num) => + + import java.nio.file.{Files,Paths} + val lines = scala.io.Source.fromFile(filename).getLines + val keep = start.toInt - 1 + val top = lines.take(keep).toList + val drop = lines.take(num.toInt).toList + Files.write(Paths.get(filename), scala.collection.JavaConversions.asJavaIterable(top ++ lines)) + + if (top.size < keep || drop.size < num.toInt) + println(s"Too few lines: removed only ${drop.size} of $num lines starting at $start") + + case _ => + println("Usage: RemoveLinesFromAFile ") + } +} diff --git a/Task/Rename-a-file/00DESCRIPTION b/Task/Rename-a-file/00DESCRIPTION index 9fe600f18f..1cc8e88e62 100644 --- a/Task/Rename-a-file/00DESCRIPTION +++ b/Task/Rename-a-file/00DESCRIPTION @@ -1 +1,9 @@ -In this task, the job is to rename the file called "input.txt" into "output.txt" and a directory called "docs" into "mydocs". This should be done twice: once "here", i.e. in the current working directory and once in the filesystem root. +In this task, the job is to rename the file called "input.txt" into "output.txt" and a directory called "docs" into "mydocs". + +This should be done twice: +once "here", i.e. in the current working directory +and once in the filesystem root. + +It can be assumed that the user has the rights to do so. +(In unix-type systems, only the user root would have +sufficient permissions in the filesystem root) diff --git a/Task/Rename-a-file/OpenEdge-Progress/rename-a-file.openedge b/Task/Rename-a-file/OpenEdge-Progress/rename-a-file.openedge new file mode 100644 index 0000000000..1023cf419a --- /dev/null +++ b/Task/Rename-a-file/OpenEdge-Progress/rename-a-file.openedge @@ -0,0 +1,5 @@ +OS-RENAME "input.txt" "output.txt". +OS-RENAME "docs" "mydocs". + +OS-RENAME "/input.txt" "/output.txt". +OS-RENAME "/docs" "/mydocs". diff --git a/Task/Rename-a-file/REXX/rename-a-file-1.rexx b/Task/Rename-a-file/REXX/rename-a-file-1.rexx index 0e7e46987f..9954440193 100644 --- a/Task/Rename-a-file/REXX/rename-a-file-1.rexx +++ b/Task/Rename-a-file/REXX/rename-a-file-1.rexx @@ -1,5 +1,9 @@ - do 2 - 'RENAME' "input.txt" "output.txt" - 'CD' "\" - 'MOVE' "\docs" "\mydocs" - end +/*REXX program renames a file & a directory (in current dir & in root).*/ +trace off /*suppress error messages, bad RC*/ + + do 2 /* [↓] perform this code twice. */ + 'RENAME' "input.txt output.txt" /*rename a particular DOS file. */ + 'MOVE' "\docs \mydocs" /*use (DOS) MOVE to rename a dir.*/ + 'CD' "\" /*for 2nd pass, change──►root dir*/ + end /*2*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Rename-a-file/REXX/rename-a-file-2.rexx b/Task/Rename-a-file/REXX/rename-a-file-2.rexx index 3c81c957bc..f8d08346e2 100644 --- a/Task/Rename-a-file/REXX/rename-a-file-2.rexx +++ b/Task/Rename-a-file/REXX/rename-a-file-2.rexx @@ -1,5 +1,10 @@ - do 2 - 'RENAME' "input.txt output.txt" - 'CD' "\" - 'MOVE' "\docs \mydocs" - end +/*REXX program renames a file & a directory (in current dir & in root).*/ +trace off /*suppress error messages, bad RC*/ +$ = '2> NUL' /*used to suppress error messages*/ + + do 2 /* [↓] perform this code twice. */ + 'RENAME' "input.txt output.txt" $ /*rename a particular DOS file. */ + 'MOVE' "\docs \mydocs" $ /*use (DOS) MOVE to rename a dir.*/ + 'CD' "\" $ /*for 2nd pass, change──►root dir*/ + end /*2*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Rename-a-file/Scala/rename-a-file-2.scala b/Task/Rename-a-file/Scala/rename-a-file-2.scala index 2eb5a4d264..123f5d670a 100644 --- a/Task/Rename-a-file/Scala/rename-a-file-2.scala +++ b/Task/Rename-a-file/Scala/rename-a-file-2.scala @@ -1,8 +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) + List(("myfile.txt", "anotherfile.txt"),("/tmp/myfile.txt", "/tmp/anotherfile.txt"), + ("mydir", "anotherdir"),("/tmp/mydir", "/tmp/anotherdir")).foreach{ case (oldf, newf) ⇒ + new java.io.File(oldf) renameTo new java.io.File(newf) + } } } diff --git a/Task/Repeat-a-string/ATS/repeat-a-string.ats b/Task/Repeat-a-string/ATS/repeat-a-string.ats new file mode 100644 index 0000000000..de9e2ca720 --- /dev/null +++ b/Task/Repeat-a-string/ATS/repeat-a-string.ats @@ -0,0 +1,32 @@ +// +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o string_repeat string_repeat.dats +// + +#include +"share/atspre_staload.hats" + +fun +string_repeat +( + x: string, n: intGte(0) +) : Strptr1 = res where +{ + val xs = + list_make_elt(n, x) + val res = stringlst_concat($UNSAFE.list_vt2t(xs)) + val ((*freed*)) = list_vt_free(xs) +} (* end of [string_repeat] *) + +(* ****** ****** *) + +implement +main0 () = let +// +val ha5 = string_repeat("ha", 5) +val ((*void*)) = println! ("ha5 = \"", ha5, "\"") +val ((*freed*)) = strptr_free (ha5) +// +in + // nothing +end // end of [main0] diff --git a/Task/Repeat-a-string/ColdFusion/repeat-a-string.cfm b/Task/Repeat-a-string/ColdFusion/repeat-a-string.cfm new file mode 100644 index 0000000000..ab0a083e46 --- /dev/null +++ b/Task/Repeat-a-string/ColdFusion/repeat-a-string.cfm @@ -0,0 +1,5 @@ + + + +#word# + diff --git a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-1.lisp b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-1.lisp index 9da1e0dcb2..518b73f346 100644 --- a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-1.lisp +++ b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-1.lisp @@ -1,5 +1,3 @@ (defun repeat-string (n string) (with-output-to-string (stream) (loop repeat n do (write-string string stream)))) - -(princ (repeat-string 5 "hi")) diff --git a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-2.lisp b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-2.lisp index a224195bec..a7a0dab8f3 100644 --- a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-2.lisp +++ b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-2.lisp @@ -1 +1,9 @@ -(make-string 5 :initial-element #\X) +(defun repeat-string (n string + &aux + (len (length string)) + (result (make-string (* n len) + :element-type (array-element-type string)))) + (loop repeat n + for i from 0 by len + do (setf (subseq result i (+ i len)) string)) + result) diff --git a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-3.lisp b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-3.lisp new file mode 100644 index 0000000000..676352eb82 --- /dev/null +++ b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-3.lisp @@ -0,0 +1 @@ +(princ (repeat-string 5 "hi")) diff --git a/Task/Repeat-a-string/Common-Lisp/repeat-a-string-4.lisp b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-4.lisp new file mode 100644 index 0000000000..a224195bec --- /dev/null +++ b/Task/Repeat-a-string/Common-Lisp/repeat-a-string-4.lisp @@ -0,0 +1 @@ +(make-string 5 :initial-element #\X) diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi index dc64f94549..21db6ef8ee 100644 --- a/Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi +++ b/Task/Repeat-a-string/Delphi/repeat-a-string-3.delphi @@ -1 +1,7 @@ -StrUtils.DupeString +function RepeatStr(const s: string; i: Cardinal): string; +begin + if i = 0 then + result := '' + else + result := s + RepeatStr(s, i-1) +end; diff --git a/Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi b/Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi new file mode 100644 index 0000000000..dc64f94549 --- /dev/null +++ b/Task/Repeat-a-string/Delphi/repeat-a-string-4.delphi @@ -0,0 +1 @@ +StrUtils.DupeString diff --git a/Task/Repeat-a-string/Eiffel/repeat-a-string.e b/Task/Repeat-a-string/Eiffel/repeat-a-string.e new file mode 100644 index 0000000000..dd88e073e4 --- /dev/null +++ b/Task/Repeat-a-string/Eiffel/repeat-a-string.e @@ -0,0 +1,6 @@ + repeat_string(a_string: STRING; times: INTEGER): STRING + require + times_positive: times > 0 + do + Result := a_string.multiply(times) + end diff --git a/Task/Repeat-a-string/Elixir/repeat-a-string.elixir b/Task/Repeat-a-string/Elixir/repeat-a-string.elixir new file mode 100644 index 0000000000..aa081759f1 --- /dev/null +++ b/Task/Repeat-a-string/Elixir/repeat-a-string.elixir @@ -0,0 +1 @@ +String.duplicate("ha", 5) diff --git a/Task/Repeat-a-string/GAP/repeat-a-string.gap b/Task/Repeat-a-string/GAP/repeat-a-string.gap index 4d0aa25728..e0dc2a1ada 100644 --- a/Task/Repeat-a-string/GAP/repeat-a-string.gap +++ b/Task/Repeat-a-string/GAP/repeat-a-string.gap @@ -1,2 +1,2 @@ -Concatenation(List([1 .. 10], n -> "BOB ")); -# "BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB " +Concatenation(ListWithIdenticalEntries(10, "BOB ")); +"BOB BOB BOB BOB BOB BOB BOB BOB BOB BOB " diff --git a/Task/Repeat-a-string/Haskell/repeat-a-string-3.hs b/Task/Repeat-a-string/Haskell/repeat-a-string-3.hs index 0576d95f03..874b9abf26 100644 --- a/Task/Repeat-a-string/Haskell/repeat-a-string-3.hs +++ b/Task/Repeat-a-string/Haskell/repeat-a-string-3.hs @@ -1 +1 @@ -cycle "ha" +[1..5] *> "ha" diff --git a/Task/Repeat-a-string/Haskell/repeat-a-string-4.hs b/Task/Repeat-a-string/Haskell/repeat-a-string-4.hs index 8ca2a5503a..0576d95f03 100644 --- a/Task/Repeat-a-string/Haskell/repeat-a-string-4.hs +++ b/Task/Repeat-a-string/Haskell/repeat-a-string-4.hs @@ -1 +1 @@ -replicate 5 '*' +cycle "ha" diff --git a/Task/Repeat-a-string/Haskell/repeat-a-string-5.hs b/Task/Repeat-a-string/Haskell/repeat-a-string-5.hs new file mode 100644 index 0000000000..8ca2a5503a --- /dev/null +++ b/Task/Repeat-a-string/Haskell/repeat-a-string-5.hs @@ -0,0 +1 @@ +replicate 5 '*' diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string-1.js b/Task/Repeat-a-string/JavaScript/repeat-a-string-1.js new file mode 100644 index 0000000000..c9c932a685 --- /dev/null +++ b/Task/Repeat-a-string/JavaScript/repeat-a-string-1.js @@ -0,0 +1,5 @@ +String.prototype.repeat = function(n) { + return new Array(1 + (n || 0)).join(this); +} + +console.log("ha".repeat(5)); // hahahahaha diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string-2.js b/Task/Repeat-a-string/JavaScript/repeat-a-string-2.js new file mode 100644 index 0000000000..05fcb35667 --- /dev/null +++ b/Task/Repeat-a-string/JavaScript/repeat-a-string-2.js @@ -0,0 +1 @@ +console.log("ha".repeat(5)); // hahahahaha diff --git a/Task/Repeat-a-string/JavaScript/repeat-a-string.js b/Task/Repeat-a-string/JavaScript/repeat-a-string.js deleted file mode 100644 index ed4f8cec4b..0000000000 --- a/Task/Repeat-a-string/JavaScript/repeat-a-string.js +++ /dev/null @@ -1,5 +0,0 @@ -String.prototype.repeat = function(n) { - return new Array(1 + n).join(this); -} - -alert("ha".repeat(5)); // hahahahaha diff --git a/Task/Repeat-a-string/PARI-GP/repeat-a-string.pari b/Task/Repeat-a-string/PARI-GP/repeat-a-string-1.pari similarity index 100% rename from Task/Repeat-a-string/PARI-GP/repeat-a-string.pari rename to Task/Repeat-a-string/PARI-GP/repeat-a-string-1.pari diff --git a/Task/Repeat-a-string/PARI-GP/repeat-a-string-2.pari b/Task/Repeat-a-string/PARI-GP/repeat-a-string-2.pari new file mode 100644 index 0000000000..90606573dd --- /dev/null +++ b/Task/Repeat-a-string/PARI-GP/repeat-a-string-2.pari @@ -0,0 +1 @@ +repeat(s,n)=concat(vector(n,i, s)); diff --git a/Task/Repeat-a-string/RapidQ/repeat-a-string.rapidq b/Task/Repeat-a-string/RapidQ/repeat-a-string.rapidq new file mode 100644 index 0000000000..725209f508 --- /dev/null +++ b/Task/Repeat-a-string/RapidQ/repeat-a-string.rapidq @@ -0,0 +1,12 @@ +'For a single char +showmessage String$(10, "-") + +'For strings with more than one char +function Repeat$(Expr as string, Count as integer) as string + dim x as integer + for x = 1 to Count + Result = Result + Expr + next +end function + +showmessage Repeat$("ha", 5) diff --git a/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-1.visual b/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-1.visual new file mode 100644 index 0000000000..b01faf8ac9 --- /dev/null +++ b/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-1.visual @@ -0,0 +1 @@ +FileContents = "".PadRight(FileSizeBytes, "X") diff --git a/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-2.visual b/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-2.visual new file mode 100644 index 0000000000..284e835568 --- /dev/null +++ b/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string-2.visual @@ -0,0 +1 @@ +FileContents = "".PadRight(3, "XO-") diff --git a/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string.visual b/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string.visual deleted file mode 100644 index 146fedc0db..0000000000 --- a/Task/Repeat-a-string/Visual-Basic-.NET/repeat-a-string.visual +++ /dev/null @@ -1,6 +0,0 @@ -FileContents = "X".PadRight(FileSizeBytes - 1, "X") - -Where: - -* FileContents is the string to populate -* FileSizeBytes is the number of repetitions (Remember that "-1" is valid as we have already specified the first character as being "X", which is to be padded on. diff --git a/Task/Resistor-mesh/00DESCRIPTION b/Task/Resistor-mesh/00DESCRIPTION index 407aef8133..1d51b6b80d 100644 --- a/Task/Resistor-mesh/00DESCRIPTION +++ b/Task/Resistor-mesh/00DESCRIPTION @@ -1,5 +1,6 @@ [[image:resistor-mesh.svg]] -Given 10 × 10 grid nodes interconnected by 1Ω resistors as shown, find the resistance between point A and B. +Given 10 × 10 grid nodes interconnected by 1Ω resistors as shown, +find the resistance between point A and B. See also [[http://xkcd.com/356/]] diff --git a/Task/Resistor-mesh/00META.yaml b/Task/Resistor-mesh/00META.yaml new file mode 100644 index 0000000000..f78a27fcb1 --- /dev/null +++ b/Task/Resistor-mesh/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- Electronics diff --git a/Task/Resistor-mesh/D/resistor-mesh.d b/Task/Resistor-mesh/D/resistor-mesh.d index eec8c05d43..50219824cd 100644 --- a/Task/Resistor-mesh/D/resistor-mesh.d +++ b/Task/Resistor-mesh/D/resistor-mesh.d @@ -3,42 +3,44 @@ import std.stdio, std.traits; enum Node.FP differenceThreshold = 1e-40; struct Node { - alias real FP; + alias FP = real; enum Kind : size_t { free, A, B } FP voltage = 0.0; - private Kind kind = Kind.free; - @property Kind fixed() const pure nothrow { return kind; } + /*const*/ private Kind kind = Kind.free; + // Remove kindGet once kind is const. + @property Kind kindGet() const pure nothrow @nogc {return kind; } } -Node.FP iter(size_t w, size_t h)(ref Node[w][h] m) pure nothrow { +Node.FP iter(size_t w, size_t h)(ref Node[w][h] m) pure nothrow @nogc { static void enforceBoundaryConditions(ref Node[w][h] m) - pure nothrow { + pure nothrow @nogc { m[1][1].voltage = 1.0; m[6][7].voltage = -1.0; } static Node.FP calcDifference(in ref Node[w][h] m, - ref Node[w][h] d) pure nothrow { + ref Node[w][h] d) pure nothrow @nogc { Node.FP total = 0.0; - foreach (i; 0 .. h) - foreach (j; 0 .. w) { + foreach (immutable i; 0 .. h) { + foreach (immutable j; 0 .. w) { Node.FP v = 0.0; { size_t n = 0; - if (i != 0) { v += m[i - 1][j].voltage; n++; } - if (j != 0) { v += m[i][j - 1].voltage; n++; } - if (i < h-1) { v += m[i + 1][j].voltage; n++; } - if (j < w-1) { v += m[i][j + 1].voltage; n++; } + if (i != 0) { v += m[i - 1][j].voltage; n++; } + if (j != 0) { v += m[i][j - 1].voltage; n++; } + if (i < h - 1) { v += m[i + 1][j].voltage; n++; } + if (j < w - 1) { v += m[i][j + 1].voltage; n++; } v = m[i][j].voltage - v / n; } d[i][j].voltage = v; - if (m[i][j].fixed == Node.Kind.free) + if (m[i][j].kindGet == Node.Kind.free) total += v ^^ 2; } + } return total; } @@ -49,16 +51,16 @@ Node.FP iter(size_t w, size_t h)(ref Node[w][h] m) pure nothrow { enforceBoundaryConditions(m); if (calcDifference(m, difference) < differenceThreshold) break; - foreach (i, const(Node[]) di; difference) - foreach (j, ref const(Node) dij; di) + foreach (immutable i, const di; difference) + foreach (immutable j, const ref dij; di) m[i][j].voltage -= dij.voltage; } Node.FP[EnumMembers!(Node.Kind).length] cur = 0.0; - foreach (i, const(Node[]) di; difference) - foreach (j, ref const(Node) dij; di) - cur[m[i][j].fixed] += dij.voltage * - (!!i + !!j + (i < h-1) + (j < w-1)); + foreach (immutable i, const di; difference) + foreach (immutable j, const ref dij; di) + cur[m[i][j].kindGet] += dij.voltage * + (!!i + !!j + (i < h-1) + (j < w-1)); return (cur[Node.Kind.A] - cur[Node.Kind.B]) / 2.0; } @@ -72,5 +74,5 @@ void main() { mesh[1][1] = Node( 1.0, Node.Kind.A); mesh[6][7] = Node(-1.0, Node.Kind.B); - writefln("R = %.19f", 2 / iter(mesh)); + writefln("R = %.19f", 2 / mesh.iter); } diff --git a/Task/Resistor-mesh/Octave/resistor-mesh.octave b/Task/Resistor-mesh/Octave/resistor-mesh.octave new file mode 100644 index 0000000000..4733e274eb --- /dev/null +++ b/Task/Resistor-mesh/Octave/resistor-mesh.octave @@ -0,0 +1,40 @@ +N = 10; +NN = N*N; +G = sparse(NN, NN); + +node = 0; +for row=1:N; + for col=1:N; + node++; + if row > 1 + G(node, node)++; + G(node, node - N) = -1; + end + if row < N; + G(node, node)++; + G(node, node + N) = -1; + end + if col > 1 + G(node, node)++; + G(node, node - 1) = -1; + end + if col < N; + G(node, node)++; + G(node, node + 1) = -1; + end + end +end + +current = sparse(NN, 1); + +Ar = 2; Ac = 2; A = Ac + N*( Ar - 1 ); +Br = 7; Bc = 8; B = Bc + N*( Br - 1 ); +current( A ) = -1; +current( B ) = +1; + +voltage = G \ current; + +VA = voltage( A ); +VB = voltage( B ); + +full( abs( VA - VB ) ) diff --git a/Task/Resistor-mesh/Python/resistor-mesh.py b/Task/Resistor-mesh/Python/resistor-mesh-1.py similarity index 100% rename from Task/Resistor-mesh/Python/resistor-mesh.py rename to Task/Resistor-mesh/Python/resistor-mesh-1.py diff --git a/Task/Resistor-mesh/Python/resistor-mesh-2.py b/Task/Resistor-mesh/Python/resistor-mesh-2.py new file mode 100644 index 0000000000..a7eea55d09 --- /dev/null +++ b/Task/Resistor-mesh/Python/resistor-mesh-2.py @@ -0,0 +1,71 @@ +import sys, copy +from fractions import Fraction + +def gauss(a, b): + n, p = len(a), len(a[0]) + for i in range(n): + t = abs(a[i][i]) + k = i + for j in range(i + 1, n): + if abs(a[j][i]) > t: + t = abs(a[j][i]) + k = j + if k != i: + for j in range(i, n): + a[i][j], a[k][j] = a[k][j], a[i][j] + b[i], b[k] = b[k], b[i] + t = 1/a[i][i] + for j in range(i + 1, n): + a[i][j] *= t + b[i] *= t + for j in range(i + 1, n): + t = a[j][i] + for k in range(i + 1, n): + a[j][k] -= t*a[i][k] + b[j] -= t * b[i] + for i in range(n - 1, -1, -1): + for j in range(i): + b[j] -= a[j][i]*b[i] + return b + +def resistor_grid(p, q, ai, aj, bi, bj): + n = p*q + I = Fraction(1, 1) + v = [0*I]*n + a = [copy.copy(v) for i in range(n)] + for i in range(p): + for j in range(q): + k = i*q + j + if i == ai and j == aj: + a[k][k] = I + else: + c = 0 + if i + 1 < p: + c += 1 + a[k][k + q] = -1 + if i >= 1: + c += 1 + a[k][k - q] = -1 + if j + 1 < q: + c += 1 + a[k][k + 1] = -1 + if j >= 1: + c += 1 + a[k][k - 1] = -1 + a[k][k] = c*I + b = [0*I]*n + k = bi*q + bj + b[k] = 1 + return gauss(a, b)[k] + +def main(arg): + r = resistor_grid(int(arg[0]), int(arg[1]), int(arg[2]), int(arg[3]), int(arg[4]), int(arg[5])) + print(r) + print(float(r)) + +main(sys.argv[1:]) + +# Output: +# python grid.py 10 10 1 1 7 6 +# 455859137025721/283319837425200 +# 1.6089912417307297 diff --git a/Task/Resistor-mesh/REXX/resistor-mesh.rexx b/Task/Resistor-mesh/REXX/resistor-mesh.rexx index c692e76121..b973a36fd9 100644 --- a/Task/Resistor-mesh/REXX/resistor-mesh.rexx +++ b/Task/Resistor-mesh/REXX/resistor-mesh.rexx @@ -1,36 +1,36 @@ /*REXX pgm calculates resistance between any 2 points on a resister grid*/ numeric digits 20 /*use moderate digits (precision)*/ -minVal=(1'e-'||(digits()*2)) / 1 /*calculate the threshold min val*/ +minVal = (1'e-' || (digits()*2)) / 1 /*calculate the threshold min val*/ if 1=='f1'x then ohms = 'ohms' /*EBCDIC machine? Use 'ohms'. */ else ohms = 'ea'x /* ASCII machine? Use Greek Ω.*/ -parse arg wide high Arow Acol Brow Bcol . -say 'minVal = ' format(minVal,,,,0) ; say -say 'resistor mesh is of size: ' wide "wide, " high 'high.' ; say +parse arg high wide Arow Acol Brow Bcol . +say 'minVal = ' format(minVal,,,,0) ; say +say 'resistor mesh is of size: ' wide "wide, " high 'high.' ; say say 'point A is at (row,col): ' Arow","Acol say 'point B is at (row,col): ' Brow","Bcol -@.=0; cell.=1 +@.=0; cell.=1 do until $ <= minVal; $=0; v = 0 @.Arow.Acol = +1 ; cell.Arow.Acol = 0 @.Brow.Bcol = -1 ; cell.Brow.Bcol = 0 - do i =1 for high; im=i-1; ip=i+1 - do j=1 for wide; jm=j-1; jp=j+1; n=0; v=0 - if i\==1 then do; v=v+@.im.j; n=n+1; end - if j\==1 then do; v=v+@.i.jm; n=n+1; end - if i", rev(s) +} diff --git a/Task/Reverse-a-string/Aime/reverse-a-string.aime b/Task/Reverse-a-string/Aime/reverse-a-string.aime index b4e1888a13..ff25141035 100644 --- a/Task/Reverse-a-string/Aime/reverse-a-string.aime +++ b/Task/Reverse-a-string/Aime/reverse-a-string.aime @@ -7,7 +7,7 @@ reverse(text s) i = length(s); while (i) { i -= 1; - b_insert(b, -1, character(s, i)); + b_insert(b, -1, s[i]); } return b_string(b); diff --git a/Task/Reverse-a-string/Dart/reverse-a-string-1.dart b/Task/Reverse-a-string/Dart/reverse-a-string-1.dart new file mode 100644 index 0000000000..8676f483af --- /dev/null +++ b/Task/Reverse-a-string/Dart/reverse-a-string-1.dart @@ -0,0 +1 @@ +String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed); diff --git a/Task/Reverse-a-string/Dart/reverse-a-string-2.dart b/Task/Reverse-a-string/Dart/reverse-a-string-2.dart new file mode 100644 index 0000000000..c2ffbc5022 --- /dev/null +++ b/Task/Reverse-a-string/Dart/reverse-a-string-2.dart @@ -0,0 +1,17 @@ +import 'package:unittest/unittest.dart'; + +String reverse(String s) => new String.fromCharCodes(s.runes.toList().reversed); + +main() { + group("Reverse a string -", () { + test("Strings with ASCII characters are reversed correctly.", () { + expect(reverse("hello, world"), equals("dlrow ,olleh")); + }); + test("Strings with non-ASCII BMP characters are reversed correctly.", () { + expect(reverse("\u4F60\u4EEC\u597D"), equals("\u597D\u4EEC\u4F60")); + }); + test("Strings with non-BMP characters are reversed correctly.", () { + expect(reverse("hello, \u{1F310}"), equals("\u{1F310} ,olleh")); + }); + }); +} diff --git a/Task/Reverse-a-string/Dart/reverse-a-string.dart b/Task/Reverse-a-string/Dart/reverse-a-string.dart deleted file mode 100644 index e9ec208922..0000000000 --- a/Task/Reverse-a-string/Dart/reverse-a-string.dart +++ /dev/null @@ -1,11 +0,0 @@ -String reverse(String s) { - StringBuffer sb=new StringBuffer(); - for(int i=s.length-1;i>=0;i--) { - sb.add(s[i]); - } - return sb.toString(); -} - -main() { - print(reverse('a string.')); -} diff --git a/Task/Reverse-a-string/Elixir/reverse-a-string.elixir b/Task/Reverse-a-string/Elixir/reverse-a-string.elixir new file mode 100644 index 0000000000..a34803b0f8 --- /dev/null +++ b/Task/Reverse-a-string/Elixir/reverse-a-string.elixir @@ -0,0 +1,2 @@ +IO.puts (String.reverse "asdf") +IO.puts (String.reverse "as⃝df̅") diff --git a/Task/Reverse-a-string/JavaScript/reverse-a-string.js b/Task/Reverse-a-string/JavaScript/reverse-a-string.js index 344ca8e062..84f953d4e8 100644 --- a/Task/Reverse-a-string/JavaScript/reverse-a-string.js +++ b/Task/Reverse-a-string/JavaScript/reverse-a-string.js @@ -1,3 +1,18 @@ -var a = "cat".split(""); -a.reverse(); -print(a.join("")); // tac +//using chained methods +function reverseStr(s) { + return s.split('').reverse().join(''); +} + +//fast method using for loop +function reverseStr(s) { + for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { } + return o; +} + +//fast method using while loop (faster with long strings in some browsers when compared with for loop) + +function reverseStr(s) { + var i = s.length, o = ''; + while (i--) o += s[i]; + return o; +} diff --git a/Task/Reverse-a-string/Julia/reverse-a-string.julia b/Task/Reverse-a-string/Julia/reverse-a-string-1.julia similarity index 100% rename from Task/Reverse-a-string/Julia/reverse-a-string.julia rename to Task/Reverse-a-string/Julia/reverse-a-string-1.julia diff --git a/Task/Reverse-a-string/Julia/reverse-a-string-2.julia b/Task/Reverse-a-string/Julia/reverse-a-string-2.julia new file mode 100644 index 0000000000..172cb13913 --- /dev/null +++ b/Task/Reverse-a-string/Julia/reverse-a-string-2.julia @@ -0,0 +1,2 @@ +julia> join(reverse(collect(graphemes("nöel")))) +"leön" diff --git a/Task/Reverse-a-string/OOC/reverse-a-string.ooc b/Task/Reverse-a-string/OOC/reverse-a-string.ooc new file mode 100644 index 0000000000..f201c89fca --- /dev/null +++ b/Task/Reverse-a-string/OOC/reverse-a-string.ooc @@ -0,0 +1,3 @@ +main: func { + "asdf" reverse() println() // prints "fdsa" +} diff --git a/Task/Reverse-a-string/Pascal/reverse-a-string-4.pascal b/Task/Reverse-a-string/Pascal/reverse-a-string-4.pascal new file mode 100644 index 0000000000..9ae90869d1 --- /dev/null +++ b/Task/Reverse-a-string/Pascal/reverse-a-string-4.pascal @@ -0,0 +1,16 @@ +procedure revString(var s:string); +var + i,j:integer; + tmp:char; +begin + i := 1; + j := length(s); + while i b+a } +"asdf".foldRight("")((a,b) => b+a) diff --git a/Task/Reverse-a-string/Scala/reverse-a-string-3.scala b/Task/Reverse-a-string/Scala/reverse-a-string-3.scala index baacf97a84..506b25116d 100644 --- a/Task/Reverse-a-string/Scala/reverse-a-string-3.scala +++ b/Task/Reverse-a-string/Scala/reverse-a-string-3.scala @@ -1,30 +1,11 @@ -def reverseString(s: String) = { - import java.lang.Character._ - - val combiningTypes = List(NON_SPACING_MARK, ENCLOSING_MARK, COMBINING_SPACING_MARK) - def isCombiningCharacter(c: Char) = combiningTypes contains c.getType - def isCombiningSurrogate(high: Char, low: Char) = combiningTypes contains getType(toCodePoint(high, low)) - def isCombining(l: List[Char]) = l match { - case List(a, b) => isCombiningSurrogate(a, b) - case List(a) => isCombiningCharacter(a) - case Nil => true - case _ => throw new IllegalArgumentException("isCombining expects a list of up to two characters") +def reverse(s: String) = { + import java.text.{Normalizer,BreakIterator} + val norm = Normalizer.normalize(s, Normalizer.Form.NFKC) // waffle -> waffle (optional) + val it = BreakIterator.getCharacterInstance + it setText norm + def break(it: BreakIterator, prev: Int, result: List[String] = Nil): List[String] = it.next match { + case BreakIterator.DONE => result + case cur => break(it, cur, norm.substring(prev, cur) :: result) } - - def cleanSurrogate(l: List[Char]) = l match { - case List(a, b) if a.isHighSurrogate && b.isLowSurrogate => l - case List(a, b) if a.isLowSurrogate => Nil - case List(a, b) => List(a) - case _ => throw new IllegalArgumentException("cleanSurrogate expects lists of two characters, exactly") - } - - def splitString(string: String) = (string+" ").iterator sliding 2 map (_.toList) map cleanSurrogate toList - - def recurse(fwd: List[List[Char]], rev: List[Char]): String = fwd match { - case Nil => rev.mkString - case c :: rest => - val (combining, remaining) = rest span isCombining - recurse(remaining, c ::: combining.foldLeft(List[Char]())(_ ::: _) ::: rev) - } - recurse(splitString(s), Nil) + break(it, it.first).mkString } diff --git a/Task/Reverse-a-string/Scala/reverse-a-string-4.scala b/Task/Reverse-a-string/Scala/reverse-a-string-4.scala new file mode 100644 index 0000000000..baacf97a84 --- /dev/null +++ b/Task/Reverse-a-string/Scala/reverse-a-string-4.scala @@ -0,0 +1,30 @@ +def reverseString(s: String) = { + import java.lang.Character._ + + val combiningTypes = List(NON_SPACING_MARK, ENCLOSING_MARK, COMBINING_SPACING_MARK) + def isCombiningCharacter(c: Char) = combiningTypes contains c.getType + def isCombiningSurrogate(high: Char, low: Char) = combiningTypes contains getType(toCodePoint(high, low)) + def isCombining(l: List[Char]) = l match { + case List(a, b) => isCombiningSurrogate(a, b) + case List(a) => isCombiningCharacter(a) + case Nil => true + case _ => throw new IllegalArgumentException("isCombining expects a list of up to two characters") + } + + def cleanSurrogate(l: List[Char]) = l match { + case List(a, b) if a.isHighSurrogate && b.isLowSurrogate => l + case List(a, b) if a.isLowSurrogate => Nil + case List(a, b) => List(a) + case _ => throw new IllegalArgumentException("cleanSurrogate expects lists of two characters, exactly") + } + + def splitString(string: String) = (string+" ").iterator sliding 2 map (_.toList) map cleanSurrogate toList + + def recurse(fwd: List[List[Char]], rev: List[Char]): String = fwd match { + case Nil => rev.mkString + case c :: rest => + val (combining, remaining) = rest span isCombining + recurse(remaining, c ::: combining.foldLeft(List[Char]())(_ ::: _) ::: rev) + } + recurse(splitString(s), Nil) +} diff --git a/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg b/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg new file mode 100644 index 0000000000..5b607e0ee1 --- /dev/null +++ b/Task/Rock-paper-scissors/ALGOL-68/rock-paper-scissors.alg @@ -0,0 +1,153 @@ +main: ( + +# rock/paper/scissors game # + +# counts of the number of times the player has chosen each move # +# we initialise each to 1 so that the total isn't zero when we are # +# choosing the computer's first move (as in the Ada version) # +INT r count := 1; +INT p count := 1; +INT s count := 1; + +# counts of how many games the player and computer have won # +INT player count := 0; +INT computer count := 0; + +print( ( "rock/paper/scissors", newline, newline ) ); + +WHILE + + CHAR player move; + + # get the players move - r => rock # + # p => paper # + # s => scissors # + # q => quit # + + WHILE + print( ( "Please enter your move (r/p/s) or q to quit: " ) ); + readf( ( $ a $, player move ) ); + read( ( newline ) ); + + ( player move /= "r" + AND player move /= "p" + AND player move /= "s" + AND player move /= "q" + ) + DO + print( ( "Unrecognised move", newline ) ) + OD; + + # continue playing until the player chooses quit # + player move /= "q" + +DO + + # decide the computer's move based on the player's history # + + CHAR computer move; + + INT move count = r count + p count + s count; + + # predict player will play rock if the random number # + # is in the range 0 .. rock / total # + # predict player will play paper if the random number # + # is in the range rock / total .. ( rock + paper ) / total # + # predict player will play scissors otherwise # + + REAL r limit = r count / move count; + REAL p limit = r limit + ( p count / move count ); + + REAL random move = next random; + + IF random move < r limit + THEN + # we predict the player will choose rock - we choose paper # + computer move := "p" + + ELIF random move < p limit + THEN + # we predict the player will choose paper - we choose scissors # + computer move := "s" + + ELSE + # we predict the player will choose scissors - we choose rock # + computer move := "r" + + FI; + + print( ( "You chose: " + player move, newline ) ); + print( ( "I chose: " + computer move, newline ) ); + + IF player move = computer move + THEN + # both players chose the same - draw # + print( ( "We draw", newline ) ) + + ELSE + # players chose different moves - there is a winner # + + BOOL player wins; + + IF player move = "r" + THEN + # player chose rock - rock blunts scissors # + # but is wrapped by paper # + player wins := ( computer move = "s" ) + + ELIF player move = "p" + THEN + # player chose paper - paper wraps rock # + # but is cut by scissors # + player wins := ( computer move = "r" ) + + ELSE + # player chose scissors - scissors cut paper # + # but are blunted by rock # + player wins := ( computer move = "p" ) + + FI; + + IF player wins + THEN + player count +:= 1; + print( ( "You win", newline ) ) + + ELSE + computer count +:= 1; + print( ( "I win", newline ) ) + FI; + + print( ( ( "You won: " + + whole( player count , 0 ) + + ", I won: " + + whole( computer count, 0 ) + ) + , newline + ) + ) + + + FI; + + IF player move = "r" + THEN + # player chose rock # + r count +:= 1 + + ELIF player move = "p" + THEN + # player chose paper # + p count +:= 1 + + ELSE + # player chose scissors # + s count +:= 1 + + FI + +OD; + +print( ( "Thanks for a most enjoyable game", newline ) ) + +) diff --git a/Task/Rock-paper-scissors/BASIC/rock-paper-scissors.basic b/Task/Rock-paper-scissors/BASIC/rock-paper-scissors.basic new file mode 100644 index 0000000000..e2f1580179 --- /dev/null +++ b/Task/Rock-paper-scissors/BASIC/rock-paper-scissors.basic @@ -0,0 +1,62 @@ +DIM pPLchoice(1 TO 3) AS INTEGER, pCMchoice(1 TO 3) AS INTEGER +DIM choices(1 TO 3) AS STRING +DIM playerwins(1 TO 3) AS INTEGER +DIM playerchoice AS INTEGER, compchoice AS INTEGER +DIM playerwon AS INTEGER, compwon AS INTEGER, tie AS INTEGER +DIM tmp AS INTEGER + +' Do it this way for QBasic; FreeBASIC supports direct array assignment. +DATA "rock", "paper", "scissors" +FOR tmp = 1 to 3 + READ choices(tmp) +NEXT +DATA 3, 1, 2 +FOR tmp = 1 to 3 + READ playerwins(tmp) +NEXT + +RANDOMIZE TIMER + +DO + ' Computer chooses first to ensure there's no "cheating". + compchoice = INT(RND * (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 3)) + SELECT CASE compchoice + CASE 0 to (pPLchoice(1)) + ' Player past choice: rock; choose paper. + compchoice = 2 + CASE (pPLchoice(1) + 1) TO (pPLchoice(1) + pPLchoice(2) + 1) + ' Player past choice: paper; choose scissors. + compchoice = 3 + CASE (pPLchoice(1) + pPLchoice(2) + 2) TO (pPLchoice(1) + pPLchoice(2) + pPLchoice(3) + 2) + ' Player past choice: scissors; choose rock. + compchoice = 1 + END SELECT + + PRINT "Rock, paper, or scissors "; + DO + PRINT "[1 = rock, 2 = paper, 3 = scissors, 0 to quit]"; + INPUT playerchoice + LOOP WHILE (playerchoice < 0) OR (playerchoice > 3) + + IF 0 = playerchoice THEN EXIT DO + + pCMchoice(compchoice) = pCMchoice(compchoice) + 1 + pPLchoice(playerchoice) = pPLchoice(playerchoice) + 1 + PRINT "You chose "; choices(playerchoice); " and I chose "; choices(compchoice); ". "; + IF (playerchoice) = compchoice THEN + PRINT "Tie!" + tie = tie + 1 + ELSEIF (compchoice) = playerwins(playerchoice) THEN + PRINT "You won!" + playerwon = playerwon + 1 + ELSE + PRINT "I won!" + compwon = compwon + 1 + END IF +LOOP + +PRINT "Some useless statistics:" +PRINT "You won "; STR$(playerwon); " times, and I won "; STR$(compwon); " times; "; STR$(tie); " ties." +PRINT , choices(1), choices(2), choices(3) +PRINT "You chose:", pPLchoice(1), pPLchoice(2), pPLchoice(3) +PRINT " I chose:", pCMchoice(1), pCMchoice(2), pCMchoice(3) diff --git a/Task/Rock-paper-scissors/C/rock-paper-scissors-2.c b/Task/Rock-paper-scissors/C/rock-paper-scissors-2.c index 2bf96d2b96..c7940317de 100644 --- a/Task/Rock-paper-scissors/C/rock-paper-scissors-2.c +++ b/Task/Rock-paper-scissors/C/rock-paper-scissors-2.c @@ -2,27 +2,102 @@ #include // other stuff #include #include -int main(int argc, const char *argv[]){ + +//This should add weighted random function to "The Elite Noob"'s code, stolen from above code because it does calculation so well +//closest I could make it to original but without pointless attempt to make code look smaller than above code by putting code on the same lines + +int rand_i(int n) +{ + int rand_max = RAND_MAX - (RAND_MAX % n); + int ret; + while ((ret = rand()) >= rand_max); + return ret/(rand_max / n); +} + +int weighed_rand(int *tbl, int len) +{ + int i, sum, r; + for (i = 0, sum = 0; i < len; sum += tbl[i++]); + if (!sum) return rand_i(len); + + r = rand_i(sum) + 1; + for (i = 0; i < len && (r -= tbl[i]) > 0; i++); + return i; +} + + + +int main(int argc, const char *argv[]) +{ + char umove[10], cmove[10], line[255]; + int user, comp; + int tbl[]={0,0,0}; + int tbllen=3; printf("Hello, Welcome to rock-paper-scissors\nBy The Elite Noob\n"); - while(1){ // infinite loop :) +mainloop: + while(1) + { // infinite loop :) printf("\n\nPlease type in 1 for Rock, 2 For Paper, 3 for Scissors, 4 to quit\n"); srand(time(NULL)); - int user, comp = (rand()%3)+1; - char line[255]; + comp = (weighed_rand(tbl, tbllen) + 1) % 3; fgets(line, sizeof(line), stdin); - while(sscanf(line, "%d", &user) != 1) { //1 match of defined specifier on input line + while(sscanf(line, "%d", &user) != 1) //1 match of defined specifier on input line + { printf("You have not entered an integer.\n"); fgets(line, sizeof(line), stdin); } - if(user != 1 && user != 2 && user != 3 && user != 4){printf("Please enter a valid number!\n");continue;} - char umove[10], cmove[10]; - if(comp == 1){strcpy(cmove, "Rock");}else if(comp == 2){strcpy(cmove, "Paper");}else{strcpy(cmove, "Scissors");} - if(user == 1){strcpy(umove, "Rock");}else if(user == 2){strcpy(umove, "Paper");}else{strcpy(umove, "Scissors");} - if(user == 4){printf("Goodbye! Thanks for playing!\n");break;} - if((comp == 1 && user == 3)||(comp == 2 && user == 1)||(comp == 3 && user == 2)){ + if( (user > 4) || (user < 1) ) + { + printf("Please enter a valid number!\n"); + continue; + } + switch (comp) + { + case 1 : + strcpy(cmove, "Rock"); + break; + case 2 : + strcpy(cmove, "Paper"); + break; + case 3 : + strcpy(cmove, "Scissors"); + break; + default : + printf("Computer Error, set comp=1\n"); + comp=1; + strcpy(cmove, "Rock"); + break; + } + switch (user) + { + case 1 : + strcpy(umove, "Rock"); + break; + case 2 : + strcpy(umove, "Paper"); + break; + case 3 : + strcpy(umove, "Scissors"); + break; + case 4 : + printf("Goodbye! Thanks for playing!\n"); + return 0; + default : + printf("Error, user number not between 1-4 exiting..."); + goto mainloop; + } + if( (user+1)%3 == comp ) + { printf("Comp Played: %s\nYou Played: %s\nSorry, You Lost!\n", cmove, umove); - }else if(comp == user){ - printf("Comp Played: %s\nYou Played: %s\nYou Tied :p\n", cmove, umove);} - else{ + } + else if(comp == user) + { + printf("Comp Played: %s\nYou Played: %s\nYou Tied :p\n", cmove, umove); + } + else + { printf("Comp Played: %s\nYou Played: %s\nYay, You Won!\n", cmove, umove); - }}return 1;} + } + tbl[user-1]++; + } +} diff --git a/Task/Rock-paper-scissors/Clojure/rock-paper-scissors.clj b/Task/Rock-paper-scissors/Clojure/rock-paper-scissors.clj new file mode 100644 index 0000000000..0a44912013 --- /dev/null +++ b/Task/Rock-paper-scissors/Clojure/rock-paper-scissors.clj @@ -0,0 +1,39 @@ +(ns rps.core + (:require [clojure.data.generators :refer [weighted]]) + (:import jline.Terminal) + (:gen-class)) + +(def what-beats {:rock :paper, :paper :scissors, :scissors :rock}) + +(defn battle [human comp] + (let [h (name human) + c (name comp)] + (cond + (= human comp) (println (format "We both picked %s. DRAW!" c)) + (= human (what-beats comp)) + (println (format "Your %s defeats computer's %s. YOU WIN!" h c)) + (= comp (what-beats human)) + (println (format "Computer's %s defeats your %s. YOU LOSE!" c h)) + :else (println (format "Wat? %s and %s ?" h c))))) + +(defn key->rps [k] + (cond + (or (= k 82) (= k 114)) :rock + (or (= k 80) (= k 112)) :paper + (or (= k 83) (= k 115)) :scissors + :else nil)) + +(defn play-game [freqs] + (println "\n(R)ock, (P)aper, (S)cissors?") + (let [term (Terminal/getTerminal) + rps (key->rps (.readCharacter term System/in))] + (if-not (nil? rps) + (do + (battle rps (what-beats (weighted freqs))) + (recur (assoc freqs rps (inc (rps freqs))))) + (println "Game Over Man! Game Over!")))) + +(defn -main + "Rock, Paper, Scissors!" + [& args] + (play-game {:rock 1, :paper 1, :scissors 1})) diff --git a/Task/Rock-paper-scissors/D/rock-paper-scissors.d b/Task/Rock-paper-scissors/D/rock-paper-scissors.d new file mode 100644 index 0000000000..91ad7670cc --- /dev/null +++ b/Task/Rock-paper-scissors/D/rock-paper-scissors.d @@ -0,0 +1,57 @@ +import std.stdio, std.random, std.string, std.conv, std.array, std.typecons; + +enum Choice { rock, paper, scissors } + +bool beats(in Choice c1, in Choice c2) pure nothrow @safe @nogc { + with (Choice) return (c1 == paper && c2 == rock) || + (c1 == scissors && c2 == paper) || + (c1 == rock && c2 == scissors); +} + +Choice genMove(in int r, in int p, in int s) @safe /*@nogc*/ { + immutable x = uniform!"[]"(1, r + p + s); + if (x < s) return Choice.rock; + if (x <= s + r) return Choice.paper; + else return Choice.scissors; +} + +Nullable!To maybeTo(To, From)(From x) pure nothrow @safe { + try { + return typeof(return)(x.to!To); + } catch (ConvException) { + return typeof(return)(); + } catch (Exception e) { + static immutable err = new Error("std.conv.to failure"); + throw err; + } +} + +void main() /*@safe*/ { + int r = 1, p = 1, s = 1; + + while (true) { + write("rock, paper or scissors? "); + immutable hs = readln.strip.toLower; + if (hs.empty) + break; + + immutable h = hs.maybeTo!Choice; + if (h.isNull) { + writeln("Wrong input: ", hs); + continue; + } + + immutable c = genMove(r, p, s); + writeln("Player: ", h.get, " Computer: ", c); + + if (beats(h, c)) writeln("Player wins\n"); + else if (beats(c, h)) writeln("Player loses\n"); + else writeln("Draw\n"); + + final switch (h.get) { + case Choice.rock: r++; break; + case Choice.paper: p++; break; + case Choice.scissors: s++; break; + } + } +} diff --git a/Task/Rock-paper-scissors/Go/rock-paper-scissors.go b/Task/Rock-paper-scissors/Go/rock-paper-scissors-1.go similarity index 100% rename from Task/Rock-paper-scissors/Go/rock-paper-scissors.go rename to Task/Rock-paper-scissors/Go/rock-paper-scissors-1.go diff --git a/Task/Rock-paper-scissors/Go/rock-paper-scissors-2.go b/Task/Rock-paper-scissors/Go/rock-paper-scissors-2.go new file mode 100644 index 0000000000..ea5e2de3e6 --- /dev/null +++ b/Task/Rock-paper-scissors/Go/rock-paper-scissors-2.go @@ -0,0 +1,257 @@ +package main + +import ( + "flag" + "fmt" + "log" + "math/rand" + "regexp" + "strings" + "time" + + "github.com/BurntSushi/toml" +) + +var help = `rps plays rock-paper-scissors with optional addition weapons. + +Usage: rps [-h] [game] + -h display help. + game is a game description file in TOML (https://github.com/mojombo/toml). + +The traditional game can be described as + +title = "Rock Paper Scissors" +win = [ + "rock breaks scissors", + "paper covers rock", + "scissors cut paper", +] + +The title is optional, it just prints out at the beginning of a game. + +The "win" list is statments where the first word wins over the last word. + +It's case sensitive so make things easy by using consistent case. +Don't use punctuation, at least not next to a first or last word. + +Additionally, you can have a "lose" key where the first word loses to the +the last, for example + +lose = ["rock falls into well"] + +To organize things with additional weapons, you can just use the winning +weapon with a list of clauses, for example + +lizard = ["poisons Spock", "eats paper"] + +The progam ignores anything in parentheses when identifying first or last +words. Examples (from RPS-101) with weapons gun, fire, and sword, + +win = [ + "gun fire(s)" + "(flaming) sword has fire" +] + +Finally, TOML is a hash, so don't duplicate keys. That means no multiple +win or lose keys. You must combine all the win statements and all the lose +statements.` + +var rps = ` +title = "Rock Paper Scissors" +win = [ + "rock breaks scissors", + "paper covers rock", + "scissors cut paper", +]` + +func main() { + h := flag.Bool("h", false, "show help") + flag.Parse() + if *h { + fmt.Println(help) + return + } + m := map[string]interface{}{} + var err error + switch flag.NArg() { + case 0: + _, err = toml.Decode(rps, &m) + case 1: + _, err = toml.DecodeFile(flag.Arg(0), &m) + default: + flag.Usage() + return + } + if err != nil { + log.Fatal(err) + } + play(parse(m)) +} + +type decision map[string]map[string]string + +type fIndex map[string]int + +func parse(m map[string]interface{}) (title string, f fIndex, d decision) { + d = decision{} + for k, v := range m { + switch t := v.(type) { + case []interface{}: + d.parseList(k, t) + case string: + if k == "title" { + title = t + } else { + log.Println("Unknown key:", k) + } + } + } + i := 0 + f = fIndex{} + for w, wl := range d { + if _, ok := f[w]; !ok { + f[w] = i + i++ + } + for l := range wl { + if _, ok := f[l]; !ok { + f[l] = i + i++ + } + } + } + for fm := range f { + if _, ok := d[fm]; !ok { + log.Println("note,", fm, "always loses!") + } + } + balanced := len(f)&1 == 1 + for _, l := range d { + if !balanced { + break + } + balanced = len(l)*2+1 == len(f) + } + if !balanced { + log.Print("note, game is unbalanced") + } + return title, f, d +} + +var r = regexp.MustCompile(`[(].*[)]`) + +func (d decision) parseList(kw string, l []interface{}) { + var ww string + for _, e := range l { + st, ok := e.(string) + if !ok { + log.Fatal("invalid", e) + } + w := strings.Fields(r.ReplaceAllLiteralString(st, "")) + if len(w) == 0 { + log.Fatalln("invalid:", kw, st) + } + lw := w[len(w)-1] + switch kw { + case "win": + ww = w[0] + case "lose": + ww, lw = lw, w[0] + default: + ww = kw + for i := 0; ; i++ { + if i == len(w) { + st = ww + " " + st + break + } + if w[i] == ww { + break + } + } + } + if lw == ww { + log.Fatalln("invalid:", st) + } + if cs, ok := d[lw][ww]; ok { + log.Fatalln("conflict:", cs, "and", st) + } + d1, ok := d[ww] + if !ok { + d1 = map[string]string{} + } + d1[lw] = st + d[ww] = d1 + } +} + +func play(title string, fx fIndex, d decision) { + rand.Seed(time.Now().Unix()) + if len(fx) == 0 { + return + } + form := make([]string, len(fx)) + for w, i := range fx { + form[i] = w + } + fmt.Println() + fmt.Println(title) + fmt.Print("Choices are ", form[0]) + for _, w := range form[1:] { + fmt.Printf(", %s", w) + } + fmt.Println(".") + fmt.Println("Enter one of these choices as your play. " + + "Anything else ends the game.") + fmt.Println("Running score shown as :") + var pw string + var aScore, pScore int + sl := 3 + wcf := make([]int, len(form)) + wct := 0 + ax := rand.Intn(len(form)) + aw := form[ax] + for { + fmt.Print("Play: ") + _, err := fmt.Scanln(&pw) + if err != nil { + break + } + px, ok := fx[pw] + if !ok { + fmt.Println(pw, "invalid.") + break + } + for f, l := range d { + if _, ok := l[pw]; ok { + wcf[fx[f]]++ + wct++ + } + } + + fmt.Printf("My play:%s%s.\n", strings.Repeat(" ", sl-2), aw) + ast := d[aw][pw] + pst := d[pw][aw] + switch { + case ax == px: + fmt.Println("Tie.") + case ast > "" && pst > "": + log.Fatalln("conflict: ", ast, "and", pst) + case ast > "": + fmt.Printf("%s. My point.\n", ast) + aScore++ + default: + fmt.Printf("%s. Your point.\n", pst) + pScore++ + } + sl, _ = fmt.Printf("%d:%d ", pScore, aScore) + ax = 0 + for rn := rand.Intn(wct); ; ax++ { + if f := wcf[ax]; rn < f { + break + } else { + rn -= f + } + } + aw = form[ax] + } +} diff --git a/Task/Rock-paper-scissors/Perl/rock-paper-scissors-1.pl b/Task/Rock-paper-scissors/Perl/rock-paper-scissors-1.pl new file mode 100644 index 0000000000..df6cccd507 --- /dev/null +++ b/Task/Rock-paper-scissors/Perl/rock-paper-scissors-1.pl @@ -0,0 +1,121 @@ +use 5.012; +use warnings; +use utf8; +use open qw(:encoding(utf-8) :std); +use Getopt::Long; + +package Game { + use List::Util qw(shuffle first); + + my $turns = 0; + my %human_choice = ( rock => 0, paper => 0, scissors => 0, ); + my %comp_choice = ( rock => 0, paper => 0, scissors => 0, ); + my %what_beats = + ( rock => 'paper', paper => 'scissors', scissors => 'rock', ); + my $comp_wins = 0; + my $human_wins = 0; + my $draws = 0; + + sub save_human_choice { + my $ch = lc pop; + if ( exists $human_choice{ $ch } ) { + ++$human_choice{ $ch }; + } + else { + die __PACKAGE__ . ":: wrong choice: '$ch'"; + } + } + + sub get_comp_choice { + my @keys = shuffle keys %human_choice; + my $ch; + my ( $prob, $rand ) = ( 0, rand ); + $ch = ( first { $rand <= ( $prob += ( $human_choice{ $_ } / $turns ) ) } @keys ) + if $turns > 0; + $ch //= $keys[0]; + $ch = $what_beats{ $ch }; + ++$comp_choice{ $ch }; + return $ch; + } + + sub make_turn { + my ( $comp_ch, $human_ch ) = ( pop(), pop() ); + ++$turns; + if ( $what_beats{ $human_ch } eq $comp_ch ) { + ++$comp_wins; + return 'I win!'; + } + elsif ( $what_beats{ $comp_ch } eq $human_ch ) { + ++$human_wins; + return 'You win!'; + } + else { + ++$draws; + return 'Draw!'; + } + } + + sub get_final_report { + my $report = + "You chose:\n" + . " rock = $human_choice{rock} times,\n" + . " paper = $human_choice{paper} times,\n" + . " scissors = $human_choice{scissors} times,\n" + . "I chose:\n" + . " rock = $comp_choice{rock} times,\n" + . " paper = $comp_choice{paper} times,\n" + . " scissors = $comp_choice{scissors} times,\n" + . "Turns: $turns\n" + . "I won: $comp_wins, you won: $human_wins, draws: $draws\n"; + return $report; + } +} + +sub main { + GetOptions( 'quiet' => \my $quiet ); + greet() if !$quiet; + while (1) { + print_next_line() if !$quiet; + my $input = get_input(); + last unless $input; + if ( $input eq 'error' ) { + print "I don't understand!\n" if !$quiet; + redo; + } + my $comp_choice = Game::get_comp_choice(); + Game::save_human_choice($input); + my $result = Game::make_turn( $input, $comp_choice ); + describe_turn_result( $input, $comp_choice, $result ) + if !$quiet; + } + print Game::get_final_report(); +} + +sub greet { + print "Welcome to the Rock-Paper-Scissors game!\n" + . "Choose 'rock', 'paper' or 'scissors'\n" + . "Enter empty line or 'quit' to quit\n"; +} + +sub print_next_line { + print 'Your choice: '; +} + +sub get_input { + my $input = <>; + print "\n" and return if !$input; # EOF + chomp $input; + return if !$input or $input =~ m/\A \s* q/xi; + return + ( $input =~ m/\A \s* r/xi ) ? 'rock' + : ( $input =~ m/\A \s* p/xi ) ? 'paper' + : ( $input =~ m/\A \s* s/xi ) ? 'scissors' + : 'error'; +} + +sub describe_turn_result { + my ( $human_ch, $comp_ch, $result ) = @_; + print "You chose \u$human_ch, I chose \u$comp_ch. $result\n"; +} + +main(); diff --git a/Task/Rock-paper-scissors/Perl/rock-paper-scissors-2.pl b/Task/Rock-paper-scissors/Perl/rock-paper-scissors-2.pl new file mode 100644 index 0000000000..82ae260dc3 --- /dev/null +++ b/Task/Rock-paper-scissors/Perl/rock-paper-scissors-2.pl @@ -0,0 +1 @@ +perl -e '@c=qw(r p s); for(1..10000){ print $c[ rand() < 0.75 ? 0 : int rand(2) + 1 ], "\n" }' | perl rps.pl --quiet diff --git a/Task/Rock-paper-scissors/Python/rock-paper-scissors.py b/Task/Rock-paper-scissors/Python/rock-paper-scissors.py index 05d91a4f21..61b61b0dbc 100644 --- a/Task/Rock-paper-scissors/Python/rock-paper-scissors.py +++ b/Task/Rock-paper-scissors/Python/rock-paper-scissors.py @@ -1,66 +1,23 @@ -#!/usr/bin/python -from random import choice, randrange -from bisect import bisect -from collections import defaultdict +from random import choice -WHATBEATS = { 'paper' : 'scissors', - 'scissors' : 'rock', - 'rock' : 'paper' } - -ORDER = ('rock', 'paper', 'scissors') - -CHOICEFREQUENCY = defaultdict(int) - -def probChoice(choices, probabilities): - total = sum(probabilities) - prob_accumulator = 0 - accumulator = [] - for p in probabilities: - prob_accumulator += p - accumulator.append(prob_accumulator) - r = randrange(total) - bsct = bisect(accumulator, r) - chc = choices[bsct] - return chc - -def checkWinner(a, b): - if b == WHATBEATS[a]: - return b - elif a == WHATBEATS[b]: - return a - - return None - -def sanitizeChoice(a): - # Drop it to lower-case - return a.lower() - -def registerPlayerChoice(choice): - CHOICEFREQUENCY[choice] += 1 - -def getRandomChoice(): - if len(CHOICEFREQUENCY) == 0: - return choice(ORDER) - choices = CHOICEFREQUENCY.keys() - probabilities = CHOICEFREQUENCY.values() - return WHATBEATS[probChoice(choices, probabilities)] +rules = {'rock': 'paper', 'scissors': 'rock', 'paper': 'scissors'} +previous = ['rock', 'paper', 'scissors'] while True: - humanChoice = raw_input() - humanChoice = sanitizeChoice(humanChoice) - if humanChoice not in ORDER: - continue + human = input('\nchoose your weapon: ') + computer = rules[choice(previous)] # choose the weapon which beats a randomly chosen weapon from "previous" - compChoice = getRandomChoice() - print "Computer picked", compChoice+",", + if human in ('quit', 'exit'): break - # Don't register the player choice until after the computer has made - # its choice. - registerPlayerChoice(humanChoice) + elif human in rules: + previous.append(human) + print('the computer played', computer, end='; ') - winner = checkWinner(humanChoice, compChoice) + if rules[computer] == human: # if what beats the computer's choice is the human's choice... + print('yay you win!') + elif rules[human] == computer: # if what beats the human's choice is the computer's choice... + print('the computer beat you... :(') + else: + print("it's a tie!") - if winner == None: - winner = "nobody" - - print winner, "wins!" + else: print("that's not a valid choice") diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx new file mode 100644 index 0000000000..4a85a226a7 --- /dev/null +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-1.rexx @@ -0,0 +1,35 @@ +/*REXX pgm plays rock─paper─scissors with a CBLF: carbon─based life form*/ +!= '────────'; err='***error!***'; @.=0 /*some pgm constants. */ +prompt=! 'Please enter one of: Rock Paper Scissors (or Quit)' +$.p='paper' ; $.s='scissors'; $.r='rock' /*computer's choices. */ +t.p=$.r ; t.s=$.p ; t.r=$.s /*thingys beats stuff.*/ +w.p=$.s ; w.s=$.r ; w.r=$.p /*stuff beats thingys.*/ +b.p='covers'; b.s='cuts' ; b.r='breaks' /*how the choice wins.*/ + + do forever; say; say prompt; say /*prompt the CBLF, get response.*/ + c=word($.p $.s $.r, random(1, 3)) /*choose the computer's 1st pick.*/ + m=max(@.r, @.p, @.s); c=w.r /*prepare to examine the history.*/ + if @.p==m then c=w.p /*emulate JC's The Amazing Karnac*/ + if @.s==m then c=w.s /* " " " " " */ + c1=left(c,1) /*C1 is used for fast comparing.*/ + parse pull u; a=strip(u) /*get the CBLF's choice (answer).*/ + upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st char*/ + ok=0 /*indicate answer isn't OK so far*/ + select /*process the CBLF's choice. */ + when words(u)==0 then say err 'nothing entered' + when words(u)>1 then say err 'too many choices: ' u + when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end + when abbrev('ROCK', a) |, + abbrev('PAPER', a) |, + abbrev('SCISSORS',a) then ok=1 /*a valid answer by CBLF.*/ + otherwise say err 'you entered a bad choice: ' u + end /*select*/ + + if \ok then iterate /*answer ¬ OK? Then get another.*/ + @.a1=@.a1+1 /*keep track of CBLF's answers. */ + say ! 'computer chose: ' c + if a1==c1 then do; say ! 'draw.'; iterate; end + if $.a1==t.c1 then say ! 'the computer wins. ' ! $.c1 b.c1 $.a1 + else say ! 'you win! ' ! $.a1 b.a1 $.c1 + end /*forever*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx new file mode 100644 index 0000000000..ab8c55e6c4 --- /dev/null +++ b/Task/Rock-paper-scissors/REXX/rock-paper-scissors-2.rexx @@ -0,0 +1,47 @@ +prompt=! 'Please enter one of: Rock Paper SCissors Lizard SPock (Vulcan) (or Quit)' +$.p='paper' ; $.s='scissors' ; $.r='rock' ; $.l='lizard' ; $.v='Spock' /*names of the thingys*/ +t.p= $.r $.v ; t.s= $.p $.l ; t.r= $.s $.l ; t.l= $.p $.v ; t.v= $.r $.s /*thingys beats stuff.*/ +w.p= $.l $.s ; w.s= $.v $.r ; w.r= $.v $.p ; w.l= $.r $.s ; w.v= $.l $.p /*stuff beats thingys.*/ +b.p='covers disproves'; b.s='cuts decapitates'; b.r='breaks crushes'; b.l='eats poisons'; b.v='vaporizes smashes' /*how the choice wins.*/ +whom.1=! 'the computer wins. ' !; whom.2=! 'you win! ' !; win=words(t.p) + + do forever; say; say prompt; say /*prompt CBLF & get response.*/ + c=word($.p $.s $.r $.l $.v',random(1,5)) /*the computer's first pick. */ + m=max(@.r,@.p,@.s,$.l,$.v) /*prepare to examine history.*/ + if @.p==m then c=word(w.p,random(1,2)) /*emulate The Amazing Karnac.*/ + if @.s==m then c=word(w.s,random(1,2)) /* " " " " */ + if @.r==m then c=word(w.r,random(1,2)) /* " " " " */ + if @.l==m then c=word(w.l,random(1,2)) /* " " " " */ + if @.v==m then c=word(w.v,random(1,2)) /* " " " " */ + c1=left(c,1) /*C1 is used for fast comparing.*/ + parse pull u; a=strip(u) /*get the CBLF's choice (answer).*/ + upper a c1 ; a1=left(a,1) /*uppercase choices, get 1st char*/ + ok=0 /*indicate answer isn't OK so far*/ + select /*process the CBLF's choice. */ + when words(u)==0 then say err 'nothing entered.' + when words(u)>1 then say err 'too many choices: ' u + when abbrev('QUIT', a) then do; say ! 'quitting.'; exit; end + when abbrev('LIZARD', a) |, + abbrev('ROCK', a) |, + abbrev('PAPER', a) |, + abbrev('Vulcan', a) |, + abbrev('SPOCK', a,2) | , + abbrev('SCISSORS',a,2) then ok=1 /*a valid CBLF answer.*/ + otherwise say err 'you entered a bad choice: ' u + end /*select*/ + + if \ok then iterate /*answer ¬ OK? Then get another.*/ + @.a1=@.a1+1 /*keep track of CBLF's answers. */ + say ! 'computer chose: ' c + if a1==c1 then do; say ! 'draw.'; iterate; end + + do who=1 for 2 /*either computer | CBLF*/ + if who==2 then parse value a1 c1 with c1 a1 + do j=1 for win + if $.a1\==word(t.c1,j) then iterate + say whom.who $.c1 word(b.c1,j) $.a1 + leave + end /*j*/ + end /*who*/ + end /*forever*/ + /*stick a fork in it, we're done.*/ diff --git a/Task/Rock-paper-scissors/REXX/rock-paper-scissors.rexx b/Task/Rock-paper-scissors/REXX/rock-paper-scissors.rexx deleted file mode 100644 index b04d9e5c15..0000000000 --- a/Task/Rock-paper-scissors/REXX/rock-paper-scissors.rexx +++ /dev/null @@ -1,36 +0,0 @@ -/*REXX pgm plays rock-paper-scissors with a CBLF (carbon-based life form*/ -!='────────'; er='***error!***'; @.=0 /*some constants for pgm*/ -z=! 'Please enter one of: Rock Paper Scissors (or Quit)' -$.p='paper'; $.s='scissors'; $.r='rock' /*computer's choices. */ -b.p=' covers '; b.s=' cuts '; b.r=' breaks ' /*how the choice wins.*/ - - do forever; say; say z; say /*prompt the CBLF & get response.*/ - c=word('rock paper scissors',random(1,3)) /*the computer's 1st pick*/ - m=max(@.r,@.p,@.s); f='paper' /*prepare to examine the history.*/ - if @.p==m then f='scissors' /*emulate JC's The Amazing Karnac*/ - if @.s==m then f='rock' /* " " " " " */ - if m\==0 then c=f /*choose based on CBLF's history.*/ - c1=left(c,1); upper c1 /*C1 is used for fast comparing.*/ - parse pull u; a=strip(u); /*get the CBLF's choice (answer).*/ - upper a; a1=left(a,1) /*uppercase answer, get 1st char.*/ - ok=0 /*indicate answer isn't OK so far*/ - select /*process the CBLF's choice. */ - when words(u)==0 then say er 'nothing entered' - when words(u)>1 then say er 'too many choices: ' u - when abbrev('QUIT',a) then do; say ! 'quitting.'; exit; end - when abbrev('ROCK',a) |, - abbrev('PAPER',a) |, - abbrev('SCISSORS',a) then ok=1 /*a valid answer by CBLF.*/ - otherwise say er 'you entered a bad choice:' u - end /*select*/ - - if \ok then iterate /*answer ¬ OK? Then get another.*/ - @.a1 = @.a1+1 /*keep track of CBLF's answers. */ - say ! 'computer chose: ' c - if a1==c1 then do; say ! 'draw.'; iterate; end - if a1=='R' & c1=='S' |, - a1=='S' & c1=='P' |, - a1=='P' & c1=='R' then say ! 'you win! ' ! $.a1 b.a1 $.c1 - else say ! 'the computer wins. ' ! $.c1 b.c1 $.a1 - end /*forever*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Rock-paper-scissors/Ruby/rock-paper-scissors.rb b/Task/Rock-paper-scissors/Ruby/rock-paper-scissors.rb index 8854039cec..5eb3488d2a 100644 --- a/Task/Rock-paper-scissors/Ruby/rock-paper-scissors.rb +++ b/Task/Rock-paper-scissors/Ruby/rock-paper-scissors.rb @@ -1,55 +1,47 @@ class RockPaperScissorsGame + CHOICES = %w[rock paper scissors quit] + BEATS = { + 'rock' => 'paper', + 'paper' => 'scissors', + 'scissors' => 'rock', + } + def initialize() - @pieces = %w[rock paper scissors] - @beats = { - 'rock' => 'paper', - 'paper' => 'scissors', - 'scissors' => 'rock', - } @plays = { - 'rock' => 1, - 'paper' => 1, + 'rock' => 1, + 'paper' => 1, 'scissors' => 1, } - @score = [0, 0] + @score = [0, 0, 0] # [0]:Human wins, [1]:Computer wins, [2]:draw play end - def humanPlay() - answer = nil + def humanPlay loop do - print "\nYour choice: #@pieces? " + print "\nYour choice: #{CHOICES}? " answer = STDIN.gets.strip.downcase next if answer.empty? - if idx = @pieces.find_index {|piece| piece.match(/^#{answer}/)} - answer = @pieces[idx] - break - else - puts "invalid answer, try again" - end + idx = CHOICES.find_index {|choice| choice.match(/^#{answer}/)} + return CHOICES[idx] if idx + puts "invalid answer, try again" end - answer end - def computerPlay() + def computerPlay total = @plays.values.reduce(:+) r = rand(total) + 1 sum = 0 - humans_choice = nil - @pieces.each do |piece| - sum += @plays[piece] - if r <= sum - humans_choice = piece - break - end + CHOICES.each do |choice| + sum += @plays[choice] + return BEATS[choice] if r <= sum end - @beats[humans_choice] end def play loop do h = humanPlay + break if h == "quit" c = computerPlay print "H: #{h}, C: #{c} => " @@ -58,16 +50,19 @@ class RockPaperScissorsGame if h == c puts "draw" - elsif h == @beats[c] + @score[2] += 1 + elsif h == BEATS[c] puts "Human wins" @score[0] += 1 else puts "Computer wins" @score[1] += 1 end - puts "score: human=#{@score[0]}, computer=#{@score[1]}" + puts "score: human=%d, computer=%d, draw=%d" % [*@score] end + @plays.each_key{|k| @plays[k] -= 1} + puts "\nhumans chose #{@plays}" end end -game = RockPaperScissorsGame.new +RockPaperScissorsGame.new diff --git a/Task/Rock-paper-scissors/Scala/rock-paper-scissors-1.scala b/Task/Rock-paper-scissors/Scala/rock-paper-scissors-1.scala new file mode 100644 index 0000000000..0c6879a694 --- /dev/null +++ b/Task/Rock-paper-scissors/Scala/rock-paper-scissors-1.scala @@ -0,0 +1,43 @@ +object RockPaperScissors extends App { + import scala.collection.mutable.LinkedHashMap + def play(beats: LinkedHashMap[Symbol,Set[Symbol]], played: scala.collection.Map[Symbol,Int]) { + val h = readLine(s"""Your move (${beats.keys mkString ", "}): """) match { + case null => println; return + case "" => return + case s => Symbol(s) + } + beats get h match { + case Some(losers) => + def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match { + case (s, i) if rand <= (accum + i) => s + case (_, i) => weighted(todo, rand, accum + i) + } + val c = weighted(played.toIterator, 1 + scala.util.Random.nextInt(played.values.sum)) match { + // choose an opponent that would beat the player's anticipated move + case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1 + } + print(s" My move: $c\n ") + c match { + case c if losers contains c => println("You won") + case c if beats(c) contains h => println("You lost") + case _ => println("We drew") // or underspecified + } + case x => println(" Unknown weapon, try again.") + } + play(beats, played get h match { + case None => played + case Some(count) => played.updated(h, count + 1) + }) + } + + def play(beats: LinkedHashMap[Symbol,Set[Symbol]]): Unit = + play(beats, beats.mapValues(_ => 1)) // init with uniform probabilities + + play(LinkedHashMap( + 'rock -> Set('lizard, 'scissors), + 'paper -> Set('rock, 'spock), + 'scissors -> Set('paper, 'lizard), + 'lizard -> Set('spock, 'paper), + 'spock -> Set('scissors, 'rock) + )) +} diff --git a/Task/Rock-paper-scissors/Scala/rock-paper-scissors-2.scala b/Task/Rock-paper-scissors/Scala/rock-paper-scissors-2.scala new file mode 100644 index 0000000000..a6b36f773c --- /dev/null +++ b/Task/Rock-paper-scissors/Scala/rock-paper-scissors-2.scala @@ -0,0 +1,60 @@ +object RockPaperScissors extends App { + def beats = Map( + 'rock -> Set('lizard, 'scissors), + 'paper -> Set('rock, 'spock), + 'scissors -> Set('paper, 'lizard), + 'lizard -> Set('spock, 'paper), + 'spock -> Set('scissors, 'rock) + ) + // init with uniform probabilities + def initPlayed = beats.mapValues(_ => 1) + def input = Symbol(readLine(s"""Your move (${beats.keys mkString ", "}): """)) + def random(max: Int) = scala.util.Random.nextInt(max) + def display(text: String) = print(text) + + def weighted(todo: Iterator[(Symbol,Int)], rand: Int, accum: Int = 0): Symbol = todo.next match { + case (s, i) if rand <= (accum + i) => s + case (_, i) => weighted(todo, rand, accum + i) + } + + def calcMyMove(random: Int => Int, played: Map[Symbol,Int]) = { + weighted(played.toIterator, 1 + random(played.values.sum)) match { + // choose an opponent that would beat the player's anticipated move + case h => beats.find{case (s, l) => l contains h}.getOrElse(beats.head)._1 + } + } + + case class Result(text: String, won: Int, lost: Int, drew: Int) { + override def toString = s"$text. Won: $won, Lost: $lost, Drew: $drew" + } + + def getResult(userWeapon: Symbol, myMove: Symbol, result: Result) = { + if (beats(userWeapon) contains myMove) + result.copy(text = "You won", won = result.won + 1) + else if (beats(myMove) contains userWeapon) + result.copy(text = "You lost", lost = result.lost + 1) + else result.copy(text = "We drew", drew = result.drew + 1) + } + + def play(input: => Symbol, display: String => Unit, random: Int => Int) + (played: Map[Symbol,Int], result: Result): Result = { + val userWeapon = input + if (userWeapon != Symbol("")) { + val newResult = if (beats contains userWeapon) { + val myMove = calcMyMove(random, played) + display(s" My move: $myMove\n ") + getResult(userWeapon, myMove, result) + } else { + result.copy(text = " Unknown weapon, try again") + } + display(newResult + "\n") + play(input, display, random)(played get userWeapon match { + case None => played + case Some(count) => played.updated(userWeapon, count + 1) + }, newResult) + } else result + } + + override def main(args: Array[String]): Unit = + play(input, display, random)(initPlayed, Result("Start", 0, 0, 0)) +} diff --git a/Task/Roman-numerals-Decode/00DESCRIPTION b/Task/Roman-numerals-Decode/00DESCRIPTION index 706c17e806..69a193e9f8 100644 --- a/Task/Roman-numerals-Decode/00DESCRIPTION +++ b/Task/Roman-numerals-Decode/00DESCRIPTION @@ -1,3 +1,5 @@ Create a function that takes a Roman numeral as its argument and returns its value as a numeric decimal integer. You don't need to validate the form of the Roman numeral. -Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. +Modern Roman numerals are written by expressing each decimal digit of the number to be encoded separately, starting with the leftmost digit and skipping any 0s. +So 1990 is rendered "MCMXC" (1000 = M, 900 = CM, 90 = XC) and 2008 is rendered "MMVIII" (2000 = MM, 8 = VIII). +The Roman numeral for 1666, "MDCLXVI", uses each letter in descending order. diff --git a/Task/Roman-numerals-Decode/Clojure/roman-numerals-decode.clj b/Task/Roman-numerals-Decode/Clojure/roman-numerals-decode.clj index 4a52f55a61..6889c95f9d 100644 --- a/Task/Roman-numerals-Decode/Clojure/roman-numerals-decode.clj +++ b/Task/Roman-numerals-Decode/Clojure/roman-numerals-decode.clj @@ -4,3 +4,11 @@ (partition-by identity) (map (partial apply +)) (reduce #(if (< %1 %2) (+ %1 %2) (- %1 %2))))) + +;; alternative +(def numerals { \I 1, \V 5, \X 10, \L 50, \C 100, \D 500, \M 1000}) +(defn from-roman [s] + (->> s .toUpperCase + (map numerals) + (reduce (fn [[sum lastv] curr] [(+ sum curr (if (< lastv curr) (* -2 lastv) 0)) curr]) [0,0]) + first)) 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 b9293e3b2b..15248919c2 100644 --- a/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d +++ b/Task/Roman-numerals-Decode/D/roman-numerals-decode-2.d @@ -1,6 +1,6 @@ import std.regex, std.algorithm; -immutable int[string] w2s; +immutable uint[string] w2s; pure nothrow static this() { w2s = ["IX": 9, "C": 100, "D": 500, "CM": 900, "I": 1, @@ -8,7 +8,7 @@ pure nothrow static this() { "V": 5, "X": 10, "IV": 4]; } -int toArabic(in string s) /*pure nothrow*/ { +uint toArabic(in string s) /*pure nothrow*/ @safe /*@nogc*/ { return s .matchAll("CM|CD|XC|XL|IX|IV|[MDCLXVI]".regex) .map!(m => w2s[m.hit]) diff --git a/Task/Roman-numerals-Decode/Eiffel/roman-numerals-decode.e b/Task/Roman-numerals-Decode/Eiffel/roman-numerals-decode.e new file mode 100644 index 0000000000..e22d150b78 --- /dev/null +++ b/Task/Roman-numerals-Decode/Eiffel/roman-numerals-decode.e @@ -0,0 +1,111 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + local + numbers: ARRAY [STRING] + do + numbers := <<"MCMXC", "MMVIII", "MDCLXVI", + -- 1990 2008 1666 + "MMMCLIX", "MCMLXXVII", "MMX">> + -- 3159 1977 2010 + across numbers as n loop + print (n.item + + " in Roman numerals is " + + roman_to_decimal (n.item).out + + " in decimal Arabic numerals.") + print ("%N") + end + end + +feature -- Roman numerals + + roman_to_decimal (a_str: STRING): INTEGER + -- Decimal representation of Roman numeral `a_str' + require + is_roman (a_str) + local + l_pos: INTEGER + cur: INTEGER -- Value of the digit read in the current iteration + prev: INTEGER -- Value of the digit read in the previous iteration + do + from + l_pos := 0 + Result := 0 + prev := 1 + max_digit_value + until + l_pos = a_str.count + loop + l_pos := l_pos + 1 + cur := roman_digit_to_decimal (a_str.at (l_pos)) + if cur <= prev then + -- Add nonincreasing digit + Result := Result + cur + else + -- Subtract previous digit from increasing digit + Result := Result - prev + (cur - prev) + end + prev := cur + end + ensure + Result >= 0 + end + + is_roman (a_string: STRING): BOOLEAN + -- Is `a_string' a valid sequence of Roman digits? + do + Result := across a_string as c all is_roman_digit (c.item) end + end + +feature {NONE} -- Implementation + + max_digit_value: INTEGER = 1000 + + is_roman_digit (a_char: CHARACTER): BOOLEAN + -- Is `a_char' a valid Roman digit? + local + l_char: CHARACTER + do + l_char := a_char.as_upper + inspect l_char + when 'I', 'V', 'X', 'L', 'C', 'D', 'M' then + Result := True + else + Result := False + end + end + + roman_digit_to_decimal (a_char: CHARACTER): INTEGER + -- Decimal representation of Roman digit `a_char' + require + is_roman_digit (a_char) + local + l_char: CHARACTER + do + l_char := a_char.as_upper + inspect l_char + when 'I' then + Result := 1 + when 'V' then + Result := 5 + when 'X' then + Result := 10 + when 'L' then + Result := 50 + when 'C' then + Result := 100 + when 'D' then + Result := 500 + when 'M' then + Result := 1000 + end + ensure + Result > 0 + end + +end diff --git a/Task/Roman-numerals-Decode/Go/roman-numerals-decode-1.go b/Task/Roman-numerals-Decode/Go/roman-numerals-decode-1.go index 2a720a779c..b2b2a11576 100644 --- a/Task/Roman-numerals-Decode/Go/roman-numerals-decode-1.go +++ b/Task/Roman-numerals-Decode/Go/roman-numerals-decode-1.go @@ -27,7 +27,7 @@ func parseRoman(s string) (r int, err error) { for i := len(is) - 1; i >= 0; i-- { // read roman digit c := is[i] - k := c == 0x305 // unicode overbar combining character + k := c == '\u0305' // unicode overbar combining character if k { if i == 0 { return 0, errors.New( @@ -39,11 +39,11 @@ func parseRoman(s string) (r int, err error) { cv := m[c] if cv == 0 { if c == 0x0305 { - return 0, errors.New(fmt.Sprintf( - "Overbar combining character invalid at position %d", i)) + return 0, fmt.Errorf( + "Overbar combining character invalid at position %d", i) } else { - return 0, errors.New(fmt.Sprintf( - "Character unrecognized as Roman digit: %c", c)) + return 0, fmt.Errorf( + "Character unrecognized as Roman digit: %c", c) } } if k { diff --git a/Task/Roman-numerals-Decode/Go/roman-numerals-decode-2.go b/Task/Roman-numerals-Decode/Go/roman-numerals-decode-2.go index a0c94bf961..3198b83225 100644 --- a/Task/Roman-numerals-Decode/Go/roman-numerals-decode-2.go +++ b/Task/Roman-numerals-Decode/Go/roman-numerals-decode-2.go @@ -2,23 +2,22 @@ package main import ( "fmt" - "strings" ) -var m = map[string]int{ - "I": 1, - "V": 5, - "X": 10, - "L": 50, - "C": 100, - "D": 500, - "M": 1000, +var m = map[rune]int{ + 'I': 1, + 'V': 5, + 'X': 10, + 'L': 50, + 'C': 100, + 'D': 500, + 'M': 1000, } // function, per task description func from_roman(roman string) (arabic int) { last_digit := 1000 - for _, r := range strings.Split(roman, "") { + for _, r := range roman { digit := m[r] if last_digit < digit { arabic -= 2 * last_digit diff --git a/Task/Roman-numerals-Decode/Python/roman-numerals-decode-2.py b/Task/Roman-numerals-Decode/Python/roman-numerals-decode-2.py index 5afb1f06d6..152c4d98d7 100644 --- a/Task/Roman-numerals-Decode/Python/roman-numerals-decode-2.py +++ b/Task/Roman-numerals-Decode/Python/roman-numerals-decode-2.py @@ -12,9 +12,3 @@ def roman_value(roman): if __name__=='__main__': for value in "MCMXC", "MMVIII", "MDCLXVI": print('%s = %i' % (value, roman_value(value))) - -""" Output: -MCMXC = 1990 -MMVIII = 2008 -MDCLXVI = 1666 -""" diff --git a/Task/Roman-numerals-Decode/R/roman-numerals-decode-1.r b/Task/Roman-numerals-Decode/R/roman-numerals-decode-1.r new file mode 100644 index 0000000000..ea771918ca --- /dev/null +++ b/Task/Roman-numerals-Decode/R/roman-numerals-decode-1.r @@ -0,0 +1,13 @@ +romanToArabic <- function(roman) { + romanLookup <- c(I=1L, V=5L, X=10L, L=50L, C=100L, D=500L, M=1000L) + rSplit <- strsplit(toupper(roman), character(0)) # Split input vector into characters + toArabic <- function(item) { + digits <- romanLookup[item] + if (length(digits) > 1L) { + smaller <- (digits[-length(digits)] < digits[-1L]) + digits[smaller] <- - digits[smaller] + } + sum(digits) + } + vapply(rSplit, toArabic, integer(1)) +} diff --git a/Task/Roman-numerals-Decode/R/roman-numerals-decode-2.r b/Task/Roman-numerals-Decode/R/roman-numerals-decode-2.r new file mode 100644 index 0000000000..e943dbfe40 --- /dev/null +++ b/Task/Roman-numerals-Decode/R/roman-numerals-decode-2.r @@ -0,0 +1 @@ +romanToArabic(c("MCMXII", "LXXXVI")) diff --git a/Task/Roman-numerals-Decode/R/roman-numerals-decode-3.r b/Task/Roman-numerals-Decode/R/roman-numerals-decode-3.r new file mode 100644 index 0000000000..48ab23d267 --- /dev/null +++ b/Task/Roman-numerals-Decode/R/roman-numerals-decode-3.r @@ -0,0 +1 @@ +as.integer(as.roman(c("MCMXII", "LXXXVI")) diff --git a/Task/Roman-numerals-Decode/Scala/roman-numerals-decode.scala b/Task/Roman-numerals-Decode/Scala/roman-numerals-decode.scala index f737b1960d..c99aeaecaf 100644 --- a/Task/Roman-numerals-Decode/Scala/roman-numerals-decode.scala +++ b/Task/Roman-numerals-Decode/Scala/roman-numerals-decode.scala @@ -9,6 +9,14 @@ def fromRoman( r:String ) : Int = { } } } +// Here is a another version that does a simple running sum: +def fromRoman2(s: String) : Int = { + val numerals = Map('I' -> 1, 'V' -> 5, 'X' -> 10, 'L' -> 50, 'C' -> 100, 'D' -> 500, 'M' -> 1000) + + s.toUpperCase.map(numerals).foldLeft((0,0)) { + case ((sum, last), curr) => (sum + curr + (if (last < curr) -2*last else 0), curr) }._1 + } +} // A small test def test( roman:String ) = println( roman + " => " + fromRoman( roman ) ) diff --git a/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-1.ss b/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-1.ss new file mode 100644 index 0000000000..5cb5adaf3c --- /dev/null +++ b/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-1.ss @@ -0,0 +1,12 @@ +(use gauche.collection) ;; for fold2 + +(define (char-val char) + (define i (string-scan "IVXLCDM" char)) + (* (expt 10 (div i 2)) (expt 5 (mod i 2)))) + +(define (decode roman) + (fold2 + (lambda (n sum prev-val) + (values ((if (< n prev-val) - +) sum n) (max n prev-val))) + 0 0 + (map char-val (reverse (string->list roman))))) diff --git a/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-2.ss b/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-2.ss new file mode 100644 index 0000000000..3a5b3a8b6a --- /dev/null +++ b/Task/Roman-numerals-Decode/Scheme/roman-numerals-decode-2.ss @@ -0,0 +1,3 @@ +(for-each + (^s (format #t "~7d: ~d\n" s (decode s))) + '("MCMLVI" "XXC" "MCMXC" "XXCIII" "IIIIX" "MIM" "LXXIIX")) diff --git a/Task/Roman-numerals-Encode/00DESCRIPTION b/Task/Roman-numerals-Encode/00DESCRIPTION index 834b23c809..93be26b833 100644 --- a/Task/Roman-numerals-Encode/00DESCRIPTION +++ b/Task/Roman-numerals-Encode/00DESCRIPTION @@ -1,3 +1,12 @@ -Create a function taking a positive integer as its parameter and returning a string containing the Roman Numeral representation of that integer. +{{omit from|GUISS}} -Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI. +Create a function taking a positive integer as its parameter +and returning a string containing the Roman Numeral representation +of that integer. + +Modern Roman numerals are written by expressing each digit separately, +starting with the left most digit and skipping any digit with a value of zero. + +In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC.
+2008 is written as 2000=MM, 8=VIII; or MMVIII.
+1666 uses each Roman symbol in descending order: MDCLXVI. diff --git a/Task/Roman-numerals-Encode/00META.yaml b/Task/Roman-numerals-Encode/00META.yaml new file mode 100644 index 0000000000..231651c1ea --- /dev/null +++ b/Task/Roman-numerals-Encode/00META.yaml @@ -0,0 +1,3 @@ +--- +category: +- String_manipulation diff --git a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-2.clj b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-2.clj index 09e2374072..a28b2b3c08 100644 --- a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-2.clj +++ b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-2.clj @@ -1,31 +1,17 @@ -(def arabic-roman-map - {1 "I", 5 "V", - 10 "X", 50 "L", - 100 "C", 500 "D", - 1000 "M", - 4 "IV", 9 "IX", - 40 "XL", 90 "XC", - 400 "CD", 900 "CM" }) +(def roman-map + (sorted-map + 1 "I", 4 "IV", 5 "V", 9 "IX", + 10 "X", 40 "XL", 50 "L", 90 "XC", + 100 "C", 400 "CD", 500 "D", 900 "CM" + 1000 "M")) -(def arabic-roman-map-sorted-keys - (sort (keys arabic-roman-map))) +(defn int->roman [n] + {:pre (integer? n)} + (loop [res (StringBuilder.), n n] + (if-let [v (roman-map n)] + (str (.append res v)) + (let [[k v] (->> roman-map keys (filter #(> n %)) last (find roman-map))] + (recur (.append res v) (- n k)))))) -(defn find-value-in-coll - [coll k] - (let [aval (find coll k)] - (if (nil? aval) "" (val aval)))) - -(defn to-roman - [result n] - (let - [closest-key-for-n (last (filter #(> n %) arabic-roman-map-sorted-keys)) - roman-value-for-n (find-value-in-coll arabic-roman-map n) - roman-value-for-closet-to-n (find-value-in-coll arabic-roman-map - closest-key-for-n)] - (if (or (<= n 0)(contains? arabic-roman-map n)) - (conj result roman-value-for-n) - (recur (conj result roman-value-for-closet-to-n) - (- n closest-key-for-n))))) - -Usage: >(to-roman [] 1999) -result: ["M" "CM" "XC" "IX"] +(int->roman 1999) +; "MCMXCIX" diff --git a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-3.clj b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-3.clj index a328e2ad8f..f1b1b495c7 100644 --- a/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-3.clj +++ b/Task/Roman-numerals-Encode/Clojure/roman-numerals-encode-3.clj @@ -1,8 +1,7 @@ -(defn a2r - [a] - (let [rv [1000 500 100 50 10 5 1] +(defn a2r [a] + (let [rv '(1000 500 100 50 10 5 1) rm (zipmap rv "MDCLXVI") - dv (->> rv (take-nth 2) next (#(interleave % %)))] + dv (->> rv (take-nth 2) next #(interleave % %))] (loop [a a rv rv dv dv r nil] (if (<= a 0) r diff --git a/Task/Roman-numerals-Encode/Eiffel/roman-numerals-encode.e b/Task/Roman-numerals-Encode/Eiffel/roman-numerals-encode.e new file mode 100644 index 0000000000..18063b7f93 --- /dev/null +++ b/Task/Roman-numerals-Encode/Eiffel/roman-numerals-encode.e @@ -0,0 +1,59 @@ +class + APPLICATION + +create + make + +feature {NONE} -- Initialization + + make + local + numbers: ARRAY [INTEGER] + do + numbers := <<1990, 2008, 1666, 3159, 1977, 2010>> + -- "MCMXC", "MMVIII", "MDCLXVI", "MMMCLIX", "MCMLXXVII", "MMX" + across numbers as n loop + print (n.item.out + " in decimal Arabic numerals is " + + decimal_to_roman (n.item) + " in Roman numerals.%N") + end + end + +feature -- Roman numerals + + decimal_to_roman (a_int: INTEGER): STRING + -- Representation of integer `a_int' as Roman numeral + require + a_int > 0 + local + dnums: ARRAY[INTEGER] + rnums: ARRAY[STRING] + + dnum: INTEGER + rnum: STRING + + i: INTEGER + do + dnums := <<1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1>> + rnums := <<"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I">> + + dnum := a_int + rnum := "" + + from + i := 1 + until + i > dnums.count or dnum <= 0 + loop + from + until + dnum < dnums[i] + loop + dnum := dnum - dnums[i] + rnum := rnum + rnums[i] + end + i := i + 1 + end + + Result := rnum + end +end diff --git a/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode.hs b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode.hs new file mode 100644 index 0000000000..1bb1ed0b84 --- /dev/null +++ b/Task/Roman-numerals-Encode/Haskell/roman-numerals-encode.hs @@ -0,0 +1,13 @@ +digit x y z k = + [[x],[x,x],[x,x,x],[x,y],[y],[y,x],[y,x,x],[y,x,x,x],[x,z]] !! + (fromInteger k - 1) + +toRoman :: Integer -> String +toRoman 0 = "" +toRoman x | x < 0 = error "Negative roman numeral" +toRoman x | x >= 1000 = 'M' : toRoman (x - 1000) +toRoman x | x >= 100 = digit 'C' 'D' 'M' q ++ toRoman r where + (q,r) = x `divMod` 100 +toRoman x | x >= 10 = digit 'X' 'L' 'C' q ++ toRoman r where + (q,r) = x `divMod` 10 +toRoman x = digit 'I' 'V' 'X' x diff --git a/Task/Roman-numerals-Encode/Maple/roman-numerals-encode.maple b/Task/Roman-numerals-Encode/Maple/roman-numerals-encode.maple new file mode 100644 index 0000000000..9087590c95 --- /dev/null +++ b/Task/Roman-numerals-Encode/Maple/roman-numerals-encode.maple @@ -0,0 +1,4 @@ +> for n in [ 1666, 1990, 2008 ] do printf( "%d\t%s\n", n, convert( n, 'roman' ) ) end: +1666 MDCLXVI +1990 MCMXC +2008 MMVIII diff --git a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-1.pl b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-1.pl index 5e3262610e..aa0de9d093 100644 --- a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-1.pl +++ b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-1.pl @@ -1,3 +1,14 @@ -per quisque in I tum C conscribementum sic - hoc tum duos multiplicamentum comementum egresso scribe. -cis +my @symbols = ( [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ); + +sub roman { + my($n, $r) = (shift, ''); + ($r, $n) = ('-', -$n) if $n < 0; # Optional handling of negative input + foreach my $s (@symbols) { + my($arabic, $roman) = @$s; + ($r, $n) = ($r .= $roman x int($n/$arabic), $n % $arabic) + if $n >= $arabic; + } + $r; +} + +say roman($_) for 1..2012; diff --git a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-2.pl b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-2.pl index 459e13a28d..5872b90eca 100644 --- a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-2.pl +++ b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-2.pl @@ -1,25 +1,2 @@ -use v5.12; -use Sub::SmartMatch; -use SmartMatch::Sugar qw(any); -use List::MoreUtils qw( natatime ); - -my %symbols = ( - 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", - 500 => "D", 1_000 => "M" -); - -my @subtractors = ( - 1_000, 100, 500, 100, 100, 10, 50, 10, 10, 1, 5, 1, 1, 0 -); - -multi roman => [0], sub { '' }; -multi roman => any, sub { - my $n = shift; - my $iter = natatime 2, @subtractors; - while( my ($cut, $minus) = $iter->() ) { - $n >= $cut - and return $symbols{$cut} . roman($n - $cut); - $n >= $cut - $minus - and return $symbols{$minus} . roman($n + $minus); - } -}; +use Math::Roman qw/roman/; +say roman($_) for 1..2012' diff --git a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-3.pl b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-3.pl index f7a00bb956..5e3262610e 100644 --- a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-3.pl +++ b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-3.pl @@ -1 +1,3 @@ -say roman($_) for 1..2_012; +per quisque in I tum C conscribementum sic + hoc tum duos multiplicamentum comementum egresso scribe. +cis diff --git a/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-4.pl b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-4.pl new file mode 100644 index 0000000000..a619c6ed02 --- /dev/null +++ b/Task/Roman-numerals-Encode/Perl/roman-numerals-encode-4.pl @@ -0,0 +1,27 @@ +use v5.12; +use Sub::SmartMatch; +use SmartMatch::Sugar qw(any); +use List::MoreUtils qw( natatime ); + +my %symbols = ( + 1 => "I", 5 => "V", 10 => "X", 50 => "L", 100 => "C", + 500 => "D", 1_000 => "M" +); + +my @subtractors = ( + 1_000, 100, 500, 100, 100, 10, 50, 10, 10, 1, 5, 1, 1, 0 +); + +multi roman => [0], sub { '' }; +multi roman => any, sub { + my $n = shift; + my $iter = natatime 2, @subtractors; + while( my ($cut, $minus) = $iter->() ) { + $n >= $cut + and return $symbols{$cut} . roman($n - $cut); + $n >= $cut - $minus + and return $symbols{$minus} . roman($n + $minus); + } +}; + +say roman($_) for 1..2_012; diff --git a/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-1.rb similarity index 100% rename from Task/Roman-numerals-Encode/Ruby/roman-numerals-encode.rb rename to Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-1.rb diff --git a/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-2.rb b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-2.rb new file mode 100644 index 0000000000..9ef28bc7ec --- /dev/null +++ b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-2.rb @@ -0,0 +1,6 @@ +Symbols = [ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ] + +def arabic_to_roman(arabic) + return '' if arabic.zero? + Symbols.each { |arabic_rep, roman_rep| return roman_rep + arabic_to_roman(arabic - arabic_rep) if arabic >= arabic_rep } +end diff --git a/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-3.rb b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-3.rb new file mode 100644 index 0000000000..a090ec06c8 --- /dev/null +++ b/Task/Roman-numerals-Encode/Ruby/roman-numerals-encode-3.rb @@ -0,0 +1,8 @@ +Symbols = [ [1000, 'M'], [900, 'CM'], [500, 'D'], [400, 'CD'], [100, 'C'], [90, 'XC'], [50, 'L'], [40, 'XL'], [10, 'X'], [9, 'IX'], [5, 'V'], [4, 'IV'], [1, 'I'] ] + +def to_roman(num) + Symbols.reduce "" do |memo, (divisor, letter)| + div, num = num.divmod(divisor) + memo + letter * div + end +end diff --git a/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust index c174b0a149..26b44eefad 100644 --- a/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust +++ b/Task/Roman-numerals-Encode/Rust/roman-numerals-encode.rust @@ -19,14 +19,14 @@ static NUMERALS: [RomanNumeral, ..13] = [ RomanNumeral {symbol: "I", value: 1} ]; -fn to_roman(num: uint) -> ~str { +fn to_roman(num: uint) -> String { for numeral in NUMERALS.iter() { if num >= numeral.value { - return numeral.symbol + to_roman(num - numeral.value); + return numeral.symbol.to_string() + to_roman(num - numeral.value); } } - return ~""; + return "".to_string(); } fn main() { diff --git a/Task/Roman-numerals-Encode/UNIX-Shell/roman-numerals-encode.sh b/Task/Roman-numerals-Encode/UNIX-Shell/roman-numerals-encode.sh new file mode 100644 index 0000000000..16febaacde --- /dev/null +++ b/Task/Roman-numerals-Encode/UNIX-Shell/roman-numerals-encode.sh @@ -0,0 +1,22 @@ +roman() { + local values=( 1000 900 500 400 100 90 50 40 10 5 4 1 ) + local roman=( + [1000]=M [900]=CM [500]=D [400]=CD + [100]=C [90]=XC [50]=L [40]=XL + [10]=X [9]=IX [5]=V [4]=IV + [1]=I + ) + local nvmber="" + local num=$1 + for value in ${values[@]}; do + while (( num >= value )); do + nvmber+=${roman[value]} + ((num -= value)) + done + done + echo $nvmber +} + +for test in 1999 24 944 1666 2008; do + printf "%d = %s\n" $test $(roman $test) +done diff --git a/Task/Roots-of-a-function/ATS/roots-of-a-function.ats b/Task/Roots-of-a-function/ATS/roots-of-a-function.ats new file mode 100644 index 0000000000..5a9aa81b68 --- /dev/null +++ b/Task/Roots-of-a-function/ATS/roots-of-a-function.ats @@ -0,0 +1,46 @@ +#include +"share/atspre_staload.hats" + +typedef d = double + +fun +findRoots +( + start: d, stop: d, step: d, f: (d) -> d, nrts: int, A: d +) : void = ( +// +if +start < stop +then let + val A2 = f(start) + var nrts: int = nrts + val () = + if A2 = 0.0 + then ( + nrts := nrts + 1; + $extfcall(void, "printf", "An exact root is found at %12.9f\n", start) + ) (* end of [then] *) + // end of [if] + val () = + if A * A2 < 0.0 + then ( + nrts := nrts + 1; + $extfcall(void, "printf", "An approximate root is found at %12.9f\n", start) + ) (* end of [then] *) + // end of [if] +in + findRoots(start+step, stop, step, f, nrts, A2) +end // end of [then] +else ( + if nrts = 0 + then $extfcall(void, "printf", "There are no roots found!\n") + // end of [if] +) (* end of [else] *) +// +) (* end of [findRoots] *) + +(* ****** ****** *) + +implement +main0 () = +findRoots (~1.0, 3.0, 0.001, lam (x) => x*x*x - 3.0*x*x + 2.0*x, 0, 0.0) diff --git a/Task/Roots-of-a-function/Go/roots-of-a-function.go b/Task/Roots-of-a-function/Go/roots-of-a-function.go index eff79c0c88..b81d1611e3 100644 --- a/Task/Roots-of-a-function/Go/roots-of-a-function.go +++ b/Task/Roots-of-a-function/Go/roots-of-a-function.go @@ -1,44 +1,37 @@ package main import ( - "fmt" - "math" -) - -func f(x float64) float64 { - return x*x*x - 3*x*x + 2*x -} - -var ( - lower float64 = -.5 - upper float64 = 2.6 - step float64 = 1 + "fmt" + "math" ) func main() { - for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step { - if x1 > upper { - x1 = upper - } - r, status := secant(x0, x1) - if status != "" && r >= x0 && r < x1 { - fmt.Printf(" %6.3f %s\n", r, status) - } - } + example := func(x float64) float64 { return x*x*x - 3*x*x + 2*x } + findroots(example, -.5, 2.6, 1) } -func secant(x0, x1 float64) (float64, string) { - var f0 float64 - f1 := f(x0) - for i := 0; i < 100; i++ { - f0, f1 = f1, f(x1) - switch { - case f1 == 0: - return x1, "exact" - case math.Abs(x1-x0) < 1e-6: - return x1, "approximate" - } - x0, x1 = x1, x1-f1*(x1-x0)/(f1-f0) - } - return 0, "" +func findroots(f func(float64) float64, lower, upper, step float64) { + for x0, x1 := lower, lower+step; x0 < upper; x0, x1 = x1, x1+step { + x1 = math.Min(x1, upper) + r, status := secant(f, x0, x1) + if status != "" && r >= x0 && r < x1 { + fmt.Printf(" %6.3f %s\n", r, status) + } + } +} + +func secant(f func(float64) float64, x0, x1 float64) (float64, string) { + var f0 float64 + f1 := f(x0) + for i := 0; i < 100; i++ { + f0, f1 = f1, f(x1) + switch { + case f1 == 0: + return x1, "exact" + case math.Abs(x1-x0) < 1e-6: + return x1, "approximate" + } + x0, x1 = x1, x1-f1*(x1-x0)/(f1-f0) + } + return 0, "" } diff --git a/Task/Roots-of-a-function/Icon/roots-of-a-function.icon b/Task/Roots-of-a-function/Icon/roots-of-a-function.icon new file mode 100644 index 0000000000..75dda199bf --- /dev/null +++ b/Task/Roots-of-a-function/Icon/roots-of-a-function.icon @@ -0,0 +1,28 @@ +procedure main() + showRoots(f, -1.0, 4, 0.002) +end + +procedure f(x) + return x^3 - 3*x^2 + 2*x +end + +procedure showRoots(f, lb, ub, step) + ox := x := lb + oy := f(x) + os := sign(oy) + while x <= ub do { + if (s := sign(y := f(x))) = 0 then write(x) + else if s ~= os then { + dx := x-ox + dy := y-oy + cx := x-dx*(y/dy) + write("~",cx) + } + (ox := x, oy := y, os := s) + x +:= step + } +end + +procedure sign(x) + return (x<0, -1) | (x>0, 1) | 0 +end diff --git a/Task/Roots-of-a-function/JavaScript/roots-of-a-function.js b/Task/Roots-of-a-function/JavaScript/roots-of-a-function.js new file mode 100644 index 0000000000..e79097b6fa --- /dev/null +++ b/Task/Roots-of-a-function/JavaScript/roots-of-a-function.js @@ -0,0 +1,30 @@ +// This function notation is sorta new, but useful here +// Part of the EcmaScript 6 Draft +// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope +var poly = (x => x*x*x - 3*x*x + 2*x); + +function sign(x) { + return (x < 0.0) ? -1 : (x > 0.0) ? 1 : 0; +} + +function printRoots(f, lowerBound, upperBound, step) { + var x = lowerBound, ox = x, + y = f(x), oy = y, + s = sign(y), os = s; + + for (; x <= upperBound ; x += step) { + s = sign(y = f(x)); + if (s == 0) { + console.log(x); + } + else if (s != os) { + var dx = x - ox; + var dy = y - oy; + var cx = x - dx * (y / dy); + console.log("~" + cx); + } + ox = x; oy = y; os = s; + } +} + +printRoots(poly, -1.0, 4, 0.002); diff --git a/Task/Roots-of-a-function/Scala/roots-of-a-function.scala b/Task/Roots-of-a-function/Scala/roots-of-a-function.scala new file mode 100644 index 0000000000..be2e3ab9ae --- /dev/null +++ b/Task/Roots-of-a-function/Scala/roots-of-a-function.scala @@ -0,0 +1,12 @@ +object RootsOfAFunction extends App { + def findRoots(fn: Double => Double, start: Double, stop: Double, step: Double, epsilon: Double) = { + for { + x <- start to stop by step + if fn(x).abs < epsilon + } yield x + } + + def fn(x: Double) = x * x * x - 3 * x * x + 2 * x + + println(findRoots(fn, -1.0, 3.0, 0.0001, 0.000000001)) +} diff --git a/Task/Roots-of-a-quadratic-function/00DESCRIPTION b/Task/Roots-of-a-quadratic-function/00DESCRIPTION index 505b94254e..189cd63840 100644 --- a/Task/Roots-of-a-quadratic-function/00DESCRIPTION +++ b/Task/Roots-of-a-quadratic-function/00DESCRIPTION @@ -26,4 +26,5 @@ Suggested by Middlebrook (D-OA), a better numerical method: to define two parame and the two roots of the quardratic are: \frac{-b}{a} f and \frac{-c}{b f} -'''Task''': do it better. This means that given a = 1, b = -10^9, and c = 1, both of the roots your program returns should be greater than 10^{-11}. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = -10^6. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of [http://dlc.sun.com/pdf/800-7895/800-7895.pdf "What Every Scientist Should Know About Floating-Point Arithmetic"] for a possible algorithm. +'''Task''': do it better. This means that given a = 1, b = -10^9, and c = 1, both of the roots your program returns should be greater than 10^{-11}. Or, if your language can't do floating-point arithmetic any more precisely than single precision, your program should be able to handle b = -10^6. Either way, show what your program gives as the roots of the quadratic in question. See page 9 of +[https://web.archive.org/web/20080921074325/http://dlc.sun.com/pdf//800-7895/800-7895.pdf "What Every Scientist Should Know About Floating-Point Arithmetic"] for a possible algorithm. 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 a855b618d7..0ca574aeab 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 @@ -5,7 +5,7 @@ CommonType!(T1, T2, T3)[] naiveQR(T1, T2, T3) pure nothrow if (isFloatingPoint!T1) { alias ReturnT = typeof(typeof(return).init[0]); if (a == 0) - return [cast(ReturnT)c / b]; // It's a linear function. + return [ReturnT(c / b)]; // It's a linear function. immutable ReturnT det = b ^^ 2 - 4 * a * c; if (det < 0) return []; // No real number root. @@ -18,7 +18,7 @@ CommonType!(T1, T2, T3)[] cautiQR(T1, T2, T3) pure nothrow if (isFloatingPoint!T1) { alias ReturnT = typeof(typeof(return).init[0]); if (a == 0) - return [cast(ReturnT)c / b]; // It's a linear function. + return [ReturnT(c / b)]; // It's a linear function. immutable ReturnT det = b ^^ 2 - 4 * a * c; if (det < 0) return []; // No real number root. diff --git a/Task/Roots-of-unity/D/roots-of-unity.d b/Task/Roots-of-unity/D/roots-of-unity.d index d60a93329c..c61df30ca9 100644 --- a/Task/Roots-of-unity/D/roots-of-unity.d +++ b/Task/Roots-of-unity/D/roots-of-unity.d @@ -1,4 +1,5 @@ -import std.stdio, std.math, std.range, std.algorithm; +import std.stdio, std.range, std.algorithm, std.complex; +import std.math: PI; auto nthRoots(in int n) pure nothrow { return n.iota.map!(k => expi(PI * 2 * (k + 1) / n)); diff --git a/Task/Roots-of-unity/PARI-GP/roots-of-unity.pari b/Task/Roots-of-unity/PARI-GP/roots-of-unity-1.pari similarity index 100% rename from Task/Roots-of-unity/PARI-GP/roots-of-unity.pari rename to Task/Roots-of-unity/PARI-GP/roots-of-unity-1.pari diff --git a/Task/Roots-of-unity/PARI-GP/roots-of-unity-2.pari b/Task/Roots-of-unity/PARI-GP/roots-of-unity-2.pari new file mode 100644 index 0000000000..93601006a6 --- /dev/null +++ b/Task/Roots-of-unity/PARI-GP/roots-of-unity-2.pari @@ -0,0 +1 @@ +nth_roots(n) = my(z);sqrtn(1,n,&z); vector(n,i, z^i); diff --git a/Task/Roots-of-unity/PARI-GP/roots-of-unity-3.pari b/Task/Roots-of-unity/PARI-GP/roots-of-unity-3.pari new file mode 100644 index 0000000000..5e622f592b --- /dev/null +++ b/Task/Roots-of-unity/PARI-GP/roots-of-unity-3.pari @@ -0,0 +1,2 @@ +sixth_root = quadgen(-3); /* 6th root of unity, exact */ +vector(6,n, sixth_root^n) /* all the 6'th roots */ diff --git a/Task/Roots-of-unity/Perl-6/roots-of-unity.pl6 b/Task/Roots-of-unity/Perl-6/roots-of-unity.pl6 index 2da09f1eba..b2c3e8d613 100644 --- a/Task/Roots-of-unity/Perl-6/roots-of-unity.pl6 +++ b/Task/Roots-of-unity/Perl-6/roots-of-unity.pl6 @@ -1,5 +1,5 @@ -sub roots_of_unity (Int $n where { $n > 0 }) { - map { exp 2i * pi/$n * $_ }, ^$n +sub roots-of-unity (Int \n where 1..*) { + map { exp 2i * pi/n * $_ }, ^n; } -printf "% .5f + % .5fi\n", .re, .im for roots_of_unity 10; +printf "%+.5f%+.5fi\n", .reals for roots-of-unity 10; diff --git a/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat b/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat new file mode 100644 index 0000000000..d54edcfc06 --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Bracmat/rosetta-code-count-examples.bracmat @@ -0,0 +1,41 @@ +( ( get-page + = + . sys$(str$("wget -q -O wget.out \"" !arg \")) + & get$("wget.out",HT ML) + ) +& get-page$"http://rosettacode.org/wiki/Category:Programming_Tasks" + : ? (table.?) ?tasklist (.table.) ? +& 0:?list +& whl + ' ( !tasklist + : ? + ( a + . (href.@(?:"/wiki/" ?href)) (title.?title) + & get-page$(str$("http://rosettacode.org/wiki/" !href)) + : ?task + & 0:?cnt + & whl + ' ( !task + : ? + ( (span.(class.mw-headline) (id.?)) + ?span + (.span.) + ?task + & !span + : ? + ( a + . (href.@(?:"/wiki/Category:" ?)) + (title.@(?:"Category:" ?)) + ) + @ + (.a.) + ? + ) + & 1+!cnt:?cnt + ) + & (!cnt.!title)+!list:?list + ) + ?tasklist + ) +& lst$(list,taskfreq,NEW) +) diff --git a/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck b/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck new file mode 100644 index 0000000000..97704ecfee --- /dev/null +++ b/Task/Rosetta-Code-Count-examples/Objeck/rosetta-code-count-examples.objeck @@ -0,0 +1,38 @@ +use HTTP; +use XML; + +class RosettaCount { + function : Main(args : String[]) ~ Nil { + taks_xml := HttpGet("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml"); + parser := XmlParser->New(taks_xml); + if(parser->Parse()) { + task_names := parser->FindElements("/api/query/categorymembers/cm"); + if(task_names <> Nil) { + each(i : task_names) { + task_name := task_names->Get(i)->As(XmlElement)->GetAttribute("title")->GetValue(); + task_url := "http://rosettacode.org/mw/index.php?title="; + task_url->Append(task_name); + task_url->Append("&action=raw"); + + task := HttpGet(task_url); + counts := task->FindAll("=={{header|"); + if(counts->Size() > 0) { + IO.Console->Print(UrlUtility->Decode(task_name))->Print(": ")->PrintLine(counts->Size()); + }; + }; + }; + }; + } + + function : HttpGet(url : String) ~ String { + xml := ""; + + client := HttpClient->New(); + lines := client->Get(url); + each(i : lines) { + xml->Append(lines->Get(i)->As(String)); + }; + + return xml; + } +} diff --git a/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala b/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala index 54e5ee53f6..824096f0f5 100644 --- a/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala +++ b/Task/Rosetta-Code-Count-examples/Scala/rosetta-code-count-examples.scala @@ -1,14 +1,25 @@ -import java.net.{URL, URLEncoder} -import scala.io.Source.fromURL +import scala.language.postfixOps -val allTasksURL = "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" -val allTasks = xml.parsing.XhtmlParser(fromURL(new URL(allTasksURL))) +object TaskCount extends App { + import java.net.{ URL, URLEncoder } + import scala.io.Source.fromURL -val regexExpr = "(?i)==\\{\\{header\\|".r -def oneTaskURL(title: String) = "http://www.rosettacode.org/w/index.php?title=%s&action=raw" format URLEncoder.encode(title.replace(' ', '_'), "UTF-8") -def count(title: String) = regexExpr findAllIn fromURL(new URL(oneTaskURL(title)))(io.Codec.UTF8).mkString length + System.setProperty("http.agent", "*") + val allTasksURL = + "http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Tasks&cmlimit=500&format=xml" + val allTasks = xml.parsing.XhtmlParser(fromURL(new URL(allTasksURL))) -val counts = for (task <- allTasks \\ "cm" \\ "@title" map (_.text)) yield scala.actors.Futures.future((task, count(task))) + val regexExpr = "(?i)==\\{\\{header\\|".r -counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println -println("\nTotal: %d examples." format (counts map (_.apply._2) sum)) + def oneTaskURL(title: String) = { + println(s"Check $title") + "http://www.rosettacode.org/w/index.php?title=%s&action=raw" format URLEncoder.encode(title.replace(' ', '_'), "UTF-8") + } + + def count(title: String) = regexExpr findAllIn fromURL(new URL(oneTaskURL(title)))(io.Codec.UTF8).mkString length + + val counts = for (task <- allTasks \\ "cm" \\ "@title" map (_.text)) yield scala.actors.Futures.future((task, count(task))) + + counts map (_.apply) map Function.tupled("%s: %d examples." format (_, _)) foreach println + println("\nTotal: %d examples." format (counts map (_.apply._2) sum)) +} diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math new file mode 100644 index 0000000000..ec82be3fcf --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-1.math @@ -0,0 +1,21 @@ +ClearAll[ImportAll] +ImportAll[lang_String] := + Module[{data, continue, cmcontinue, extra, xml, next}, + data = {}; + continue = True; + cmcontinue = ""; + While[continue, + extra = If[cmcontinue =!= "", "&cmcontinue=" <> cmcontinue, ""]; + xml = Import["http://www.rosettacode.org/w/api.php?action=query&list=categorymembers&cmtitle=Category:" <> lang <> "&cmlimit=500&format=xml" <> extra, "XML"]; + AppendTo[data, Cases[xml, XMLElement["cm", _, {}], \[Infinity]]]; + next = Flatten[Cases[xml, {"cmcontinue" -> _}, \[Infinity]]]; + If[Length[next] > 0, + next = First[next]; + cmcontinue = "cmcontinue" /. next; + , + continue = False; + ]; + ]; + Cases[Flatten[data], HoldPattern["title" -> x_] :> x, \[Infinity]] + ] +Complement[ImportAll["Programming_Tasks"], ImportAll["Mathematica"]] diff --git a/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math new file mode 100644 index 0000000000..eb66f82ff9 --- /dev/null +++ b/Task/Rosetta-Code-Find-unimplemented-tasks/Mathematica/rosetta-code-find-unimplemented-tasks-2.math @@ -0,0 +1,13 @@ +url = "http://rosettacode.org/wiki/Reports:Tasks_not_implemented_in_Mathematica"; +html = Import[url, "XMLObject"]; +pos = Position[html, XMLElement["div", {"class" -> "mw-content-ltr", "dir" -> "ltr", "lang" -> "en"}, ___]]; +pos = First[pos]; +data = Extract[html, pos]; +pos = Position[data, XMLElement["li", {}, {XMLElement["a", {"shape" -> "rect", "href" -> _, "title" -> x_}, {x_}]}]]; +data = Extract[data, pos]; +data = data[[All, -1, -1, 2]]; +data = {"title", "href"} /. # & /@ %; +data[[All, 2]] = "http://rosettacode.org" <> # & /@ data[[All, 2]]; +newb = data[[All, 1]]; +data = Hyperlink @@@ data; +data // Column diff --git a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d index 32127e6c94..3ccae7f35a 100644 --- a/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d +++ b/Task/Rosetta-Code-Fix-code-tags/D/rosetta-code-fix-code-tags-1.d @@ -1,5 +1,4 @@ -import std.stdio, std.regex; -import std.string: replace, split, format; +import std.stdio, std.regex, std.string, std.array; immutable langs = "_div abap actionscript actionscript3 ada apache applescript apt_sources asm asp autoit avisynth bash basic4gl bf 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 index ce8ec0d3b5..3d124e3dad 100644 --- 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 @@ -11,7 +11,27 @@ public class FixCodeTags 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 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 diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION index 8e3b0c36aa..a0d8d53879 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/00DESCRIPTION @@ -45,6 +45,6 @@ Sample output on March 30 2014: 40. 307 - Liberty BASIC ...
-A complete ranked listing of all '''514''' languages (from the REXX example) is included here ──► [[RC_POP.OUT]]. +A complete ranked listing of all '''548''' 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/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk b/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk index c4edb28367..7eaa25845a 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/AutoHotkey/rosetta-code-rank-languages-by-popularity.ahk @@ -1,71 +1,86 @@ -StringCaseSense, On -Progress, b2 w120 zh0 fs9, Please wait ... -Sleep, 10 +MembsUrl = http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000 +ValidUrl = http://rosettacode.org/wiki/Category:Programming_Languages +WebRequest := ComObjCreate("WinHttp.WinHttpRequest.5.1") -Link = http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000 -FileDelete, Cats.html -URLDownloadToFile, %Link%, Cats.html -FileRead, Cats, Cats.html +; Get the webpages +WebRequest.Open("GET", MembsUrl),WebRequest.Send() +MembsPage := WebRequest.ResponseText +WebRequest.Open("GET", ValidUrl),WebRequest.Send() +ValidPage := WebRequest.ResponseText -Link1 = http://rosettacode.org/wiki/Category:Programming_Languages -FileDelete, lang1.htm -URLDownloadToFile, %Link1%, Lang1.htm -FileRead, Lang1, Lang1.htm +; Replace special characters +StringReplace, MembsPage, MembsPage, ΜC++, µC++, All +StringReplace, MembsPage, MembsPage, МК-61/52, MK-61/52, All +StringReplace, ValidPage, ValidPage, ΜC++, µC++, All +StringReplace, ValidPage, ValidPage, МК-61/52, MK-61/52, All -LookFor = (\(previous 200\) \(
next 200 -RegExMatch(Lang1, LookFor, Link) ; Link2 -StringReplace, Link2, Link2, &, & +ValidREx := "s)href=""([^""]+)"" title=""Category:([^""]+)"">(?=.*
";j;"
)" +MembsREx := "title=""Category:(.+?)"">.+?\((\d+) members?\)" -FileDelete, lang2.htm -URLDownloadToFile, http://www.rosettacode.org%Link2%, Lang2.htm -FileRead, Lang2, Lang2.htm -Languages := Lang1 Lang2 +; Iterate through all matches for valid languages +ValidLangs := [], FoundPos := 0 +While FoundPos := RegExMatch(ValidPage, ValidREx, Match, FoundPos+1) + ValidLangs[Match2] := Match1 -; create list of categories with member count -Loop, Parse, Cats, `n, `r +; Iterate through all matches for categories with members +MembsLangs := [], Dupes := [], Detected := 0, FoundPos := 0 +While FoundPos := RegExMatch(MembsPage, MembsREx, Match, FoundPos+1) { - If InStr(A_LoopField, "
  • ") { - LookFor = title=\"Category:(.+?)" - RegExMatch(A_LoopField, LookFor, Name) - RegExMatch(A_LoopField, "(\d*)\smembers", Count) - CatsList .= Count1 "|" Name1 "`r`n" - } + ; If it isn't a valid language or is a duplicate, skip it + if !ValidLangs.HasKey(Match1) || Dupes.HasKey(Match1) + continue + + Dupes.Insert(Match1, true) + Detected++ + + ; Initialize this member count + if !IsObject(MembsLangs[Match2]) + MembsLangs[Match2] := [Match1] + else + MembsLangs[Match2].Insert(Match1) } -; create list of languages -RegExMatch(Languages, "(

    Subcategories

    )(.*)previous 200", Match) -LookFor =
    (.*?)(.*) -While RegExMatch(Match2, LookFor, Match) - LangList .= Match1 "`r`n" +; Sort the languages with the highest member count first +Sorted := [] +for Members, Languages in MembsLangs + Sorted.Insert(1, [Members, Languages]) -; create the final list -Loop, Parse, CatsList, `n, `r +; Initialize the GUI +Gui, New, HwndGuiHwnd +Gui, Add, Text, w300 Center, %Detected% languages detected +Gui, Add, Edit, w300 vSearchText gSearch, Filter languages +Gui, Add, ListView, w300 r20 Grid gOpen vMyListView, Rank|Members|Category + +; Populate the list view +LV_ModifyCol(1, "Integer"), LV_ModifyCol(2, "Integer"), LV_ModifyCol(3, 186) +for Rank, Languages in Sorted + for Key, Language in Languages[2] + LV_Add("", Rank, Languages[1], Language) + +Gui, Show,, Rosetta Code +return + +Open: +if (A_GuiEvent == "DoubleClick") { - StringSplit, out, A_LoopField, | - If RegExMatch(LangList, "m)^" out2 "$") - FinalList .= A_LoopField "`r`n" + LV_GetText(Language, A_EventInfo, 3) + Run, % "http://rosettacode.org" ValidLangs[Language] } +return -Sort, FinalList, RN -Gui, -MinimizeBox -Gui, Margin, 6 -Gui, Add, ListView, y10 w363 r20 Grid, Rank|Members|Category -Loop, Parse, FinalList, `n, `r -{ - If A_LoopField { - StringSplit, Item, A_LoopField, | - LV_Add("", A_Index, Item1, Item2) - } -} +Search: +GuiControlGet, SearchText +GuiControl, -Redraw, MyListView -LV_ModifyCol(1, "Integer") -LV_ModifyCol(2, "Integer") -LV_ModifyCol(3, 250) -FormatTime, Timestamp,, dd MMM yyyy -Progress, Off -Gui, Show,, Rosetta Categories - %Timestamp% -Return +LV_Delete() +for Rank, Languages in Sorted + for Key, Language in Languages[2] + if InStr(Language, SearchText) + LV_Add("", Rank, Languages[1], Language) + +GuiControl, +Redraw, MyListView +return GuiClose: - ExitApp -Return +ExitApp +return diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat b/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat new file mode 100644 index 0000000000..83bfd932bc --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Bracmat/rosetta-code-rank-languages-by-popularity.bracmat @@ -0,0 +1,91 @@ + ( get-page + = url type + . !arg:(?url.?type) + & sys$(str$("wget -q -O wget.out \"" !url \")) + & get$("wget.out",!type) { Type can be JSN, X ML, HT ML or just ML. } + ) +& ( get-langs + = arr lang + . :?arr + & !arg:? (.h2.) ?arg (h2.?) ? { Only analyse part of page between the h2 elements. } + & whl + ' ( !arg + : ? + ( a + . ? + ( title + . @(?:"Category:" ?):?lang + & !lang !arr:?arr + ) + ? + ) + ?arg + ) + & !arr + ) +& ( get-cats + = page langs list count pat li A Z + . !arg:(?page.?langs) + & 0:?list + & whl + ' ( !langs:%?lang ?langs + & { Use macro substitution to create a fast pattern. } + ' ( ? + (a.? (title.$lang) ?) { $lang is replaced by the actual language. } + ? + (.a.) + @(?:? #?count " " ?) + ) + : (=?pat) + & ( !page + : ?A + ( (li.) ?li (.li.) ?Z + & !li:!pat + ) + & !A !Z:?page { Remove found item from page. (Not necessary at all.)} + & !count + | 0 { The language has no examples. } + . + ) + \L !lang { Bracmat normalizes a\Lx+b\Ly+a\Lz to a\L(x*z)+b\Ly, so } + + !list { it's easy to collect categories with the same count. } + : ?list + ) + & !list + ) +& get-cats + $ ( get-page + $ ( "http://www.rosettacode.org/w/index.php?title=Special:Categories&limit=5000" + . HT,ML + ) + . get-langs + $ ( get-page + $ ( "http://rosettacode.org/wiki/Category:Programming_Languages" + . HT ML + ) + ) + ) + : ?cats +& :?list +& whl + ' ( !cats:(?count.)\L?tiedcats+?cats + & :?ties + & whl + ' ( !tiedcats:@(?:"Category:" ?name)*?tiedcats + & !ties !name:?ties + ) + & (!count.!ties) !list:?list + ) +& 1:?rank +& whl + ' ( !rank:?tiedRank + & !list:(?count.?ties) ?list + & whl + ' ( !ties:%?name ?ties + & @(!tiedRank:? [?len) { We want some padding for the highest ranks. } + & @(" ":? [!len ?sp) { Skip blanks up to the length of the rank. } + & out$(str$(!sp !tiedRank ". " !count " - " !name)) + & 1+!rank:?rank + ) + ) +& ; diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go b/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go index a4d7241492..cd56083abe 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Go/rosetta-code-rank-languages-by-popularity.go @@ -1,114 +1,115 @@ package main import ( - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "sort" - "strconv" - "strings" + "encoding/xml" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + "net/url" + "regexp" + "sort" + "strconv" + "strings" ) var baseQuery = "http://rosettacode.org/mw/api.php?action=query" + - "&format=xml&list=categorymembers&cmlimit=500" + "&format=xml&list=categorymembers&cmlimit=500" func req(u string, foundCm func(string)) string { - resp, err := http.Get(u) - if err != nil { - fmt.Println(err) // connection or request fail - return "" - } - defer resp.Body.Close() - for p := xml.NewDecoder(resp.Body); ; { - t, err := p.RawToken() - switch s, ok := t.(xml.StartElement); { - case err == io.EOF: - return "" - case err != nil: - fmt.Println(err) - return "" - case !ok: - continue - case s.Name.Local == "cm": - for _, a := range s.Attr { - if a.Name.Local == "title" { - foundCm(a.Value) - } - } - case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && - s.Attr[0].Name.Local == "cmcontinue": - return url.QueryEscape(s.Attr[0].Value) - } - } - return "" + resp, err := http.Get(u) + if err != nil { + log.Fatal(err) // connection or request fail + } + defer resp.Body.Close() + for p := xml.NewDecoder(resp.Body); ; { + t, err := p.RawToken() + switch s, ok := t.(xml.StartElement); { + case err == io.EOF: + return "" + case err != nil: + log.Fatal(err) + case !ok: + continue + case s.Name.Local == "cm": + for _, a := range s.Attr { + if a.Name.Local == "title" { + foundCm(a.Value) + } + } + case s.Name.Local == "categorymembers" && len(s.Attr) > 0 && + s.Attr[0].Name.Local == "cmcontinue": + return url.QueryEscape(s.Attr[0].Value) + } + } + return "" } // satisfy sort interface (reverse sorting) type pop struct { - string - int + string + int } type popList []pop func (pl popList) Len() int { return len(pl) } func (pl popList) Swap(i, j int) { pl[i], pl[j] = pl[j], pl[i] } func (pl popList) Less(i, j int) bool { - switch d := pl[i].int - pl[j].int; { - case d > 0: - return true - case d < 0: - return false - } - return pl[i].string < pl[j].string + switch d := pl[i].int - pl[j].int; { + case d > 0: + return true + case d < 0: + return false + } + return pl[i].string < pl[j].string } func main() { - // get languages, store in a map - langMap := make(map[string]bool) - storeLang := func(cm string) { - if strings.HasPrefix(cm, "Category:") { - cm = cm[9:] - } - langMap[cm] = true - } - languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages" - continueAt := req(languageQuery, storeLang) - for continueAt > "" { - continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) - } - // allocate slice for sorting - s := make(popList, 0, len(langMap)) + // get languages, store in a map + langMap := make(map[string]bool) + storeLang := func(cm string) { + if strings.HasPrefix(cm, "Category:") { + cm = cm[9:] + } + langMap[cm] = true + } + languageQuery := baseQuery + "&cmtitle=Category:Programming_Languages" + continueAt := req(languageQuery, storeLang) + for continueAt != "" { + continueAt = req(languageQuery+"&cmcontinue="+continueAt, storeLang) + } + // allocate slice for sorting + s := make(popList, 0, len(langMap)) - // get big list of categories - resp, err := http.Get("http://rosettacode.org/mw/index.php" + - "?title=Special:Categories&limit=5000") - var page []byte - if err == nil { - page, err = ioutil.ReadAll(resp.Body) - resp.Body.Close() - } - if err != nil { - fmt.Println(err) - return - } - // split out fields of interest and populate sortable slice - rx := regexp.MustCompile("
  • (.*).*[(]([0-9]+) member") - for _, sm := range rx.FindAllSubmatch(page, -1) { - ls := string(sm[1]) - if langMap[ls] { - if n, err := strconv.Atoi(string(sm[2])); err == nil { - s = append(s, pop{ls, n}) - } - } - } + // get big list of categories + resp, err := http.Get("http://rosettacode.org/mw/index.php" + + "?title=Special:Categories&limit=5000") + if err != nil { + log.Fatal(err) + } + page, err := ioutil.ReadAll(resp.Body) + resp.Body.Close() - // output - sort.Sort(s) - for i, lang := range s { - fmt.Printf("%3d. %3d - %s\n", i+1, lang.int, lang.string) - } + // split out fields of interest and populate sortable slice + rx := regexp.MustCompile("
  • (.*).*[(]([0-9]+) member") + for _, sm := range rx.FindAllSubmatch(page, -1) { + ls := string(sm[1]) + if langMap[ls] { + if n, err := strconv.Atoi(string(sm[2])); err == nil { + s = append(s, pop{ls, n}) + } + } + } + + // output + sort.Sort(s) + lastCnt, lastIdx := -1, 1 + for i, lang := range s { + if lang.int != lastCnt { + lastCnt = lang.int + lastIdx = i + 1 + } + fmt.Printf("%3d. %3d - %s\n", lastIdx, lang.int, lang.string) + } } diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck b/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck new file mode 100644 index 0000000000..a13790c030 --- /dev/null +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Objeck/rosetta-code-rank-languages-by-popularity.objeck @@ -0,0 +1,80 @@ +use HTTP; +use RegEx; +use XML; +use Collection; + +class RosettaRank { + function : Main(args : String[]) ~ Nil { + langs_xml := ""; + client := HttpClient->New(); + in := client->Get("http://rosettacode.org/mw/api.php?action=query&list=categorymembers&cmtitle=Category:Programming_Languages&cmlimit=5000&format=xml"); + each(i : in) { + langs_xml += in->Get(i)->As(String); + }; + + langs := StringSet->New(); + parser := XmlParser->New(langs_xml); + if(parser->Parse()) { + # get first item + results := parser->FindElements("/api/query/categorymembers/cm"); + each(i : results) { + element := results->Get(i)->As(XmlElement); + name := element->GetAttribute("title")->GetValue(); + offset := name->Find(':'); + if(offset > -1) { + lang := name->SubString(offset + 1, name->Size() - offset - 1); + langs->Insert(lang->ReplaceAll(" ", " ")); + }; + }; + }; + + langs_counts := IntMap->New(); + client := HttpClient->New(); + html := client->Get("http://rosettacode.org/mw/index.php?title=Special:Categories&limit=5000"); + each(i : html) { + lines := html->Get(i)->As(String); + html_elements := lines->Split("\n"); + each(j : html_elements) { + element := html_elements[j]; + name : String; count : String; + regex := RegEx->New("
  • "); + found := regex->FindFirst(element); + if(found <> Nil) { + group1 := found->Size(); + regex := RegEx->New("(\\w|\\s)+"); + found := regex->Match(element, group1); + if(found <> Nil & found->Size() > 0) { + name := found; + # skip over some junk characters + group2 := group1 + found->Size() + 10; + regex := RegEx->New("\\s\\("); + found := regex->Match(element, group2); + if(found <> Nil) { + group3 := group2 + found->Size(); + regex := RegEx->New("\\d+"); + found := regex->Match(element, group3); + if(found <> Nil & found->Size() > 0) { + count := found; + }; + }; + }; + }; + + if(name <> Nil & count <> Nil) { + if(langs->Has(name)) { + langs_counts->Insert(count->ToInt(), name); + }; + name := Nil; count := Nil; + }; + }; + }; + + keys := langs_counts->GetKeys(); + count := 1; + for(i := keys->Size() - 1; i >= 0; i -=1;) { + key := keys->Get(i); + IO.Console->Print(count)->Print(". ")->Print(key)->Print(" - ")->PrintLine(langs_counts->Find(key)->As(String)); + count += 1; + }; + } +} diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 b/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 index d74a58525f..474201cd18 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/Perl-6/rosetta-code-rank-languages-by-popularity.pl6 @@ -1,7 +1,7 @@ -shell "wget -O languages.html 'http://rosettacode.org/wiki/Category:Programming_Languages'"; -shell "wget -O categories.html 'http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000'"; +my $languages = qx{wget -O - 'http://rosettacode.org/wiki/Category:Programming_Languages'}; +my $categories = qx{wget -O - 'http://www.rosettacode.org/mw/index.php?title=Special:Categories&limit=5000'}; -my @lines = slurp('languages.html').lines; +my @lines = $languages.lines; shift @lines until @lines[0] ~~ / '

    Subcategories

    ' /; my \languages = set gather for @lines { last if / '/bodycontent' /; @@ -9,7 +9,7 @@ my \languages = set gather for @lines { / '
  • ' (.*?) '
  • ' /; } -@lines = slurp('categories.html').lines; +@lines = $categories.lines; my @results = sort -*.[0], gather for @lines { take [+$1, ~$0] if / '
  • ' diff --git a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx b/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx index 4e3240ecf5..474daa148f 100644 --- a/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx +++ b/Task/Rosetta-Code-Rank-languages-by-popularity/REXX/rosetta-code-rank-languages-by-popularity.rexx @@ -15,15 +15,18 @@ call reader 'cat' /*append to the catHeap*/ cat.j=space(cat.j); _=cat.j; upper _ /*remove excess blanks.*/ if _=='' | \L._ then iterate /*blank or ¬ a language*/ if \datatype(mems,'W') then iterate /*"members" ¬ numeric.*/ + #.0=#.0+mems /*bump #members found. */ if u._\==0 then do /*[↓] handle duplicates*/ - do f=1 for # until _==@u.f; end /*f*/ - #.f=#.f+mems; iterate j + do f=1 for # until _==@u.f + end /*f*/ + #.f=#.f+mems; iterate j end /* [↑] languages that are in different cases.*/ u._=u._+1 #=#+1; #.#=#.#+mems; @.#=cat.j; @u.#=_ /*bump counter, assign.*/ end /*j=1 until ···*/ !.= /*array holds indication of TIED.*/ -call tell right(#,9) '(total) number of languages detected.', , 1 +call tell right(comma(#) ,9) '(total) number of languages detected.' +call tell right(comma(#.0),9) '(total) number of entries detected.', , 1 call eSort #,0 /*sort the languages along with #*/ r=0 /*add true rank (tR) ──► entries.*/ tied=; do j=# by -1 for #; r=r+1; tR=r; !tR.j=r; jp=j+1; jm=j-1 @@ -36,15 +39,15 @@ tied=; do j=# by -1 for #; r=r+1; tR=r; !tR.j=r; jp=j+1; jm=j-1 call eSort #,1 /*sort the languages along with @*/ listed=0; w=length(#); rank=0 /* [↓] show by ascending rank. */ - do j=# by -1 for # while #.j>=cutoff; listed=listed+1; rank=rank+1 - call tell right('rank:' right(!tR.j,w),20-1) right(!.j,7), - right('('#.j left("entr"s(#.j,'ies',"y")')', 9),20) @.j - end /*j=# by ···*/ /* [↑] s(···) pluralizes a word*/ + do t=# by -1 for # while #.t>=cutoff; listed=listed+1; rank=rank+1 + call tell right('rank:' right(!tR.t,w),20-1) right(!.t,7), + right('('#.t left("entr"s(#.t,'ies',"y")')', 9),20) @.t + end /*t=# by ···*/ /* [↑] s(···) pluralizes a word*/ call tell left('',27) '☼ end-of-list. ☼', 1, 2 -if cutoff==0 then exit /*was there a CUTOFF speciified? */ -call tell ' Listing stopped due to a cutoff of' cutoff".", 1 -call tell listed 'language's(#) "found with number of entries ≥" cutoff,1,1 +if cutoff==0 then exit /*was there a CUTOFF specified?*/ +call tell ' Listing stopped due to a cutoff of' comma(cutoff)".", 1 +call tell listed 'language's(listed) "found with number of entries ≥" cutoff,1,1 exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────ESORT subroutine────────────────────*/ eSort: procedure expose #. @. !tr.; arg N,p2; h=N /*sort by # entries*/ @@ -76,9 +79,9 @@ old.7='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ do recs=0 while lines(inFID)\==0 /*read a file, 1 line at a time.*/ $=translate(linein(inFID),,'9'x) /*handle any stray tab characters*/ $$=space($); if $$=='' then iterate /*ignore all blank lines. */ - do k=1 while old.k\=='' /*translate Unicode variations. */ - if pos(old.k, $$) \==0 then $$=changestr(old.k, $$, new.k) - end /*k*/ /* [↑] handle different spellings*/ + do v=1 while old.v\=='' /*translate Unicode variations. */ + if pos(old.v, $$) \==0 then $$=changestr(old.v, $$, new.v) + end /*v*/ /* [↑] handle different spellings*/ if ig_ast then do; ig_ast=pos(' * ',$)==0; if ig_ast then iterate; end $u=$$; upper $u /*get an uppercase version. */ if pos('RETRIEVED FROM',$u)\==0 then leave /*a pseudo End-Of-Data.*/ @@ -92,12 +95,17 @@ old.7='??-61/52' ; new.6= 'MK-61/52' /*somewhere a mistranslated: MK- */ catHeap=catHeap $$ /*append to the (CATegory) heap. */ end /*while lines···*/ -call tell right(recs,9) 'records read from file: ' inFID +call tell right(comma(recs),9) 'records read from file: ' inFID return -/*──────────────────────────────────S subroutine────────────────────────*/ -s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*plural*/ /*──────────────────────────────────TELL subroutine─────────────────────*/ tell: do '0'arg(2); call lineout outFID,' ' ; say ; end call lineout outFID,arg(1) ; say arg(1) do '0'arg(3); call lineout outFID,' ' ; say ; end return /*show before blanks lines (if any), MSG, show after blank lines*/ +/*──────────────────────────────────one─liner subroutines───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────*/ +comma: procedure; parse arg _,c,p,t; c=pickBlank(c,","); o=p(p 3); p=abs(o); t=p(t 999999999); if \isInt(p) | \isInt(t) | p==0 | arg()>4 then return _; n=_'.9'; #=123456789; k=0; return comma_() +comma_: if o<0 then do; b=verify(_,' '); if b==0 then return _; e=length(_)-verify(reverse(_),' ')+1; end; else do; b=verify(n,#,"M"); e=verify(n,#'0',,verify(n,#"0.",'M'))-p-1; end; do j=e to b by -p while k i + (or (<= a i m) (<= A i M)) (+ 13) + (or (<= n i z) (<= N i Z)) (- 13)))))) + +(apply str (map rot-13 "The Quick Brown Fox Jumped Over The Lazy Dog!")) + +; An alternative implementation using a map: +(let [A (into #{} "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") + Am (->> (cycle A) (drop 26) (take 52) (zipmap A))] + (defn rot13 [^String in] + (apply str (map #(Am % %) in)))) + +(rot13 "The Quick Brown Fox Jumped Over The Lazy Dog!") diff --git a/Task/Rot-13/Lua/rot-13.lua b/Task/Rot-13/Lua/rot-13.lua index fe4c0a490b..2d55a69cac 100644 --- a/Task/Rot-13/Lua/rot-13.lua +++ b/Task/Rot-13/Lua/rot-13.lua @@ -1,5 +1,5 @@ -function rot(l, o) return (l < 26 and l > -1) and string.char((l+13)%26 + o) end -a, A = string.byte'a', string.byte'A' -val = io.read() -val = val:gsub("(.)", function(l) return rot(l:byte()-a,a) or rot(l:byte()-A,A) or l end) -print(val) +function rot13(s) + local a = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + local b = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm" + return (s:gsub("%a", function(c) return b:sub(a:find(c)) end)) +end diff --git a/Task/Rot-13/NewLISP/rot-13.newlisp b/Task/Rot-13/NewLISP/rot-13.newlisp new file mode 100644 index 0000000000..d7c37e5df5 --- /dev/null +++ b/Task/Rot-13/NewLISP/rot-13.newlisp @@ -0,0 +1,9 @@ +(define (rot13 str) + (join + (map + (fn(c) + (cond + ((<= "A" (upper-case c) "M") (char (+ (char c) 13))) + ((<= "N" (upper-case c) "Z") (char (- (char c) 13))) + (true c))) + (explode str)))) diff --git a/Task/Rot-13/Perl/rot-13-1.pl b/Task/Rot-13/Perl/rot-13-1.pl index ee3074a0a0..16348e6bfe 100644 --- a/Task/Rot-13/Perl/rot-13-1.pl +++ b/Task/Rot-13/Perl/rot-13-1.pl @@ -1,7 +1,5 @@ sub rot13 { - my $string = shift; - $string =~ tr/A-Za-z/N-ZA-Mn-za-m/; - return $string; + shift =~ tr/A-Za-z/N-ZA-Mn-za-m/r; } print rot13($_) while (<>); diff --git a/Task/Rot-13/Python/rot-13-1.py b/Task/Rot-13/Python/rot-13-1.py index 8feb958ea7..4babdcbb75 100644 --- a/Task/Rot-13/Python/rot-13-1.py +++ b/Task/Rot-13/Python/rot-13-1.py @@ -1,21 +1,4 @@ -#!/usr/bin/env python -import string -def rot13(s): - """Implement the rot-13 encoding function: "rotate" each letter by the - letter that's 13 steps from it (wrapping from z to a) - """ - return s.translate( - string.maketrans( - string.ascii_uppercase + string.ascii_lowercase, - string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + - string.ascii_lowercase[13:] + string.ascii_lowercase[:13] - ) - ) -if __name__ == "__main__": - """Peform line-by-line rot-13 encoding on any files listed on our - command line or act as a standard UNIX filter (if no arguments - specified). - """ - import fileinput - for line in fileinput.input(): - print rot13(line), # (Note the trailing comma; avoid double-spacing our output)! +>>> u'foo'.encode('rot13') +'sbb' +>>> 'sbb'.decode('rot13') +u'foo' diff --git a/Task/Rot-13/Python/rot-13-2.py b/Task/Rot-13/Python/rot-13-2.py index 2b433c8cac..ee0f3652da 100644 --- a/Task/Rot-13/Python/rot-13-2.py +++ b/Task/Rot-13/Python/rot-13-2.py @@ -1,21 +1,5 @@ -#!/usr/bin/env python -import string -def rot13(s): - """Implement the rot-13 encoding function: "rotate" each letter by the - letter that's 13 steps from it (wrapping from z to a) - """ - return s.translate( - str.maketrans( - string.ascii_uppercase + string.ascii_lowercase, - string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + - string.ascii_lowercase[13:] + string.ascii_lowercase[:13] - ) - ) -if __name__ == "__main__": - """Peform line-by-line rot-13 encoding on any files listed on our - command line or act as a standard UNIX filter (if no arguments - specified). - """ - import fileinput - for line in fileinput.input(): - print(rot13(line), end="") +>>> import codecs +>>> codecs.encode("The quick brown fox jumps over the lazy dog", "rot13") +'Gur dhvpx oebja sbk whzcf bire gur ynml qbt' +>>> codecs.decode(_, "rot13") +'The quick brown fox jumps over the lazy dog' diff --git a/Task/Rot-13/Python/rot-13-3.py b/Task/Rot-13/Python/rot-13-3.py new file mode 100644 index 0000000000..8feb958ea7 --- /dev/null +++ b/Task/Rot-13/Python/rot-13-3.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +import string +def rot13(s): + """Implement the rot-13 encoding function: "rotate" each letter by the + letter that's 13 steps from it (wrapping from z to a) + """ + return s.translate( + string.maketrans( + string.ascii_uppercase + string.ascii_lowercase, + string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + + string.ascii_lowercase[13:] + string.ascii_lowercase[:13] + ) + ) +if __name__ == "__main__": + """Peform line-by-line rot-13 encoding on any files listed on our + command line or act as a standard UNIX filter (if no arguments + specified). + """ + import fileinput + for line in fileinput.input(): + print rot13(line), # (Note the trailing comma; avoid double-spacing our output)! diff --git a/Task/Rot-13/Python/rot-13-4.py b/Task/Rot-13/Python/rot-13-4.py new file mode 100644 index 0000000000..2b433c8cac --- /dev/null +++ b/Task/Rot-13/Python/rot-13-4.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python +import string +def rot13(s): + """Implement the rot-13 encoding function: "rotate" each letter by the + letter that's 13 steps from it (wrapping from z to a) + """ + return s.translate( + str.maketrans( + string.ascii_uppercase + string.ascii_lowercase, + string.ascii_uppercase[13:] + string.ascii_uppercase[:13] + + string.ascii_lowercase[13:] + string.ascii_lowercase[:13] + ) + ) +if __name__ == "__main__": + """Peform line-by-line rot-13 encoding on any files listed on our + command line or act as a standard UNIX filter (if no arguments + specified). + """ + import fileinput + for line in fileinput.input(): + print(rot13(line), end="") diff --git a/Task/Rot-13/Python/rot-13-5.py b/Task/Rot-13/Python/rot-13-5.py new file mode 100644 index 0000000000..cf36434c8f --- /dev/null +++ b/Task/Rot-13/Python/rot-13-5.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python +from __future__ import print_function +import string +lets = string.ascii_lowercase +key = {x:y for (x,y) in zip(lets[13:]+lets[:14], lets)} +key.update({x.upper():key[x].upper() for x in key.keys()}) +encode = lambda x: ''.join((key.get(c,c) for c in x)) +if __name__ == '__main__': + """Peform line-by-line rot-13 encoding on any files listed on our + command line or act as a standard UNIX filter (if no arguments + specified). + """ + import fileinput + for line in fileinput.input(): + print(encode(line), end="") diff --git a/Task/Rot-13/REXX/rot-13.rexx b/Task/Rot-13/REXX/rot-13.rexx index 7add3dfbca..94031a425e 100644 --- a/Task/Rot-13/REXX/rot-13.rexx +++ b/Task/Rot-13/REXX/rot-13.rexx @@ -1,30 +1,25 @@ -/*REXX program to encode several text strings with ROT 13 algorithm. */ +/*REXX program encodes several text strings with the ROT-13 algorithm.*/ aa = 'foo' -say 'simple text = 'aa -say ' rot13 text = 'rot13(aa) -say - + say 'simple text = 'aa + say 'rot-13 text = 'rot13(aa) + say bb = 'bar' -say 'simple text = 'bb -say ' rot13 text = 'rot13(bb) -say - + say 'simple text = 'bb + say 'rot-13 text = 'rot13(bb) + say cc = "Noyr jnf V, 'rer V fnj Ryon." -say 'simple text = 'cc -say ' rot13 text = 'rot13(cc) -say - + say 'simple text = 'cc + say 'rot-13 text = 'rot13(cc) + say dd = 'abc? ABC!' -say 'simple text = 'dd -say ' rot13 text = 'rot13(dd) -say - + say 'simple text = 'dd + say 'rot-13 text = 'rot13(dd) + say ee = 'abjurer NOWHERE' -say 'simple text = 'ee -say ' rot13 text = 'rot13(ee) + say 'simple text = 'ee + say 'rot-13 text = 'rot13(ee) exit /*stick a fork in it, we're done.*/ - /*──────────────────────────────────ROT13 subroutine────────────────────*/ -rot13: return translate(arg(1),, - 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ',, - 'nopqrstuvwxyzNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLM') +rot13: return translate(arg(1), , + 'abcdefghijklmABCDEFGHIJKLMnopqrstuvwxyzNOPQRSTUVWXYZ', , + 'nopqrstuvwxyzNOPQRSTUVWXYZabcdefghijklmABCDEFGHIJKLM') diff --git a/Task/Rot-13/SQL/rot-13-1.sql b/Task/Rot-13/SQL/rot-13-1.sql new file mode 100644 index 0000000000..ae9ca105fb --- /dev/null +++ b/Task/Rot-13/SQL/rot-13-1.sql @@ -0,0 +1,6 @@ +select translate( + 'The quick brown fox jumps over the lazy dog.', + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', + 'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm' + ) + from dual; diff --git a/Task/Rot-13/SQL/rot-13.sql b/Task/Rot-13/SQL/rot-13-2.sql similarity index 100% rename from Task/Rot-13/SQL/rot-13.sql rename to Task/Rot-13/SQL/rot-13-2.sql diff --git a/Task/Rot-13/TXR/rot-13.txr b/Task/Rot-13/TXR/rot-13-1.txr similarity index 96% rename from Task/Rot-13/TXR/rot-13.txr rename to Task/Rot-13/TXR/rot-13-1.txr index 07d08b6923..59b663eee6 100644 --- a/Task/Rot-13/TXR/rot-13.txr +++ b/Task/Rot-13/TXR/rot-13-1.txr @@ -7,7 +7,7 @@ ("H" "U") ("I" "V") ("J" "W") ("K" "X") ("L" "Y") ("M" "Z") ("N" "A") ("O" "B") ("P" "C") ("Q" "D") ("R" "E") ("S" "F") ("T" "G") ("U" "H") ("V" "I") ("W" "J") ("X" "K") ("Y" "L") ("Z" "M")) -@(collect :vars ()) +@(repeat) @line @ (output :filter rot13) @line diff --git a/Task/Rot-13/TXR/rot-13-2.txr b/Task/Rot-13/TXR/rot-13-2.txr new file mode 100644 index 0000000000..9a6a390763 --- /dev/null +++ b/Task/Rot-13/TXR/rot-13-2.txr @@ -0,0 +1,9 @@ +@(do + (defun rot13 (ch) + (cond + ((<= #\A (chr-toupper ch) #\M) (+ ch 13)) + ((<= #\N (chr-toupper ch) #\Z) (- ch 13)) + (t ch))) + + (each ((l (gun (get-line nil)))) + (put-line [mapcar rot13 l]))) diff --git a/Task/Rot-13/Tcl/rot-13-1.tcl b/Task/Rot-13/Tcl/rot-13-1.tcl index 2e6801495b..007cd4b59e 100644 --- a/Task/Rot-13/Tcl/rot-13-1.tcl +++ b/Task/Rot-13/Tcl/rot-13-1.tcl @@ -6,3 +6,5 @@ proc rot13 line { N A O B P C Q D R E S F T G U H V I W J X K Y L Z M } $line } +set tx "Hello, World !" +puts "$tx : [rot13 $tx]" diff --git a/Task/Run-length-encoding/D/run-length-encoding-2.d b/Task/Run-length-encoding/D/run-length-encoding-2.d index d267d1c852..86ee12c73e 100644 --- a/Task/Run-length-encoding/D/run-length-encoding-2.d +++ b/Task/Run-length-encoding/D/run-length-encoding-2.d @@ -1,7 +1,7 @@ import std.stdio, std.array, std.conv; // Similar to the 'look and say' function. -string encode(in string input) pure /*nothrow*/ { +string encode(in string input) pure nothrow @safe { if (input.empty) return input; char last = input[$ - 1]; @@ -21,7 +21,7 @@ string encode(in string input) pure /*nothrow*/ { return count.text ~ last ~ output; } -string decode(in string input) pure { +string decode(in string input) pure /*@safe*/ { string i, result; foreach (immutable c; input) diff --git a/Task/Runtime-evaluation-In-an-environment/Bracmat/runtime-evaluation-in-an-environment.bracmat b/Task/Runtime-evaluation-In-an-environment/Bracmat/runtime-evaluation-in-an-environment.bracmat new file mode 100644 index 0000000000..3b68e49e3e --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Bracmat/runtime-evaluation-in-an-environment.bracmat @@ -0,0 +1,9 @@ +( ( eval-with-x + = code a b argument + . !arg:((=?code),?a,?b,?argument) + & (!b:?x&!code$!argument) + + -1*(!a:?x&!code$!argument) + ) +& out$(eval-with-x$((='(.$x^!arg)),3,5,2)) +& out$(eval-with-x$((='(.$x^!arg)),12,13,2)) +); diff --git a/Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment.lua b/Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-1.lua similarity index 100% rename from Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment.lua rename to Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-1.lua diff --git a/Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-2.lua b/Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-2.lua new file mode 100644 index 0000000000..dac22fc4fd --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/Lua/runtime-evaluation-in-an-environment-2.lua @@ -0,0 +1,7 @@ +env = {} +f = load("return x", nil, nil, env) +env.x = tonumber(io.read()) -- user enters 2 +a = f() +env.x = tonumber(io.read()) -- user enters 3 +b = f() +print(a + b) --> outputs 5 diff --git a/Task/Runtime-evaluation-In-an-environment/MATLAB/runtime-evaluation-in-an-environment.m b/Task/Runtime-evaluation-In-an-environment/MATLAB/runtime-evaluation-in-an-environment.m new file mode 100644 index 0000000000..dfd4d75401 --- /dev/null +++ b/Task/Runtime-evaluation-In-an-environment/MATLAB/runtime-evaluation-in-an-environment.m @@ -0,0 +1,7 @@ +function r = calcit(f, val1, val2) + x = val1; + a = eval(f); + x = val2; + b = eval(f); + r = b-a; +end diff --git a/Task/Runtime-evaluation/00DESCRIPTION b/Task/Runtime-evaluation/00DESCRIPTION index 7f7df6dbe7..d104759f95 100644 --- a/Task/Runtime-evaluation/00DESCRIPTION +++ b/Task/Runtime-evaluation/00DESCRIPTION @@ -1,4 +1,5 @@ - Demonstrate your language's ability for programs to execute code written in the language provided at runtime. Show us what kind of program fragments are permitted (e.g. expressions vs. statements), how you get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. +Demonstrate your language's ability for programs to execute code written in the language provided at runtime. +Show us what kind of program fragments are permitted (e.g. expressions vs. statements), how you get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. diff --git a/Task/Runtime-evaluation/ALGOL-68/runtime-evaluation.alg b/Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-1.alg similarity index 100% rename from Task/Runtime-evaluation/ALGOL-68/runtime-evaluation.alg rename to Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-1.alg diff --git a/Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-2.alg b/Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-2.alg new file mode 100644 index 0000000000..c8ea6aa919 --- /dev/null +++ b/Task/Runtime-evaluation/ALGOL-68/runtime-evaluation-2.alg @@ -0,0 +1,35 @@ +# procedure to call the Algol 68G evaluate procedure # +# the environment of the evaluation will be the caller's environment # +# with "code", "x" and "y" defined as the procedure parameters # +PROC ev = ( STRING code, INT x, INT y )STRING: evaluate( code ); + +BEGIN + + INT i := 1; + INT j := 2; + REAL x := 4.2; + REAL y := 0.7164; + + # evaluates "i + j" in the current environment # + print( ( evaluate( "i + j" ), newline ) ); + + # evaluates "x + y" in the environment of the procedure body of ev # + print( ( ev( "x + y", i, j ), newline ) ); + + # evaluates "x + y" in the current environment, so shows a different # + # result to the previous call # + print( ( evaluate( "x + y" ), newline ) ); + + # prints "code" because code is defined in the environment of the # + # call to evaluate (in ev) although it is not defined in this # + # environment # + print( ( ev( "code", 1, 2 ), newline ) ); + + # prints "code + codecode + code" - see above # + print( ( ev( "code + code", 1, 2 ), newline ) ) + +END + +# if this next call was executed, a runtime error would occur as x and y # +# do not exist anymore # +# ;print( ( evaluate( "x + y" ), newline ) ) # diff --git a/Task/Runtime-evaluation/Frink/runtime-evaluation.frink b/Task/Runtime-evaluation/Frink/runtime-evaluation.frink new file mode 100644 index 0000000000..878950ba47 --- /dev/null +++ b/Task/Runtime-evaluation/Frink/runtime-evaluation.frink @@ -0,0 +1 @@ +eval["length = 1234 feet + 2 inches"] diff --git a/Task/Runtime-evaluation/Groovy/runtime-evaluation-3.groovy b/Task/Runtime-evaluation/Groovy/runtime-evaluation-3.groovy index 59f015de56..ab6a0b8a86 100644 --- a/Task/Runtime-evaluation/Groovy/runtime-evaluation-3.groovy +++ b/Task/Runtime-evaluation/Groovy/runtime-evaluation-3.groovy @@ -1,4 +1,4 @@ -def context = new B inding() +def context = new Binding() context.startYear = 2008 context.endYear = 2121 def years3 = new GroovyShell(context).evaluate(''' diff --git a/Task/Runtime-evaluation/Groovy/runtime-evaluation-4.groovy b/Task/Runtime-evaluation/Groovy/runtime-evaluation-4.groovy index 13a7e08b80..f7161bbf8b 100644 --- a/Task/Runtime-evaluation/Groovy/runtime-evaluation-4.groovy +++ b/Task/Runtime-evaluation/Groovy/runtime-evaluation-4.groovy @@ -1,4 +1,4 @@ -def years4 = new GroovyShell( new B inding(startYear: 2008, endYear: 2121) ).evaluate(''' +def years4 = new GroovyShell( new Binding(startYear: 2008, endYear: 2121) ).evaluate(''' (startYear..endYear).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" } diff --git a/Task/Runtime-evaluation/Groovy/runtime-evaluation-5.groovy b/Task/Runtime-evaluation/Groovy/runtime-evaluation-5.groovy index 592422caf7..470a37d509 100644 --- a/Task/Runtime-evaluation/Groovy/runtime-evaluation-5.groovy +++ b/Task/Runtime-evaluation/Groovy/runtime-evaluation-5.groovy @@ -1,4 +1,4 @@ -def binding = new B inding(startYear: 2008, endYear: 2121) +def binding = new Binding(startYear: 2008, endYear: 2121) new GroovyShell( binding ).evaluate(''' yearList = (startYear..endYear).findAll { Date.parse("yyyy-MM-dd", "${it}-12-25").format("EEE") == "Sun" diff --git a/Task/Runtime-evaluation/Lua/runtime-evaluation.lua b/Task/Runtime-evaluation/Lua/runtime-evaluation-1.lua similarity index 100% rename from Task/Runtime-evaluation/Lua/runtime-evaluation.lua rename to Task/Runtime-evaluation/Lua/runtime-evaluation-1.lua diff --git a/Task/Runtime-evaluation/Lua/runtime-evaluation-2.lua b/Task/Runtime-evaluation/Lua/runtime-evaluation-2.lua new file mode 100644 index 0000000000..6f3c6d17da --- /dev/null +++ b/Task/Runtime-evaluation/Lua/runtime-evaluation-2.lua @@ -0,0 +1,2 @@ +f = load("return 42") +f() --> returns 42 diff --git a/Task/Runtime-evaluation/MATLAB/runtime-evaluation.m b/Task/Runtime-evaluation/MATLAB/runtime-evaluation.m new file mode 100644 index 0000000000..87a27e1aab --- /dev/null +++ b/Task/Runtime-evaluation/MATLAB/runtime-evaluation.m @@ -0,0 +1,37 @@ +function testEval + fprintf('Expressions:\n') + x = eval('5+10^2') + eval('y = (x-100).*[1 2 3]') + eval('z = strcat(''my'', '' string'')') + try + w eval(' = 45') + catch + fprintf('Runtime error: interpretation of w is a function\n\n') + end + % eval('v') = 5 + % Invalid at compile-time as MATLAB interprets as using eval as a variable + + fprintf('Other Statements:\n') + nl = sprintf('\n'); + eval(['for k = 1:20' nl ... + 'fprintf(''%.3f\n'', k)' nl ... + 'if k == 3' nl ... + 'break' nl ... + 'end' nl ... + 'end']) + true == eval('1') + try + true eval(' == 1') + catch + fprintf('Runtime error: interpretation of == 1 is of input to true\n\n') + end + + fprintf('Programming on the fly:\n') + userIn = true; + codeBlock = ''; + while userIn + userIn = input('Enter next line of code: ', 's'); + codeBlock = [codeBlock nl userIn]; + end + eval(codeBlock) +end diff --git a/Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol b/Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol new file mode 100644 index 0000000000..86c94ac934 --- /dev/null +++ b/Task/Runtime-evaluation/REBOL/runtime-evaluation.rebol @@ -0,0 +1,3 @@ +a: -5 +b: 7 +answer: do [abs a * b] ; => 35 diff --git a/Task/Runtime-evaluation/REXX/runtime-evaluation.rexx b/Task/Runtime-evaluation/REXX/runtime-evaluation.rexx index 0cd7cca4b7..58380d13dd 100644 --- a/Task/Runtime-evaluation/REXX/runtime-evaluation.rexx +++ b/Task/Runtime-evaluation/REXX/runtime-evaluation.rexx @@ -1,12 +1,12 @@ -/*REXX program to illustrate ability to execute code written at runtime.*/ -numeric digits 10000000 +/*REXX program illustrates ability to execute code entered at "runtime".*/ +numeric digits 10000000 /*ten million digits should do it*/ bee=51 -stuff='bee=min(-2,44); say 13*2 "[from inside the box."; abc=abs(bee)' +stuff= 'bee=min(-2,44); say 13*2 "[from inside the box.]"; abc=abs(bee)' interpret stuff say 'bee=' bee say 'abc=' abc say - + /* [↓] now, we hear from da user*/ say 'enter an expression:' pull expression say @@ -16,7 +16,7 @@ interpret '?='expression say say 'length of result='length(?) -say ' left 50 bytes of result='left(?,50)'...' -say 'right 50 bytes of result=...'right(?,50) +say ' left 50 bytes of result='left(?,50)'···' +say 'right 50 bytes of result=···'right(?,50) /*stick a fork in it, we're done.*/ diff --git a/Task/Runtime-evaluation/UNIX-Shell/runtime-evaluation.sh b/Task/Runtime-evaluation/UNIX-Shell/runtime-evaluation.sh new file mode 100644 index 0000000000..9b2d9b2bb5 --- /dev/null +++ b/Task/Runtime-evaluation/UNIX-Shell/runtime-evaluation.sh @@ -0,0 +1,4 @@ +$ a=42 +$ b=a +$ eval "echo \$$b" +42 diff --git a/Task/S-Expressions/Perl-6/s-expressions.pl6 b/Task/S-Expressions/Perl-6/s-expressions.pl6 index 5fbec5f7ff..37c50be690 100644 --- a/Task/S-Expressions/Perl-6/s-expressions.pl6 +++ b/Task/S-Expressions/Perl-6/s-expressions.pl6 @@ -1,7 +1,7 @@ grammar S-Exp { rule TOP {^ $}; - token s-list { '(' ~ ')' [ ** [\s+] | '' ] } + token s-list { '(' ~ ')' [ + % [\s+] | '' ] } token in_list { | } proto token s-token {*} diff --git a/Task/S-Expressions/Ruby/s-expressions.rb b/Task/S-Expressions/Ruby/s-expressions.rb index e7796a378d..5d38e101ce 100644 --- a/Task/S-Expressions/Ruby/s-expressions.rb +++ b/Task/S-Expressions/Ruby/s-expressions.rb @@ -62,14 +62,12 @@ class SExpr end def symbol_or_number(word) + Integer(word) + rescue ArgumentError begin - Integer(word) + Float(word) rescue ArgumentError - begin - Float(word) - rescue ArgumentError - word.to_sym - end + word.to_sym end end @@ -120,5 +118,5 @@ sexpr = SExpr.new <string (help port))) + +(define (string-read port) + (define (help port) + (let ((char (read-char port))) + (cond + ((or (eof-object? char) (char-whitespace? char)) '()) + ((eq? char #\) ) (unread-char char port) '()) + (#t (cons char (help port)))))) + (list->string (help port))) + +(define (format-sexpr expr) + (define (help expr pad) + (if + (list? expr) + (begin + (format #t "~a(~%" (make-string pad #\tab)) + (for-each (lambda (x) (help x (1+ pad))) expr) + (format #t "~a)~%" (make-string pad #\tab))) + (format #t "~a~a~%" (make-string pad #\tab) expr))) + (help expr 0)) + +(format-sexpr (sexpr-read + (open-input-string "((data \"quoted data\" 123 4.5) (data (!@# (4.5) \"(more\" \"data)\")))"))) diff --git a/Task/SEDOLs/Clojure/sedols.clj b/Task/SEDOLs/Clojure/sedols.clj new file mode 100644 index 0000000000..bcb38694eb --- /dev/null +++ b/Task/SEDOLs/Clojure/sedols.clj @@ -0,0 +1,6 @@ +(defn sedols [xs] + (letfn [(sedol [ys] (let [weights [1 3 1 7 3 9] + convtonum (map #(Character/getNumericValue %) ys) + check (-> (reduce + (map * weights convtonum)) (rem 10) (->> (- 10)) (rem 10))] + (str ys check)))] + (map #(sedol %) xs))) diff --git a/Task/SEDOLs/D/sedols-1.d b/Task/SEDOLs/D/sedols-1.d index e9ca975227..0e9327b08e 100644 --- a/Task/SEDOLs/D/sedols-1.d +++ b/Task/SEDOLs/D/sedols-1.d @@ -1,20 +1,20 @@ import std.stdio, std.algorithm, std.string, std.numeric, std.ascii; -char checksum(in char[] sedol) +char checksum(in char[] sedol) pure @safe /*@nogc*/ in { assert(sedol.length == 6); - foreach (c; sedol) - assert(isDigit(c) || (isUpper(c) && !canFind("AEIOU", c))); + foreach (immutable c; sedol) + assert(c.isDigit || (c.isUpper && !"AEIOU".canFind(c))); } out (result) { - assert(isDigit(result)); + assert(result.isDigit); } body { - 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]); - return '0' + 10 - (d % 10); + static immutable c2v = (in dchar c) => c.isDigit ? c - '0' : (c - 'A' + 10); + immutable int d = sedol.map!c2v.dotProduct([1, 3, 1, 7, 3, 9]); + return digits[10 - (d % 10)]; } void main() { - foreach (sedol; "710889 B0YBKJ 406566 B0YBLH 228276 - B0YBKL 557910 B0YBKR 585284 B0YBKT".split()) - writeln(sedol, checksum(sedol)); + foreach (const sedol; "710889 B0YBKJ 406566 B0YBLH 228276 + B0YBKL 557910 B0YBKR 585284 B0YBKT".split) + writeln(sedol, sedol.checksum); } diff --git a/Task/SEDOLs/D/sedols-2.d b/Task/SEDOLs/D/sedols-2.d index dc25dc08dd..893475b6e7 100644 --- a/Task/SEDOLs/D/sedols-2.d +++ b/Task/SEDOLs/D/sedols-2.d @@ -1,6 +1,6 @@ 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 @safe /*@nogc*/ in { assert(sedol.length == 6, "SEDOL must be 6 chars long."); enum uint mask = 0b11_1110_1111_1011_1110_1110_1110; @@ -11,13 +11,13 @@ in { "SEDOL with wrong char."); } out(result) { assert(result.isDigit); - static int c2v(in dchar c) pure nothrow { + static int c2v(in dchar c) pure nothrow @safe @nogc { 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]; + static immutable int[] weights = [1, 3, 1, 7, 3, 9]; int sum = 0; foreach (immutable i, immutable c; sedol) { diff --git a/Task/SEDOLs/D/sedols-3.d b/Task/SEDOLs/D/sedols-3.d index 504a6e8b35..8a5ba23dae 100644 --- a/Task/SEDOLs/D/sedols-3.d +++ b/Task/SEDOLs/D/sedols-3.d @@ -1,12 +1,9 @@ -import std.stdio, std.algorithm, std.string, std.numeric; - -auto checksum(string s) { - auto m = s.map!q{ a>='0' && a<='9' ? a-'0' : a-'A'+10 }(); - return '0' + 10 - m.dotProduct([1,3,1,7,3,9]) % 10; -} - void main() { - foreach (sedol; "710889 B0YBKJ 406566 B0YBLH 228276 - B0YBKL 557910 B0YBKR 585284 B0YBKT".split()) - writeln(sedol, sedol.checksum()); + import std.stdio, std.algorithm, std.string, std.numeric,std.ascii; + + foreach (const s; "710889 B0YBKJ 406566 B0YBLH 228276 + B0YBKL 557910 B0YBKR 585284 B0YBKT".split) + writeln(s, '0' + 10 - s + .map!(c => c.isDigit ? c - '0' : c - 'A' + 10) + .dotProduct([1, 3, 1, 7, 3, 9]) % 10); } diff --git a/Task/SEDOLs/Delphi/sedols.delphi b/Task/SEDOLs/Delphi/sedols.delphi new file mode 100644 index 0000000000..5e2796d38d --- /dev/null +++ b/Task/SEDOLs/Delphi/sedols.delphi @@ -0,0 +1,79 @@ +program Sedol; + +{$APPTYPE CONSOLE} + +uses + SysUtils; + + +const + SEDOL_CHR_COUNT = 6; + DIGITS = ['0'..'9']; + LETTERS = ['A'..'Z']; + VOWELS = ['A', 'E', 'I', 'O', 'U']; + ACCEPTABLE_CHRS = DIGITS + LETTERS - VOWELS; + WEIGHTS : ARRAY [1..SEDOL_CHR_COUNT] of integer = (1, 3, 1, 7, 3, 9); + LETTER_OFFSET = 9; + + +function AddSedolCheckDigit(Sedol : string) : string; +var + iChr : integer; + Checksum : integer; + CheckDigit : char; +begin + if Sedol <> uppercase(Sedol) then + raise ERangeError.CreateFmt('%s contains lower case characters',[Sedol]); + if length(Sedol) <> SEDOL_CHR_COUNT then + raise ERangeError.CreateFmt('"%s" length is invalid. Should be 6 characters',[Sedol]); + + Checksum := 0; + for iChr := 1 to SEDOL_CHR_COUNT do + begin + + if Sedol[iChr] in Vowels then + raise ERangeError.CreateFmt('%s contains a vowel (%s) at chr %d',[Sedol, Sedol[iChr], iChr]); + if not (Sedol[iChr] in ACCEPTABLE_CHRS) then + raise ERangeError.CreateFmt('%s contains an invalid chr (%s) at position %d',[Sedol, Sedol[iChr], iChr]); + + if Sedol[iChr] in DIGITS then + Checksum := Checksum + (ord(Sedol[iChr]) - ord('0')) * WEIGHTS[iChr] + else + Checksum := Checksum + (ord(Sedol[iChr]) - ord('A') + 1 + LETTER_OFFSET) * WEIGHTS[iChr]; + + end; + + Checksum := (Checksum mod 10); + if Checksum <> 0 then + Checksum := 10 - Checksum; + CheckDigit := chr(CheckSum + ord('0')); + + Result := Sedol + CheckDigit; +end; + + +procedure Test(First6 : string); +begin + writeln(First6, ' becomes ', AddSedolCheckDigit(First6)); +end; + + +begin + try + Test('710889'); + Test('B0YBKJ'); + Test('406566'); + Test('B0YBLH'); + Test('228276'); + Test('B0YBKL'); + Test('557910'); + Test('B0YBKR'); + Test('585284'); + Test('B0YBKT'); + Test('B00030'); + except + on E : Exception do + writeln(E.Message); + end; + readln; +end. diff --git a/Task/SEDOLs/Ruby/sedols.rb b/Task/SEDOLs/Ruby/sedols.rb index 4fb92ebdbf..a35e5124c4 100644 --- a/Task/SEDOLs/Ruby/sedols.rb +++ b/Task/SEDOLs/Ruby/sedols.rb @@ -1,14 +1,14 @@ Sedol_char = "0123456789BCDFGHJKLMNPQRSTVWXYZ" def char2value(c) - raise "No vowels" unless Sedol_char.include?(c) + raise ArgumentError, "No vowels" unless Sedol_char.include?(c) c.to_i(36) end Sedolweight = [1,3,1,7,3,9] def checksum(sedol) - raise "Invalid length" unless sedol.size == Sedolweight.size + raise ArgumentError, "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 diff --git a/Task/SEDOLs/Transact-SQL/sedols.sql b/Task/SEDOLs/Transact-SQL/sedols.sql new file mode 100644 index 0000000000..9b61a649da --- /dev/null +++ b/Task/SEDOLs/Transact-SQL/sedols.sql @@ -0,0 +1,63 @@ +CREATE FUNCTION [dbo].[fn_CheckSEDOL] +( @SEDOL varchar(50) ) +RETURNS varchar(7) +AS +BEGIN + declare @true bit = 1, + @false bit = 0, + @isSEDOL bit, + @sedol_weights varchar(6) ='131739', + @sedol_len int = LEN(@SEDOL), + @sum int = 0 + + + if ((@sedol_len = 6)) + begin + select @SEDOL = UPPER(@SEDOL) + Declare @vowels varchar(5) = 'AEIOU', + @letters varchar(21) = 'BCDFGHJKLMNPQRSTVWXYZ', + @i int=1, + @isStillGood bit = @true, + @char char = '', + @weighting int =0 + + select @isSEDOL = @false + + while ((@i < 7) and (@isStillGood = @true)) + begin + select @char = SUBSTRING(@SEDOL,@i,1), + @weighting = CONVERT (INT,SUBSTRING(@sedol_weights, @i, 1)) + if (CHARINDEX(@char, @vowels) > 0) -- no vowels please + begin + select @isStillGood=@false + end + else + begin + if (ISNUMERIC(@char) = @true) -- is a number + begin + select @sum = @sum + (ASCII(@char) - 48) * @weighting + end + else if (CHARINDEX(@char, @letters) = 0) -- test for the rest of the alphabet + begin + select @isStillGood=@false + end + else + begin + select @sum = @sum + (ASCII(@char) - 55) * @weighting + end + end + select @i = @i +1 + end -- of while loop + if (@isStillGood = @true) + begin + declare @checksum int = (10 - (@sum%10))%10 + select @SEDOL = @SEDOL + CONVERT(CHAR,@checksum) + end + end + else + begin + select @SEDOL = '' + end + -- Return the result of the function + RETURN @SEDOL +END diff --git a/Task/SHA-1/D/sha-1.d b/Task/SHA-1/D/sha-1.d index 241192056f..e81de61639 100644 --- a/Task/SHA-1/D/sha-1.d +++ b/Task/SHA-1/D/sha-1.d @@ -1,5 +1,5 @@ -import std.stdio, std.digest.sha; - void main() { - writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of()); + import std.stdio, std.digest.sha; + + writefln("%-(%02x%)", "Ars longa, vita brevis".sha1Of); } diff --git a/Task/SHA-1/Haskell/sha-1.hs b/Task/SHA-1/Haskell/sha-1.hs new file mode 100644 index 0000000000..08de7d8ef5 --- /dev/null +++ b/Task/SHA-1/Haskell/sha-1.hs @@ -0,0 +1,14 @@ +module Digestor + where +import Data.Digest.Pure.SHA +import qualified Data.ByteString.Lazy as B + +convertString :: String -> B.ByteString +convertString phrase = B.pack $ map ( fromIntegral . fromEnum ) phrase + +convertToSHA1 :: String -> String +convertToSHA1 word = showDigest $ sha1 $ convertString word + +main = do + putStr "Rosetta Code SHA1-codiert: " + putStrLn $ convertToSHA1 "Rosetta Code" diff --git a/Task/SHA-1/J/sha-1-1.j b/Task/SHA-1/J/sha-1-1.j index 01f71a244f..1e843a5d7d 100644 --- a/Task/SHA-1/J/sha-1-1.j +++ b/Task/SHA-1/J/sha-1-1.j @@ -17,10 +17,11 @@ K=: ((32#2) #: 16b5a827999 16b6ed9eba1 16b8f1bbcdc 16bca62c1d6) {~ <.@%&20 plus=:+&.((32#2)&#.) -process=:3 :0 - H=. #: 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 - W=. (, [: , 1 |."#. _3 _8 _14 _16 ~:/@:{ ])^:64 y ]\~ _32 - 'A B C D E'=. H +H=: #: 16b67452301 16befcdab89 16b98badcfe 16b10325476 16bc3d2e1f0 + +process=:4 :0 + W=. (, [: , 1 |."#. _3 _8 _14 _16 ~:/@:{ ])^:64 x ]\~ _32 + 'A B C D E'=. y=._32[\,y for_t. i.80 do. TEMP=. (5|.A) plus (t f B,C,D) plus E plus (W{~t) plus K t E=. D @@ -29,7 +30,7 @@ process=:3 :0 B=. A A=. TEMP end. - ,H plus A,B,C,D,:E + ,y plus A,B,C,D,:E ) -sha1=: _512 process\ pad +sha1=: [:> [: process&.>/ ( $w is rw { reverse gather for ^4 { take $w % 256; $w div= 256 } }, @H; + Blob.new: map { reverse .polymod(256 xx 3) }, @H; } say sha1(.encode('ascii')), " $_" diff --git a/Task/SHA-1/PicoLisp/sha-1.l b/Task/SHA-1/PicoLisp/sha-1.l index 3e893a227c..92d52a721e 100644 --- a/Task/SHA-1/PicoLisp/sha-1.l +++ b/Task/SHA-1/PicoLisp/sha-1.l @@ -1,4 +1,116 @@ +(de leftRotate (X C) + (| (mod32 (>> (- C) X)) (>> (- 32 C) X)) ) + +(de mod32 (N) + (& N `(hex "FFFFFFFF")) ) + +(de not32 (N) + (x| N `(hex "FFFFFFFF")) ) + +(de add32 @ + (mod32 (pass +)) ) + +(de sha1 (Str) + (let Len (length Str) + (setq Str + (conc + (need + (- + 8 + (* 64 (/ (+ Len 1 8 63) 64)) ) + (conc + (mapcar char (chop Str)) + (cons `(hex "80")) ) + 0 ) + (flip + (make + (setq Len (* 8 Len)) + (do 8 + (link (& Len 255)) + (setq Len (>> 8 Len )) ) ) ) ) ) ) + (let + (H0 `(hex "67452301") + H1 `(hex "EFCDAB89") + H2 `(hex "98BADCFE") + H3 `(hex "10325476") + H4 `(hex "C3D2E1F0") ) + (while Str + (let + (A H0 B H1 C H2 D H3 E H4 + W (conc + (make + (do 16 + (link + (apply + | + (mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) ) + (need 64 0) ) ) + (for (I 17 (>= 80 I) (inc I)) + (set (nth W I) + (leftRotate + (x| + (get W (- I 3)) + (get W (- I 8)) + (get W (- I 14)) + (get W (- I 16)) ) + 1 ) ) ) + (use (Tmp F K) + (for I 80 + (cond + ((>= 20 I) + (setq + F (| (& B C) (& (not32 B) D)) + K `(hex "5A827999") ) ) + ((>= 40 I) + (setq + F (x| B C D) + K `(hex "6ED9EBA1") ) ) + ((>= 60 I) + (setq + F (| (& B C) (& B D) (& C D)) + K `(hex "8F1BBCDC") ) ) + (T + (setq + F (x| B C D) + K `(hex "CA62C1D6") ) ) ) + (setq + Tmp (add32 (leftRotate A 5) F E K (get W I) ) + E D + D C + C (leftRotate B 30) + B A + A Tmp ) ) ) + (setq + H0 (add32 H0 A) + H1 (add32 H1 B) + H2 (add32 H2 C) + H3 (add32 H3 D) + H4 (add32 H4 E) ) ) ) + (mapcan + '((N) + (flip + (make + (do 4 + (link (& 255 N)) + (setq N (>> 8 N)) ) ) ) ) + (list H0 H1 H2 H3 H4) ) ) ) + (let Str "Rosetta Code" - (pack - (mapcar '((B) (pad 2 (hex B))) - (native "libcrypto.so" "SHA1" '(B . 20) Str (length Str) '(NIL (20))) ) ) ) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (sha1 Str) ) ) ) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (native + "libcrypto.so" + "SHA1" + '(B . 20) + Str + (length Str) + '(NIL (20)) ) ) ) ) ) + +(bye) diff --git a/Task/SHA-1/Ruby/sha-1-3.rb b/Task/SHA-1/Ruby/sha-1-3.rb index 64c5cc4b97..99012d2e64 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 # ffffffff + mask = 0xffffffff s = proc{|n, x| ((x << n) & mask) | (x >> (32 - n))} f = [ proc {|b, c, d| (b & c) | (b.^(mask) & d)}, @@ -21,41 +21,22 @@ def sha1(string) # initial hash h = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0] + bit_len = string.size << 3 + string += "\x80" + while (string.size % 64) != 56 + string += "\0" + end + string = string.force_encoding('ascii-8bit') + [bit_len >> 32, bit_len & mask].pack("N2") + + if string.size % 64 != 0 + fail "failed to pad to correct length" + end + io = StringIO.new(string) block = "" - term = false # appended "\x80" in second-last block? - last = false # last block? - until last - # Read next block of 16 words (64 bytes, 512 bits). - io.read(64, block) or ( - # Work around a bug in Rubinius 1.2.4. At eof, - # MRI and JRuby already replace block with "". - block.clear - ) - # Unpack block into 32-bit words "N". - case len = block.length - when 64 - # Unpack 16 words. - w = block.unpack("N16") - when 56..63 - # Second-last block: append padding, unpack 16 words. - block.concat("\x80"); term = true - block.concat("\0" * (63 - len)) - w = block.unpack("N16") - when 0..55 - # Last block: append padding, unpack 14 words. - block.concat(term ? "\0" : "\x80") - block.concat("\0" * (55 - len)) - w = block.unpack("N14") - - # Append bit length, 2 words. - bit_len = string.length << 3 - w.push(bit_len >> 32, bit_len & mask) - last = true - else - fail "impossible" - end + while io.read(64, block) + w = block.unpack("N16") # Process block. (16..79).each {|t| w[t] = s[1, w[t-3] ^ w[t-8] ^ w[t-14] ^ w[t-16]]} diff --git a/Task/SHA-256/Clojure/sha-256.clj b/Task/SHA-256/Clojure/sha-256.clj new file mode 100644 index 0000000000..71f290f02d --- /dev/null +++ b/Task/SHA-256/Clojure/sha-256.clj @@ -0,0 +1,2 @@ +(use 'pandect.core) +(sha256 "Rosetta code") diff --git a/Task/SHA-256/D/sha-256-1.d b/Task/SHA-256/D/sha-256-1.d new file mode 100644 index 0000000000..39e61290a0 --- /dev/null +++ b/Task/SHA-256/D/sha-256-1.d @@ -0,0 +1,5 @@ +void main() { + import std.stdio, std.digest.sha; + + writefln("%-(%02x%)", "Rosetta code".sha256Of); +} diff --git a/Task/SHA-256/D/sha-256.d b/Task/SHA-256/D/sha-256-2.d similarity index 91% rename from Task/SHA-256/D/sha-256.d rename to Task/SHA-256/D/sha-256-2.d index 6988d93211..75caafb639 100644 --- a/Task/SHA-256/D/sha-256.d +++ b/Task/SHA-256/D/sha-256-2.d @@ -19,7 +19,7 @@ struct SHA256 { alias TResult = ubyte[256 / 8]; version(WORDS_BIGENDIAN) { - static uint bswap(in uint n) pure nothrow { return n; } + static uint bswap(in uint n) pure nothrow @safe @nogc { return n; } } // Bytes used to pad the buffer to the next 64-byte boundary. @@ -30,7 +30,7 @@ struct SHA256 { Takes a pointer to a 256 bit block of data (eight 32 bit ints) and intializes it to the start constants of the SHA256 algorithm. This must be called before using hash in the call to sha256_hash. */ - void init() pure nothrow { + void init() pure nothrow @safe @nogc { state = [0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU, 0x1f83d9abU, 0x5be0cd19U]; total[] = 0; @@ -42,7 +42,7 @@ struct SHA256 { the initialization function) update the context for the next LEN bytes starting at BUFFER. It is not required that LEN is a multiple of 64. */ - void processBytes(in ubyte[] inBuffer) pure nothrow { + void processBytes(in ubyte[] inBuffer) pure nothrow @nogc { // When we already have some bits in our internal // buffer concatenate both inputs first. const(ubyte)* inBufferPtr = inBuffer.ptr; @@ -61,10 +61,8 @@ struct SHA256 { processBlock(bufferB[0 .. bufLen & ~63]); bufLen &= 63; - // The regions in the following copy operation - // cannot overlap. - memcpy(bufferB.ptr, - &bufferB[(left_over + add) & ~63], bufLen); + // The regions in the following copy operation cannot overlap. + memcpy(bufferB.ptr, &bufferB[(left_over + add) & ~63], bufLen); } inBufferPtr += add; @@ -99,15 +97,15 @@ struct SHA256 { the next len bytes starting at buffer. It is necessary that len is a multiple of 64. */ void processBlock(in ubyte[] inBuffer) - pure nothrow in { + pure nothrow @nogc in { assert(inBuffer.length % 64 == 0); } body { // Round functions. - static uint F1(in uint e, in uint f, in uint g) pure nothrow { + static uint F1(in uint e, in uint f, in uint g) pure nothrow @safe @nogc { return g ^ (e & (f ^ g)); } - static uint F2(in uint a, in uint b, in uint c) pure nothrow { + static uint F2(in uint a, in uint b, in uint c) pure nothrow @safe @nogc { return (a & b) | (c & (a | b)); } @@ -132,18 +130,18 @@ struct SHA256 { if (total[0] < len) total[1]++; - static uint rol(in uint x, in uint n) pure nothrow { + static uint rol(in uint x, in uint n) pure nothrow @safe @nogc { return (x << n) | (x >> (32 - n)); } - static uint S0(in uint x) pure nothrow { + static uint S0(in uint x) pure nothrow @safe @nogc { return rol(x, 25) ^ rol(x, 14) ^ (x >> 3); } - static uint S1(in uint x) pure nothrow { + static uint S1(in uint x) pure nothrow @safe @nogc { return rol(x, 15) ^ rol(x, 13) ^ (x >> 10); } - static uint SS0(in uint x) pure nothrow { + static uint SS0(in uint x) pure nothrow @safe @nogc { return rol(x, 30) ^ rol(x,19) ^ rol(x, 10); } - static uint SS1(in uint x) pure nothrow { + static uint SS1(in uint x) pure nothrow @safe @nogc { return rol(x, 26) ^ rol(x, 21) ^ rol(x, 7); } - uint M(in uint I) nothrow { + uint M(in uint I) pure nothrow @safe @nogc { immutable uint tm = S1(x[(I - 2) & 0x0f]) + x[(I - 7) & 0x0f] + S0(x[(I - 15) & 0x0f]) + @@ -154,7 +152,7 @@ struct SHA256 { static void R(in uint a, in uint b, in uint c, ref uint d, in uint e, in uint f, in uint g, ref uint h, - in uint k, in uint m) pure nothrow { + in uint k, in uint m) pure nothrow @safe @nogc { immutable t0 = SS0(a) + F2(a, b, c); immutable t1 = h + SS1(e) + F1(e, f, g) + k + m; d += t1; @@ -268,7 +266,7 @@ struct SHA256 { resBuf. Important: On some systems it is required that resBuf is correctly aligned for a 32-bit value. */ - void conclude() pure nothrow { + void conclude() pure nothrow @nogc { // Take yet unprocessed bytes into account. immutable bytes = bufLen; immutable size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4; @@ -294,7 +292,7 @@ struct SHA256 { result must be in little endian byte order. Important: On some systems it is required that resBuf is correctly aligned for a 32-bit value. */ - ref TResult read(ref TResult resBuf) const pure nothrow { + ref TResult read(return ref TResult resBuf) pure nothrow @nogc { foreach (immutable i, immutable s; state) (cast(uint*)resBuf.ptr)[i] = bswap(s); return resBuf; @@ -307,7 +305,7 @@ struct SHA256 { the wanted ASCII representation of the message digest. Important: On some systems it is required that resBuf be correctly aligned for a 32 bits value. */ - ref TResult finish(ref TResult resBuf) pure nothrow { + ref TResult finish(return ref TResult resBuf) pure nothrow @nogc { conclude; return read(resBuf); } @@ -317,8 +315,8 @@ struct SHA256 { buffer. The result is always in little endian byte order, so that a byte-wise output yields to the wanted ASCII representation of the message digest. */ - static ref TResult digest(in ubyte[] inBuffer, ref TResult resBuf) - pure nothrow { + static ref TResult digest(in ubyte[] inBuffer, return ref TResult resBuf) + pure nothrow @nogc { SHA256 sha = void; // Initialize the computation context. @@ -333,7 +331,7 @@ struct SHA256 { /// ditto - static TResult digest(in ubyte[] inBuffer) pure nothrow { + static TResult digest(in ubyte[] inBuffer) pure nothrow @nogc { align(4) TResult resBuf = void; return digest(inBuffer, resBuf); } diff --git a/Task/SHA-256/Emacs-Lisp/sha-256.l b/Task/SHA-256/Emacs-Lisp/sha-256.l new file mode 100644 index 0000000000..c69d46775b --- /dev/null +++ b/Task/SHA-256/Emacs-Lisp/sha-256.l @@ -0,0 +1 @@ +(secure-hash 'sha256 "Rosetta code") ;; as string of hex digits diff --git a/Task/SHA-256/NewLISP/sha-256.newlisp b/Task/SHA-256/NewLISP/sha-256.newlisp new file mode 100644 index 0000000000..b39925b4fb --- /dev/null +++ b/Task/SHA-256/NewLISP/sha-256.newlisp @@ -0,0 +1,4 @@ +;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html +;; (import native functions from the crypto library, provided by OpenSSL) +(module "crypto.lsp") +(crypto:sha256 "Rosetta Code") diff --git a/Task/SHA-256/Objective-C/sha-256.m b/Task/SHA-256/Objective-C/sha-256.m index d949ec0cac..51e32f5604 100644 --- a/Task/SHA-256/Objective-C/sha-256.m +++ b/Task/SHA-256/Objective-C/sha-256.m @@ -1,21 +1,19 @@ -#import +#import +#import -@implementation AppDelegate - -- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { - NSString* key = @"secret"; - NSString* data = @"Message"; - - const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding]; - const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding]; - unsigned char cHMAC[CC_SHA256_DIGEST_LENGTH]; - CCHmac(kCCHmacAlgSHA256, cKey, strlen(cKey), cData, strlen(cData), cHMAC); - - NSMutableString* result = [NSMutableString stringWithCapacity:(CC_SHA256_DIGEST_LENGTH * 2)]; - - for(CC_LONG i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) - [result appendFormat:@"%02x", cHMAC[i]]; - - NSLog(@"Sha-256: %@", result); +int main(int argc, char ** argv) { + NSString * msg = @"Rosetta code"; + unsigned char buf[CC_SHA256_DIGEST_LENGTH]; + const char * rc = [msg cStringUsingEncoding:NSASCIIStringEncoding]; + if (! CC_SHA256(rc, strlen(rc), buf)) { + NSLog(@"Failure..."); + return -1; + } + NSMutableString * res = [NSMutableString stringWithCapacity:(CC_SHA256_DIGEST_LENGTH * 2)]; + for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { + [res appendFormat:@"%02x", buf[i]]; + } + NSLog(@"Output: %@", res); + return 0; } diff --git a/Task/SHA-256/Perl-6/sha-256.pl6 b/Task/SHA-256/Perl-6/sha-256.pl6 index ad15f3705a..9ccbff63c4 100644 --- a/Task/SHA-256/Perl-6/sha-256.pl6 +++ b/Task/SHA-256/Perl-6/sha-256.pl6 @@ -1,4 +1,4 @@ -say .list».fmt("%02x").join given sha256 "Rosetta code"; +say sha256 "Rosetta code"; constant primes = grep &is-prime, 2 .. *; sub init(&f) { @@ -14,10 +14,9 @@ multi sha256(Str $str where all($str.ords) < 128) { } 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; - - push @b, reverse gather for ^8 { take $l%256; $l div=256 } + my @b = $data.list, 0x80; + push @b, 0 until (8 * @b - 448) %% 512; + push @b, reverse (8 * $data).polymod(256 xx 7); my @word = :256[@b.shift xx 4] xx @b/4; my @H = init(&sqrt)[^8]; @@ -41,7 +40,5 @@ multi sha256(Blob $data) { } @H = @H Z[m+] @h; } - return Blob.new: map -> $word is rw { - reverse gather for ^4 { take $word % 256; $word div= 256 } - }, @H; + return Blob.new: map { reverse .polymod(256 xx 3) }, @H; } diff --git a/Task/SHA-256/PicoLisp/sha-256.l b/Task/SHA-256/PicoLisp/sha-256.l new file mode 100644 index 0000000000..3de1f9403f --- /dev/null +++ b/Task/SHA-256/PicoLisp/sha-256.l @@ -0,0 +1,160 @@ +(setq *Sha256-K + (mapcar hex + '("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B" + "59F111F1" "923F82A4" "AB1C5ED5" "D807AA98" "12835B01" + "243185BE" "550C7DC3" "72BE5D74" "80DEB1FE" "9BDC06A7" + "C19BF174" "E49B69C1" "EFBE4786" "0FC19DC6" "240CA1CC" + "2DE92C6F" "4A7484AA" "5CB0A9DC" "76F988DA" "983E5152" + "A831C66D" "B00327C8" "BF597FC7" "C6E00BF3" "D5A79147" + "06CA6351" "14292967" "27B70A85" "2E1B2138" "4D2C6DFC" + "53380D13" "650A7354" "766A0ABB" "81C2C92E" "92722C85" + "A2BFE8A1" "A81A664B" "C24B8B70" "C76C51A3" "D192E819" + "D6990624" "F40E3585" "106AA070" "19A4C116" "1E376C08" + "2748774C" "34B0BCB5" "391C0CB3" "4ED8AA4A" "5B9CCA4F" + "682E6FF3" "748F82EE" "78A5636F" "84C87814" "8CC70208" + "90BEFFFA" "A4506CEB" "BEF9A3F7" "C67178F2") ) ) + +(de rightRotate (X C) + (| (mod32 (>> C X)) (mod32 (>> (- C 32) X))) ) + +(de mod32 (N) + (& N `(hex "FFFFFFFF")) ) + +(de not32 (N) + (x| N `(hex "FFFFFFFF")) ) + +(de add32 @ + (mod32 (pass +)) ) + +(de sha256 (Str) + (let Len (length Str) + (setq Str + (conc + (need + (- + 8 + (* 64 (/ (+ Len 1 8 63) 64)) ) + (conc (mapcar char (chop Str)) (cons `(hex "80"))) + 0 ) + (flip + (make + (setq Len (* 8 Len)) + (do 8 + (link (& Len 255)) + (setq Len (>> 8 Len )) ) ) ) ) ) ) + (let + (H0 `(hex "6A09E667") + H1 `(hex "BB67AE85") + H2 `(hex "3C6EF372") + H3 `(hex "A54FF53A") + H4 `(hex "510E527F") + H5 `(hex "9B05688C") + H6 `(hex "1F83D9AB") + H7 `(hex "5BE0CD19") ) + (while Str + (let + (A H0 + B H1 + C H2 + D H3 + E H4 + F H5 + G H6 + H H7 + W + (conc + (make + (do 16 + (link + (apply + | + (mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) ) + (need 48 0) ) ) + (for (I 17 (>= 64 I) (inc I)) + (let + (Wi15 (get W (- I 15)) + Wi2 (get W (- I 2)) + S0 + (x| + (rightRotate Wi15 7) + (rightRotate Wi15 18) + (>> 3 Wi15) ) + S1 + (x| + (rightRotate Wi2 17) + (rightRotate Wi2 19) + (>> 10 Wi2) ) ) + (set (nth W I) + (add32 + (get W (- I 16)) + S0 + (get W (- I 7)) + S1 ) ) ) ) + (use (Tmp1 Tmp2) + (for I 64 + (setq + Tmp1 + (add32 + H + (x| + (rightRotate E 6) + (rightRotate E 11) + (rightRotate E 25) ) + (x| (& E F) (& (not32 E) G)) + (get *Sha256-K I) + (get W I) ) + Tmp2 + (add32 + (x| + (rightRotate A 2) + (rightRotate A 13) + (rightRotate A 22) ) + (x| + (& A B) + (& A C) + (& B C) ) ) + H G + G F + F E + E (add32 D Tmp1) + D C + C B + B A + A (add32 Tmp1 Tmp2) ) ) ) + (setq + H0 (add32 H0 A) + H1 (add32 H1 B) + H2 (add32 H2 C) + H3 (add32 H3 D) + H4 (add32 H4 E) + H5 (add32 H5 F) + H6 (add32 H6 G) + H7 (add32 H7 H) ) ) ) + (mapcan + '((N) + (flip + (make + (do 4 + (link (& 255 N)) + (setq N (>> 8 N)) ) ) ) ) + (list H0 H1 H2 H3 H4 H5 H6 H7) ) ) ) + +(let Str "Rosetta code" + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (sha256 Str) ) ) ) + (println + (pack + (mapcar + '((B) (pad 2 (hex B))) + (native + "libcrypto.so" + "SHA256" + '(B . 32) + Str + (length Str) + '(NIL (32)) ) ) ) ) ) + +(bye) diff --git a/Task/SHA-256/Rust/sha-256.rust b/Task/SHA-256/Rust/sha-256.rust new file mode 100644 index 0000000000..455c61f2e7 --- /dev/null +++ b/Task/SHA-256/Rust/sha-256.rust @@ -0,0 +1,9 @@ +extern crate rustc; + +use rustc::util::sha2::{Sha256, Digest}; + +fn main() { + let mut digest = Sha256::new(); + digest.input_str("Rosetta code"); + assert!(digest.result_str() == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf".to_string()); +} diff --git a/Task/SHA-256/Scala/sha-256.scala b/Task/SHA-256/Scala/sha-256.scala new file mode 100644 index 0000000000..962bf37d65 --- /dev/null +++ b/Task/SHA-256/Scala/sha-256.scala @@ -0,0 +1,11 @@ +object RosettaSHA256 extends App { + + def MD5(s: String): String = { + // Besides "MD5", "SHA-256", and other hashes are available + val m = java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8")) + m.map("%02x".format(_)).mkString + } + + assert(MD5("Rosetta code") == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf") + println("Successfully completed without errors.") +} diff --git a/Task/SHA-256/Smalltalk/sha-256.st b/Task/SHA-256/Smalltalk/sha-256.st new file mode 100644 index 0000000000..15bf31563e --- /dev/null +++ b/Task/SHA-256/Smalltalk/sha-256.st @@ -0,0 +1 @@ +(SHA256 new hashStream: 'Rosetta code' readStream) hex. diff --git a/Task/SQL-based-authentication/Go/sql-based-authentication.go b/Task/SQL-based-authentication/Go/sql-based-authentication.go new file mode 100644 index 0000000000..7947e39f1e --- /dev/null +++ b/Task/SQL-based-authentication/Go/sql-based-authentication.go @@ -0,0 +1,79 @@ +package main + +import ( + "bytes" + "crypto/md5" + "crypto/rand" + "database/sql" + "fmt" + + _ "github.com/go-sql-driver/mysql" +) + +func connectDB() (*sql.DB, error) { + return sql.Open("mysql", "rosetta:code@/rc") +} + +func createUser(db *sql.DB, user, pwd string) error { + salt := make([]byte, 16) + rand.Reader.Read(salt) + _, err := db.Exec(`insert into users (username, pass_salt, pass_md5) + values (?, ?, ?)`, user, salt, saltHash(salt, pwd)) + if err != nil { + return fmt.Errorf("User %s already exits", user) + } + return nil +} + +func authenticateUser(db *sql.DB, user, pwd string) error { + var salt, hash []byte + row := db.QueryRow(`select pass_salt, pass_md5 from users + where username=?`, user) + if err := row.Scan(&salt, &hash); err != nil { + return fmt.Errorf("User %s unknown", user) + } + if !bytes.Equal(saltHash(salt, pwd), hash) { + return fmt.Errorf("User %s invalid password", user) + } + return nil +} + +func saltHash(salt []byte, pwd string) []byte { + h := md5.New() + h.Write(salt) + h.Write([]byte(pwd)) + return h.Sum(nil) +} + +func main() { + // demonstrate + db, err := connectDB() + defer db.Close() + createUser(db, "sam", "123") + err = authenticateUser(db, "sam", "123") + if err == nil { + fmt.Println("User sam authenticated") + } + + // extra + fmt.Println() + // show contents of database + rows, _ := db.Query(`select username, pass_salt, pass_md5 from users`) + var user string + var salt, hash []byte + for rows.Next() { + rows.Scan(&user, &salt, &hash) + fmt.Printf("%s %x %x\n", user, salt, hash) + } + // try creating same user again + err = createUser(db, "sam", "123") + fmt.Println(err) + // try authenticating unknown user + err = authenticateUser(db, "pam", "123") + fmt.Println(err) + // try wrong password + err = authenticateUser(db, "sam", "1234") + fmt.Println(err) + // clear table to run program again + db.Exec(`truncate table users`) +} diff --git a/Task/SQL-based-authentication/Objeck/sql-based-authentication.objeck b/Task/SQL-based-authentication/Objeck/sql-based-authentication.objeck new file mode 100644 index 0000000000..ea122efbcb --- /dev/null +++ b/Task/SQL-based-authentication/Objeck/sql-based-authentication.objeck @@ -0,0 +1,104 @@ +use ODBC; +use Encryption; + +class SqlTest { + @conn : Connection; + + function : Main(args : String[]) ~ Nil { + SqlTest->New()->Run(); + } + + New() { + @conn := Connection->New("test", "root", "helloworld"); + } + + method : Run() ~ Nil { + CreateUser("objeck", "beer"); + AuthenticateUser("objeck", "beer"); + leaving { + @conn->Close(); + }; + } + + method : AuthenticateUser(username : String, password : String) ~ Nil { + status := false; + ps : ParameterStatement; + result : ResultSet; + if(@conn->IsOpen()) { + sql := "SELECT pass_salt, pass_md5 FROM users WHERE username = ?"; + ps := @conn->CreateParameterStatement(sql); + ps->SetVarchar(1, username); + + result := ps->Select(); + if(result <> Nil & result->Next()) { + salt_buffer := Byte->New[16]; + result->GetBlob(1, salt_buffer); + salt := ""; + for(i := 0; i < 16; i+=1;) { + salt->Append(salt_buffer[i]); + }; + + db_password_buffer := Byte->New[16]; + result->GetBlob(2, db_password_buffer); + + password->Append(salt); + user_password_buffer := Hash->MD5(password->ToByteArray()); + + IO.Console->Print("user: authenticated=")->PrintLine(IsEqual(db_password_buffer, user_password_buffer)); + }; + + }; + + leaving { + if(ps <> Nil) { + ps->Close(); + }; + + if(ps <> Nil) { + ps->Close(); + }; + }; + } + + method : CreateUser(username : String, password : String) ~ Nil { + salt := ""; + for(i := 0; i < 16; i+=1;) { salt->Append((Float->Random() * 100)->As(Int)); }; + salt := salt->SubString(16); + + password->Append(salt); + md5_password := Hash->MD5(password->ToByteArray()); + + ps : ParameterStatement; + if(@conn->IsOpen()) { + sql := "INSERT INTO users(username, pass_salt, pass_md5) VALUES (?, ?, ?)"; + ps := @conn->CreateParameterStatement(sql); + ps->SetVarchar(1, username); + ps->SetBytes(2, salt->ToByteArray()); + ps->SetBytes(3, md5_password); + + IO.Console->Print("adding user: username=")->Print(username) + ->Print(", salt=")->Print(salt) + ->Print(", status=")->PrintLine(ps->Update()); + }; + + leaving { + if(ps <> Nil) { + ps->Close(); + }; + }; + } + + method : IsEqual(left : Byte[], right : Byte[]) ~ Bool { + if(left->Size() <> right->Size()) { + return false; + }; + + each(i : left) { + if(left[i] <> right[i]) { + return false; + }; + }; + + return true; + } +} diff --git a/Task/Safe-addition/00DESCRIPTION b/Task/Safe-addition/00DESCRIPTION index e8e0d9c2c3..7e920c4d7e 100644 --- a/Task/Safe-addition/00DESCRIPTION +++ b/Task/Safe-addition/00DESCRIPTION @@ -1,4 +1,4 @@ -Implementation of [[wp:Interval_arithmetic|interval arithmetic]] and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations *↑ and *↓ defined as: ''a'' +↓ ''b'' ≤ ''a'' + ''b'' ≤ ''a'' +↑ ''b''. Additionally it is desired that the width of the interval (''a'' +↑ ''b'') - (''a'' +↓ ''b'') would be about the machine epsilon after removing the exponent part. +Implementation of [[wp:Interval_arithmetic|interval arithmetic]] and more generally fuzzy number arithmetic require operations that yield safe upper and lower bounds of the exact result. For example, for an addition, it is the operations +↑ and +↓ defined as: ''a'' +↓ ''b'' ≤ ''a'' + ''b'' ≤ ''a'' +↑ ''b''. Additionally it is desired that the width of the interval (''a'' +↑ ''b'') - (''a'' +↓ ''b'') would be about the machine epsilon after removing the exponent part. Differently to the standard floating-point arithmetic, safe interval arithmetic is '''accurate''' (but still imprecise). I.e. the result of each defined operation contains (though does not identify) the exact mathematical outcome. diff --git a/Task/Same-Fringe/D/same-fringe-2.d b/Task/Same-Fringe/D/same-fringe-2.d index 269f3c456d..85d854d2a2 100644 --- a/Task/Same-Fringe/D/same-fringe-2.d +++ b/Task/Same-Fringe/D/same-fringe-2.d @@ -41,7 +41,7 @@ struct Fringe(T) { alias const(BinaryTreeNode!T)* BT; private Stack!BT stack; - pure nothrow invariant() { + pure nothrow invariant { assert(stack.empty || isLeaf(stack.head)); } @@ -49,9 +49,9 @@ struct Fringe(T) { if (t != null) { stack.push(t); if (!isLeaf(t)) { - // Here invariant() doesn't hold. - // invariant() isn't called for private methods. - nextLeaf(); + // Here the invariant doesn't hold. + // invariant isn't called for private methods. + nextLeaf; } } } diff --git a/Task/Same-Fringe/D/same-fringe-3.d b/Task/Same-Fringe/D/same-fringe-3.d new file mode 100644 index 0000000000..654039254e --- /dev/null +++ b/Task/Same-Fringe/D/same-fringe-3.d @@ -0,0 +1,44 @@ +import std.stdio, std.concurrency, std.range, std.algorithm; + +struct Node(T) { + T data; + Node* L, R; +} + +Generator!T fringe(T)(Node!T* t1) { + return new typeof(return)({ + if (t1 != null) { + if (t1.L == null && t1.R == null) // Is a leaf. + yield(t1.data); + else + foreach (data; t1.L.fringe.chain(t1.R.fringe)) + yield(data); + } + }); +} + +bool sameFringe(T)(Node!T* t1, Node!T* t2) { + return t1.fringe.equal(t2.fringe); +} + +void main() { + alias N = Node!int; + + auto t1 = new N(10, new N(20, new N(30, new N(40), new N(50)))); + auto t2 = new N(1, new N(2, new N(3, new N(40), new N(50)))); + sameFringe(t1, t2).writeln; + + auto t3 = new N(1, new N(2, new N(3, new N(40), new N(51)))); + sameFringe(t1, t3).writeln; + + auto t4 = new N(1, new N(2, new N(3, new N(40)))); + sameFringe(t1, t4).writeln; + + N* t5; + sameFringe(t1, t5).writeln; + sameFringe(t5, t5).writeln; + + auto t6 = new N(2); + auto t7 = new N(1, new N(2)); + sameFringe(t6, t7).writeln; +} diff --git a/Task/Same-Fringe/REXX/same-fringe-3.rexx b/Task/Same-Fringe/REXX/same-fringe-3.rexx index c4949a57fc..87b643f505 100644 --- a/Task/Same-Fringe/REXX/same-fringe-3.rexx +++ b/Task/Same-Fringe/REXX/same-fringe-3.rexx @@ -1,87 +1,81 @@ -/*REXX pgm examines leaves of two binary trees. Tree used is as above.*/ -_=left('',28); say _ ' A A ' - say _ ' / \ ◄────1st tree / \ ' - say _ ' / \ / \ ' - say _ ' / \ / \ ' - say _ ' B C B C ' - say _ ' / \ / 2nd tree────► / \ / ' - say _ ' D E F D E F ' - say _ ' / / \ / / \ ' - say _ 'G H I G δ I ' -say; #=0 /*#: # of leaves. */ -parse var # done. 1 node. /*set all these variables to zero*/ -call make_tree '1st' -call make_tree '2nd' -z1=root.1st; L1=node.1st.z1; done.1st.z1=1 /*L1 is a leaf on 1st tree*/ -z2=z1; L2=node.2nd.z2; done.2nd.z2=1 /*L2 " " " " 2nd " */ +/*REXX program examines the leaves of two binary trees (as shown below).*/ +_=left('',28); say _ " A A " + say _ " / \ ◄════1st tree / \ " + say _ " / \ / \ " + say _ " / \ / \ " + say _ " B C B C " + say _ " / \ / 2nd tree════► / \ / " + say _ " D E F D E F " + say _ " / / \ / / \ " + say _ "G H I G δ I " +say +#=0; done.=0; node.=0 /*initialize # leaves,DONE.,NODE.*/ +call make_tree 1 /*define tree number 1 (1st tree)*/ +call make_tree 2 /* " " " 2 (2nd " )*/ +z1=root.1; L1=node.1.z1; done.1.z1=1 /*L1 is a leaf on tree number 1. */ +z2=z1; L2=node.2.z2; done.2.z2=1 /*L2 " " " " " " 2. */ - do #%2 /*loop for the number of leaves. */ + do # % 2 /*loop for the number of leaves. */ if L1==L2 then do - if L1==0 then call sayX 'The trees are equal.' - say ' The ' L1 " leaf is identical in both trees." - do until \done.1st.z1 - z1=go_next(z1,'1st'); L1=node.1st.z1 - end - done.1st.z1=1 - do until \done.2nd.z2 - z2=go_next(z2,'2nd'); L2=node.2nd.z2 - end - done.2nd.z2=1 + if L1==0 then call sayX 'The trees are equal.' + say ' The ' L1 " leaf is identical in both trees." + do until \done.1.z1 + z1=go_next(z1,1); L1=node.1.z1 + end + done.1.z1=1 + do until \done.2.z2 + z2=go_next(z2,2); L2=node.2.z2 + end + done.2.z2=1 end else select when L1==0 then call sayX L2 'exceeds leaves in 1st tree' when L2==0 then call sayX L1 'exceeds leaves in 2nd tree' - otherwise call sayX 'A difference is: ' L1 '¬=' L2 + otherwise call sayX 'A difference is: ' L1 '¬=' L2 end /*select*/ - end /*#%2*/ + end /*# % 2*/ exit /*──────────────────────────────────GO_NEXT subroutine──────────────────*/ -go_next: procedure expose node.; arg q,t /*find next node.*/ -next=0 -if node.t.q._Lson\==0 then /*is there a left branch in tree?*/ - if node.t.q._Lson.done==0 then do /*has this node been visited yet?*/ - next=node.t.q._Lson /*──► next node. */ - node.t.q._Lson.done=1 /*mark Lson done.*/ - end -if next==0 then - if node.t.q._Rson\==0 then /*is there a right tree branch ? */ - if node.t.q._Rson.done==0 then do /*has this node been visited yet?*/ - next=node.t.q._Rson /*──► next node*/ - node.t.q._Rson.done=1 /*mark Rson don*/ - end -if next==0 then next=node.t.q._dad /*process the father node. */ +go_next: procedure expose node.; arg q,t /*find next node.*/ +next=. +if node.t.q._Lson\==0 &, /*is there a left branch in tree?*/ + node.t.q._Lson.vis==0 then do /*has this node been visited yet?*/ + next=node.t.q._Lson /*──► next node. */ + node.t.q._Lson.vis=1 /*leftside done. */ + end +if next==. &, + node.t.q._Rson\==0 &, /*is there a right tree branch ? */ + node.t.q._Rson.vis==0 then do /*has this node been VISited yet?*/ + next=node.t.q._Rson /*──► next node. */ + node.t.q._Rson.vis=1 /*rightside done.*/ + end +if next==. then next=node.t.q._dad /*process the father node. */ return next /*the next node (or 0, if done).*/ /*──────────────────────────────────MAKE_NODE subroutine────────────────*/ -make_node: parse arg name,t; # = #+1 /*make a new node/branch on tree.*/ -q = node.t.0 + 1; node.t.q = name; node.t.q._dad = 0 -node.t.q._Lson = 0; node.t.q._Rson = 0; node.t.0 = q +make_node: parse arg name,t; # = #+1 /*make a new node/branch on tree.*/ +q = node.t.0 + 1 ; node.t.q = name ; node.t.q._dad = 0 +node.t.q._Lson = 0 ; node.t.q._Rson = 0 ; node.t.0 = q return q /*number of the node just created*/ /*──────────────────────────────────MAKE_TREE subroutine────────────────*/ -make_tree: procedure expose node. root. #; arg tree /*build a tree.*/ - hhh='δ' /*the odd duck in the whole tree.*/ -if tree=='1ST' then hhh='H' - a=make_node('A',tree); root.tree=a - b=make_node('B',tree); call sonL b,a,tree - c=make_node('C',tree); call sonR c,a,tree - d=make_node('D',tree); call sonL d,b,tree - e=make_node('E',tree); call sonR e,b,tree - f=make_node('F',tree); call sonL f,c,tree - g=make_node('G',tree); call sonL g,d,tree - /*quack?*/ h=make_node(hhh,tree); call sonL h,f,tree - i=make_node('I',tree); call sonR i,f,tree +make_tree: procedure expose node. root. #; parse arg tree /*build trees*/ +if tree==1 then hhh='H' /* [↓] must be a wood duck*/ + else hhh='δ' /*the odd duck in the whole tree.*/ + a=make_node('A', tree); root.tree=a + b=make_node('B', tree); call son 'L', b,a,tree + c=make_node('C', tree); call son 'R', c,a,tree + d=make_node('D', tree); call son 'L', d,b,tree + e=make_node('E', tree); call son 'R', e,b,tree + f=make_node('F', tree); call son 'L', f,c,tree + g=make_node('G', tree); call son 'L', g,d,tree +/*quacks like a duck?*/ h=make_node(hhh, tree); call son 'L', h,f,tree + i=make_node('I', tree); call son 'R', i,f,tree return /*──────────────────────────────────SAYX subroutine─────────────────────*/ -sayX: say; say arg(1); say; exit /*tell msg & exit.*/ -/*──────────────────────────────────SONL subroutine─────────────────────*/ -sonL: procedure expose node.; parse arg son,dad,t /*build left son. */ - node.t.son._dad=dad; q=node.t.dad._Lson -if q\==0 then do; node.t.q._dad=son; node.t.son._Lson=q; end -node.t.dad._Lson=son -return -/*──────────────────────────────────SONR subroutine─────────────────────*/ -sonR: procedure expose node.; parse arg son,dad,t /*build right son.*/ - node.t.son._dad=dad; q=node.t.dad._Rson -if q\==0 then do; node.t.q._dad=son; node.t.son._Rson=q; end -node.t.dad._Rson=son -if node.t.dad._Lson>0 then node.t.le._brother=node.t.dad._Rson +sayX: say; say arg(1); say; exit /*tell msg and exit.*/ +/*──────────────────────────────────SON subroutine──────────────────────*/ +son: procedure expose node.; parse arg ?,son,dad,t; LR = '_'?"SON" +node.t.son._dad=dad; q=node.t.dad.LR /*define which son [↑] */ +if q\==0 then do; node.t.q._dad=son; node.t.son.LR=q; end +node.t.dad.LR=son +if ?=='R' & node.t.dad.LR>0 then node.t.le._brother=node.t.dad.LR return diff --git a/Task/Same-Fringe/Scheme/same-fringe.ss b/Task/Same-Fringe/Scheme/same-fringe.ss new file mode 100644 index 0000000000..cd94d404dd --- /dev/null +++ b/Task/Same-Fringe/Scheme/same-fringe.ss @@ -0,0 +1,35 @@ +; binary tree helpers from "Structure and Interpretation of Computer Programs" 2.3.3 +(define (entry tree) (car tree)) +(define (left-branch tree) (cadr tree)) +(define (right-branch tree) (caddr tree)) +(define (make-tree entry left right) + (list entry left right)) + +; returns a list of leftmost nodes from each level of the tree +(define (descend tree ls) + (if (null? (left-branch tree)) + (cons tree ls) + (descend (left-branch tree) (cons tree ls)))) + +; updates the list to contain leftmost nodes from each remaining level +(define (ascend ls) + (cond + ((and (null? (cdr ls)) (null? (right-branch (car ls)))) '()) + ((null? (right-branch (car ls))) (cdr ls)) + (else + (let ((ls (cons (right-branch (car ls)) + (cdr ls)))) + (if (null? (left-branch (car ls))) + ls + (descend (left-branch (car ls)) ls)))))) + +; loops thru each list until the end (true) or nodes are unequal (false) +(define (same-fringe? t1 t2) + (let next ((l1 (descend t1 '())) + (l2 (descend t2 '()))) + (cond + ((and (null? l1) (null? l2)) #t) + ((or (null? l1) + (null? l2) + (not (eq? (entry (car l1)) (entry (car l2))))) #f) + (else (next (ascend l1) (ascend l2)))))) diff --git a/Task/Scope-Function-names-and-labels/Eiffel/scope-function-names-and-labels.e b/Task/Scope-Function-names-and-labels/Eiffel/scope-function-names-and-labels.e new file mode 100644 index 0000000000..2c46d2290a --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Eiffel/scope-function-names-and-labels.e @@ -0,0 +1,21 @@ +--assume A, B and C to be valid classes +class X +feature -- alias for "feature {ANY}" +-- ANY is the class at the top of the class hierarchy and all classes inherit from it +-- features following this clause are given "global" scope: these features are visible to every class + +feature {A, B, C, X} +-- features following this clause are only visible to the specified classes (and their descendants) +-- classes not in this set do not even know of the existence of these features + +feature {A, B, C} +-- similar to above, except other instances of X cannot access these features + +feature {X} +-- features following this clause are only visible to instances of X (and its descendants) + +feature {NONE} +-- NONE is the class at the bottom of the class hierarchy and inherits from every class +-- features following this clause are only visible to this particular instance of X + +end diff --git a/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-1.go b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-1.go new file mode 100644 index 0000000000..f76803d063 --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-1.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + "runtime" + + "ex" +) + +func main() { + // func nested() { ... not allowed here + + // this is okay, variable f declared and assigned a function literal. + f := func() { + // this mess prints the name of the function to show that it's an + // anonymous function defined in package main + pc, _, _, _ := runtime.Caller(0) + fmt.Println(runtime.FuncForPC(pc).Name(), "here!") + } + + ex.X(f) // function value passed to exported function + + // ex.x() non-exported function not visible here +} diff --git a/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-2.go b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-2.go new file mode 100644 index 0000000000..ea22caf9df --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-2.go @@ -0,0 +1,17 @@ +package ex + +import ( + "fmt" + "runtime" +) + +// X is exported. +func X(x func()) { + pc, _, _, _ := runtime.Caller(0) + fmt.Println(runtime.FuncForPC(pc).Name(), "calling argument x...") + x() +} + +func x() { // not exported, x not upper case. + panic("top level x") +} diff --git a/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-3.go b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-3.go new file mode 100644 index 0000000000..ad4ba8d94d --- /dev/null +++ b/Task/Scope-Function-names-and-labels/Go/scope-function-names-and-labels-3.go @@ -0,0 +1,29 @@ +package main + +import "fmt" + +func main() { + // labels loop and y both in scope of main +loop: + for false { + continue loop + } + goto y +y: + y := 0 // variable namespace is separate from label namespace + + func() { + // goto loop ...loop not visible from this literal + + // label y in outer scope not visible so it's okay to define a label y + // here too. + y: + for { + break y + } + y++ // regular lexical scoping applies to variables. + }() + fmt.Println(y) +} + +// end: // labels not allowed outside function blocks diff --git a/Task/Scope-Function-names-and-labels/REXX/scope-function-names-and-labels.rexx b/Task/Scope-Function-names-and-labels/REXX/scope-function-names-and-labels.rexx index ba680af863..951ca0d30b 100644 --- a/Task/Scope-Function-names-and-labels/REXX/scope-function-names-and-labels.rexx +++ b/Task/Scope-Function-names-and-labels/REXX/scope-function-names-and-labels.rexx @@ -1,13 +1,17 @@ -/*REXX program demonstrates use of labels and a CALL. */ +/*REXX program demonstrates use of labels and a CALL statement. */ zz=4 -signal do_add -ttt=sinD(30) /*this REXX statement is never executed.*/ +signal do_add /*transfer program control to a label.*/ +ttt=sinD(30) /*this REXX statement is never executed.*/ + /* [↓] Note the case doesn't matter. */ +do_Add: /*coming here from the SIGNAL statement.*/ -do_add: /*coming here from the SIGNAL statement.*/ +say 'calling the sub: add.2.args' +call add.2.args 1,7 /*pass two arguments: 1 and a 7 */ +say 'sum =' result +exit /*stick a fork in it, 'cause we're done.*/ +/*────────────────────────────────subroutines (or functions)────────────*/ +add.2.args: procedure; parse arg x,y; return x+y -say 'calling the sub add.2.args' -call add.2.args 1,7 -say 'sum=' result -exit /*stick a fork in it, 'cause we're done.*/ - -add.2.args: procedure; parse arg x,y; return x+y +add.2.args: say 'Whoa Nelly!! Has the universe run amok?' + /* [↑] dead code, never XEQed*/ +add.2.args: return arg(1) + arg(2) /*concise, but never executed.*/ diff --git a/Task/Scope-modifiers/00DESCRIPTION b/Task/Scope-modifiers/00DESCRIPTION index c4533ae259..344c6da0ac 100644 --- a/Task/Scope-modifiers/00DESCRIPTION +++ b/Task/Scope-modifiers/00DESCRIPTION @@ -1,3 +1,7 @@ -Most programming languages offer support for [[Creating a function|subroutines]]. When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). These sets may also be defined by special modifiers to the variable and function declarations. +Most programming languages offer support for [[Creating a function|subroutines]]. +When execution changes between subroutines, different sets of variables and functions ("scopes") are available to the program. +Frequently these sets are defined by the placement of the variable and function declarations ("static scoping" or "lexical scoping"). +These sets may also be defined by special modifiers to the variable and function declarations. -Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. If your language has no scope modifiers, note it. +Show the different scope modifiers available in your language and briefly explain how they change the scope of their variable or function. +If your language has no scope modifiers, note it. diff --git a/Task/Scope-modifiers/Eiffel/scope-modifiers.e b/Task/Scope-modifiers/Eiffel/scope-modifiers.e new file mode 100644 index 0000000000..dcd990b367 --- /dev/null +++ b/Task/Scope-modifiers/Eiffel/scope-modifiers.e @@ -0,0 +1,21 @@ +feature + some_procedure(int: INTEGER; char: CHARACTER) + local + r: REAL + i: INTEGER + do + -- r, i and s have scope here + -- as well as int and char + -- some_procedure and some_function additionally have scope here + end + + s: STRING + + some_function(int: INTEGER): INTEGER + do + -- s and Result have scope here + -- as well as int (int here differs from the int of some_procedure) + -- some_procedure and some_function additionally have scope here + end + + -- s, some_procedure and some_function have scope here diff --git a/Task/Scope-modifiers/Ruby/scope-modifiers.rb b/Task/Scope-modifiers/Ruby/scope-modifiers.rb new file mode 100644 index 0000000000..7a5d8e0edd --- /dev/null +++ b/Task/Scope-modifiers/Ruby/scope-modifiers.rb @@ -0,0 +1,9 @@ +class Demo + #public methods here + + protected + #protect methods here + + private + #private methods +end diff --git a/Task/Search-a-list/Maxima/search-a-list.maxima b/Task/Search-a-list/Maxima/search-a-list.maxima new file mode 100644 index 0000000000..8a52882fae --- /dev/null +++ b/Task/Search-a-list/Maxima/search-a-list.maxima @@ -0,0 +1,9 @@ +haystack: ["Zig","Zag","Wally","Ronald","Bush","Zig","Zag","Krusty","Charlie","Bush","Bozo"]; +needle: "Zag"; + +findneedle(needle, haystack, [opt]):=block([idx], + idx: sublist_indices(haystack, lambda([w], w=needle)), + if emptyp(idx) then throw('notfound), + if emptyp(opt) then return(idx), + opt: first(opt), + if opt='f then first(idx) else if opt='l then last(idx) else throw('unknownmode)); diff --git a/Task/Search-a-list/Python/search-a-list-3.py b/Task/Search-a-list/Python/search-a-list-3.py index d6b8f52d37..d3ac44d093 100644 --- a/Task/Search-a-list/Python/search-a-list-3.py +++ b/Task/Search-a-list/Python/search-a-list-3.py @@ -9,5 +9,4 @@ if haystack.count(n) == 1: assert hi == haystack.index(n), "index == hi_index if needle occurs only once" - >>> diff --git a/Task/Search-a-list/UNIX-Shell/search-a-list.sh b/Task/Search-a-list/UNIX-Shell/search-a-list.sh new file mode 100644 index 0000000000..5269a8f166 --- /dev/null +++ b/Task/Search-a-list/UNIX-Shell/search-a-list.sh @@ -0,0 +1,15 @@ +if [ $1 ];then +haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo" + +index=$(echo $haystack|tr " " "\n"|grep -in "^$1$") +if [ $? = 0 ];then +quantity_of_hits=$(echo $index|tr " " "\n"|wc -l|tr -d " ") +first_index=$(echo $index|cut -f 1 -d ":") +if [ $quantity_of_hits = 1 ];then +echo The sole index for $1 is: $first_index +else +echo The smallest index for $1 is: $first_index +greatest_index=$(echo $index|tr " " "\n"|tail -1|cut -f 1 -d ":") +echo "The greatest index for $1 is: $greatest_index";fi +else echo $1 is absent from haystatck.;fi +else echo Must provide string to find in haystack.;fi diff --git a/Task/Secure-temporary-file/Clojure/secure-temporary-file.clj b/Task/Secure-temporary-file/Clojure/secure-temporary-file.clj index 2300e7c00d..d1d9402f17 100644 --- a/Task/Secure-temporary-file/Clojure/secure-temporary-file.clj +++ b/Task/Secure-temporary-file/Clojure/secure-temporary-file.clj @@ -1,2 +1,3 @@ -user=> (doto (java.io.File/createTempFile "pre" ".suff") .deleteOnExit) -# +(let [temp-file (java.io.File/createTempFile "pre" ".suff")] + ; insert logic here that would use temp-file + (.delete temp-file)) diff --git a/Task/Secure-temporary-file/Emacs-Lisp/secure-temporary-file.l b/Task/Secure-temporary-file/Emacs-Lisp/secure-temporary-file.l new file mode 100644 index 0000000000..7241b786b6 --- /dev/null +++ b/Task/Secure-temporary-file/Emacs-Lisp/secure-temporary-file.l @@ -0,0 +1,3 @@ +(make-temp-file "prefix") +=> +"/tmp/prefix25452LPe" diff --git a/Task/Secure-temporary-file/Go/secure-temporary-file.go b/Task/Secure-temporary-file/Go/secure-temporary-file.go index e48c66a889..aa03714f37 100644 --- a/Task/Secure-temporary-file/Go/secure-temporary-file.go +++ b/Task/Secure-temporary-file/Go/secure-temporary-file.go @@ -1,3 +1,32 @@ -import "io/ioutil" +package main -file_obj, err := ioutil.TempFile("", "foo") +import ( + "fmt" + "io/ioutil" + "log" + "os" +) + +func main() { + f, err := ioutil.TempFile("", "foo") + if err != nil { + log.Fatal(err) + } + defer f.Close() + + // We need to make sure we remove the file + // once it is no longer needed. + defer os.Remove(f.Name()) + + // … use the file via 'f' … + fmt.Fprintln(f, "Using temporary file:", f.Name()) + f.Seek(0, 0) + d, err := ioutil.ReadAll(f) + if err != nil { + log.Fatal(err) + } + fmt.Printf("Wrote and read: %s\n", d) + + // The defer statements above will close and remove the + // temporary file here (or on any return of this function). +} diff --git a/Task/Secure-temporary-file/Icon/secure-temporary-file.icon b/Task/Secure-temporary-file/Icon/secure-temporary-file.icon new file mode 100644 index 0000000000..37e00f944b --- /dev/null +++ b/Task/Secure-temporary-file/Icon/secure-temporary-file.icon @@ -0,0 +1,5 @@ +procedure main() + write("Creating: ",fName := !open("mktemp","rp")) + write(f := open(fName,"w"),"Hello, world") + close(f) +end diff --git a/Task/Secure-temporary-file/Scala/secure-temporary-file.scala b/Task/Secure-temporary-file/Scala/secure-temporary-file.scala index 78a2159a63..5b2f9ab2a3 100644 --- a/Task/Secure-temporary-file/Scala/secure-temporary-file.scala +++ b/Task/Secure-temporary-file/Scala/secure-temporary-file.scala @@ -1,14 +1,18 @@ -import java.io.File +import java.io.{File, FileWriter, IOException} -try { - // Create temp file - val filename = File.createTempFile("prefix", ".suffix") + def writeStringToFile(file: File, data: String, appending: Boolean = false) = + using(new FileWriter(file, appending))(_.write(data)) - // Delete temp file when program exits - filename.deleteOnExit + def using[A <: {def close() : Unit}, B](resource: A)(f: A => B): B = + try f(resource) finally resource.close() - System.out.println(filename) - -} catch { - case _: java.io.IOException => -} + try { + val file = File.createTempFile("_rosetta", ".passwd") + // Just an example how you can fill a file + using(new FileWriter(file))(writer => rawDataIter.foreach(line => writer.write(line))) + scala.compat.Platform.collectGarbage() // JVM Windows related bug workaround JDK-4715154 + file.deleteOnExit() + println(file) + } catch { + case e: IOException => println(s"Running Example failed: ${e.getMessage}") + } diff --git a/Task/Self-describing-numbers/C++/self-describing-numbers.cpp b/Task/Self-describing-numbers/C++/self-describing-numbers-1.cpp similarity index 94% rename from Task/Self-describing-numbers/C++/self-describing-numbers.cpp rename to Task/Self-describing-numbers/C++/self-describing-numbers-1.cpp index 8ec259b3c0..5b03e8d9ba 100644 --- a/Task/Self-describing-numbers/C++/self-describing-numbers.cpp +++ b/Task/Self-describing-numbers/C++/self-describing-numbers-1.cpp @@ -71,4 +71,3 @@ int main( int argc, char* argv[] ) return 0; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/Self-describing-numbers/C++/self-describing-numbers-2.cpp b/Task/Self-describing-numbers/C++/self-describing-numbers-2.cpp new file mode 100644 index 0000000000..aa61cfc2c2 --- /dev/null +++ b/Task/Self-describing-numbers/C++/self-describing-numbers-2.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +bool is_self_describing(unsigned long long int n) noexcept { + if (n == 0) { + return false; + } + + std::array digits = {0}, counts = {0}; + std::size_t i = digits.size(); + + do { + counts[digits[--i] = n % 10]++; + } while ((n /= 10) > 0 && i < digits.size()); + + return n == 0 && std::equal(begin(digits) + i, end(digits), begin(counts)); +} + +int main() { + for (unsigned long long int i = 0; i < 10000000000; ++i) { + if (is_self_describing(i)) { + std::cout << i << "\n"; + } + } +} 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 cdea65c1a7..1501ddc2d1 100644 --- a/Task/Self-describing-numbers/D/self-describing-numbers-1.d +++ b/Task/Self-describing-numbers/D/self-describing-numbers-1.d @@ -1,10 +1,10 @@ import std.stdio, std.algorithm, std.range, std.conv, std.string; -bool isSelfDescribing(in long n) /*pure nothrow*/ { - auto nu = n.text.representation.map!q{a - '0'}; +bool isSelfDescribing(in long n) pure nothrow @safe { + auto nu = n.text.representation.map!q{ a - '0' }; return nu.length.iota.map!(a => nu.count(a)).equal(nu); } void main() { - 4_000_000.iota.filter!isSelfDescribing.writeln; + 4_000_.iota.filter!isSelfDescribing.writeln; } diff --git a/Task/Self-describing-numbers/D/self-describing-numbers-2.d b/Task/Self-describing-numbers/D/self-describing-numbers-2.d index 227f5d4bbe..69a209233c 100644 --- a/Task/Self-describing-numbers/D/self-describing-numbers-2.d +++ b/Task/Self-describing-numbers/D/self-describing-numbers-2.d @@ -1,6 +1,4 @@ -import std.stdio; - -bool isSelfDescribing2(long n) { +bool isSelfDescribing2(ulong n) nothrow @nogc { if (n <= 0) return false; @@ -8,35 +6,38 @@ bool isSelfDescribing2(long n) { digits[] = 0; d[] = 0; int i; + if (n < uint.max) { uint nu = cast(uint)n; for (i = 0; nu > 0 && i < digits.length; nu /= 10, i++) { - d[i] = cast(ubyte)(nu % 10); + d[i] = nu % 10; digits[d[i]]++; } if (nu > 0) return false; } else { for (i = 0; n > 0 && i < digits.length; n /= 10, i++) { - d[i] = cast(ubyte)(n % 10); + d[i] = n % 10; digits[d[i]]++; } if (n > 0) return false; } - foreach (k; 0 .. i) + foreach (immutable k; 0 .. i) if (d[k] != digits[i - k - 1]) return false; return true; } void main() { - foreach (x; [1210, 2020, 21200, 3211000, - 42101000, 521001000, 6210001000]) - assert(isSelfDescribing2(x)); + import std.stdio; - foreach (i; 0 .. 4_000_000) - if (isSelfDescribing2(i)) - writeln(i); + foreach (immutable x; [1210, 2020, 21200, 3211000, + 42101000, 521001000, 6210001000]) + assert(x.isSelfDescribing2); + + foreach (immutable i; 0 .. 4_000_000) + if (i.isSelfDescribing2) + i.writeln; } diff --git a/Task/Self-describing-numbers/PHP/self-describing-numbers.php b/Task/Self-describing-numbers/PHP/self-describing-numbers.php new file mode 100644 index 0000000000..f912626542 --- /dev/null +++ b/Task/Self-describing-numbers/PHP/self-describing-numbers.php @@ -0,0 +1,18 @@ + $value) { + if (substr_count($number, $place) != $value) { + return false; + } + } + return true; +} + +for ($i = 0; $i <= 50000000; $i += 10) { + if (is_describing($i)) { + echo $i . PHP_EOL; + } +} + +?> diff --git a/Task/Self-describing-numbers/Perl-6/self-describing-numbers.pl6 b/Task/Self-describing-numbers/Perl-6/self-describing-numbers.pl6 index 90e9224ea2..9ad674fdfd 100644 --- a/Task/Self-describing-numbers/Perl-6/self-describing-numbers.pl6 +++ b/Task/Self-describing-numbers/Perl-6/self-describing-numbers.pl6 @@ -2,17 +2,20 @@ my @values = <1210 2020 21200 3211000 42101000 521001000 6210001000 27 115508>; for @values -> $test { - say "$test is {$test.&sdn ?? '' !! 'NOT ' }a self describing number."; + say "$test is {sdn($test) ?? '' !! 'NOT ' }a self describing number."; } -sub sdn ($num) { - my @digits; - my $chars = $num.chars; - @digits[$_]++ for $num.comb; - return 0 if @digits.elems > $chars; - @digits[$_] //= '0' for ^$chars; - my $string = join '', @digits; - return 1 if $num eq $string; +sub sdn($n) { + my $s = $n.Str; + my $chars = $s.chars; + my @a = +«$s.comb; + my @b; + for @a -> $i { + return False if $i >= $chars; + ++@b[$i]; + } + @b[$_] //= 0 for ^$chars; + @a eqv @b; } -say $_ if $_.&sdn for ^9999999; +.say if .&sdn for ^9999999; diff --git a/Task/Self-describing-numbers/UNIX-Shell/self-describing-numbers.sh b/Task/Self-describing-numbers/UNIX-Shell/self-describing-numbers.sh new file mode 100644 index 0000000000..5fdcad93b7 --- /dev/null +++ b/Task/Self-describing-numbers/UNIX-Shell/self-describing-numbers.sh @@ -0,0 +1,20 @@ +selfdescribing() { + local n=$1 + local count=() + local i + for ((i=0; i<${#n}; i++)); do + ((count[${n:i:1}]++)) + done + for ((i=0; i<${#n}; i++)); do + (( ${n:i:1} == ${count[i]:-0} )) || return 1 + done + return 0 +} + +for n in 0 1 10 11 1210 2020 21200 3211000 42101000; do + if selfdescribing $n; then + printf "%d\t%s\n" $n yes + else + printf "%d\t%s\n" $n no + fi +done diff --git a/Task/Self-referential-sequence/D/self-referential-sequence-1.d b/Task/Self-referential-sequence/D/self-referential-sequence-1.d index 35ba0bfc29..e678bbb015 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-1.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-1.d @@ -1,15 +1,17 @@ import std.stdio, std.algorithm, std.conv; -string[] selfReferentialSeq(string n, string[] seen=[]) { - static string[][string] cache; - if (n in cache) return cache[n]; - if (canFind(seen, n)) return []; +string[] selfReferentialSeq(string n, string[] seen=[]) nothrow { + __gshared static string[][string] cache; + if (n in cache) + return cache[n]; + if (seen.canFind(n)) + return []; int[10] digit_count; - foreach (d; n) + foreach (immutable d; n) digit_count[d - '0']++; string term; - foreach_reverse (d; 0 .. 10) + foreach_reverse (immutable d; 0 .. 10) if (digit_count[d] > 0) term ~= text(digit_count[d], d); return cache[n] = [n] ~ selfReferentialSeq(term, [n] ~ seen); @@ -20,7 +22,7 @@ void main() { int max_len; int[] max_vals; - foreach (n; 1 .. limit) { + foreach (immutable n; 1 .. limit) { const seq = n.text().selfReferentialSeq(); if (seq.length > max_len) { max_len = seq.length; @@ -32,6 +34,6 @@ void main() { writeln("values: ", max_vals); writeln("iterations: ", max_len); writeln("sequence:"); - foreach (idx, val; max_vals[0].text().selfReferentialSeq()) + foreach (const idx, const val; max_vals[0].text.selfReferentialSeq) writefln("%2d %s", idx + 1, val); } 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 778dbfe160..48bc968f11 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-2.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-2.d @@ -8,7 +8,7 @@ struct Permutations(bool doCopy=true, T) { static if (!doCopy) T[] result; - this(T)(T[] items, int r=-1) pure /*nothrow*/ { + this(T)(T[] items, int r=-1) pure nothrow @safe { this.items = items; immutable int n = items.length; if (r < 0) @@ -20,19 +20,20 @@ struct Permutations(bool doCopy=true, T) { } else { this.stopped = false; this.indices = n.iota.array; - this.cycles = iota(n, n_minus_r, -1).array; + //this.cycles = iota(n, n_minus_r, -1).array; // Not nothrow. + this.cycles = iota(n_minus_r + 1, n + 1).retro.array; } static if (!doCopy) result = new T[r]; } - @property bool empty() const pure nothrow { + @property bool empty() const pure nothrow @safe @nogc { return this.stopped; } static if (doCopy) { - @property T[] front() const pure nothrow { + @property T[] front() const pure nothrow @safe { assert(!this.stopped); auto result = new T[r]; foreach (immutable i, ref re; result) @@ -40,7 +41,7 @@ struct Permutations(bool doCopy=true, T) { return result; } } else { - @property T[] front() pure nothrow { + @property T[] front() pure nothrow @safe @nogc { assert(!this.stopped); foreach (immutable i, ref re; this.result) re = items[indices[i]]; @@ -48,14 +49,14 @@ struct Permutations(bool doCopy=true, T) { } } - void popFront() pure /*nothrow*/ { + void popFront() pure nothrow /*@safe*/ @nogc { assert(!this.stopped); int i = r - 1; while (i >= 0) { immutable int j = cycles[i] - 1; if (j > 0) { cycles[i] = j; - swap(indices[i], indices[$ - j]); + indices[i].swap(indices[$ - j]); return; } cycles[i] = indices.length - i; @@ -63,7 +64,7 @@ struct Permutations(bool doCopy=true, T) { assert(n1 >= 0); immutable int num = indices[i]; - // copy isn't nothrow. + // copy isn't @safe. indices[i + 1 .. n1 + 1].copy(indices[i .. n1]); indices[n1] = num; i--; @@ -75,7 +76,7 @@ struct Permutations(bool doCopy=true, T) { Permutations!(doCopy, T) permutations(bool doCopy=true, T) (T[] items, int r=-1) -pure /*nothrow*/ { +pure nothrow @safe { return Permutations!(doCopy, T)(items, r); } @@ -86,8 +87,8 @@ import std.stdio, std.typecons, std.conv, std.algorithm, std.array, enum maxIters = 1_000_000; -string A036058(in string ns) pure { - return ns.group.map!(t => t[1].text ~ cast(char)t[0]).join; +string A036058(in string ns) pure nothrow @safe { + return ns.representation.group.map!(t => t[1].text ~ char(t[0])).join; } int A036058_length(bool doPrint=false)(string numberString="0") { @@ -99,12 +100,12 @@ int A036058_length(bool doPrint=false)(string numberString="0") { static if (doPrint) writefln(" %2d %s", iterations, numberString); - numberString = cast(string)(numberString - .dup - .representation - .sort() - .release - .assumeUnique); + numberString = numberString + .dup + .representation + .sort() + .release + .assumeUTF; if (lastThree[].canFind(numberString)) break; @@ -124,12 +125,12 @@ Tuple!(int,int[]) max_A036058_length(R)(R startRange = 11.iota) { auto max_len = tuple(-1, (int[]).init); foreach (n; startRange) { - immutable string sns = cast(string)(n - .to!(char[]) - .representation - .sort() - .release - .assumeUnique); + immutable sns = n + .to!(char[]) + .representation + .sort() + .release + .assumeUTF; if (sns !in alreadyDone) { alreadyDone[sns] = true; diff --git a/Task/Self-referential-sequence/D/self-referential-sequence-3.d b/Task/Self-referential-sequence/D/self-referential-sequence-3.d index 2a66b2d602..0db8e3759d 100644 --- a/Task/Self-referential-sequence/D/self-referential-sequence-3.d +++ b/Task/Self-referential-sequence/D/self-referential-sequence-3.d @@ -58,7 +58,7 @@ Rec* findRec(char* s, Rec* root) nothrow { next = root.p[c]; if (!next) { nNodes++; - next = recPool.newItem(); + next = recPool.newItem; root.p[c] = next; } root = next; @@ -66,7 +66,7 @@ Rec* findRec(char* s, Rec* root) nothrow { return root; } -void nextNum(char* s) nothrow { +void nextNum(char* s) nothrow @nogc { int[10] cnt; for (int i = 0; s[i]; i++) cnt[s[i] - '0']++; @@ -105,7 +105,7 @@ void main() nothrow { char[32] buf; rec_root = recPool.newItem(); - foreach (i; 0 .. MAXN) { + foreach (immutable i; 0 .. MAXN) { sprintf(buf.ptr, "%d", i); int l = getLen(buf.ptr, 0); if (l < ml) @@ -119,10 +119,10 @@ void main() nothrow { } printf("seq leng: %d\n\n", ml); - foreach (i; 0 .. nLongest) { + foreach (immutable i; 0 .. nLongest) { sprintf(buf.ptr, "%d", longest[i]); // print len+1 so we know repeating starts from when - foreach (l; 0 .. ml + 1) { + foreach (immutable l; 0 .. ml + 1) { printf("%2d: %s\n", getLen(buf.ptr, 0), buf.ptr); nextNum(buf.ptr); } diff --git a/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy b/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy index e72e9eedd6..64911f8aa7 100644 --- a/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy +++ b/Task/Self-referential-sequence/Groovy/self-referential-sequence-1.groovy @@ -1,13 +1,26 @@ Number.metaClass.getSelfReferentialSequence = { - def number = delegate as String; def sequence = [] + def number = delegate as String; def sequence = [] - while (!sequence.contains(number)) { - sequence << number - def encoded = new StringBuilder() - ((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit -> - encoded.append(text.size()).append(digit) - } - number = encoded.toString() + while (!sequence.contains(number)) { + sequence << number + def encoded = new StringBuilder() + ((number as List).sort().join('').reverse() =~ /(([0-9])\2*)/).each { matcher, text, digit -> + encoded.append(text.size()).append(digit) } - sequence + number = encoded.toString() + } + sequence +} + +def maxSeqSize = { List values -> + values.inject([seqSize: 0, seeds: []]) { max, n -> + if (n % 100000 == 99999) println 'HT' + else if (n % 10000 == 9999) print '.' + def seqSize = n.selfReferentialSequence.size() + switch (seqSize) { + case max.seqSize: max.seeds << n + case { it < max.seqSize }: return max + default: return [seqSize: seqSize, seeds: [n]] + } + } } diff --git a/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy b/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy index b061ddef87..8a9a9af594 100644 --- a/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy +++ b/Task/Self-referential-sequence/Groovy/self-referential-sequence-2.groovy @@ -1 +1,7 @@ -9009.selfReferentialSequence.each { println it } +def max = maxSeqSize(0..<1000000) + +println "\nLargest sequence size among seeds < 1,000,000\n" +println "Seeds: ${max.seeds}\n" +println "Size: ${max.seqSize}\n" +println "Sample sequence:" +max.seeds[0].selfReferentialSequence.each { println it } diff --git a/Task/Self-referential-sequence/Java/self-referential-sequence.java b/Task/Self-referential-sequence/Java/self-referential-sequence.java new file mode 100644 index 0000000000..20ef3eca98 --- /dev/null +++ b/Task/Self-referential-sequence/Java/self-referential-sequence.java @@ -0,0 +1,77 @@ +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.stream.IntStream; + +public class SelfReferentialSequence { + + static Map cache = new ConcurrentHashMap<>(10_000); + + public static void main(String[] args) { + Seeds res = IntStream.range(0, 1000_000) + .parallel() + .mapToObj(n -> summarize(n, false)) + .collect(Seeds::new, Seeds::accept, Seeds::combine); + + System.out.println("Seeds:"); + res.seeds.forEach(e -> System.out.println(Arrays.toString(e))); + + System.out.println("\nSequence:"); + summarize(res.seeds.get(0)[0], true); + } + + static int[] summarize(int seed, boolean display) { + String n = String.valueOf(seed); + + String k = Arrays.toString(n.chars().sorted().toArray()); + if (!display && cache.get(k) != null) + return new int[]{seed, cache.get(k)}; + + Set seen = new HashSet<>(); + StringBuilder sb = new StringBuilder(); + + int[] freq = new int[10]; + + while (!seen.contains(n)) { + seen.add(n); + + int len = n.length(); + for (int i = 0; i < len; i++) + freq[n.charAt(i) - '0']++; + + sb.setLength(0); + for (int i = 9; i >= 0; i--) { + if (freq[i] != 0) { + sb.append(freq[i]).append(i); + freq[i] = 0; + } + } + if (display) + System.out.println(n); + n = sb.toString(); + } + + cache.put(k, seen.size()); + + return new int[]{seed, seen.size()}; + } + + static class Seeds { + int largest = Integer.MIN_VALUE; + List seeds = new ArrayList<>(); + + void accept(int[] s) { + int size = s[1]; + if (size >= largest) { + if (size > largest) { + largest = size; + seeds.clear(); + } + seeds.add(s); + } + } + + void combine(Seeds acc) { + acc.seeds.forEach(this::accept); + } + } +} diff --git a/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx b/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx index 8d1d9da58c..7cf5e211c0 100644 --- a/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx +++ b/Task/Self-referential-sequence/REXX/self-referential-sequence.rexx @@ -1,14 +1,14 @@ -/*REXX program to generate a self-referential sequence and list the maxs*/ -parse arg low high .; maxL=0; seeds=; max$$= +/*REXX pgm generates a self-referential sequence and lists the maximums.*/ +parse arg low high .; maxL=0; seeds=; max$$= if low=='' then low=1 /*no low? Then use the default*/ -if high=='' then high=1000000 /*no high? " " " " */ +if high=='' then high=1000000 /* " high? " " " " */ /*══════════════════════════════════════════════════traipse through #'s.*/ - do seed=low to high; n=seed; $.=0; $$=n; $.n=1 + do seed=low to high; n=seed; $.=0; $$=n; $.n=1 - do j=1 until x==n /*generate interation sequence. */ + do j=1 until x==n /*generate a self─referential seq*/ x=n; n= - do k=9 to 0 by -1 /*gen new sequence*/ - _=countstr(k,x); if _\==0 then n=n || _ || k + do k=9 by -1 for 10 /*gen new sequence*/ + _=countstr(k,x); if _\==0 then n=n||_||k end /*k*/ if $.n then leave /*sequence been generated before?*/ $$=$$'-'n; $.n=1 /*add number to sequence & roster*/ @@ -28,8 +28,7 @@ hdr=copies('─',30); say 'maximum sequence length =' maxL do j=1 for words(max$$); say say hdr "iteration sequence for: " word(seeds,j) ' ('maxL "iterations)" q=translate(word(max$$,j),,'-') - do k=1 for words(q) - say word(q,k) - end /*k*/ + do k=1 for words(q); say word(q,k) + end /*k*/ end /*j*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Self-referential-sequence/TXR/self-referential-sequence-1.txr b/Task/Self-referential-sequence/TXR/self-referential-sequence-1.txr new file mode 100644 index 0000000000..af8902f0f6 --- /dev/null +++ b/Task/Self-referential-sequence/TXR/self-referential-sequence-1.txr @@ -0,0 +1,59 @@ +@(do + ;; Syntactic sugar for calling reduce-left + (defmacro reduce-with ((acc init item sequence) . body) + ^(reduce-left (lambda (,acc ,item) ,*body) ,sequence ,init)) + + ;; Macro similar to clojure's ->> and -> + (defmacro opchain (val . ops) + ^[[chain ,*[mapcar [iffi consp (op cons 'op)] ops]] ,val]) + + ;; Reduce integer to a list of integers representing its decimal digits. + (defun digits (n) + (if (< n 10) + (list n) + (opchain n tostring list-str (mapcar (op - @1 #\0))))) + + (defun dcount (ds) + (digits (length ds))) + + ;; Perform a look-say step like (1 2 2) --"one 1, two 2's"-> (1 1 2 2). + (defun summarize-prev (ds) + (opchain ds copy (sort @1 >) (partition-by identity) + (mapcar [juxt dcount first]) flatten)) + + ;; Take a starting digit string and iterate the look-say steps, + ;; to generate the whole sequence, which ends when convergence is reached. + (defun convergent-sequence (ds) + (reduce-with (cur-seq nil ds [giterate true summarize-prev ds]) + (if (member ds cur-seq) + (return-from convergent-sequence cur-seq) + (nconc cur-seq (list ds))))) + + ;; A candidate sequence is one which begins with montonically + ;; decreasing digits. We don't bother with (9 0 9 0) or (9 0 0 9); + ;; which yield identical sequences to (9 9 0 0). + (defun candidate-seq (n) + (let ((ds (digits n))) + (if [apply >= ds] + (convergent-sequence ds)))) + + ;; Discover the set of longest sequences. + (defun find-longest (limit) + (reduce-with (max-seqs nil new-seq [mapcar candidate-seq (range 1 limit)]) + (let ((cmp (- (opchain max-seqs first length) (length new-seq)))) + (cond ((> cmp 0) max-seqs) + ((< cmp 0) (list new-seq)) + (t (nconc max-seqs (list new-seq))))))) + + (defvar *results* (find-longest 1000000)) + + (each ((result *results*)) + (flet ((strfy (list) ;; (strfy '((1 2 3 4) (5 6 7 8))) -> ("1234" "5678") + (mapcar [chain (op mapcar tostring) cat-str] list))) + (let* ((seed (first result)) + (seeds (opchain seed perm uniq (remove-if zerop @1 first)))) + (put-line `Seed value(s): @(strfy seeds)`) + (put-line) + (put-line `Iterations: @(length result)`) + (put-line) + (put-line `Sequence: @(strfy result)`))))) diff --git a/Task/Self-referential-sequence/TXR/self-referential-sequence-2.txr b/Task/Self-referential-sequence/TXR/self-referential-sequence-2.txr new file mode 100644 index 0000000000..f9a12b59d1 --- /dev/null +++ b/Task/Self-referential-sequence/TXR/self-referential-sequence-2.txr @@ -0,0 +1,32 @@ +@(do + (defun count-and-say (str) + (let* ((s [sort (copy-str str) <]) + (out `@[s 0]0`)) + (each ((x s)) + (if (eql x [out -1]) + (inc [out -2]) + (set out `@{out}1@x`))) + out)) + + (defun ref-seq-len (n : doprint) + (let ((s (tostring n)) hist) + (while t + (push s hist) + (if doprint (pprinl s)) + (set s (count-and-say s)) + (each ((item hist) + (i (range 0 2))) + (when (equal s item) + (return-from ref-seq-len (length hist))))))) + + (defun find-longest (top) + (let (nums (len 0)) + (each ((x (range 0 top))) + (let ((l (ref-seq-len x))) + (when (> l len) (set len l) (set nums nil)) + (when (= l len) (push x nums)))) + (list nums len))) + + (let ((r (find-longest 1000000))) + (format t "Longest: ~a\n" r) + (ref-seq-len (first (first r)) t))) diff --git a/Task/Self-referential-sequence/TXR/self-referential-sequence-3.txr b/Task/Self-referential-sequence/TXR/self-referential-sequence-3.txr new file mode 100644 index 0000000000..26b959d698 --- /dev/null +++ b/Task/Self-referential-sequence/TXR/self-referential-sequence-3.txr @@ -0,0 +1,47 @@ +@(do + ;; Macro very similar to Racket's for/fold + (defmacro for-accum (accum-var-inits each-vars . body) + (let ((accum-vars [mapcar first accum-var-inits]) + (block-sym (gensym)) + (next-args [mapcar (ret (progn @rest (gensym))) accum-var-inits]) + (nvars (length accum-var-inits))) + ^(let ,accum-var-inits + (flet ((iter (,*next-args) + ,*[mapcar (ret ^(set ,@1 ,@2)) accum-vars next-args])) + (each ,each-vars + ,*body) + (list ,*accum-vars))))) + + (defun next (s) + (let ((v (vector 10 0))) + (each ((c s)) + (inc [v (- #\9 c)])) + (cat-str + (collect-each ((x v) + (i (range 9 0 -1))) + (when (> x 0) + `@x@i`))))) + + (defun seq-of (s) + (for* ((ns ())) + ((not (member s ns)) (reverse ns)) + ((push s ns) (set s (next s))))) + + (defun sort-string (s) + [sort (copy s) >]) + + (tree-bind (len nums seq) + (for-accum ((*len nil) (*nums nil) (*seq nil)) + ((n (range 1000000 0 -1))) ;; start at the high end + (let* ((s (tostring n)) + (sorted (sort-string s))) + (if (equal s sorted) + (let* ((seq (seq-of s)) + (len (length seq))) + (cond ((or (not *len) (> len *len)) (iter len (list s) seq)) + ((= len *len) (iter len (cons s *nums) seq)))) + (iter *len + (if (and *nums (member sorted *nums)) (cons s *nums) *nums) + *seq)))) + (put-line `Numbers: @{nums ", "}\nLength: @len`) + (each ((n seq)) (put-line ` @n`))) diff --git a/Task/Semordnilap/Aime/semordnilap.aime b/Task/Semordnilap/Aime/semordnilap.aime index 271519b279..3ccd7fa31a 100644 --- a/Task/Semordnilap/Aime/semordnilap.aime +++ b/Task/Semordnilap/Aime/semordnilap.aime @@ -7,7 +7,7 @@ reverse(text s) i = length(s); while (i) { i -= 1; - b_insert(b, -1, character(s, i)); + b_insert(b, -1, s[i]); } return b_string(b); @@ -50,9 +50,7 @@ main(void) } while (r_greater(r, s, s)); } - o_text("Semordnilap pairs: "); - o_integer(p); - o_text("\n"); + o_form("Semordnilap pairs: ~\n", p); return 0; } diff --git a/Task/Semordnilap/Clojure/semordnilap.clj b/Task/Semordnilap/Clojure/semordnilap.clj index 37b96f7511..53f56924c0 100644 --- a/Task/Semordnilap/Clojure/semordnilap.clj +++ b/Task/Semordnilap/Clojure/semordnilap.clj @@ -1,21 +1,24 @@ -(use 'clojure.java.io) -(require '[clojure.string :as string]) +(ns rosettacode.semordnilaps + (:require [clojure.string :as str]) + [clojure.java.io :as io ])) -(def dict-file (or (first *command-line-args*) "unixdict.txt")) +(def dict-file + (or (first *command-line-args*) "unixdict.txt")) -(def dict (set (line-seq (reader dict-file)))) +(def dict (-> dict-file io/reader line-seq set)) (defn semordnilap? [word] - (let [rev (string/reverse word)] - (and (not (= word rev)) (dict rev)))) + (let [rev (str/reverse word)] + (and (not= word rev) (dict rev)))) (def semordnilaps - (filter (fn [[x y]] (<= (compare x y) 0)) - (map (fn [word] [word (string/reverse word)]) - (filter semordnilap? dict)))) + (->> dict + (filter semordnilap?) + (map #([% (str/reverse %)])) + (filter (fn [[x y]] (<= (compare x y) 0))))) (printf "There are %d semordnilaps in %s. Here are 5:\n" (count semordnilaps) dict-file) -(dorun (map println (sort (take 5 (shuffle semordnilaps))))) +(dorun (->> semordnilaps shuffle (take 5) sort (map println))) diff --git a/Task/Semordnilap/D/semordnilap-1.d b/Task/Semordnilap/D/semordnilap-1.d index 9fe4275413..0013f71ca8 100644 --- a/Task/Semordnilap/D/semordnilap-1.d +++ b/Task/Semordnilap/D/semordnilap-1.d @@ -1,11 +1,13 @@ -import std.stdio, std.file, std.string, std.algorithm; - void main() { + import std.stdio, std.file, std.string, std.algorithm; + bool[string] seenWords; size_t pairCount = 0; - foreach (const word; readText("unixdict.txt").toLower.splitter) { - const drow = word.dup.reverse; // Deprecated. + foreach (const word; "unixdict.txt".readText.toLower.splitter) { + //const drow = word.dup.reverse(); + auto drow = word.dup; + drow.reverse(); if (drow in seenWords) { if (pairCount++ < 5) writeln(word, " ", drow); diff --git a/Task/Semordnilap/Eiffel/semordnilap-1.e b/Task/Semordnilap/Eiffel/semordnilap-1.e new file mode 100644 index 0000000000..ea5a951358 --- /dev/null +++ b/Task/Semordnilap/Eiffel/semordnilap-1.e @@ -0,0 +1,80 @@ +note + description: "Summary description for {SEMORDNILAP}." + author: "" + date: "$Date$" + revision: "$Revision$" + +class + SEMORDNILAP +create + make + + feature + make + --read wordlist "unixdict.txt", search across wordlist with binary_search + local + count,i,j, middle, upper, lower: INTEGER + reverse: STRING + do + read_wordlist + create solution.make_empty + from + i:= 1 + until + i> word_array.count + loop + word_array[i].mirror + reverse:=word_array[i] + from + lower:= i+1 + upper:= word_array.count + until + lower>=upper + loop + + middle:= (upper-lower)//2+lower + if reverse.is_case_insensitive_equal (word_array[middle]) then + count:= count+1 + upper:= 0 + lower:= 1 + solution.force (word_array[middle],count) + elseif reverse.is_less (word_array[middle]) then + upper:= middle-1 + else + lower:= middle+1 + end + end + if lower < word_array.count and then reverse.is_case_insensitive_equal (word_array[lower]) then + count:= count+1 + upper:= 0 + lower:= 1 + solution.force (word_array[middle],count) + end + i:= i+1 + end + end + + solution: ARRAY[STRING] + +feature {NONE} + read_wordlist + local + l_file: PLAIN_TEXT_FILE + wordlist: LIST[STRING] + i: INTEGER + do + create l_file.make_open_read_write ("unixdict.txt") + l_file.read_stream (l_file.count) + wordlist:=l_file.last_string.split ('%N') + create word_array.make_empty + from + i:= 1 + until + i> wordlist.count + loop + word_array.force( wordlist.at (i),i) + i:= i+1 + end + end + word_array: ARRAY[STRING] +end diff --git a/Task/Semordnilap/Eiffel/semordnilap-2.e b/Task/Semordnilap/Eiffel/semordnilap-2.e new file mode 100644 index 0000000000..9b26bdb297 --- /dev/null +++ b/Task/Semordnilap/Eiffel/semordnilap-2.e @@ -0,0 +1,16 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + create se.make + across se.solution.subarray (27, 32)as s loop io.put_string (s.item.out+"%T"); s.item.mirror; io.put_string(s.item.out+"%N") end + io.put_string ("There are "+se.solution.count.out+" pairs.") + end + + se: SEMORDNILAP +end diff --git a/Task/Semordnilap/Java/semordnilap.java b/Task/Semordnilap/Java/semordnilap.java index e973f04a9a..82f657e1ae 100644 --- a/Task/Semordnilap/Java/semordnilap.java +++ b/Task/Semordnilap/Java/semordnilap.java @@ -1,13 +1,14 @@ -import java.io.*; +import java.nio.file.*; import java.util.*; -public class Semordnilaps { +public class Semordnilap { - public static void main(String[] args) throws IOException { - List lst = readLines("unixdict.txt"); + public static void main(String[] args) throws Exception { + List lst = Files.readAllLines(Paths.get("unixdict.txt")); Set seen = new HashSet<>(); int count = 0; for (String w : lst) { + w = w.toLowerCase(); String r = new StringBuilder(w).reverse().toString(); if (seen.contains(r)) { if (count++ < 5) @@ -16,15 +17,4 @@ public class Semordnilaps { } System.out.println("\nSemordnilap pairs found: " + count); } - - private static List readLines(String fn) throws IOException { - List lines; - try (BufferedReader br = new BufferedReader(new FileReader(fn))) { - lines = new ArrayList<>(); - String line; - while ((line = br.readLine()) != null) - lines.add(line.trim().toLowerCase()); - } - return lines; - } } diff --git a/Task/Semordnilap/Mathematica/semordnilap.math b/Task/Semordnilap/Mathematica/semordnilap.math index d4121e1e33..e81dcd7bc0 100644 --- a/Task/Semordnilap/Mathematica/semordnilap.math +++ b/Task/Semordnilap/Mathematica/semordnilap.math @@ -1,3 +1,4 @@ data = Import["http://www.puzzlers.org/pub/wordlists/unixdict.txt", "List"]; -result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]] && # =!= StringReverse[#] &], (# ===StringReverse[#2]) &]; +result = DeleteDuplicates[ Select[data, MemberQ[data, StringReverse[#]] + && # =!= StringReverse[#] &], (# ===StringReverse[#2]) &]; Print[Length[result], Take[result, 5]] diff --git a/Task/Semordnilap/REXX/semordnilap-2.rexx b/Task/Semordnilap/REXX/semordnilap-2.rexx index e014ab994e..3f884e033c 100644 --- a/Task/Semordnilap/REXX/semordnilap-2.rexx +++ b/Task/Semordnilap/REXX/semordnilap-2.rexx @@ -1,15 +1,15 @@ -/*REXX program finds palindrome pairs using a dictionary (UNIXDICT.TXT)*/ -#=0 /*number of palindromes (so far).*/ -parse arg iFID .; if iFID=='' then iFID='UNIXDICT.TXT' /*use default?*/ -@.= /*caseless non-duplicated words. */ - do while lines(ifid)\==0; _=linein(iFID); u=translate(space(_,0)) - if length(u)<2 | @.u\=='' then iterate /*can't be a unique pal.*/ - r=reverse(u) - if @.r\=='' then do; #=#+1 /*found palindrome pair.*/ - if #<6 then say @.r',' _ /*only list first 5 pals*/ - end - @.u=_ - end /*while*/ -say /*a unique palindrome pair = a semordnilap*/ -say "There're" # 'unique palindrome pairs in the dictionary file:' iFID +/*REXX program finds palindrome pairs using a dictionary (UNIXDICT.TXT).*/ +#=0 /*# palindromes (so far)*/ +parse arg iFID .; if iFID=='' then iFID='UNIXDICT.TXT' /*use default?*/ +@.= /*caseless no-duped word*/ + do while lines(iFID)\==0; _=space(linein(iFID),0); parse upper var _ u + if length(_)<2 | @.u\=='' then iterate /*can't be a unique pal.*/ + r=reverse(u) /*get the reverse of U. */ + if @.r\=='' then do; #=#+1 /*found palindrome pair?*/ + if #<6 then say @.r',' _ /*only list first 5 pals*/ + end /* [↑] bump count, show*/ + @.u=_ /*define palindromic pal*/ + end /*while*/ /* [↑] read dictionary.*/ +say +say "There're" # 'unique palindrome pairs in the dictionary file: ' iFID /*stick a fork in it, we're done.*/ diff --git a/Task/Semordnilap/Ruby/semordnilap.rb b/Task/Semordnilap/Ruby/semordnilap.rb index 89239a4acd..baf9159ccc 100644 --- a/Task/Semordnilap/Ruby/semordnilap.rb +++ b/Task/Semordnilap/Ruby/semordnilap.rb @@ -1,8 +1,8 @@ -DICT=File.readlines("unixdict.txt").collect &:chomp +dict = File.readlines("unixdict.txt").collect(&:strip) i = 0 -res = DICT.collect(&:reverse).sort.select {|z| - i+=1 while z > DICT[i] and i < DICT.length-1 - z == DICT[i] and z < z.reverse -} +res = dict.collect(&:reverse).sort.select do |z| + i += 1 while z > dict[i] and i < dict.length-1 + z == dict[i] and z < z.reverse +end puts "There are #{res.length} semordnilaps, of which the following are 5:" -res.sample(5).each {|z| puts "#{z} #{z.reverse}"} +res.take(5).each {|z| puts "#{z} #{z.reverse}"} diff --git a/Task/Send-an-unknown-method-call/J/send-an-unknown-method-call.j b/Task/Send-an-unknown-method-call/J/send-an-unknown-method-call.j new file mode 100644 index 0000000000..352c17ecd7 --- /dev/null +++ b/Task/Send-an-unknown-method-call/J/send-an-unknown-method-call.j @@ -0,0 +1,21 @@ + sum =: +/ + prod =: */ + count =: # + + nameToDispatch =: 'sum' NB. pick a name already defined + + ". nameToDispatch,' 1 2 3' +6 + nameToDispatch~ 1 2 3 +6 + nameToDispatch (128!:2) 1 2 3 +6 + + nameToDispatch =: 'count' NB. pick another name + + ". nameToDispatch,' 1 2 3' +3 + nameToDispatch~ 1 2 3 +3 + nameToDispatch (128!:2) 1 2 3 +3 diff --git a/Task/Send-an-unknown-method-call/Mathematica/send-an-unknown-method-call.math b/Task/Send-an-unknown-method-call/Mathematica/send-an-unknown-method-call.math new file mode 100644 index 0000000000..4aa5c15606 --- /dev/null +++ b/Task/Send-an-unknown-method-call/Mathematica/send-an-unknown-method-call.math @@ -0,0 +1 @@ +ToExpression[Input["function? E.g. Sin",]][Input["value? E.g. 0.4123"]] diff --git a/Task/Send-an-unknown-method-call/Scala/send-an-unknown-method-call.scala b/Task/Send-an-unknown-method-call/Scala/send-an-unknown-method-call.scala new file mode 100644 index 0000000000..43dd5c04ca --- /dev/null +++ b/Task/Send-an-unknown-method-call/Scala/send-an-unknown-method-call.scala @@ -0,0 +1,12 @@ +class Example { + def foo(x: Int): Int = 42 + x +} + +object Main extends App { + val example = new Example + + val meth = example.getClass.getMethod("foo", classOf[Int]) + + assert(meth.invoke(example, 5.asInstanceOf[AnyRef]) == 47.asInstanceOf[AnyRef], "Not confirm expectation.") + println(s"Successfully completed without errors. [total ${scala.compat.Platform.currentTime - executionStart} ms]") +} diff --git a/Task/Send-email/Clojure/send-email.clj b/Task/Send-email/Clojure/send-email.clj new file mode 100644 index 0000000000..3d63f3f18d --- /dev/null +++ b/Task/Send-email/Clojure/send-email.clj @@ -0,0 +1,11 @@ +(require '[postal.core :refer [send-message]]) + +(send-message {:host "smtp.gmail.com" + :ssl true + :user your_username + :pass your_password} + {:from "you@yourdomain.com" + :to ["your_friend@example.com"] + :cc ["bob@builder.com" "dora@explorer.com"] + :subject "Yo" + :body "Testing."}) diff --git a/Task/Send-email/D/send-email.d b/Task/Send-email/D/send-email.d index 0deef206e0..4e9fc74cfc 100644 --- a/Task/Send-email/D/send-email.d +++ b/Task/Send-email/D/send-email.d @@ -1,10 +1,10 @@ -import std.net.curl; - void main() { - auto smtp = SMTP("smtps://smtp.gmail.com"); - smtp.setAuthentication("someuser@gmail.com", "somepassword"); - smtp.mailTo = [""]; - smtp.mailFrom = ""; - smtp.message = "Subject:test\n\nExample Message"; - smtp.perform(); + import std.net.curl; + + auto s = SMTP("smtps://smtp.gmail.com"); + s.setAuthentication("someuser@gmail.com", "somepassword"); + s.mailTo = [""]; + s.mailFrom = ""; + s.message = "Subject:test\n\nExample Message"; + s.perform; } diff --git a/Task/Send-email/Go/send-email.go b/Task/Send-email/Go/send-email-1.go similarity index 100% rename from Task/Send-email/Go/send-email.go rename to Task/Send-email/Go/send-email-1.go diff --git a/Task/Send-email/Go/send-email-2.go b/Task/Send-email/Go/send-email-2.go new file mode 100644 index 0000000000..fb1360862f --- /dev/null +++ b/Task/Send-email/Go/send-email-2.go @@ -0,0 +1,7 @@ +procedure main(args) + mail := open("mailto:"||args[1], "m", "Subject : "||args[2], + "X-Note: automatically send by Unicon") | + stop("Cannot send mail to ",args[1]) + every write(mail , !&input) + close (mail) +end diff --git a/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares.coffee b/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares.coffee new file mode 100644 index 0000000000..9290f11d4c --- /dev/null +++ b/Task/Sequence-of-non-squares/CoffeeScript/sequence-of-non-squares.coffee @@ -0,0 +1,19 @@ +non_square = (n) -> n + Math.floor(1/2 + Math.sqrt(n)) + +is_square = (n) -> + r = Math.floor(Math.sqrt(n)) + r * r is n + +do -> + first_22_non_squares = (non_square i for i in [1..22]) + console.log first_22_non_squares + + # test is_square has no false negatives: + for i in [1..10000] + throw Error("is_square broken") unless is_square i*i + + # test non_square is valid for first million values of n + for i in [1..1000000] + throw Error("non_square broken") if is_square non_square(i) + + console.log "success" diff --git a/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d b/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d index 47710f48a0..85217cf267 100644 --- a/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d +++ b/Task/Sequence-of-non-squares/D/sequence-of-non-squares.d @@ -1,6 +1,6 @@ import std.stdio, std.math, std.algorithm, std.range; -int nonSquare(in int n) pure nothrow { +int nonSquare(in int n) pure nothrow @safe @nogc { return n + cast(int)(0.5 + real(n).sqrt); } diff --git a/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e b/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e new file mode 100644 index 0000000000..618c6d472f --- /dev/null +++ b/Task/Sequence-of-non-squares/Eiffel/sequence-of-non-squares.e @@ -0,0 +1,42 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + non_square(22) + end + + non_square(n:INTEGER) + require + n_positive: n>=1 + local + i: INTEGER + non_sq, part: REAL_64 + math: DOUBLE_MATH + square: BOOLEAN + do + create math + from + i:= 1 + until + i> n + loop + part:=(0.5+math.sqrt (i.to_double)) + non_sq:= i+part.floor + io.put_string (non_sq.out + " ") + if math.sqrt (non_sq)-math.sqrt (non_sq).floor=0 then + square:= True + end + i:= i+1 + end + if square= TRUE then + io.put_string ("%NThere are squares for n equal to "+ n.out + "." ) + else + io.put_string ("%NThere are no squares for n equal to "+ n.out + ".") + end + end +end diff --git a/Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares.pascal b/Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-1.pascal similarity index 100% rename from Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares.pascal rename to Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-1.pascal diff --git a/Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-2.pascal b/Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-2.pascal new file mode 100644 index 0000000000..34a0dae891 --- /dev/null +++ b/Task/Sequence-of-non-squares/Pascal/sequence-of-non-squares-2.pascal @@ -0,0 +1,50 @@ +program seqNonSq; + //sequence of non-squares + //n = i + floor(1/2 + sqrt(i)) + function NonSquare(i: LongInt): LongInt; + Begin + NonSquare := i+trunc(sqrt(i) + 0.5); + end; + + procedure First22; + var + i : integer; + begin + For i := 1 to 21 do + write(NonSquare(i):3,','); + writeln(NonSquare(22):3); + end; + + procedure OutSquare(i: integer); + var + n : LongInt; + begin + n := NonSquare(i); + writeln('Square ',n,' found at ',i); + end; + +procedure Test(Limit: LongWord); + var + i ,n,sq,sn : LongWord; + Begin + sn := 1; + sq := 1; + For i := 1 to Limit do + begin + n := NonSquare(i); + if n >= sq then + begin + if n > sq then + begin + sq := sq+2*sn+1; inc(sn); + end + else + OutSquare(i); + end; + end; + end; + + Begin + First22; + Test(1000*1000*1000); + end. diff --git a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx index 7812d2a68e..3014021735 100644 --- a/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx +++ b/Task/Sequence-of-non-squares/REXX/sequence-of-non-squares.rexx @@ -1,35 +1,27 @@ -/*REXX program to show some non-square numbers.*/ - - do j=1 for 22 - say right(j,6) right(j+floor(1/2 + sqrt(j)),7) - end - +/*REXX program displays some non─square numbers (with validation check).*/ + do j=1 for 22 + say right(j,6) right(j+floor(1/2 + sqrt(j)),7) + end /*j*/ oops=0 - - do k=1 for 1000000-1 - n=k+floor(.5+sqrt(k)) - iroot=isqrt(n) - if iroot*iroot==n then oops=oops+1 - end - + do k=1 for 1000000-1 + n=k+floor(.5+sqrt(k)) + iroot=isqrt(n) + if iroot*iroot==n then oops=oops+1 + end /*k*/ say -say oops 'squares found up to' k-1 -exit - -/*-------------------------------FLOOR subroutine----------------------*/ -floor:procedure; parse arg x;return trunc(x-(x<0)) - -/*-------------------------------SQRT subroutine-----------------------*/ -sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() -numeric digits 11; g=x/4; m.=11; p=d+d%4+2 - 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 /*return the normalized square root of X.*/ - -/*-------------------------------ISQRT subroutine----------------------*/ -isqrt:procedure;parse arg x; x=trunc(x); r=0; q=1 +say oops 'squares found up to' k-1 +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────FLOOR subroutine────────────────────*/ +floor: procedure; parse arg x; return trunc(x- (x<0) ) +/*──────────────────────────────────ISQRT subroutine────────────────────*/ +isqrt: procedure; parse arg x; x=trunc(x); r=0; q=1 do while q<=x; q=q*4; end - do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_; r=r+q; end - end -return r /*return the integer square root of X.*/ + do while q>1; q=q%4; _=x-r-q; r=r%2; if _>=0 then do; x=_;r=r+q;end;end +return r /*return the integer square root of X. */ +/*──────────────────────────────────SQRT subroutine─────────────────────*/ +sqrt: procedure; parse arg x,f; if x=0 then return 0; d=digits() +numeric digits 11; g=x/4; m.=11; p=d+d%4+2 + 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 /*return the normalized square root of X.*/ diff --git a/Task/Set-consolidation/D/set-consolidation-1.d b/Task/Set-consolidation/D/set-consolidation-1.d index 039df92bd1..b428df7a07 100644 --- a/Task/Set-consolidation/D/set-consolidation-1.d +++ b/Task/Set-consolidation/D/set-consolidation-1.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm, std.array; -dchar[][] consolidate(dchar[][] sets) { +dchar[][] consolidate(dchar[][] sets) @safe { foreach (set; sets) - set.sort; + set.sort(); foreach (i, ref si; sets[0 .. $ - 1]) { if (si.empty) @@ -17,7 +17,7 @@ dchar[][] consolidate(dchar[][] sets) { return sets.filter!"!a.empty".array; } -void main() { +void main() @safe { [['A', 'B'], ['C','D']].consolidate.writeln; [['A','B'], ['B','D']].consolidate.writeln; diff --git a/Task/Set-consolidation/D/set-consolidation-2.d b/Task/Set-consolidation/D/set-consolidation-2.d index 90784204ed..6280d36d75 100644 --- a/Task/Set-consolidation/D/set-consolidation-2.d +++ b/Task/Set-consolidation/D/set-consolidation-2.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm, std.array; -dchar[][] consolidate(dchar[][] sets) { +dchar[][] consolidate(dchar[][] sets) @safe { foreach (set; sets) - set.sort; + set.sort(); dchar[][] consolidateR(dchar[][] s) { if (s.length < 2) @@ -20,7 +20,7 @@ dchar[][] consolidate(dchar[][] sets) { return consolidateR(sets); } -void main() { +void main() @safe { [['A', 'B'], ['C','D']].consolidate.writeln; [['A','B'], ['B','D']].consolidate.writeln; diff --git a/Task/Set-consolidation/REXX/set-consolidation.rexx b/Task/Set-consolidation/REXX/set-consolidation.rexx index e2863263ef..7b23e359c0 100644 --- a/Task/Set-consolidation/REXX/set-consolidation.rexx +++ b/Task/Set-consolidation/REXX/set-consolidation.rexx @@ -1,53 +1,53 @@ -/*REXX program shows how to consolidate a sample bunch of sets. */ -sets.= /*assign all SETS. to null. */ +/*REXX program demonstrates how to consolidate a sample bunch of sets.*/ +sets. = /*assign all SETS. to null.*/ sets.1 = '{A,B} {C,D}' sets.2 = "{A,B} {B,D}" sets.3 = '{A,B} {C,D} {D,B}' sets.4 = '{H,I,K} {A,B} {C,D} {D,B} {F,G,H}' sets.5 = '{snow,ice,slush,frost,fog} {iceburgs,icecubes} {rain,fog,sleet}' - do j=1 while sets.j\=='' /*traipse through the sample sets*/ + do j=1 while sets.j\=='' /*traipse through the sample sets*/ call SETcombo sets.j /*have the other guy do the work.*/ end /*j*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────SETcombo subroutine─────────────────*/ -SETcombo: procedure; parse arg bunch; n=words(bunch); newBunch= +/*──────────────────────────────────SETCOMBO subroutine─────────────────*/ +SETcombo: procedure; parse arg bunch; n=words(bunch); newBunch= say ' the old sets=' space(bunch) - do k=1 for n /*change all commas to a blank. */ + do k=1 for n /* [↓] change commas to a blank.*/ @.k=translate(word(bunch,k),,'},{') /*create a list of words (=a set)*/ - end /*k*/ /*... and also remove the braces.*/ + end /*k*/ /*··· and also remove the braces.*/ - do until \changed; changed=0 /*consolidate some sets (maybe).*/ - do set=1 for n-1 - do item=1 for words(@.set); x=word(@.set,item) - do other=set+1 to n - if isIn(x,@.other) then do; changed=1 - @.set=@.set @.other; @.other= - iterate set - end + do until \changed; changed=0 /*consolidate some sets (maybe).*/ + do set=1 for n-1 + do item=1 for words(@.set); x=word(@.set,item) + do other=set+1 to n + if isIn(x,@.other) then do; changed=1 /*has changed.*/ + @.set=@.set @.other; @.other= + iterate set + end end /*other*/ end /*item*/ end /*set*/ end /*until ¬changed*/ - do set=1 for n; new= /*remove duplicates in a set. */ - do items=1 for words(@.set) - x=word(@.set,items); if x==',' then iterate; if x=='' then leave + do set=1 for n; new= /*remove duplicates in a set. */ + do items=1 for words(@.set); x=word(@.set, items) + if x==',' then iterate; if x=='' then leave new=new x /*start building the new set. */ - do forever; if \isIn(x,@.set) then leave - _=wordpos(x,@.set) + do until \isIn(x, @.set) + _=wordpos(x, @.set) @.set=subword(@.set,1,_-1) ',' subword(@.set,_+1) /*purify set.*/ - end /*forever*/ + end /*until ¬isIn*/ end /*items*/ - @.set=translate(strip(new),','," ") + @.set=translate(strip(new), ',', " ") end /*set*/ - do new=1 for n; if @.new=='' then iterate + do new=1 for n; if @.new=='' then iterate newBunch=space(newbunch '{'@.new"}") end /*new*/ say ' the new sets=' newBunch; say return -/*──────────────────────────────────isIn subroutine─────────────────────*/ -isIn: return wordpos(arg(1),arg(2))\==0 /*is (word) arg1 in set arg2? */ +/*──────────────────────────────────ISIN subroutine─────────────────────*/ +isIn: return wordpos(arg(1), arg(2))\==0 /*is (word) arg1 in set arg2? */ diff --git a/Task/Set-consolidation/Ruby/set-consolidation.rb b/Task/Set-consolidation/Ruby/set-consolidation.rb index 12418f2bdc..1ded3e52d0 100644 --- a/Task/Set-consolidation/Ruby/set-consolidation.rb +++ b/Task/Set-consolidation/Ruby/set-consolidation.rb @@ -1,17 +1,13 @@ require 'set' -tests = [[['A', 'B'], ['C','D']], -[['A','B'], ['B','D']], -[['A','B'], ['C','D'], ['D','B']], -[['H','I','K'], ['A','B'], ['C','D'], ['D','B'], ['F','G','H']]] -tests = tests.map{|sets| sets.map(&:to_set)} +tests = [[[:A,:B], [:C,:D]], + [[:A,:B], [:B,:D]], + [[:A,:B], [:C,:D], [:D,:B]], + [[:H,:I,:K], [:A,:B], [:C,:D], [:D,:B], [:F,:G,:H]]] +tests.map!{|sets| sets.map(&:to_set)} -tests.map do |sets| - loop until sets.combination(2).none? do |a,b| - if a.intersect?(b) then - a.merge(b) - sets.delete(b) - end +tests.each do |sets| + until sets.combination(2).none?{|a,b| a.merge(b) && sets.delete(b) if a.intersect?(b)} end p sets end diff --git a/Task/Set-consolidation/Scala/set-consolidation.scala b/Task/Set-consolidation/Scala/set-consolidation.scala new file mode 100644 index 0000000000..23040376eb --- /dev/null +++ b/Task/Set-consolidation/Scala/set-consolidation.scala @@ -0,0 +1,27 @@ +object SetConsolidation extends App { + def consolidate[Type](sets: Set[Set[Type]]): Set[Set[Type]] = { + var result = sets // each iteration combines two sets and reiterates, else returns + for (i <- sets; j <- sets - i; k = i.intersect(j); + if result == sets && k.nonEmpty) result = result - i - j + i.union(j) + if (result == sets) sets else consolidate(result) + } + + // Tests: + def parse(s: String) = + s.split(",").map(_.split("").toSet).toSet + def pretty[Type](sets: Set[Set[Type]]) = + sets.map(_.mkString("{",",","}")).mkString(" ") + val tests = List( + parse("AB,CD") -> Set(Set("A", "B"), Set("C", "D")), + parse("AB,BD") -> Set(Set("A", "B", "D")), + parse("AB,CD,DB") -> Set(Set("A", "B", "C", "D")), + parse("HIK,AB,CD,DB,FGH") -> Set(Set("A", "B", "C", "D"), Set("F", "G", "H", "I", "K")) + ) + require(Set("A", "B", "C", "D") == Set("B", "C", "A", "D")) + assert(tests.forall{case (test, expect) => + val result = consolidate(test) + println(s"${pretty(test)} -> ${pretty(result)}") + expect == result + }) + +} diff --git a/Task/Set-of-real-numbers/00DESCRIPTION b/Task/Set-of-real-numbers/00DESCRIPTION index ddfac94216..e1b12b70f2 100644 --- a/Task/Set-of-real-numbers/00DESCRIPTION +++ b/Task/Set-of-real-numbers/00DESCRIPTION @@ -28,6 +28,6 @@ Note that if ''a'' = ''b'', of the four only [''a'', ''a''] would be non-empty. * You can use your machine's native real number representation, which is probably IEEE floating point, and assume it's good enough (it usually is). '''Optional work''' -* Have a method to determin if a given set is empty (contains no element). +* Create a function to determine if a given set is empty (contains no element). * Define ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x2%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 A]'' = {''x'' | 0 < ''x'' < 10 and |sin(π ''x''²)| > 1/2 }, ''[http://www.wolframalpha.com/input/?i=%7Csin%28pi+x%29%7C%3E1%2F2%2C+0+%3C+x+%3C+10 B]'' = {''x'' | 0 < ''x'' < 10 and |sin(π ''x'')| > 1/2}, calculate the length of the real axis covered by the set ''A'' − ''B''. Note that |sin(π ''x'')| > 1/2 is the same as ''n'' + 1/6 < ''x'' < ''n'' + 5/6 for all integers ''n''; your program does not need to derive this by itself. diff --git a/Task/Set-of-real-numbers/Clojure/set-of-real-numbers.clj b/Task/Set-of-real-numbers/Clojure/set-of-real-numbers.clj new file mode 100644 index 0000000000..e15a5bcfba --- /dev/null +++ b/Task/Set-of-real-numbers/Clojure/set-of-real-numbers.clj @@ -0,0 +1,34 @@ +(ns rosettacode.real-set) + +(defn >=|<= [lo hi] #(<= lo % hi)) + +(defn >|< [lo hi] #(< lo % hi)) + +(defn >=|< [lo hi] #(and (<= lo %) (< % hi))) + +(defn >|<= [lo hi] #(and (< lo %) (<= % hi))) + +(def ⋃ some-fn) +(def ⋂ every-pred) +(defn ∖ + ([s1] s1) + ([s1 s2] + #(and (s1 %) (not (s2 %)))) + ([s1 s2 s3] + #(and (s1 %) (not (s2 %)) (not (s3 %)))) + ([s1 s2 s3 & ss] + (fn [x] (every? #(not (% x)) (list* s1 s2 s3 ss))))) + +(clojure.pprint/pprint + (map #(map % [0 1 2]) + [(⋃ (>|<= 0 1) (>=|< 0 2)) + (⋂ (>=|< 0 2) (>|<= 1 2)) + (∖ (>=|< 0 3) (>|< 0 1)) + (∖ (>=|< 0 3) (>=|<= 0 1))]) + +(def ∅ (constantly false)) +(def R (constantly true)) +(def Z integer?) +(def Q ratio?) +(def I #(∖ R Z Q)) +(def N #(∖ Z neg?)) diff --git a/Task/Set-of-real-numbers/D/set-of-real-numbers.d b/Task/Set-of-real-numbers/D/set-of-real-numbers.d new file mode 100644 index 0000000000..bcdda17e71 --- /dev/null +++ b/Task/Set-of-real-numbers/D/set-of-real-numbers.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/Go/set-of-real-numbers-1.go b/Task/Set-of-real-numbers/Go/set-of-real-numbers-1.go new file mode 100644 index 0000000000..70d02c0f0b --- /dev/null +++ b/Task/Set-of-real-numbers/Go/set-of-real-numbers-1.go @@ -0,0 +1,28 @@ +package main + +import "fmt" + +type Set func(float64) bool + +func Union(a, b Set) Set { return func(x float64) bool { return a(x) || b(x) } } +func Inter(a, b Set) Set { return func(x float64) bool { return a(x) && b(x) } } +func Diff(a, b Set) Set { return func(x float64) bool { return a(x) && !b(x) } } +func open(a, b float64) Set { return func(x float64) bool { return a < x && x < b } } +func closed(a, b float64) Set { return func(x float64) bool { return a <= x && x <= b } } +func opCl(a, b float64) Set { return func(x float64) bool { return a < x && x <= b } } +func clOp(a, b float64) Set { return func(x float64) bool { return a <= x && x < b } } + +func main() { + s := make([]Set, 4) + s[0] = Union(opCl(0, 1), clOp(0, 2)) // (0,1] ∪ [0,2) + s[1] = Inter(clOp(0, 2), opCl(1, 2)) // [0,2) ∩ (1,2] + s[2] = Diff(clOp(0, 3), open(0, 1)) // [0,3) − (0,1) + s[3] = Diff(clOp(0, 3), closed(0, 1)) // [0,3) − [0,1] + + for i := range s { + for x := float64(0); x < 3; x++ { + fmt.Printf("%v ∈ s%d: %t\n", x, i, s[i](x)) + } + fmt.Println() + } +} diff --git a/Task/Set-of-real-numbers/Go/set-of-real-numbers-2.go b/Task/Set-of-real-numbers/Go/set-of-real-numbers-2.go new file mode 100644 index 0000000000..48da2dc279 --- /dev/null +++ b/Task/Set-of-real-numbers/Go/set-of-real-numbers-2.go @@ -0,0 +1,11 @@ + A := Inter(open(0, 10), func(x float64) bool { + return math.Abs(math.Sin(math.Pi*x*x)) > .5 + }) + B := Inter(open(0, 10), func(x float64) bool { + return math.Abs(math.Sin(math.Pi*x)) > .5 + }) + C := Diff(A, B) + // Can't get lengths, can only test for ∈ + for x := float64(5.98); x < 6.025; x += 0.01 { + fmt.Printf("%.2f ∈ A−B: %t\n", x, C(x)) + } diff --git a/Task/Set-of-real-numbers/Go/set-of-real-numbers-3.go b/Task/Set-of-real-numbers/Go/set-of-real-numbers-3.go new file mode 100644 index 0000000000..cb318a8e5a --- /dev/null +++ b/Task/Set-of-real-numbers/Go/set-of-real-numbers-3.go @@ -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-of-real-numbers/Mathematica/set-of-real-numbers.math b/Task/Set-of-real-numbers/Mathematica/set-of-real-numbers.math new file mode 100644 index 0000000000..0c516d6599 --- /dev/null +++ b/Task/Set-of-real-numbers/Mathematica/set-of-real-numbers.math @@ -0,0 +1,27 @@ +(* defining functions *) +setcc[a_, b_] := a <= x <= b +setoo[a_, b_] := a < x < b +setco[a_, b_] := a <= x < b +setoc[a_, b_] := a < x <= b +setSubtract[s1_, s2_] := s1 && Not[s2]; (* new function; subtraction not built in *) +inSetQ[y_, set_] := set /. x -> y +(* testing sets *) +set1 = setoc[0, 1] || setco[0, 2] (* union built in as || shortcut (OR) *); +Print[set1] +Print["First trial set, (0, 1] ∪ [0, 2) , testing for {0,1,2}:"] +Print[inSetQ[#, set1] & /@ {0, 1, 2}] +set2 = setco[0, 2] && setoc[1, 2]; (* intersection built in as && shortcut (AND) *) +Print[] +Print[set2] +Print["Second trial set, [0, 2) ∩ (1, 2], testing for {0,1,2}:"] +Print[inSetQ[#, set2] & /@ {0, 1, 2}] +Print[] +set3 = setSubtract[setco[0, 3], setoo[0, 1]]; +Print[set3] +Print["Third trial set, [0, 3) \[Minus] (0, 1), testing for {0,1,2}"] +Print[inSetQ[#, set3] & /@ {0, 1, 2}] +Print[] +set4 = setSubtract[setco[0, 3], setcc[0, 1]]; +Print[set4] +Print["Fourth trial set, [0,3)\[Minus][0,1], testing for {0,1,2}:"] +Print[inSetQ[#, set4] & /@ {0, 1, 2}] diff --git a/Task/Set-of-real-numbers/Python/set-of-real-numbers.py b/Task/Set-of-real-numbers/Python/set-of-real-numbers.py index 6516e079c6..8dd126b586 100644 --- a/Task/Set-of-real-numbers/Python/set-of-real-numbers.py +++ b/Task/Set-of-real-numbers/Python/set-of-real-numbers.py @@ -5,43 +5,42 @@ class Setr(): '=' if includehi else '', hi) - def includes(self, X): + def __contains__(self, X): return eval(self.eqn, locals()) - def union(self, b): + # union + def __or__(self, b): ans = Setr(0,0) ans.eqn = "(%sor%s)" % (self.eqn, b.eqn) return ans - def intersection(self, b): + # intersection + def __and__(self, b): ans = Setr(0,0) ans.eqn = "(%sand%s)" % (self.eqn, b.eqn) return ans - def difference(self, b): + # difference + def __sub__(self, b): ans = Setr(0,0) ans.eqn = "(%sand not%s)" % (self.eqn, b.eqn) return ans - def union(self, b): - ans = Setr(0,0) - ans.eqn = "(%sor%s)" % (self.eqn, b.eqn) - return ans - def __repr__(self): return "Setr%s" % self.eqn -sets = [Setr(0,1, 0,1).union(Setr(0,2, 1,0)), - Setr(0,2, 1,0).intersection(Setr(1,2, 0,1)), - Setr(0,3, 1,0).difference(Setr(0,1, 0,0)), - Setr(0,3, 1,0).difference(Setr(0,1, 1,1)), - ] +sets = [ + Setr(0,1, 0,1) | Setr(0,2, 1,0), + Setr(0,2, 1,0) & Setr(1,2, 0,1), + Setr(0,3, 1,0) - Setr(0,1, 0,0), + Setr(0,3, 1,0) - Setr(0,1, 1,1), +] settexts = '(0, 1] ∪ [0, 2);[0, 2) ∩ (1, 2];[0, 3) − (0, 1);[0, 3) − [0, 1]'.split(';') for s,t in zip(sets, settexts): print("Set %s %s. %s" % (t, ', '.join("%scludes %i" - % ('in' if s.includes(v) else 'ex', v) + % ('in' if v in s else 'ex', v) for v in range(3)), s.eqn)) diff --git a/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-1.rb b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-1.rb new file mode 100644 index 0000000000..f3000a824a --- /dev/null +++ b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-1.rb @@ -0,0 +1,171 @@ +class Rset + Set = Struct.new(:lo, :hi, :inc_lo, :inc_hi) do + def include?(x) + (inc_lo ? lo<=x : lo Boolean values + end + end + + def self.[](lo, hi, inc_hi=true) + self.new(lo, hi, true, inc_hi) + end + + def self.from_s(str) + raise ArgumentError unless str =~ /(\[|\()(.+),(.+)(\]|\))/ + b0, lo, hi, b1 = $~.captures # $~ : Regexp.last_match + lo = Rational(lo) + lo = lo.numerator if lo.denominator == 1 + hi = Rational(hi) + hi = hi.numerator if hi.denominator == 1 + self.new(lo, hi, b0=='[', b1==']') + end + + def dup + new_Rset(@sets.map(&:dup)) + end + + def include?(x) + @sets.any?{|set| set.include?(x)} + end + + def empty? + @sets.empty? + end + + def union(other) + sets = (@sets+other.sets).map(&:dup).sort_by{|set| [set.lo, set.hi]} + work = [] + pre = sets.shift + sets.each do |post| + if valid?(pre.hi, post.lo, !pre.inc_hi, !post.inc_lo) + work << pre + pre = post + else + pre.inc_lo |= post.inc_lo if pre.lo == post.lo + if pre.hi < post.hi + pre.hi = post.hi + pre.inc_hi = post.inc_hi + elsif pre.hi == post.hi + pre.inc_hi |= post.inc_hi + end + end + end + work << pre if pre + new_Rset(work) + end + alias | union + + def intersection(other) + sets = @sets.map(&:dup) + work = [] + other.sets.each do |oset| + sets.each do |set| + if set.hi < oset.lo or oset.hi < set.lo + # ignore + elsif oset.lo < set.lo and set.hi < oset.hi + work << set + else + lo = [set.lo, oset.lo].max + if set.lo == oset.lo + inc_lo = set.inc_lo && oset.inc_lo + else + inc_lo = (set.lo < oset.lo) ? oset.inc_lo : set.inc_lo + end + hi = [set.hi, oset.hi].min + if set.hi == oset.hi + inc_hi = set.inc_hi && oset.inc_hi + else + inc_hi = (set.hi < oset.hi) ? set.inc_hi : oset.inc_hi + end + work << Set[lo, hi, inc_lo, inc_hi] if valid?(lo, hi, inc_lo, inc_hi) + end + end + end + new_Rset(work) + end + alias & intersection + + def difference(other) + sets = @sets.map(&:dup) + other.sets.each do |oset| + work = [] + sets.each do |set| + if set.hi < oset.lo or oset.hi < set.lo + work << set + elsif oset.lo < set.lo and set.hi < oset.hi + # delete + else + if set.lo < oset.lo + inc_hi = (set.hi==oset.lo and !set.inc_hi) ? false : !oset.inc_lo + work << Set[set.lo, oset.lo, set.inc_lo, inc_hi] + elsif valid?(set.lo, oset.lo, set.inc_lo, !oset.inc_lo) + work << Set[set.lo, set.lo, true, true] + end + if oset.hi < set.hi + inc_lo = (oset.hi==set.lo and !set.inc_lo) ? false : !oset.inc_hi + work << Set[oset.hi, set.hi, inc_lo, set.inc_hi] + elsif valid?(oset.hi, set.hi, !oset.inc_hi, set.inc_hi) + work << Set[set.hi, set.hi, true, true] + end + end + end + sets = work + end + new_Rset(sets) + end + alias - difference + + # symmetric difference + def ^(other) + (self - other) | (other - self) + end + + def ==(other) + return false if self.class != other.class + @sets == other.sets + end + + def length + @sets.inject(0){|len, set| len + set.length} + end + + def to_s + "#{self.class}" + @sets.map(&:to_s).join(',') + end + alias inspect to_s + + protected + + attr_accessor :sets + + private + + def new_Rset(sets) + rset = self.class.new # empty set + rset.sets = sets + rset + end + + def valid?(lo, hi, inc_lo, inc_hi) + lo < hi or (lo==hi and inc_lo and inc_hi) + end +end + +def Rset(lo, hi, inc_hi=false) + Rset.new(lo, hi, false, inc_hi) +end diff --git a/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-2.rb b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-2.rb new file mode 100644 index 0000000000..81b4b8ff3e --- /dev/null +++ b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-2.rb @@ -0,0 +1,45 @@ +p a = Rset[1,2,false] +[1,2,3].each{|x|puts "#{x} => #{a.include?(x)}"} +puts +a = Rset[0,2,false] #=> Rset[0,2) +b = Rset(1,3) #=> Rset(1,3) +c = Rset[0,1,false] #=> Rset[0,1) +d = Rset(2,3,true) #=> Rset(2,3] +puts "#{a} | #{b} -> #{a | b}" +puts "#{c} | #{d} -> #{c | d}" +puts +puts "#{a} & #{b} -> #{a & b}" +puts "#{c} & #{d} -> #{c & d}" +puts "(#{c} & #{d}).empty? -> #{(c&d).empty?}" +puts +puts "#{a} - #{b} -> #{a - b}" +puts "#{a} - #{a} -> #{a - a}" +e = Rset(0,3,true) +f = Rset[1,2] +puts "#{e} - #{f} -> #{e - f}" + +puts "\nTest :" +test_set = [["(0, 1]", "|", "[0, 2)"], + ["[0, 2)", "&", "(1, 2]"], + ["[0, 3)", "-", "(0, 1)"], + ["[0, 3)", "-", "[0, 1]"] ] +test_set.each do |sa,ope,sb| + str = "#{sa} #{ope} #{sb}" + e = eval("Rset.from_s(sa) #{ope} Rset.from_s(sb)") + puts "%s -> %s" % [str, e] + (0..2).each{|i| puts " #{i} : #{e.include?(i)}"} +end + +puts +test_set = ["x = Rset[0,2] | Rset(3,7) | Rset[8,10]", + "y = Rset(7,9) | Rset(5,6) | Rset[1,4]", + "x | y", "x & y", "x - y", "y - x", "x ^ y", + "y ^ x == (x | y) - (x & y)"] +x = y = nil +test_set.each {|str| puts "#{str} -> #{eval(str)}"} + +puts +inf = 1.0 / 0.0 # infinity +puts "a = #{a = Rset(-inf,inf)}" +puts "b = #{b = Rset.from_s('[1/3,11/7)')}" +puts "a - b -> #{a - b}" diff --git a/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-3.rb b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-3.rb new file mode 100644 index 0000000000..4935c61ccd --- /dev/null +++ b/Task/Set-of-real-numbers/Ruby/set-of-real-numbers-3.rb @@ -0,0 +1,31 @@ +str, e = "e = Rset.new", nil +puts "#{str} -> #{eval(str)}\t\t# create empty set" +str = "e.empty?" +puts "#{str} -> #{eval(str)}" +puts + +include Math +lohi = Enumerator.new do |y| + t = 1 / sqrt(6) + 0.step do |n| + y << [sqrt(12*n+1) * t, sqrt(12*n+5) * t] + y << [sqrt(12*n+7) * t, sqrt(12*n+11) * t] + end +end + +a = Rset.new +loop do + lo, hi = lohi.next + break if 10 <= lo + a |= Rset(lo, hi) +end +a &= Rset(0,10) + +b = (0...10).inject(Rset.new){|res,i| res |= Rset(i+1/6r,i+5/6r)} + +puts "a : #{a}" +puts "a.length : #{a.length}" +puts "b : #{b}" +puts "b.length : #{b.length}" +puts "a - b : #{a - b}" +puts "(a-b).length : #{(a-b).length}" diff --git a/Task/Set-puzzle/00DESCRIPTION b/Task/Set-puzzle/00DESCRIPTION index 872f652a4d..f2ede9c7b0 100644 --- a/Task/Set-puzzle/00DESCRIPTION +++ b/Task/Set-puzzle/00DESCRIPTION @@ -1,4 +1,8 @@ -Set Puzzles are created with a deck of cards from the [[wp:Set (game)|Set Game™]]. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up. There are 81 cards in a deck. Each card contains a unique variation of the following four features: ''color, symbol, number and shading''. +{{omit from|GUISS}} + +Set Puzzles are created with a deck of cards from the [[wp:Set (game)|Set Game™]]. The object of the puzzle is to find sets of 3 cards in a rectangle of cards that have been dealt face up.
    +There are 81 cards in a deck. +Each card contains a unique variation of the following four features: ''color, symbol, number and shading''. ; there are three colors: '''red''', '''green''', or '''purple''' @@ -8,9 +12,18 @@ Set Puzzles are created with a deck of cards from the [[wp:Set (game)|Set Game ; there are three shadings: '''solid''', '''open''', or '''striped''' -Three cards form a ''set'' if each feature is either the same on each card, or is different on each card. For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. +Three cards form a ''set'' if each feature is either the same on each card, or is different on each card.
    +For instance: all 3 cards are red, all 3 cards have a different symbol, all 3 cards have a different number of symbols, all 3 cards are striped. -There are two degrees of difficulty: [http://www.setgame.com/set/rules_basic.htm ''basic''] and [http://www.setgame.com/set/rules_advanced.htm ''advanced'']. The basic mode deals 9 cards, that contain exactly 4 sets; the advanced mode deals 12 cards that contain exactly 6 sets. When creating sets you may use the same card more than once. The task is to write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. For instance: +There are two degrees of difficulty: [http://www.setgame.com/set/rules_basic.htm ''basic''] and [http://www.setgame.com/set/rules_advanced.htm ''advanced''].
    +The basic mode deals 9 cards, that contain exactly 4 sets; +the advanced mode deals 12 cards that contain exactly 6 sets. +When creating sets you may use the same card more than once. + +;The task: +Is to write code that deals the cards (9 or 12, depending on selected mode) from a shuffled deck in which the total number of sets that could be found is 4 (or 6, respectively); and print the contents of the cards and the sets. + +For instance: '''DEALT 9 CARDS:''' diff --git a/Task/Set-puzzle/00META.yaml b/Task/Set-puzzle/00META.yaml new file mode 100644 index 0000000000..5fed04c595 --- /dev/null +++ b/Task/Set-puzzle/00META.yaml @@ -0,0 +1,4 @@ +--- +category: +- Puzzles +note: Cards diff --git a/Task/Set-puzzle/Ada/set-puzzle-1.ada b/Task/Set-puzzle/Ada/set-puzzle-1.ada new file mode 100644 index 0000000000..3e57247b74 --- /dev/null +++ b/Task/Set-puzzle/Ada/set-puzzle-1.ada @@ -0,0 +1,18 @@ +package Set_Puzzle is + + type Three is range 1..3; + type Card is array(1 .. 4) of Three; + type Cards is array(Positive range <>) of Card; + type Set is array(Three) of Positive; + + procedure Deal_Cards(Dealt: out Cards); + -- ouputs an array with disjoint cards + + function To_String(C: Card) return String; + + generic + with procedure Do_something(C: Cards; S: Set); + procedure Find_Sets(Given: Cards); + -- calls Do_Something once for each set it finds. + +end Set_Puzzle; diff --git a/Task/Set-puzzle/Ada/set-puzzle-2.ada b/Task/Set-puzzle/Ada/set-puzzle-2.ada new file mode 100644 index 0000000000..7146edce28 --- /dev/null +++ b/Task/Set-puzzle/Ada/set-puzzle-2.ada @@ -0,0 +1,78 @@ +with Ada.Numerics.Discrete_Random; + +package body Set_Puzzle is + + package Rand is new Ada.Numerics.Discrete_Random(Three); + R: Rand.Generator; + + function Locate(Some: Cards; C: Card) return Natural is + -- returns index of card C in Some, or 0 if not found + begin + for I in Some'Range loop + if C = Some(I) then + return I; + end if; + end loop; + return 0; + end Locate; + + procedure Deal_Cards(Dealt: out Cards) is + function Random_Card return Card is + (Rand.Random(R), Rand.Random(R), Rand.Random(R), Rand.Random(R)); + begin + for I in Dealt'Range loop + -- draw a random card until different from all card previously drawn + Dealt(I) := Random_Card; -- draw random card + while Locate(Dealt(Dealt'First .. I-1), Dealt(I)) /= 0 loop + -- Dealt(I) has been drawn before + Dealt(I) := Random_Card; -- draw another random card + end loop; + end loop; + end Deal_Cards; + + procedure Find_Sets(Given: Cards) is + function To_Set(A, B: Card) return Card is + -- returns the unique card C, which would make a set with A and B + C: Card; + begin + for I in 1 .. 4 loop + if A(I) = B(I) then + C(I) := A(I); -- all three the same + else + C(I) := 6 - A(I) - B(I); -- all three different; + end if; + end loop; + return C; + end To_Set; + + X: Natural; + + begin + for I in Given'Range loop + for J in Given'First .. I-1 loop + X := Locate(Given, To_Set(Given(I), Given(J))); + if I < X then -- X=0 is no set, 0 < X < I is a duplicate + Do_Something(Given, (J, I, X)); + end if; + end loop; + end loop; + end Find_Sets; + + function To_String(C: Card) return String is + + Col: constant array(Three) of String(1..6) + := ("Red ", "Green ", "Purple"); + Sym: constant array(Three) of String(1..8) + := ("Oval ", "Squiggle", "Diamond "); + Num: constant array(Three) of String(1..5) + := ("One ", "Two ", "Three"); + Sha: constant array(Three) of String(1..7) + := ("Solid ", "Open ", "Striped"); + + begin + return (Col(C(1)) & " " & Sym(C(2)) & " " & Num(C(3)) & " " & Sha(C(4))); + end To_String; + +begin + Rand.Reset(R); +end Set_Puzzle; diff --git a/Task/Set-puzzle/Ada/set-puzzle-3.ada b/Task/Set-puzzle/Ada/set-puzzle-3.ada new file mode 100644 index 0000000000..a530932f94 --- /dev/null +++ b/Task/Set-puzzle/Ada/set-puzzle-3.ada @@ -0,0 +1,50 @@ +with Ada.Text_IO, Set_Puzzle, Ada.Command_Line; + +procedure Puzzle is + + package TIO renames Ada.Text_IO; + + Card_Count: Positive := Positive'Value(Ada.Command_Line.Argument(1)); + Required_Sets: Positive := Positive'Value(Ada.Command_Line.Argument(2)); + + Cards: Set_Puzzle.Cards(1 .. Card_Count); + + function Cnt_Sets(C: Set_Puzzle.Cards) return Natural is + Cnt: Natural := 0; + procedure Count_Sets(C: Set_Puzzle.Cards; S: Set_Puzzle.Set) is + begin + Cnt := Cnt + 1; + end Count_Sets; + procedure CS is new Set_Puzzle.Find_Sets(Count_Sets); + begin + CS(C); + return Cnt; + end Cnt_Sets; + + procedure Print_Sets(C: Set_Puzzle.Cards) is + procedure Print_A_Set(C: Set_Puzzle.Cards; S: Set_Puzzle.Set) is + begin + TIO.Put("(" & Integer'Image(S(1)) & "," & Integer'Image(S(2)) + & "," & Integer'Image(S(3)) & " ) "); + end Print_A_Set; + procedure PS is new Set_Puzzle.Find_Sets(Print_A_Set); + begin + PS(C); + TIO.New_Line; + end Print_Sets; + +begin + loop -- deal random cards + Set_Puzzle.Deal_Cards(Cards); + exit when Cnt_Sets(Cards) = Required_Sets; + end loop; -- until number of sets is as required + + for I in Cards'Range loop -- print the cards + if I < 10 then + TIO.Put(" "); + end if; + TIO.Put_Line(Integer'Image(I) & " " & Set_Puzzle.To_String(Cards(I))); + end loop; + + Print_Sets(Cards); -- print the sets +end Puzzle; diff --git a/Task/Set-puzzle/D/set-puzzle.d b/Task/Set-puzzle/D/set-puzzle-1.d similarity index 64% rename from Task/Set-puzzle/D/set-puzzle.d rename to Task/Set-puzzle/D/set-puzzle-1.d index ccad40f77e..9e16b4fdea 100644 --- a/Task/Set-puzzle/D/set-puzzle.d +++ b/Task/Set-puzzle/D/set-puzzle-1.d @@ -1,12 +1,12 @@ import std.stdio, std.random, std.array, std.conv, std.traits, - std.exception; + std.exception, std.range, std.algorithm; const class SetDealer { protected { - enum Color : ubyte {green, purple, red} - enum Number : ubyte {one, two, three} - enum Symbol : ubyte {oval, diamond, squiggle} - enum Fill : ubyte {open, striped, solid} + enum Color: ubyte {green, purple, red} + enum Number: ubyte {one, two, three} + enum Symbol: ubyte {oval, diamond, squiggle} + enum Fill: ubyte {open, striped, solid} static struct Card { Color c; @@ -15,40 +15,33 @@ const class SetDealer { Fill f; } - immutable Card[81] deck; + static immutable Card[81] deck; } - this() pure nothrow { - Card[] tmpdeck; - + static this() pure nothrow @safe { immutable colors = [EnumMembers!Color]; immutable numbers = [EnumMembers!Number]; immutable symbols = [EnumMembers!Symbol]; immutable fill = [EnumMembers!Fill]; - foreach (immutable i; 0 .. deck.length) - tmpdeck ~= Card(colors[i / 27], - numbers[(i / 9) % 3], - symbols[(i / 3) % 3], - fill[i % 3]); - - // randomShuffle(tmpdeck); /* not pure nothrow */ - - deck = assumeUnique(tmpdeck); + deck = deck.length.iota.map!(i => Card(colors[i / 27], + numbers[(i / 9) % 3], + symbols[(i / 3) % 3], + fill[i % 3])).array; } // randomSample produces a sorted output that's convenient in our // case because we're printing to stout. Normally you would want // to shuffle. immutable(Card)[] deal(in uint numCards) const { - enforce(numCards < deck.length, "number of cards too large"); - return deck[].randomSample(numCards).array(); + enforce(numCards < deck.length, "Number of cards too large"); + return deck[].randomSample(numCards).array; } // The summed enums of valid sets are always zero or a multiple // of 3. bool validSet(in ref Card c1, in ref Card c2, in ref Card c3) - const pure nothrow { + const pure nothrow @safe @nogc { return !((c1.c + c2.c + c3.c) % 3 || (c1.n + c2.n + c3.n) % 3 || (c1.s + c2.s + c3.s) % 3 || @@ -56,7 +49,7 @@ const class SetDealer { } immutable(Card)[3][] findSets(in Card[] cards, in uint target = 0) - const pure nothrow { + const pure nothrow @safe { immutable len = cards.length; if (len < 3) return null; @@ -90,19 +83,14 @@ const final class SetPuzzleDealer : SetDealer { } void main() { - const dealer = new SetPuzzleDealer(); - const cards = dealer.deal(); + const dealer = new SetPuzzleDealer; + const cards = dealer.deal; - writefln("\nDEALT %d CARDS:\n", cards.length); - foreach (c; cards) - writeln(cast()c); + writefln("DEALT %d CARDS:", cards.length); + writefln("%(%s\n%)", cards); immutable sets = dealer.findSets(cards); immutable len = sets.length; - writefln("\nFOUND %d %s:\n", len, len == 1 ? "SET" : "SETS"); - foreach (set; sets) { - foreach (c; set) - writeln(cast()c); - writeln(); - } + writefln("\nFOUND %d SET%s:", len, len == 1 ? "" : "S"); + writefln("%(%(%s\n%)\n\n%)", sets); } diff --git a/Task/Set-puzzle/D/set-puzzle-2.d b/Task/Set-puzzle/D/set-puzzle-2.d new file mode 100644 index 0000000000..5551333f0a --- /dev/null +++ b/Task/Set-puzzle/D/set-puzzle-2.d @@ -0,0 +1,19 @@ +void main() { + import std.stdio, std.algorithm, std.range, std.random, combinations3; + + enum nDraw = 9, nGoal = nDraw / 2; + auto deck = cartesianProduct("red green purple".split, + "one two three".split, + "oval squiggle diamond".split, + "solid open striped".split).array; + + retry: + auto draw = deck.randomSample(nDraw).map!(t => [t[]]).array; + const sets = draw.combinations(3).filter!(cs => cs.dup + .transposed.all!(t => t.array.sort().uniq.count % 2)).array; + if (sets.length != nGoal) + goto retry; + + writefln("Dealt %d cards:\n%(%-(%8s %)\n%)\n", draw.length, draw); + writefln("Containing:\n%(%(%-(%8s %)\n%)\n\n%)", sets); +} diff --git a/Task/Set-puzzle/Go/set-puzzle.go b/Task/Set-puzzle/Go/set-puzzle.go index 5c680a48ad..95a6be8747 100644 --- a/Task/Set-puzzle/Go/set-puzzle.go +++ b/Task/Set-puzzle/Go/set-puzzle.go @@ -6,11 +6,11 @@ import ( "time" ) -var ( - number = []string{"1", "2", "3"} - color = []string{"red", "green", "purple"} - shade = []string{"solid", "open", "striped"} - shape = []string{"oval", "squiggle", "diamond"} +const ( + number = [3]string{"1", "2", "3"} + color = [3]string{"red", "green", "purple"} + shade = [3]string{"solid", "open", "striped"} + shape = [3]string{"oval", "squiggle", "diamond"} ) type card int @@ -25,15 +25,7 @@ func (c card) String() string { func main() { rand.Seed(time.Now().Unix()) - basic() - advanced() -} - -func basic() { game("Basic", 9, 4) -} - -func advanced() { game("Advanced", 12, 6) } @@ -59,7 +51,7 @@ func game(level string, cards, sets int) { l3: for _, c3 := range d[:j] { for f := card(1); f < 81; f *= 3 { - if (c1/f%3+c2/f%3+c3/f%3)%3 != 0 { + if (c1/f%3 + c2/f%3 + c3/f%3) % 3 != 0 { continue l3 // not a set } } @@ -77,9 +69,6 @@ func game(level string, cards, sets int) { } fmt.Println("Sets:") for _, s := range found { - fmt.Println(" ", s[0]) - fmt.Println(" ", s[1]) - fmt.Println(" ", s[2]) - fmt.Println() + fmt.Printf(" %s\n %s\n %s\n",s[0],s[1],s[2]) } } diff --git a/Task/Set-puzzle/Java/set-puzzle.java b/Task/Set-puzzle/Java/set-puzzle.java index 7d8742b42d..e62a45fa5e 100644 --- a/Task/Set-puzzle/Java/set-puzzle.java +++ b/Task/Set-puzzle/Java/set-puzzle.java @@ -1,9 +1,9 @@ import java.util.*; -import org.apache.commons.lang3.ArrayUtils; public class SetPuzzle { enum Color { + GREEN(0), PURPLE(1), RED(2); private Color(int v) { @@ -13,6 +13,7 @@ public class SetPuzzle { } enum Number { + ONE(0), TWO(1), THREE(2); private Number(int v) { @@ -22,6 +23,7 @@ public class SetPuzzle { } enum Symbol { + OVAL(0), DIAMOND(1), SQUIGGLE(2); private Symbol(int v) { @@ -31,6 +33,7 @@ public class SetPuzzle { } enum Fill { + OPEN(0), STRIPED(1), SOLID(2); private Fill(int v) { @@ -40,20 +43,22 @@ public class SetPuzzle { } private static class Card implements Comparable { + Color c; Number n; Symbol s; Fill f; + @Override public String toString() { return String.format("[Card: %s, %s, %s, %s]", c, n, s, f); } + @Override public int compareTo(Card o) { return (c.val - o.c.val) * 10 + (n.val - o.n.val); } } - private static Card[] deck; public static void main(String[] args) { @@ -79,7 +84,7 @@ public class SetPuzzle { int cnt; do { Collections.shuffle(Arrays.asList(deck)); - cards = ArrayUtils.subarray(deck, 0, numCards); + cards = Arrays.copyOfRange(deck, 0, numCards); cnt = 0; outer: diff --git a/Task/Set-puzzle/Mathematica/set-puzzle.math b/Task/Set-puzzle/Mathematica/set-puzzle.math new file mode 100644 index 0000000000..0aeeae3d57 --- /dev/null +++ b/Task/Set-puzzle/Mathematica/set-puzzle.math @@ -0,0 +1,18 @@ +colors = {Red, Green, Purple}; +symbols = {"0", "\[TildeTilde]", "\[Diamond]"}; +numbers = {1, 2, 3}; +shadings = {"\[FilledSquare]", "\[Square]", "\[DoublePrime]"}; + +validTripleQ[l_List] := Entropy[l] != Entropy[{1, 1, 2}]; +validSetQ[cards_List] := And @@ (validTripleQ /@ Transpose[cards]); + +allCards = Tuples[{colors, symbols, numbers, shadings}]; + +deal[{numDeal_, setNum_}] := Module[{cards, count = 0}, + While[count != setNum, + cards = RandomSample[allCards, numDeal]; + count = Count[Subsets[cards, {3}], _?validSetQ]]; + + cards]; + +Row[{Style[#2, #1], #3, #4}] & @@@ deal[{9, 4}] diff --git a/Task/Set-puzzle/Python/set-puzzle.py b/Task/Set-puzzle/Python/set-puzzle-1.py similarity index 100% rename from Task/Set-puzzle/Python/set-puzzle.py rename to Task/Set-puzzle/Python/set-puzzle-1.py diff --git a/Task/Set-puzzle/Python/set-puzzle-2.py b/Task/Set-puzzle/Python/set-puzzle-2.py new file mode 100644 index 0000000000..056c9b286c --- /dev/null +++ b/Task/Set-puzzle/Python/set-puzzle-2.py @@ -0,0 +1,21 @@ +import random, pprint +from itertools import product, combinations + +N_DRAW = 9 +N_GOAL = N_DRAW // 2 + +deck = list(product("red green purple".split(), + "one two three".split(), + "oval squiggle diamond".split(), + "solid open striped".split())) + +sets = [] +while len(sets) != N_GOAL: + draw = random.sample(deck, N_DRAW) + sets = [cs for cs in combinations(draw, 3) + if all(len(set(t)) in [1, 3] for t in zip(*cs))] + +print "Dealt %d cards:" % len(draw) +pprint.pprint(draw) +print "\nContaining %d sets:" % len(sets) +pprint.pprint(sets) diff --git a/Task/Set-puzzle/REXX/set-puzzle.rexx b/Task/Set-puzzle/REXX/set-puzzle.rexx new file mode 100644 index 0000000000..d87536e22c --- /dev/null +++ b/Task/Set-puzzle/REXX/set-puzzle.rexx @@ -0,0 +1,99 @@ +/*REXX program finds "sets" (solutions) for the SET puzzle (game). */ +parse arg game seed . /*get optional # cards to deal. */ +if game ==',' | game=='' then game=9 /*Not specified? Then use default*/ +if seed==',' | seed=='' then seed=77 /* " " " " " */ +call aGame 0 /*with tell=0, suppress output. */ +call aGame 1 /*with tell=1, allow output. */ +exit sets /*stick a fork in it, we're done.*/ +/*──────────────────────────────────AGAME subroutine────────────────────*/ +aGame: tell=arg(1); good=game%2 /*enable or disable the output. */ + /* [↑] GOOD is the right # sets.*/ + do seed=seed until good==sets /*generate deals until good# sets*/ + call random ,,seed /*repeatability for last invoke. */ + call genFeatures /*generate various card features.*/ + call genDeck /*generate a deck (with 81 cards)*/ + call dealer game /*deal a number of cards (game). */ + call findSets game%2 /*find sets from the dealt cards.*/ + end /*until*/ /*when leaving, SETS is right num*/ +return /*return to invoker of this sub. */ +/*──────────────────────────────────DEALER subroutine───────────────────*/ +dealer: call sey 'dealing' game "cards:",,. /*shuffle and deal cards*/ + do cards=1 until cards==game /*keep dealing 'til done*/ + _=random(1,words(##)); ##=delword(##,_,1) /*pick card; delete it. */ + @.cards=deck._ /*add it to the tableau.*/ + call sey right('card' cards,30) " " @.cards /*display card to screen*/ + do j=1 for words(@.cards) /*define cells for card.*/ + @.cards.j=word(@.cards,j) /*define a cell for card*/ + end /*j*/ + end /*cards*/ +return +/*──────────────────────────────────DEFFEATURES subroutine──────────────*/ +defFeatures: parse arg what,v; _=words(v) /*obtain what to define.*/ +if _\==values then do; call sey 'error,' what "features ¬=" values,.,. + exit -1 + end /* [↑] check for typos.*/ + do k=1 for words(values) /*define all possibles. */ + call value what'.'k, word(values,k) /*define a card feature.*/ + end /*k*/ +return +/*──────────────────────────────────GENDECK subroutine──────────────────*/ +genDeck: #=0; ##= /*#cards in deck; ##=shuffle aid.*/ + do num=1 for values; xnum=word(numbers, num) + do col=1 for values; xcol=word(colors, col) + do sym=1 for values; xsym=word(symbols, sym) + do sha=1 for values; xsha=word(shadings, sha) + #=#+1; ##=## #; deck.#=xnum xcol xsym xsha /*create a card.*/ + end /*sha*/ + end /*num*/ + end /*sym*/ + end /*col*/ +return /*#: the number of cards in deck.*/ +/*──────────────────────────────────GENFEATURES subroutine──────────────*/ +genFeatures: features=3; groups=4; values=3 /*define # feats,grps,vals*/ +numbers = 'one two three' ; call defFeatures 'number', numbers +colors = 'red green purple' ; call defFeatures 'color', colors +symbols = 'oval squiggle diamond' ; call defFeatures 'symbol', symbols +shadings= 'solid open striped' ; call defFeatures 'shading', shadings +return +/*──────────────────────────────────GENPOSS subroutine──────────────────*/ +genPoss: p=0; sets=0; sep=' ───── '; !.= /*define some REXX variables.*/ + do i=1 for game /* [↓] the IFs eliminate dups.*/ + do j=i+1 to game; if j==i then iterate + do k=j+1 to game; if k==j | k==i then iterate + p=p+1; !.p.1=@.i; !.p.2=@.j; !.p.3=@.k + end /*k*/ + end /*j*/ + end /*i*/ /* [↑] build permutation list. */ +return +/*──────────────────────────────────FINDSETS subroutine─────────────────*/ +findSets: parse arg n; call genPoss /*N: the number of sets to find.*/ +call sey /*find any sets generated above. */ + do j=1 for p /*P is the # of possible sets. */ + do f=1 for features + do g=1 for groups; !!.j.f.g=word(!.j.f, g) + end /*g*/ + end /*f*/ + ok=1 /*everything is OK so far. */ + do g=1 for groups; _=!!.j.1.g /*generate strings to hole poss. */ + equ=1 /* [↓] handles all equal feats. */ + do f=2 to features while equ; equ=equ & _==!!.j.f.g + end /*f*/ + dif=1 + __=!!.j.1.g /* [↓] handles all unequal feats*/ + do f=2 to features while \equ + dif=dif & wordpos(!!.j.f.g,__)==0 + __=__ !!.j.f.g /*append to string for next test.*/ + end /*f*/ + ok=ok&(equ|dif) /*now, see if all equal | unequal*/ + end /*g*/ + + if \ok then iterate /*Is this set OK? Nope, skip it.*/ + sets=sets+1 /*bump the number of sets found. */ + call sey right('set' sets": ",15) !.j.1 sep !.j.2 sep !.j.3 + end /*j*/ + +call sey sets 'sets found.',. +return +/*──────────────────────────────────SEY subroutine──────────────────────*/ +sey: if \tell then return /*should output be suppressed? */ +if arg(2)==. then say; say arg(1); if arg(3)==. then say; return diff --git a/Task/Set/00DESCRIPTION b/Task/Set/00DESCRIPTION index 2b448b91e0..b26872fe6a 100644 --- a/Task/Set/00DESCRIPTION +++ b/Task/Set/00DESCRIPTION @@ -11,8 +11,11 @@ Show each of these set operations: * A ⊆ B -- ''subset''; true if every element in set A is also in set B. * A = B -- ''equality''; true if every element of set A is in set B and vice-versa. -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. +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. +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/Prolog/set.pro b/Task/Set/Prolog/set-1.pro similarity index 100% rename from Task/Set/Prolog/set.pro rename to Task/Set/Prolog/set-1.pro diff --git a/Task/Set/Prolog/set-2.pro b/Task/Set/Prolog/set-2.pro new file mode 100644 index 0000000000..5a3815a148 --- /dev/null +++ b/Task/Set/Prolog/set-2.pro @@ -0,0 +1,55 @@ +%% Set creation + +?- list_to_ord_set([1,2,3,4], A), list_to_ord_set([2,4,6,8], B). +A = [1, 2, 3, 4], +B = [2, 4, 6, 8]. + +%% Test m ∈ S -- "m is an element in set S" + +?- ord_memberchk(2, $A). +true. + +%% A ∪ B -- union; a set of all elements either in set A or in set B. + +?- ord_union($A, $B, Union). +Union = [1, 2, 3, 4, 6, 8]. + +%% A ∩ B -- intersection; a set of all elements in both set A and set B. + +?- ord_intersection($A, $B, Intersection). +Intersection = [2, 4]. + +%% A ∖ B -- difference; a set of all elements in set A, except those in set B. + +?- ord_subtract($A, $B, Diff). +Diff = [1, 3]. + +%% A ⊆ B -- subset; true if every element in set A is also in set B. + +?- ord_subset($A, $B). +false. + +?- ord_subset([2,4], $B). +true. + +%% A = B -- equality; true if every element of set A is in set B and vice-versa. + +?- $A == $B. +false. + +?- $A == [1,2,3,4]. +true. + +%% Definition of a proper subset: + +ord_propsubset(A, B) :- + ord_subset(A, B), + \+(A == B). + +%% add/remove elements + +?- ord_add_element($A, 19, NewA). +NewA = [1, 2, 3, 4, 19]. + +?- ord_del_element($NewA, 3, NewerA). +NewerA = [1, 2, 4, 19]. diff --git a/Task/Set/Python/set.py b/Task/Set/Python/set.py index e9a892bff3..2964927ca2 100644 --- a/Task/Set/Python/set.py +++ b/Task/Set/Python/set.py @@ -1,49 +1,49 @@ >>> s1, s2 = {1, 2, 3, 4}, {3, 4, 5, 6} ->>> s1 | s2; # Union +>>> s1 | s2 # Union {1, 2, 3, 4, 5, 6} ->>> s1 & s2; # Intersection +>>> s1 & s2 # Intersection {3, 4} ->>> s1 - s2; # Difference +>>> s1 - s2 # Difference {1, 2} ->>> s1 < s1; # True subset +>>> s1 < s1 # True subset False ->>> {3, 1} < s1; # True subset +>>> {3, 1} < s1 # True subset True ->>> s1 <= s1; # Subset +>>> s1 <= s1 # Subset True ->>> {3, 1} <= s1; # Subset +>>> {3, 1} <= s1 # Subset True ->>> {3, 2, 4, 1} == s1; # Equality +>>> {3, 2, 4, 1} == s1 # Equality True ->>> s1 == s2; # Equality +>>> s1 == s2 # Equality False ->>> 2 in s1; # Membership +>>> 2 in s1 # Membership True ->>> 10 not in s1; # Non-membership +>>> 10 not in s1 # Non-membership True ->>> {1, 2, 3, 4, 5} > s1; # True superset +>>> {1, 2, 3, 4, 5} > s1 # True superset True ->>> {1, 2, 3, 4} > s1; # True superset +>>> {1, 2, 3, 4} > s1 # True superset False ->>> {1, 2, 3, 4} >= s1; # Superset +>>> {1, 2, 3, 4} >= s1 # Superset True ->>> s1 ^ s2; # Symmetric difference +>>> s1 ^ s2 # Symmetric difference {1, 2, 5, 6} ->>> len(s1); # Cardinality +>>> len(s1) # Cardinality 4 ->>> s1.add(99); # Mutability +>>> s1.add(99) # Mutability >>> s1 {99, 1, 2, 3, 4} ->>> s1.discard(99); # Mutability +>>> s1.discard(99) # Mutability >>> s1 {1, 2, 3, 4} ->>> s1 |= s2; # Mutability +>>> s1 |= s2 # Mutability >>> s1 {1, 2, 3, 4, 5, 6} ->>> s1 -= s2; # Mutability +>>> s1 -= s2 # Mutability >>> s1 {1, 2} ->>> s1 ^= s2; # Mutability +>>> s1 ^= s2 # Mutability >>> s1 {1, 2, 3, 4, 5, 6} >>> diff --git a/Task/Set/REXX/set.rexx b/Task/Set/REXX/set.rexx index 8f18027a83..4b3a49b759 100644 --- a/Task/Set/REXX/set.rexx +++ b/Task/Set/REXX/set.rexx @@ -50,7 +50,7 @@ if add then do; set_=_2; t=_1; s=_1; end if (eq | subset) & \has then return 0 end /*j*/ -if subset then return 1 -if eq then if arg()>3 then return 1 - else return set$('equal',_2,_1,1) +if subset then return 1 +if eq then if arg()>3 then return 1 + else return set$('equal',_2,_1,1) return set.t diff --git a/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d b/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d index 3e5742a3eb..01c13d6e3d 100644 --- a/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d +++ b/Task/Seven-sided-dice-from-five-sided-dice/D/seven-sided-dice-from-five-sided-dice.d @@ -2,12 +2,12 @@ import std.random; import verify_distribution_uniformity_naive: distCheck; /// Generates a random number in [1, 5]. -int dice5() /*pure nothrow*/ { +int dice5() /*pure nothrow*/ @safe { return uniform(1, 6); } /// Naive, generates a random number in [1, 7] using dice5. -int fiveToSevenNaive() /*pure nothrow*/ { +int fiveToSevenNaive() /*pure nothrow*/ @safe { immutable int r = dice5() + dice5() * 5 - 6; return (r < 21) ? (r % 7) + 1 : fiveToSevenNaive(); } @@ -16,7 +16,7 @@ int fiveToSevenNaive() /*pure nothrow*/ { Generates a random number in [1, 7] using dice5, minimizing calls to dice5. */ -int fiveToSevenSmart() { +int fiveToSevenSmart() @safe { static int rem = 0, max = 1; while (rem / 7 == max / 7) { @@ -39,7 +39,7 @@ int fiveToSevenSmart() { return result + 1; } -void main() { +void main() /*@safe*/ { enum int N = 400_000; distCheck(&dice5, N, 1); distCheck(&fiveToSevenNaive, N, 1); diff --git a/Task/Seven-sided-dice-from-five-sided-dice/Julia/seven-sided-dice-from-five-sided-dice.julia b/Task/Seven-sided-dice-from-five-sided-dice/Julia/seven-sided-dice-from-five-sided-dice.julia new file mode 100644 index 0000000000..a0b85a991a --- /dev/null +++ b/Task/Seven-sided-dice-from-five-sided-dice/Julia/seven-sided-dice-from-five-sided-dice.julia @@ -0,0 +1,6 @@ +dice5() = rand(1:5) + +function dice7() + r = 5*dice5() + dice5() - 6 + r < 21 ? (r%7 + 1) : dice7() +end diff --git a/Task/Shell-one-liner/Maple/shell-one-liner.maple b/Task/Shell-one-liner/Maple/shell-one-liner.maple new file mode 100644 index 0000000000..d9b3297bb8 --- /dev/null +++ b/Task/Shell-one-liner/Maple/shell-one-liner.maple @@ -0,0 +1 @@ +maple -c'print(HELLO);' -cquit diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d index 55dcde026e..a8c3df8cd2 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-1.d @@ -1,12 +1,12 @@ import std.stdio, std.string, std.algorithm, std.array; -auto sierpinskiCarpet(in int n) pure nothrow { +auto sierpinskiCarpet(in int n) pure nothrow @safe { auto r = ["#"]; - foreach (_; 0 .. n) { - auto p = r.map!q{a ~ a ~ a}.array; + foreach (immutable _; 0 .. n) { + const p = r.map!q{a ~ a ~ a}.array; r = p ~ r.map!q{a ~ a.replace("#", " ") ~ a}.array ~ p; } - return r.join("\n"); + return r.join('\n'); } void main() { diff --git a/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d index c4f15b4087..552fb1a554 100644 --- a/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d +++ b/Task/Sierpinski-carpet/D/sierpinski-carpet-3.d @@ -1,6 +1,6 @@ import std.stdio, std.array; -char[][] sierpinskiCarpet(in size_t n) pure nothrow { +char[][] sierpinskiCarpet(in size_t n) pure nothrow @safe { auto mat = uninitializedArray!(typeof(return))(3 ^^ n, 3 ^^ n); foreach (immutable r, row; mat) { diff --git a/Task/Sierpinski-carpet/Euphoria/sierpinski-carpet.euphoria b/Task/Sierpinski-carpet/Euphoria/sierpinski-carpet.euphoria new file mode 100644 index 0000000000..1402f91924 --- /dev/null +++ b/Task/Sierpinski-carpet/Euphoria/sierpinski-carpet.euphoria @@ -0,0 +1,26 @@ +include std/math.e + +integer order = 4 + +function InCarpet(atom x, atom y) + while 1 do + if x = 0 or y = 0 then + return 1 + elsif floor(mod(x,3)) = 1 and floor(mod(y,3)) = 1 then + return 0 + end if + x /= 3 + y /= 3 + end while +end function + +for i = 0 to power(3,order)-1 do + for j = 0 to power(3,order)-1 do + if InCarpet(i,j) = 1 then + puts(1,"#") + else + puts(1," ") + end if + end for + puts(1,'\n') +end for diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j index 47a6f121b8..4517e27fc4 100644 --- a/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-2.j @@ -1 +1,27 @@ -((#:7 5 7){_2{.<)^:N' ' + N=:2 + (a:(<1;1)}3 3$<)^:N' ' +┌─────────────┬─────────────┬─────────────┐ +│┌───┬───┬───┐│┌───┬───┬───┐│┌───┬───┬───┐│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│ +├─────────────┼─────────────┼─────────────┤ +│┌───┬───┬───┐│ │┌───┬───┬───┐│ +││ │ │ ││ ││ │ │ ││ +│├───┼───┼───┤│ │├───┼───┼───┤│ +││ │ │ ││ ││ │ │ ││ +│├───┼───┼───┤│ │├───┼───┼───┤│ +││ │ │ ││ ││ │ │ ││ +│└───┴───┴───┘│ │└───┴───┴───┘│ +├─────────────┼─────────────┼─────────────┤ +│┌───┬───┬───┐│┌───┬───┬───┐│┌───┬───┬───┐│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│ +└─────────────┴─────────────┴─────────────┘ diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j index 2672852bbb..3462c3d4d3 100644 --- a/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-3.j @@ -1,10 +1,4 @@ - ' #'{~(#:7 5 7) ,/@(1 3 ,/"2@|: */)^:N ,.1 -######### -# ## ## # -######### -### ### -# # # # -### ### -######### -# ## ## # -######### + #:7 5 7 +1 1 1 +1 0 1 +1 1 1 diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-4.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-4.j new file mode 100644 index 0000000000..0767ad3cd7 --- /dev/null +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-4.j @@ -0,0 +1,27 @@ + N=:2 + ((#:7 5 7){_2{.<)^:N' ' +┌─────────────┬─────────────┬─────────────┐ +│┌───┬───┬───┐│┌───┬───┬───┐│┌───┬───┬───┐│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│ +├─────────────┼─────────────┼─────────────┤ +│┌───┬───┬───┐│ │┌───┬───┬───┐│ +││ │ │ ││ ││ │ │ ││ +│├───┼───┼───┤│ │├───┼───┼───┤│ +││ │ │ ││ ││ │ │ ││ +│├───┼───┼───┤│ │├───┼───┼───┤│ +││ │ │ ││ ││ │ │ ││ +│└───┴───┴───┘│ │└───┴───┴───┘│ +├─────────────┼─────────────┼─────────────┤ +│┌───┬───┬───┐│┌───┬───┬───┐│┌───┬───┬───┐│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│├───┼───┼───┤│├───┼───┼───┤│├───┼───┼───┤│ +││ │ │ │││ │ │ │││ │ │ ││ +│└───┴───┴───┘│└───┴───┴───┘│└───┴───┴───┘│ +└─────────────┴─────────────┴─────────────┘ diff --git a/Task/Sierpinski-carpet/J/sierpinski-carpet-5.j b/Task/Sierpinski-carpet/J/sierpinski-carpet-5.j new file mode 100644 index 0000000000..531230e51e --- /dev/null +++ b/Task/Sierpinski-carpet/J/sierpinski-carpet-5.j @@ -0,0 +1,40 @@ + N=:2 + ' #'{~(#:7 5 7) ,/@(1 3 ,/"2@|: */)^:N ,.1 +######### +# ## ## # +######### +### ### +# # # # +### ### +######### +# ## ## # +######### + N=:3 + ' #'{~(#:7 5 7) ,/@(1 3 ,/"2@|: */)^:N ,.1 +########################### +# ## ## ## ## ## ## ## ## # +########################### +### ###### ###### ### +# # # ## # # ## # # # +### ###### ###### ### +########################### +# ## ## ## ## ## ## ## ## # +########################### +######### ######### +# ## ## # # ## ## # +######### ######### +### ### ### ### +# # # # # # # # +### ### ### ### +######### ######### +# ## ## # # ## ## # +######### ######### +########################### +# ## ## ## ## ## ## ## ## # +########################### +### ###### ###### ### +# # # ## # # ## # # # +### ###### ###### ### +########################### +# ## ## ## ## ## ## ## ## # +########################### diff --git a/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia b/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia new file mode 100644 index 0000000000..6127797262 --- /dev/null +++ b/Task/Sierpinski-carpet/Julia/sierpinski-carpet.julia @@ -0,0 +1,12 @@ +pprint(matrix) = for i = 1:size(matrix,1) println(join(matrix[i,:])) end + +spaces(m,n) = [" " for i=1:m, j=1:n] + +function sierpinski(n, token = "*") + x = [token for i=1:1, j=1:1] + for i = 1:n + t = spaces(size(x)...) + x = [[x x x] ; [x t x] ; [x x x]] + end + x +end diff --git a/Task/Sierpinski-carpet/Objeck/sierpinski-carpet.objeck b/Task/Sierpinski-carpet/Objeck/sierpinski-carpet.objeck new file mode 100644 index 0000000000..93b5947722 --- /dev/null +++ b/Task/Sierpinski-carpet/Objeck/sierpinski-carpet.objeck @@ -0,0 +1,29 @@ +class SierpinskiCarpet { + function : Main(args : String[]) ~ Nil { + Carpet(3); + } + + function : InCarpet(x : Int, y : Int) ~ Bool { + while(x<>0 & y<>0) { + if(x % 3 = 1 & y % 3 = 1) { + return false; + }; + + x /= 3; + y /= 3; + }; + + return true; + } + + function : Carpet(n : Int) ~ Nil { + power := 3.0->Power(n->As(Float)); + for(i := 0; i < power; i+=1;) { + for(j := 0; j < power; j+=1;) { + c := InCarpet(i, j) ? '*' : ' '; + c->Print(); + }; + IO.Console->PrintLine(); + }; + } +} diff --git a/Task/Sierpinski-carpet/VBScript/sierpinski-carpet.vb b/Task/Sierpinski-carpet/VBScript/sierpinski-carpet.vb new file mode 100644 index 0000000000..7bab21b102 --- /dev/null +++ b/Task/Sierpinski-carpet/VBScript/sierpinski-carpet.vb @@ -0,0 +1,32 @@ +Function InCarpet(i,j) + If i > 0 And j > 0 Then + Do While i > 0 And j > 0 + If i Mod 3 = 1 And j Mod 3 = 1 Then + InCarpet = " " + Exit Do + Else + InCarpet = "#" + End If + i = Int(i / 3) + j = Int(j / 3) + Loop + Else + InCarpet = "#" + End If +End Function + +Function Carpet(n) + k = 3^n - 1 + x2 = 0 + y2 = 0 + For y = 0 To k + For x = 0 To k + x2 = x + y2 = y + WScript.StdOut.Write InCarpet(x2,y2) + Next + WScript.StdOut.WriteBlankLines(1) + Next +End Function + +Carpet(WScript.Arguments(0)) diff --git a/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d b/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d index 90b9fcb301..3ac9885a9a 100644 --- a/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d +++ b/Task/Sierpinski-triangle-Graphical/D/sierpinski-triangle-graphical.d @@ -1,6 +1,6 @@ -import grayscale_image; - void main() { + import grayscale_image; + enum order = 8, margin = 10, width = 2 ^^ order; @@ -8,8 +8,8 @@ void main() { auto im = new Image!Gray(width + 2 * margin, width + 2 * margin); im.clear(Gray.white); - foreach (y; 0 .. width) - foreach (x; 0 .. width) + foreach (immutable y; 0 .. width) + foreach (immutable x; 0 .. width) if ((x & y) == 0) im[x + margin, y + margin] = Gray.black; im.savePGM("sierpinski.pgm"); diff --git a/Task/Sierpinski-triangle-Graphical/Java/sierpinski-triangle-graphical.java b/Task/Sierpinski-triangle-Graphical/Java/sierpinski-triangle-graphical.java new file mode 100644 index 0000000000..ed592bf023 --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Java/sierpinski-triangle-graphical.java @@ -0,0 +1,58 @@ +import javax.swing.*; +import java.awt.*; + +/** +* SierpinskyTriangle.java +* Draws a SierpinskyTriangle in a JFrame +* The order of complexity is given from command line, but +* defaults to 3 +* +* @author Istarnion +*/ + +class SierpinskyTriangle { + + public static void main(String[] args) { + int i = 3; // Default to 3 + if(args.length >= 1) { + try { + i = Integer.parseInt(args[0]); + } + catch(NumberFormatException e) { + System.out.println("Usage: 'java SierpinskyTriangle [level]'\nNow setting level to "+i); + } + } + final int level = i; + + JFrame frame = new JFrame("Sierpinsky Triangle - Java"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JPanel panel = new JPanel() { + @Override + public void paintComponent(Graphics g) { + g.setColor(Color.BLACK); + drawSierpinskyTriangle(level, 20, 20, 360, (Graphics2D)g); + } + }; + + panel.setPreferredSize(new Dimension(400, 400)); + + frame.add(panel); + frame.pack(); + frame.setResizable(false); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + private static void drawSierpinskyTriangle(int level, int x, int y, int size, Graphics2D g) { + if(level <= 0) return; + + g.drawLine(x, y, x+size, y); + g.drawLine(x, y, x, y+size); + g.drawLine(x+size, y, x, y+size); + + drawSierpinskyTriangle(level-1, x, y, size/2, g); + drawSierpinskyTriangle(level-1, x+size/2, y, size/2, g); + drawSierpinskyTriangle(level-1, x, y+size/2, size/2, g); + } +} diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py new file mode 100644 index 0000000000..57dda5208a --- /dev/null +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-1.py @@ -0,0 +1,20 @@ +#!/usr/bin/env python +########################################################################################## +# import necessary modules +# ------------------------ +from numpy import * +import turtle + +########################################################################################## +# Functions defining the drawing actions +# (used by the function DrawSierpinskiTriangle). +# ---------------------------------------------- +def Left(turn, point, fwd, angle, turt): + turt.left(angle) + return [turn, point, fwd, angle, turt] +def Right(turn, point, fwd, angle, turt): + turt.right(angle) + return [turn, point, fwd, angle, turt] +def Forward(turn, point, fwd, angle, turt): + turt.forward(fwd) + return [turn, point, fwd, angle, turt] diff --git a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py similarity index 68% rename from Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py rename to Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py index 0a4e4ea172..172ab41e55 100644 --- a/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical.py +++ b/Task/Sierpinski-triangle-Graphical/Python/sierpinski-triangle-graphical-2.py @@ -1,28 +1,10 @@ -#!/usr/bin/env python -################################################################################################ -# import necessary modules -# ------------------------ -from numpy import * -import turtle -################################################################################################ -# Functions defining the drawing actions (used by the function DrawSierpinskiTriangle). -# ------------------------------------------------------------------------------------- -def Left(turn, point, fwd, angle, turt): - turt.left(angle) - return [turn, point, fwd, angle, turt] -def Right(turn, point, fwd, angle, turt): - turt.right(angle) - return [turn, point, fwd, angle, turt] -def Forward(turn, point, fwd, angle, turt): - turt.forward(fwd) - return [turn, point, fwd, angle, turt] -################################################################################################ +########################################################################################## # The drawing function # -------------------- # # level level of Sierpinski triangle (minimum value = 1) # ss screensize (Draws on a screen of size ss x ss. Default value = 400.) -#----------------------------------------------------------------------------------------------- +#----------------------------------------------------------------------------------------- def DrawSierpinskiTriangle(level, ss=400): # typical values turn = 0 # initial turn (0 to start horizontally) @@ -73,6 +55,6 @@ def DrawSierpinskiTriangle(level, ss=400): # Draw it. for i in path: [turn, point, fwd, angle, turt]=decode[i](turn, point, fwd, angle, turt) -################################################################################################ +########################################################################################## DrawSierpinskiTriangle(5) diff --git a/Task/Sierpinski-triangle/00DESCRIPTION b/Task/Sierpinski-triangle/00DESCRIPTION index 992a322309..b4e0765099 100644 --- a/Task/Sierpinski-triangle/00DESCRIPTION +++ b/Task/Sierpinski-triangle/00DESCRIPTION @@ -1,4 +1,5 @@ -Produce an ASCII representation of a [[wp:Sierpinski triangle|Sierpinski triangle]] of order N. For example, the Sierpinski triangle of order 4 should look like this: +Produce an ASCII representation of a [[wp:Sierpinski triangle|Sierpinski triangle]] of order N. +For example, the Sierpinski triangle of order 4 should look like this:
                            *
                           * *
    @@ -18,4 +19,5 @@ Produce an ASCII representation of a [[wp:Sierpinski triangle|Sierpinski triangl
             * * * * * * * * * * * * * * * *
     
    -See [[Sierpinski triangle/Graphical]] for graphics images of this pattern. See also [[Sierpinski carpet]] +See [[Sierpinski triangle/Graphical]] for graphics images of this pattern. +See also [[Sierpinski carpet]] diff --git a/Task/Sierpinski-triangle/ATS/sierpinski-triangle.ats b/Task/Sierpinski-triangle/ATS/sierpinski-triangle.ats new file mode 100644 index 0000000000..394bb42239 --- /dev/null +++ b/Task/Sierpinski-triangle/ATS/sierpinski-triangle.ats @@ -0,0 +1,42 @@ +(* ****** ****** *) +// +// How to compile: +// +// patscc -DATS_MEMALLOC_LIBC -o sierpinski sierpinski.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +#define SIZE 16 + +implement +main0 () = +{ +// +var x: int +// +val () = +for (x := SIZE-1; x >= 0; x := x-1) +{ + var i: int + val () = + for (i := 0; i < x; i := i+1) + { + val () = print_char(' ') + } + var y: int + val () = + for (y := 0; y + x < SIZE; y := y+1) + { + val y = g0int2uint_int_uint(y) + val x = g0int2uint_int_uint(x) + val () = print_string(if (x land y) != 0 then " " else "* ") + } + val ((*flushed*)) = print_newline() +} +// +} (* end of [main0] *) diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d index 0e6cb48876..d52c586a0b 100644 --- a/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-1.d @@ -1,6 +1,6 @@ -import std.stdio, std.algorithm, std.string, std.array; +void main() /*@safe*/ { + import std.stdio, std.algorithm, std.string, std.array; -void main() { enum level = 4; auto d = ["*"]; foreach (immutable n; 0 .. level) { @@ -8,5 +8,5 @@ void main() { d = d.map!(a => sp ~ a ~ sp).array ~ d.map!(a => a ~ " " ~ a).array; } - d.join("\n").writeln; + d.join('\n').writeln; } diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d index a30aae41c9..c30a82f1d3 100644 --- a/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-2.d @@ -1,19 +1,14 @@ -import std.string; +import std.string, std.range, std.algorithm; -string sierpinski(int n) { - auto parts = ["*"]; - auto space = " "; - foreach (i; 0 .. n) { - string[] parts2; - foreach (x; parts) - parts2 ~= space ~ x ~ space; - foreach (x; parts) - parts2 ~= x ~ " " ~ x; - parts = parts2; - space ~= space; +string sierpinski(int level) pure nothrow /*@safe*/ { + auto d = ["*"]; + foreach (immutable i; 0 .. level) { + immutable sp = " ".replicate(2 ^^ i); + d = d.map!(a => sp ~ a ~ sp).array ~ + d.map!(a => a ~ " " ~ a).array; } - return parts.join("\n"); + return d.join('\n'); } -pragma(msg, sierpinski(4)); +pragma(msg, 4.sierpinski); void main() {} diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-3.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-3.d new file mode 100644 index 0000000000..0154e88f76 --- /dev/null +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-3.d @@ -0,0 +1,17 @@ +void showSierpinskiTriangle(in uint order) nothrow @safe @nogc { + import core.stdc.stdio: putchar; + + foreach_reverse (immutable y; 0 .. 2 ^^ order) { + foreach (immutable _; 0 .. y) + ' '.putchar; + foreach (immutable x; 0 .. 2 ^^ order - y) { + putchar((x & y) ? ' ' : '*'); + ' '.putchar; + } + '\n'.putchar; + } +} + +void main() nothrow @safe @nogc { + 4.showSierpinskiTriangle; +} diff --git a/Task/Sierpinski-triangle/D/sierpinski-triangle-4.d b/Task/Sierpinski-triangle/D/sierpinski-triangle-4.d new file mode 100644 index 0000000000..fd26fb8c09 --- /dev/null +++ b/Task/Sierpinski-triangle/D/sierpinski-triangle-4.d @@ -0,0 +1,42 @@ +import core.stdc.stdio: putchar; +import std.algorithm: swap; + + +void showSierpinskiTriangle(in uint nLevels) nothrow @safe +in { + assert(nLevels > 0); +} body { + alias Row = bool[]; + + static void applyRules(in Row r1, Row r2) pure nothrow @safe @nogc { + r2[0] = r1[0] || r1[1]; + r2[$ - 1] = r1[$ - 2] || r1[$ - 1]; + foreach (immutable i; 1 .. r2.length - 1) + r2[i] = r1[i - 1] != r1[i] || r1[i] != r1[i + 1]; + } + + static void showRow(in Row r) nothrow @safe @nogc { + foreach (immutable b; r) + putchar(b ? '#' : ' '); + '\n'.putchar; + } + + immutable width = 2 ^^ (nLevels + 1) - 1; + auto row1 = new Row(width); + auto row2 = new Row(width); + row1[width / 2] = true; + + foreach (immutable _; 0 .. 2 ^^ nLevels) { + showRow(row1); + applyRules(row1, row2); + row1.swap(row2); + } +} + + +void main() @safe nothrow { + foreach (immutable i; 1 .. 6) { + i.showSierpinskiTriangle; + '\n'.putchar; + } +} diff --git a/Task/Sierpinski-triangle/Python/sierpinski-triangle-3.py b/Task/Sierpinski-triangle/Python/sierpinski-triangle-3.py new file mode 100644 index 0000000000..47eec71f74 --- /dev/null +++ b/Task/Sierpinski-triangle/Python/sierpinski-triangle-3.py @@ -0,0 +1,4 @@ +x = 1 +while True: + print(bin(x)[2:].replace('0', ' ')) + x ^= x<<1 diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb index c3f6244522..8510bbbe9d 100644 --- a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-2.rb @@ -2,10 +2,10 @@ def sierpinski_triangle(n) triangle = ["*"] n.times do |i| sp = " " * (2**i) - triangle = triangle.collect {|x| sp + x + sp} + \ + triangle = triangle.collect {|x| sp + x + sp} + triangle.collect {|x| x + " " + x} end - triangle.join("\n") + triangle end puts sierpinski_triangle(4) diff --git a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb index 4236273765..20e1636303 100644 --- a/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb +++ b/Task/Sierpinski-triangle/Ruby/sierpinski-triangle-3.rb @@ -1,9 +1,8 @@ def sierpinski_triangle(n) - - (0..(n-1)).inject(["*"]) {|triangle, i| - space = " " * (2**i) - triangle.map {|x| space + x + space} + triangle.map {|x| x + " " + x} - } + (0...n).inject(["*"]) {|triangle, i| + space = " " * (2**i) + triangle.map {|x| space + x + space} + triangle.map {|x| x + " " + x} + } end puts sierpinski_triangle(4) diff --git a/Task/Sieve-of-Eratosthenes/00DESCRIPTION b/Task/Sieve-of-Eratosthenes/00DESCRIPTION index 1e7e8981ac..0af7155246 100644 --- a/Task/Sieve-of-Eratosthenes/00DESCRIPTION +++ b/Task/Sieve-of-Eratosthenes/00DESCRIPTION @@ -1,5 +1,6 @@ {{clarified-review}} -The [[wp:Sieve_of_Eratosthenes|Sieve of Eratosthenes]] is a simple algorithm that finds the prime numbers up to a given integer. Implement this algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed ''wheels'', i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. +The [[wp:Sieve_of_Eratosthenes|Sieve of Eratosthenes]] is a simple algorithm that finds the prime numbers up to a given integer. Implement this algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. +That means especially that you shouldn't optimize by using pre-computed ''wheels'', i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement this as an alternative version. @@ -8,4 +9,5 @@ If there's an easy way to add such a wheel based optimization, implement this as ;Cf: * [[Primality by trial division]]. +* [[Sequence of primes by Trial Division]]. * [[Prime decomposition]]. diff --git a/Task/Sieve-of-Eratosthenes/360-Assembly/sieve-of-eratosthenes.360 b/Task/Sieve-of-Eratosthenes/360-Assembly/sieve-of-eratosthenes.360 new file mode 100644 index 0000000000..044b190eb7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/360-Assembly/sieve-of-eratosthenes.360 @@ -0,0 +1,71 @@ +* Sieve of Eratosthenes +ERATOST CSECT + USING ERATOST,R12 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'ERATOST' +STM STM R14,R12,12(R13) save calling context + ST R13,4(R15) + ST R15,8(R13) + LR R12,R15 set addessability +* ---- CODE + LA R4,1 I=1 + LA R6,1 increment + L R7,N limit +LOOPI BXH R4,R6,ENDLOOPI do I=2 to N + LR R1,R4 R1=I + BCTR R1,0 + LA R14,CRIBLE(R1) + CLI 0(R14),X'01' + BNE ENDIF if not CRIBLE(I) + LR R5,R4 J=I + LR R8,R4 + LR R9,R7 +LOOPJ BXH R5,R8,ENDLOOPJ do J=I*2 to N by I + LR R1,R5 R1=J + BCTR R1,0 + LA R14,CRIBLE(R1) + MVI 0(R14),X'00' CRIBLE(J)='0'B + B LOOPJ +ENDLOOPJ EQU * +ENDIF EQU * + B LOOPI +ENDLOOPI EQU * + LA R4,1 I=1 + LA R6,1 + L R7,N +LOOP BXH R4,R6,ENDLOOP do I=1 to N + LR R1,R4 R1=I + BCTR R1,0 + LA R14,CRIBLE(R1) + CLI 0(R14),X'01' + BNE NOTPRIME if not CRIBLE(I) + CVD R4,P P=I + UNPK Z,P Z=P + MVC C,Z C=Z + OI C+L'C-1,X'F0' zap sign + MVC WTOBUF(8),C+8 + WTO MF=(E,WTOMSG) +NOTPRIME EQU * + B LOOP +ENDLOOP EQU * +RETURN EQU * + LM R14,R12,12(R13) restore context + XR R15,R15 set return code to 0 + BR R14 return to caller +* ---- DATA +I DS F +J DS F + DS 0F +P DS PL8 packed +Z DS ZL16 zoned +C DS CL16 character +WTOMSG CNOP 0,4 + DC H'80' length of WTO buffer + DC H'0' must be binary zeroes +WTOBUF DC 80C' ' + LTORG +N DC F'100000' +CRIBLE DC 100000X'01' + YREGS + END ERATOST diff --git a/Task/Sieve-of-Eratosthenes/ALGOL-60/sieve-of-eratosthenes.alg b/Task/Sieve-of-Eratosthenes/ALGOL-60/sieve-of-eratosthenes.alg new file mode 100644 index 0000000000..84f9f37b92 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/ALGOL-60/sieve-of-eratosthenes.alg @@ -0,0 +1,40 @@ +'BEGIN' + 'INTEGER' 'ARRAY' CANDIDATES(/0..1000/); + 'INTEGER' I,J,K; + 'COMMENT' SET LINE-LENGTH=120,SET LINES-PER-PAGE=62,OPEN; + SYSACT(1,6,120); SYSACT(1,8,62); SYSACT(1,12,1); + 'FOR' I := 0 'STEP' 1 'UNTIL' 1000 'DO' + 'BEGIN' + CANDIDATES(/I/) := 1; + 'END'; + CANDIDATES(/0/) := 0; + CANDIDATES(/1/) := 0; + I := 0; + 'FOR' I := I 'WHILE' I 'LESS' 1000 'DO' + 'BEGIN' + 'FOR' I := I 'WHILE' I 'LESS' 1000 + 'AND' CANDIDATES(/I/) 'EQUAL' 0 'DO' + I := I+1; + 'IF' I 'LESS' 1000 'THEN' + 'BEGIN' + J := 2; + K := J*I; + 'FOR' K := K 'WHILE' K 'LESS' 1000 'DO' + 'BEGIN' + CANDIDATES(/K/) := 0; + J := J + 1; + K := J*I; + 'END'; + I := I+1; + 'END' + 'END'; + 'FOR' I := 0 'STEP' 1 'UNTIL' 999 'DO' + 'IF' CANDIDATES(/I/) 'NOTEQUAL' 0 'THEN' + 'BEGIN' + OUTINTEGER(1,I); + OUTSTRING(1,'(' IS PRIME')'); + 'COMMENT' NEW LINE; + SYSACT(1,14,1) + 'END' + 'END' +'END' diff --git a/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk b/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk new file mode 100644 index 0000000000..e1cf20d893 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/AWK/sieve-of-eratosthenes.awk @@ -0,0 +1,18 @@ +# usage: gawk -v n=101 -f sieve.awk + +function sieve(n) { # print n,":" + for(i=2; i<=n; i++) a[i]=1; + for(i=2; i<=sqrt(n);i++) for(j=2;j<=n;j++) a[i*j]=0; + for(i=2; i<=n; i++) if(a[i]) printf i" " + print "" +} + +BEGIN { print "Sieve of Eratosthenes:" + if(n>1) sieve(n) + } + + { n=$1+0 } +n<2 { exit } + { sieve(n) } + +END { print "Bye!" } diff --git a/Task/Sieve-of-Eratosthenes/Batch-File/sieve-of-eratosthenes.bat b/Task/Sieve-of-Eratosthenes/Batch-File/sieve-of-eratosthenes.bat new file mode 100644 index 0000000000..2345736254 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Batch-File/sieve-of-eratosthenes.bat @@ -0,0 +1,20 @@ +:: Sieve of Eratosthenes for Rosetta Code - PG +@echo off +setlocal ENABLEDELAYEDEXPANSION +setlocal ENABLEEXTENSIONS +rem echo on +set /p n=limit: +rem set n=100 +for /L %%i in (1,1,%n%) do set crible.%%i=1 +for /L %%i in (2,1,%n%) do ( + if !crible.%%i! EQU 1 ( + set /A w = %%i * 2 + for /L %%j in (!w!,%%i,%n%) do ( + set crible.%%j=0 + ) + ) +) +for /L %%i in (2,1,%n%) do ( + if !crible.%%i! EQU 1 echo %%i +) +pause diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-1.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-1.c new file mode 100644 index 0000000000..19fc26679c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-1.c @@ -0,0 +1,28 @@ +#include +#include + +char* +eratosthenes(int n, int *c) +{ + char* sieve; + int i, j, m; + + if(n < 2) + return NULL; + + *c = n-1; /* primes count */ + m = (int) sqrt((double) n); + + /* calloc initializes to zero */ + sieve = calloc(n+1,sizeof(char)); + sieve[0] = 1; + sieve[1] = 1; + for(i = 2; i <= m; i++) + if(!sieve[i]) + for (j = i*i; j <= n; j += i) + if(!sieve[j]){ + sieve[j] = 1; + --(*c); + } + return sieve; +} diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c new file mode 100644 index 0000000000..4fb0a8523d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-2.c @@ -0,0 +1,39 @@ +#include +#include +void sieve(int *, int); + +int main(int argc, char *argv) +{ + int *array, n=10; + array =(int *)malloc(sizeof(int)); + sieve(array,n); + return 0; +} + +void sieve(int *a, int n) +{ + int i=0, j=0; + + for(i=2; i<=n; i++) { + a[i] = 1; + } + + for(i=2; i<=n; i++) { + printf("\ni:%d", i); + if(a[i] == 1) { + for(j=i; (i*j)<=n; j++) { + printf ("\nj:%d", j); + printf("\nBefore a[%d*%d]: %d", i, j, a[i*j]); + a[(i*j)] = 0; + printf("\nAfter a[%d*%d]: %d", i, j, a[i*j]); + } + } + } + + printf("\nPrimes numbers from 1 to %d are : ", n); + for(i=2; i<=n; i++) { + if(a[i] == 1) + printf("%d, ", i); + } + printf("\n\n"); +} diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-3.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-3.c new file mode 100644 index 0000000000..7eea9c8868 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes-3.c @@ -0,0 +1,25 @@ +i:2 +j:2 +Before a[2*2]: 1 +After a[2*2]: 0 +j:3 +Before a[2*3]: 1 +After a[2*3]: 0 +j:4 +Before a[2*4]: 1 +After a[2*4]: 0 +j:5 +Before a[2*5]: 1 +After a[2*5]: 0 +i:3 +j:3 +Before a[3*3]: 1 +After a[3*3]: 0 +i:4 +i:5 +i:6 +i:7 +i:8 +i:9 +i:10 +Primes numbers from 1 to 10 are : 2, 3, 5, 7, diff --git a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c b/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c deleted file mode 100644 index b2229c3d6b..0000000000 --- a/Task/Sieve-of-Eratosthenes/C/sieve-of-eratosthenes.c +++ /dev/null @@ -1,29 +0,0 @@ -#include -#include - -char* eratosthenes (int n, int *c) -{ - char* sieve; - int i, j, m; - - if (n < 2) { *c = 0; return NULL; } - - *c = n-1; /* primes count */ - m = (int) sqrt ((double) n); - - /* calloc initializes to zero */ - sieve = calloc (n+1, sizeof(char)); - sieve[0] = 1; - sieve[1] = 1; - for (i = 2; i <= m; i++) { - if (sieve[i] == 0) { - for (j = i*i; j <= n; j += i) { - if (sieve[j] == 0) { - sieve[j] = 1; - --(*c); - } - } - } - } - return sieve; -} diff --git a/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes.cmake b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes.cmake new file mode 100644 index 0000000000..f393b5d6c1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/CMake/sieve-of-eratosthenes.cmake @@ -0,0 +1,35 @@ +function(eratosthenes var limit) + # Check for integer overflow. With CMake using 32-bit signed integer, + # this check fails when limit > 46340. + if(NOT limit EQUAL 0) # Avoid division by zero. + math(EXPR i "(${limit} * ${limit}) / ${limit}") + if(NOT limit EQUAL ${i}) + message(FATAL_ERROR "limit is too large, would cause integer overflow") + endif() + endif() + + # Use local variables prime_2, prime_3, ..., prime_${limit} as array. + # Initialize array to y => yes it is prime. + foreach(i RANGE 2 ${limit}) + set(prime_${i} y) + endforeach(i) + + # Gather a list of prime numbers. + set(list) + foreach(i RANGE 2 ${limit}) + if(prime_${i}) + # Append this prime to list. + list(APPEND list ${i}) + + # For each multiple of i, set n => no it is not prime. + # Optimization: start at i squared. + math(EXPR square "${i} * ${i}") + if(NOT square GREATER ${limit}) # Avoid fatal error. + foreach(m RANGE ${square} ${limit} ${i}) + set(prime_${m} n) + endforeach(m) + endif() + endif(prime_${i}) + endforeach(i) + set(${var} ${list} PARENT_SCOPE) +endfunction(eratosthenes) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj index b861c756fb..33f66ac07b 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-1.clj @@ -1,23 +1,19 @@ -(defn primes-up-to [n] +(defn primes-to + "Returns a list of all primes from 2 to n" + [n] (let [n (int n)] - "Returns a list of all primes from 2 to n" - (let [root (int (Math/round (Math/floor (Math/sqrt n))))] - (loop [i (int 3) - a (int-array n) - result (transient [2])] - (if (>= i n) + (let [root (-> n Math/sqrt int)] + (loop [i (int 2), a (boolean-array (inc n)), result (transient [])] + (if (> i n) (persistent! result) - (recur (+ i (int 2)) - (if (<= i root) - (loop [arr a - inc (+ i i) - j (* i i)] - (if (>= j n) + (recur (inc i) + (if (and (<= i root) (not (aget a i))) + (loop [arr a, j (* i i)] + (if (> j n) arr - (recur (do (aset arr j (int 1)) arr) - inc - (+ j inc)))) + (recur (do (aset arr j true) arr) + (+ j i)))) a) - (if (zero? (aget a i)) + (if (not (aget a i)) (conj! result i) result))))))) diff --git a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj index 67ce5a32ba..90d5448ce6 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-2.clj @@ -1,19 +1,10 @@ -(defn primes [max-prime] - (let [new-sieve (fn [] - (let [v (reduce conj (vector-of :boolean) (range (inc max-prime)))] - (assoc (assoc v 0 false) 1 false))), - - sieve (fn [S] - (loop [s S, n 2] - (let [n**2 (* n n)] - (if (<= n**2 max-prime) - (recur (if (s n) - (reduce #(assoc %1 %2 false) s (range n**2 (inc max-prime) n)) - s) - (inc n)) - s)))), - - bitset-contents (fn [S] - (map second (filter first (map vector S (range (count S))))))] - - (bitset-contents (sieve (new-sieve))))) +(defn primes + "Computes all prime numbers up to a given number using sieve of Eratosthenes" + [n] + (loop [cs (range 2 n) ; candidates + ps [2]] ; results + (let [lp (last ps) + ncs (-> (range lp n lp) set (remove cs))] + (if (> lp (Math/sqrt n)) + (concat ps ncs) + (recur ncs (concat ps [(first ncs)])))))) 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 4b0736fa8e..54d0323d00 100644 --- a/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj +++ b/Task/Sieve-of-Eratosthenes/Clojure/sieve-of-eratosthenes-3.clj @@ -1,11 +1,14 @@ -(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)]))))))) +(defn primes [max-prime] + (let [sieve (fn [s n] + (if (<= (* n n) max-prime) + (recur (if (s n) + (reduce #(assoc %1 %2 false) s (range (* n n) (inc max-prime) n)) + s) + (inc n)) + s))] + (-> (vector-of :boolean) ; form the return vector + (reduce conj (range (inc max-prime))) + (assoc 0 false) + (assoc 1 false) + (sieve 2) + #(->> % count range (map vector %) (filter first) (map second))))) diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d index 9c1e32abca..0c36804b9f 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-1.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.range, std.functional; -uint[] sieve(in uint limit) { +uint[] sieve(in uint limit) nothrow @safe { if (limit < 2) return []; auto composite = new bool[limit]; @@ -10,10 +10,10 @@ uint[] sieve(in uint limit) { for (uint k = n * n; k < limit; k += n) composite[k] = true; - //return iota(2, limit).filter!(not!composite)().array(); - return iota(2, limit).filter!(i => !composite[i])().array(); + //return iota(2, limit).filter!(not!composite).array; + return iota(2, limit).filter!(i => !composite[i]).array; } void main() { - writeln(sieve(50)); + 50.sieve.writeln; } 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 2d0bf669cb..2dd37e7003 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 @safe { if (m < 3) return null; immutable size_t n = m - 1; @@ -8,13 +8,13 @@ size_t[] sieve(in size_t m) pure nothrow { auto F = new size_t[((n + 2) / 2) / bpc + 1]; F[] = size_t.max; - size_t isSet(in size_t i) nothrow { + size_t isSet(in size_t i) nothrow @safe @nogc { immutable size_t offset = i / bpc; immutable size_t mask = 1 << (i % bpc); return F[offset] & mask; } - void resetBit(in size_t i) nothrow { + void resetBit(in size_t i) nothrow @safe @nogc { immutable size_t offset = i / bpc; immutable size_t mask = 1 << (i % bpc); if ((F[offset] & mask) != 0) diff --git a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d index 4d5d9716ea..807bc2b9c4 100644 --- a/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d +++ b/Task/Sieve-of-Eratosthenes/D/sieve-of-eratosthenes-3.d @@ -2,7 +2,7 @@ struct Prime { uint[] a = [2]; - private void grow() pure nothrow { + private void grow() pure nothrow @safe { immutable p0 = a[$ - 1] + 1; auto b = new bool[p0]; @@ -18,7 +18,7 @@ struct Prime { a ~= p0 + i; } - uint opCall(in uint n) pure nothrow { + uint opCall(in uint n) pure nothrow @safe { while (n >= a.length) grow; return a[n]; diff --git a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-1.dart b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-1.dart new file mode 100644 index 0000000000..fc5951db14 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-1.dart @@ -0,0 +1,33 @@ +// helper function to pretty print an Iterable +String iterableToString(Iterable seq) { + String str = "["; + Iterator i = seq.iterator; + if (i.moveNext()) str += i.current.toString(); + while(i.moveNext()) { + str += ", " + i.current.toString(); + } + return str + "]"; +} + +main() { + int limit = 1000; + int strt = new DateTime.now().millisecondsSinceEpoch; + Set sieve = new Set(); + + for(int i = 2; i <= limit; i++) { + sieve.add(i); + } + for(int i = 2; i * i <= limit; i++) { + if(sieve.contains(i)) { + for(int j = i * i; j <= limit; j += i) { + sieve.remove(j); + } + } + } + var sortedValues = new List.from(sieve); + int elpsd = new DateTime.now().millisecondsSinceEpoch - strt; + print("Found " + sieve.length.toString() + " primes up to " + limit.toString() + + " in " + elpsd.toString() + " milliseconds."); + print(iterableToString(sortedValues)); // expect sieve.length to be 168 up to 1000... +// Expect.equals(168, sieve.length); +} diff --git a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-2.dart b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-2.dart new file mode 100644 index 0000000000..72bb4c5909 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-2.dart @@ -0,0 +1,35 @@ +import 'dart:math'; + +List SoEOdds(int limit) { + List prms = new List(); + if (limit < 2) return prms; + prms.add(2); + if (limit < 3) return prms; + int lmt = (limit - 3) >> 1; + int bfsz = (lmt >> 5) + 1; + int sqrtlmt = (sqrt(limit) - 3).floor() >> 1; + var buf = new List(); + for (int i = 0; i < bfsz; i++) + buf.add(0); + for (int i = 0; i <= sqrtlmt; i++) + if ((buf[i >> 5] & (1 << (i & 31))) == 0) { + int p = i + i + 3; + for (int j = (p * p - 3) >> 1; j <= lmt; j += p) + buf[j >> 5] |= 1 << (j & 31); + } + for (int i = 0; i <= lmt; i++) + if ((buf[i >> 5] & (1 << (i & 31))) == 0) + prms.add(i + i + 3); + return prms; +} + +void main() { + int limit = 10000000; + int strt = new DateTime.now().millisecondsSinceEpoch; + List primes = SoEOdds(limit); + int count = primes.length; + int elpsd = new DateTime.now().millisecondsSinceEpoch - strt; + print("Found " + count.toString() + " primes up to " + limit.toString() + + " in " + elpsd.toString() + " milliseconds."); +// print(iterableToString(primes)); // expect sieve.length to be 168 up to 1000... +} diff --git a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-3.dart b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-3.dart new file mode 100644 index 0000000000..33625f1fc5 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes-3.dart @@ -0,0 +1,77 @@ +import 'dart:collection'; + +class _SoEPagedIterator implements Iterator { + static const int _BFSZ = 1 << 16; + static const int _BFBTS = _BFSZ * 32; + static const int _BFRNG = _BFBTS * 2; + int _prime = null; + int _bi = -1; + int _lowi = 0; + List _bpa = new List(); + Iterator _bps; + List _buf = new List(); + int get current => this._prime; + bool moveNext() { + // the following redundant local variable declaration is necessary to + // prevent the dart2js compiler from "tree-shaking" and eliminating some + // essential code from the below, which doesn't happen with the Dart VM compiler. + int lowi = this._lowi; + while (true) { + if (this._bi < 1) { + if (this._bi < 0) { this._bi++; this._prime = 2; break; } + int nxt = 3 + (this._lowi << 1) + _BFRNG; + this._buf.clear(); + for (int i = 0; i < _BFSZ; i++) this._buf.add(0); // faster initialization: + if (lowi <= 0) { // special culling for first page as no base primes yet: + for (int i = 0, p = 3, sqr = 9; sqr < nxt; i++, p += 2, sqr = p * p) + if ((this._buf[i >> 5] & (1 << (i & 31))) == 0) + for (int j = (sqr - 3) >> 1; j < _BFBTS; j += p) + this._buf[j >> 5] |= 1 << (j & 31); + } else { // after the first page: + if (this._bpa.length == 0) { // if this is the first page after the zero one: + this._bps = new _SoEPagedIterator(); // initialize separate base primes stream: + this._bps.moveNext(); // advance to the only even prime of two + this._bps.moveNext(); // advance past 2 to the next prime of 3 + } + // get enough base primes for the page range... + for (var lp = this._bps.current, sqr = lp * lp; sqr < nxt; + this._bps.moveNext(), lp = this._bps.current, sqr = lp * lp) this._bpa.add(lp); + for (var i = 0; i < this._bpa.length; i++) { + int p = this._bpa[i]; + int s = (p * p - 3) >> 1; + if (s >= this._lowi) // adjust start index based on page lower limit... + s -= this._lowi; + else { + int r = (this._lowi - s) % p; + s = (r != 0) ? p - r : 0; + } + for (var j = s; j < _BFBTS; j += p) + this._buf[j >> 5] |= 1 << (j & 31); + } + } + } + while (this._bi < _BFBTS && ((this._buf[this._bi >> 5] & (1 << (this._bi & 31))) != 0)) + this._bi++; // find next marker still with prime status + if (this._bi < _BFBTS) { // within buffer: output computed prime + this._prime = 3 + ((this._lowi + this._bi++) << 1); break; } + else { // beyond buffer range: advance buffer + this._bi = 0; + this._lowi += _BFBTS; + lowi = this._lowi; + } + } return true; + } +} + +class SoEPagedOddsInfGen extends IterableBase { + Iterator get iterator { return new _SoEPagedIterator(); } +} + +void main() { + int n = 1000000000; + int strt = new DateTime.now().millisecondsSinceEpoch; + int count = new SoEPagedOddsInfGen().takeWhile((p) => p <= n).length; + int elpsd = new DateTime.now().millisecondsSinceEpoch - strt; + print("For a range of " + n.toString() + ", " + count.toString() + + " primes found in " + elpsd.toString() + " milliseconds."); +} diff --git a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart b/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart deleted file mode 100644 index f6b4871b18..0000000000 --- a/Task/Sieve-of-Eratosthenes/Dart/sieve-of-eratosthenes.dart +++ /dev/null @@ -1,34 +0,0 @@ -// helper function to pretty print an Iterable -String iterableToString(Iterable seq) { - String str = "["; - Iterator i = seq.iterator(); - while(i.hasNext()) { - str += i.next(); - if(i.hasNext()) { - str += ","; - } - } - return str + "]"; -} - -main() { - int limit = 1000; - Set sieve = new Set(); - - for(int i = 2; i <= limit; i++) { - sieve.add(i); - } - for(int i = 2; i * i <= limit; i++) { - if(sieve.contains(i)) { - for(int j = i * i; j <= limit; j += i) { - sieve.remove(j); - } - } - } - var sortedValues = new List.from(sieve); - sortedValues.sort((int arg1, int arg2) { - return arg1.compareTo(arg2); - }); - print(iterableToString(sortedValues)); - Expect.equals(168, sieve.length); -} diff --git a/Task/Sieve-of-Eratosthenes/Delphi/sieve-of-eratosthenes.delphi b/Task/Sieve-of-Eratosthenes/Delphi/sieve-of-eratosthenes.delphi new file mode 100644 index 0000000000..02e23ba915 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Delphi/sieve-of-eratosthenes.delphi @@ -0,0 +1,85 @@ +program erathostenes; + +{$APPTYPE CONSOLE} + +type + TSieve = class + private + fPrimes: TArray; + procedure InitArray; + procedure Sieve; + function getNextPrime(aStart: integer): integer; + function getPrimeArray: TArray; + public + function getPrimes(aMax: integer): TArray; + end; + + { TSieve } + +function TSieve.getNextPrime(aStart: integer): integer; +begin + result := aStart; + while not fPrimes[result] do + inc(result); +end; + +function TSieve.getPrimeArray: TArray; +var + i, n: integer; +begin + n := 0; + setlength(result, length(fPrimes)); // init array with maximum elements + for i := 2 to high(fPrimes) do + begin + if fPrimes[i] then + begin + result[n] := i; + inc(n); + end; + end; + setlength(result, n); // reduce array to actual elements +end; + +function TSieve.getPrimes(aMax: integer): TArray; +begin + setlength(fPrimes, aMax); + InitArray; + Sieve; + result := getPrimeArray; +end; + +procedure TSieve.InitArray; +begin + for i := 2 to high(fPrimes) do + fPrimes[i] := true; +end; + +procedure TSieve.Sieve; +var + i, n, max: integer; +begin + max := length(fPrimes); + i := 2; + while i < sqrt(max) do + begin + n := sqr(i); + while n < max do + begin + fPrimes[n] := false; + inc(n, i); + end; + i := getNextPrime(i + 1); + end; +end; + +var + i: integer; + Sieve: TSieve; + +begin + Sieve := TSieve.Create; + for i in Sieve.getPrimes(100) do + write(i, ' '); + Sieve.Free; + readln; +end. diff --git a/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-1.l b/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-1.l new file mode 100644 index 0000000000..4ae80d14d5 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-1.l @@ -0,0 +1,7 @@ +(defun sieve-set (limit) + (let ((xs (make-vector (1+ limit) 0))) + (loop for i from 2 to limit + when (zerop (aref xs i)) + collect i + and do (loop for m from (* i i) to limit by i + do (aset xs m 1))))) diff --git a/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-2.l b/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-2.l new file mode 100644 index 0000000000..e1f6b2b5b8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Emacs-Lisp/sieve-of-eratosthenes-2.l @@ -0,0 +1,7 @@ +(defun sieve (limit) + (let ((xs (vconcat [0 0] (number-sequence 2 limit)))) + (loop for i from 2 to (sqrt limit) + when (aref xs i) + do (loop for m from (* i i) to limit by i + do (aset xs m 0))) + (remove 0 xs))) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs new file mode 100644 index 0000000000..b5304c006e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-1.fs @@ -0,0 +1,21 @@ +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //Co Inductive Stream for laziness + new (v,cont) = { v = v; cont = cont } end +let primes = + let rec pculls p cull = CIS(cull, fun() -> pculls p (cull + p)) + let rec allculls (ps:CIS<_>) = //stream of streams of composite culls + CIS(pculls ps.v (ps.v * ps.v),fun() -> allculls (ps.cont())) + let rec (^^) (xs:CIS) (ys:CIS) = //union op for CIS's + match compare xs.v ys.v with + | -1 -> CIS(xs.v, fun() -> xs.cont() ^^ ys) // < + | 0 -> CIS(xs.v, fun() -> xs.cont() ^^ ys.cont()) // == + | _ -> CIS(ys.v, fun() -> xs ^^ ys.cont()) //must be > (= 1) + let rec join (cmpsts:CIS>) = + CIS(cmpsts.v.v, fun() -> cmpsts.v.cont() ^^ join (cmpsts.cont())) + let rec mkPrms cnd (cmpsts:CIS<_>) = + let ncnd = cnd + 1u + if cnd >= cmpsts.v then mkPrms ncnd (cmpsts.cont()) //implements 'minus' + else CIS(cnd,fun()->mkPrms ncnd cmpsts) //found a prime + let rec basePrimes = CIS(2u, fun() -> mkPrms 3u initCmpsts) + and initCmpsts = join (allculls (basePrimes)) + let genseq cis = Seq.unfold (fun (cs:CIS<_>) -> Some(cs.v, cs.cont())) cis + genseq (mkPrms 2u initCmpsts) diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs new file mode 100644 index 0000000000..d048100abe --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-2.fs @@ -0,0 +1,21 @@ +type CIS<'T> = struct val v:'T val cont:unit->CIS<'T> //Co Inductive Stream for laziness + new (v,cont) = { v = v; cont = cont } end +let primes = + let rec pculls p cull = CIS(cull, fun() -> pculls p (cull + 2u * p)) + let rec allculls (ps:CIS<_>) = //stream of streams of composite culls + CIS(pculls ps.v (ps.v * ps.v),fun() -> allculls (ps.cont())) + let rec (^^) (xs:CIS) (ys:CIS) = //union op for CIS's + match compare xs.v ys.v with + | -1 -> CIS(xs.v, fun() -> xs.cont() ^^ ys) // < + | 0 -> CIS(xs.v, fun() -> xs.cont() ^^ ys.cont()) // == + | _ -> CIS(ys.v, fun() -> xs ^^ ys.cont()) //must be > (= 1) + let rec join (cmpsts:CIS>) = + CIS(cmpsts.v.v, fun() -> cmpsts.v.cont() ^^ join (cmpsts.cont())) + let rec mkPrms cnd (cmpsts:CIS<_>) = + let ncnd = cnd + 2u + if cnd >= cmpsts.v then mkPrms ncnd (cmpsts.cont()) //implements 'minus' + else CIS(cnd,fun()->mkPrms ncnd cmpsts) //found a prime + let rec oddBasePrimes = CIS(3u, fun() -> mkPrms 5u initCmpsts) + and initCmpsts = join (allculls (oddBasePrimes)) + let genseq cis = Seq.unfold (fun (cs:CIS<_>) -> Some(cs.v, cs.cont())) cis + seq { yield 2u; yield! genseq (mkPrms 3u initCmpsts) } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs new file mode 100644 index 0000000000..eda1d46ed1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-3.fs @@ -0,0 +1,11 @@ +let primes limit = + let buf = System.Collections.BitArray(int limit + 1, true) + let cull p = { p * p .. p .. limit } |> Seq.iter (fun c -> buf.[int c] <- false) + { 2u .. uint32 (sqrt (double limit)) } |> Seq.iter (fun c -> if buf.[int c] then cull c) + { 2u .. limit } |> Seq.map (fun i -> if buf.[int i] then i else 0u) |> Seq.filter ((<>) 0u) + +[] +let main argv = + if argv = null || argv.Length = 0 then failwith "no command line argument for limit!!!" + printfn "%A" (primes (System.UInt32.Parse argv.[0]) |> Seq.length) + 0 // return an integer exit code diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs new file mode 100644 index 0000000000..4c9836434c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-4.fs @@ -0,0 +1,9 @@ +let primes limit = + let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u + let buf = System.Collections.BitArray(int lmtb + 1, true) + let cull i = let p = i + i + 3u in let s = p * (i + 1u) + i in + { s .. p .. lmtb } |> Seq.iter (fun c -> buf.[int c] <- false) + { 0u .. lmtbsqrt } |> Seq.iter (fun i -> if buf.[int i] then cull i ) + let oddprms = { 0u .. lmtb } |> Seq.map (fun i -> if buf.[int i] then i + i + 3u else 0u) + |> Seq.filter ((<>) 0u) + seq { yield 2u; yield! oddprms } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs new file mode 100644 index 0000000000..7093f14210 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-5.fs @@ -0,0 +1,8 @@ +let primes limit = + let lmtb,lmtbsqrt = (limit - 3u) / 2u, (uint32 (sqrt (double limit)) - 3u) / 2u + let buf = System.Collections.BitArray(int lmtb + 1, true) + let rec culltest i = if i <= lmtbsqrt then + let p = i + i + 3u in let s = p * (i + 1u) + i in + let rec cullp c = if c <= lmtb then buf.[int c] <- false; cullp (c + p) + (if buf.[int i] then cullp s); culltest (i + 1u) in culltest 0u + seq {yield 2u; for i = 0u to lmtb do if buf.[int i] then yield i + i + 3u } diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs new file mode 100644 index 0000000000..c1e54606e3 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-6.fs @@ -0,0 +1,3 @@ + let rec count i acc = + if i > int lmtb then acc else if buf.[i] then count (i + 1) (acc + 1) else count (i + 1) acc + count 0 1 diff --git a/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs new file mode 100644 index 0000000000..b63afd6809 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/F-Sharp/sieve-of-eratosthenes-7.fs @@ -0,0 +1,17 @@ + let nmrtr() = + let i = ref -2 + let rec nxti() = i:=!i + 1;if !i <= int lmtb && not buf.[!i] then nxti() else !i <= int lmtb + let inline curr() = if !i < 0 then (if !i= -1 then 2u else failwith "Enumeration not started!!!") + else let v = uint32 !i in v + v + 3u + { new System.Collections.Generic.IEnumerator<_> with + member this.Current = curr() + interface System.Collections.IEnumerator with + member this.Current = box (curr()) + member this.MoveNext() = if !i< -1 then i:=!i+1;true else nxti() + member this.Reset() = failwith "IEnumerator.Reset() not implemented!!!"a + interface System.IDisposable with + member this.Dispose() = () } + { new System.Collections.Generic.IEnumerable<_> with + member this.GetEnumerator() = nmrtr() + interface System.Collections.IEnumerable with + member this.GetEnumerator() = nmrtr() :> System.Collections.IEnumerator } diff --git a/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap b/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap index b98bf39ed0..08e0232d7c 100644 --- a/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap +++ b/Task/Sieve-of-Eratosthenes/GAP/sieve-of-eratosthenes.gap @@ -1,20 +1,25 @@ Eratosthenes := function(n) - local sieve, cur, mul; - sieve := [1 .. n]*0; - sieve[1] := 1; - cur := 1; - while cur <= n do - if sieve[cur] = 0 then - mul := cur*cur; - while mul <= n do - sieve[mul] := 1; - mul := mul + cur; - od; - fi; - cur := cur + 1; - od; - return Filtered([1 .. n], x -> sieve[x] = 0); + local a, i, j; + a := ListWithIdenticalEntries(n, true); + if n < 2 then + return []; + else + for i in [2 .. n] do + if a[i] then + j := i*i; + if j > n then + return Filtered([2 .. n], i -> a[i]); + else + while j <= n do + a[j] := false; + j := j + i; + od; + fi; + fi; + od; + fi; end; Eratosthenes(100); -# [ 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 ] + +[ 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 ] diff --git a/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy b/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy index 16490d2ef3..558677b74c 100644 --- a/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy +++ b/Task/Sieve-of-Eratosthenes/Groovy/sieve-of-eratosthenes-1.groovy @@ -1,11 +1,11 @@ def sievePrimes = { bound -> def isPrime = new BitSet(bound) isPrime[0..1] = false - isPrime[2.. if (isPrime[pc]) { - ((pc**2).. case span (< head b) a of (h,t)-> Just (h, minus t b:r)) + . scanl1 (zipWith(+) . tail) $ tails [1..] diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs new file mode 100644 index 0000000000..6800fccdcf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-11.hs @@ -0,0 +1,23 @@ +> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+)) $ repeat [2..] +[ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] +[ 4, 6, 8,10,12,14,16,18, 20, 22, 24, 26, 28, 30] +[ 6, 9,12,15,18,21,24,27, 30, 33, 36, 39, 42, 45] +[ 8,12,16,20,24,28,32,36, 40, 44, 48, 52, 56, 60] +[10,15,20,25,30,35,40,45, 50, 55, 60, 65, 70, 75] +[12,18,24,30,36,42,48,54, 60, 66, 72, 78, 84, 90] +[14,21,28,35,42,49,56,63, 70, 77, 84, 91, 98,105] +[16,24,32,40,48,56,64,72, 80, 88, 96,104,112,120] +[18,27,36,45,54,63,72,81, 90, 99,108,117,126,135] +[20,30,40,50,60,70,80,90,100,110,120,130,140,150] + +> mapM_ (print . take 15) $ take 10 $ scanl1 (zipWith(+) . tail) $ tails [1..] +[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] +[ 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32] +[ 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51] +[ 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60, 64, 68, 72] +[ 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95] +[ 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96,102,108,114,120] +[ 49, 56, 63, 70, 77, 84, 91, 98,105,112,119,126,133,140,147] +[ 64, 72, 80, 88, 96,104,112,120,128,136,144,152,160,168,176] +[ 81, 90, 99,108,117,126,135,144,153,162,171,180,189,198,207] +[100,110,120,130,140,150,160,170,180,190,200,210,220,230,240] 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 51c7d0cd11..2b6656ce04 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-4.hs @@ -1,6 +1,6 @@ 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]) + eratos (p : xs) | p*p>m = p : xs + | otherwise = p : eratos (xs `minus` [p*p, p*p+2*p..m]) minus a@(x:xs) b@(y:ys) = case compare x y of LT -> x : minus xs b 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 48431cbef8..2d43670c1c 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-5.hs @@ -1,10 +1,3 @@ -primes = _Y $ ((2:) . minus [3..] - . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) - -_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 +primesE = sieve [2..] -- slow, ~ n^2 + where + sieve (p:xs) = p : sieve (minus xs [p,p+p..]) diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs index ec753807e2..08a67954c3 100644 --- a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-6.hs @@ -1,9 +1,6 @@ -primes :: [Int] -primes = 2 : _Y ((3 :) . gaps 5 . _U . map(\p-> [p*p, p*p+2*p..])) +primesEQ = after 4 [2..] (sieve primesEQ) -- faster, ~ n^1.5 + where -- q==p*p + sieve (p:t) q xs = after (head t^2) (minus xs [q,q+p..]) (sieve t) -gaps k s@(x:xs) | k < x = k : gaps (k+2) s -- ~= ([k,k+2..] \\ s), when - | otherwise = gaps (k+2) xs -- k<=x && null(s \\ [k,k+2..]) - -_U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub . sort . concat - where - pairs (xs:ys:t) = union xs ys : pairs t +after q (x:xs) k | x < q = x : after q xs k + | otherwise = k x xs diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs new file mode 100644 index 0000000000..48431cbef8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-7.hs @@ -0,0 +1,10 @@ +primes = _Y $ ((2:) . minus [3..] + . foldr (\x-> (x*x :) . union [x*x+x, x*x+2*x..]) []) + +_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-8.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs new file mode 100644 index 0000000000..5dbe9fadb9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-8.hs @@ -0,0 +1,9 @@ +primes :: [Int] +primes = 2 : _Y ((3 :) . gaps 5 . _U . map(\p-> [p*p, p*p+2*p..])) + +gaps k s@(x:xs) | k < x = k : gaps (k+2) s -- ~= ([k,k+2..] \\ s) + | otherwise = gaps (k+2) xs -- when null(s\\[k,k+2..]) + +_U ((x:xs):t) = x : (union xs . _U . pairs) t -- ~= nub . sort . concat + where + pairs (xs:ys:t) = union xs ys : pairs t diff --git a/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs new file mode 100644 index 0000000000..c6b54a210f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Haskell/sieve-of-eratosthenes-9.hs @@ -0,0 +1,2 @@ +zipWith (flip (!!)) [0..] + . scanl1 minus . scanl1 (zipWith(+)) $ repeat [2..] diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-1.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-1.j new file mode 100644 index 0000000000..bdbcef567a --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-1.j @@ -0,0 +1,2 @@ + 10|13 +3 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-10.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-10.j new file mode 100644 index 0000000000..dac74e190f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-10.j @@ -0,0 +1,10 @@ +sieve1=: 3 : 0 + m=. <.%:y + z=. $0 + b=. y{.1 + while. m>:j=. 1+b i. 0 do. + b=. b+.y$(-j){.1 + z=. z,j + end. + z,1+I.-.b + ) diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-11.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-11.j new file mode 100644 index 0000000000..92011e64fa --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-11.j @@ -0,0 +1,10 @@ +sieve2=: 3 : 0 + m=. <.%:y + z=. y (>:#]) 2 3 5 7 + b=. 1,}.y$+./(*/z)$&>(-z){.&.>1 + while. m>:j=. 1+b i. 0 do. + b=. b+.y$(-j){.1 + z=. z,j + end. + z,1+I.-.b +) diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-12.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-12.j new file mode 100644 index 0000000000..e7182672de --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-12.j @@ -0,0 +1,9 @@ + 0=|/~ i.8 +1 0 0 0 0 0 0 0 +1 1 1 1 1 1 1 1 +1 0 1 0 1 0 1 0 +1 0 0 1 0 0 1 0 +1 0 0 0 1 0 0 0 +1 0 0 0 0 1 0 0 +1 0 0 0 0 0 1 0 +1 0 0 0 0 0 0 1 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-2.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-2.j new file mode 100644 index 0000000000..17ca81333b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-2.j @@ -0,0 +1,4 @@ + 2 3 4 |/ 2 3 4 +0 1 0 +2 0 1 +2 3 0 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-3.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-3.j new file mode 100644 index 0000000000..1de2ff44ad --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-3.j @@ -0,0 +1,6 @@ + |/~ 0 1 2 3 4 +0 1 2 3 4 +0 0 0 0 0 +0 1 0 1 0 +0 1 2 0 1 +0 1 2 3 0 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-4.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-4.j new file mode 100644 index 0000000000..640715c2d5 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-4.j @@ -0,0 +1,2 @@ + i. 5 +0 1 2 3 4 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-5.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-5.j new file mode 100644 index 0000000000..3ea4ef6e2e --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-5.j @@ -0,0 +1,6 @@ + 0=|/~ i.5 +1 0 0 0 0 +1 1 1 1 1 +1 0 1 0 1 +1 0 0 1 0 +1 0 0 0 1 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-6.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-6.j new file mode 100644 index 0000000000..93ecc74c3d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-6.j @@ -0,0 +1,2 @@ + +/0=|/~ i.5 +5 1 2 2 3 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-7.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-7.j new file mode 100644 index 0000000000..5a64cf51fe --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-7.j @@ -0,0 +1,2 @@ + 2=+/0=|/~ i.5 +0 0 1 1 0 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-8.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-8.j new file mode 100644 index 0000000000..ff7912e920 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-8.j @@ -0,0 +1,4 @@ + I.2=+/0=|/~ i.5 +2 3 + I.2=+/0=|/~ i.100 +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 diff --git a/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-9.j b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-9.j new file mode 100644 index 0000000000..4579a2b48f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/J/sieve-of-eratosthenes-9.j @@ -0,0 +1 @@ +sieve0=: verb def 'I.2=+/0=|/~ i.y' diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-4.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-4.java new file mode 100644 index 0000000000..afccf1681c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-4.java @@ -0,0 +1,54 @@ +import java.util.Iterator; +import java.util.PriorityQueue; +import java.math.BigInteger; + +// generates all prime numbers +public class InfiniteSieve implements Iterator { + + private static class NonPrimeSequence implements Comparable { + BigInteger currentMultiple; + BigInteger prime; + + public NonPrimeSequence(BigInteger p) { + prime = p; + currentMultiple = p.multiply(p); // start at square of prime + } + @Override public int compareTo(NonPrimeSequence other) { + // sorted by value of current multiple + return currentMultiple.compareTo(other.currentMultiple); + } + } + + private BigInteger i = BigInteger.valueOf(2); + // priority queue of the sequences of non-primes + // the priority queue allows us to get the "next" non-prime quickly + final PriorityQueue nonprimes = new PriorityQueue(); + + @Override public boolean hasNext() { return true; } + @Override public BigInteger next() { + // skip non-prime numbers + for ( ; !nonprimes.isEmpty() && i.equals(nonprimes.peek().currentMultiple); i = i.add(BigInteger.ONE)) { + // for each sequence that generates this number, + // have it go to the next number (simply add the prime) + // and re-position it in the priority queue + while (nonprimes.peek().currentMultiple.equals(i)) { + NonPrimeSequence x = nonprimes.poll(); + x.currentMultiple = x.currentMultiple.add(x.prime); + nonprimes.offer(x); + } + } + // prime + // insert a NonPrimeSequence object into the priority queue + nonprimes.offer(new NonPrimeSequence(i)); + BigInteger result = i; + i = i.add(BigInteger.ONE); + return result; + } + + public static void main(String[] args) { + Iterator sieve = new InfiniteSieve(); + for (int i = 0; i < 25; i++) { + System.out.println(sieve.next()); + } + } +} diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-5.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-5.java new file mode 100644 index 0000000000..eb8cbc7a0d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-5.java @@ -0,0 +1,59 @@ +import java.util.Iterator; +import java.util.HashMap; + +// generates all prime numbers up to about 10 ^ 19 if one can wait 1000's of years or so... +public class SoEInfHashMap implements Iterator { + + long candidate = 2; + Iterator baseprimes = null; + long basep = 3; + long basepsqr = 9; + // HashMap of the sequences of non-primes + // the hash map allows us to get the "next" non-prime reasonably quickly + // but further allows re-insertions to take amortized constant time + final HashMap nonprimes = new HashMap<>(); + + @Override public boolean hasNext() { return true; } + @Override public Long next() { + // do the initial primes separately to initialize the base primes sequence + if (this.candidate <= 5L) if (this.candidate++ == 2L) return 2L; else { + this.candidate++; if (this.candidate == 5L) return 3L; else { + this.baseprimes = new SoEInfHashMap(); + this.baseprimes.next(); this.baseprimes.next(); // throw away 2 and 3 + return 5L; + } } + // skip non-prime numbers including squares of next base prime + for ( ; this.candidate >= this.basepsqr || //equals nextbase squared => not prime + nonprimes.containsKey(this.candidate); candidate += 2) { + // insert a square root prime sequence into hash map if to limit + if (candidate >= basepsqr) { // if square of base prime, always equal + long adv = this.basep << 1; + nonprimes.put(this.basep * this.basep + adv, adv); + this.basep = this.baseprimes.next(); + this.basepsqr = this.basep * this.basep; + } + // else for each sequence that generates this number, + // have it go to the next number (simply add the advance) + // and re-position it in the hash map at an emply slot + else { + long adv = nonprimes.remove(this.candidate); + long nxt = this.candidate + adv; + while (this.nonprimes.containsKey(nxt)) nxt += adv; //unique keys + this.nonprimes.put(nxt, adv); + } + } + // prime + long tmp = candidate; this.candidate += 2; return tmp; + } + + public static void main(String[] args) { + int n = 100000000; + long strt = System.currentTimeMillis(); + SoEInfHashMap sieve = new SoEInfHashMap(); + int count = 0; + while (sieve.next() <= n) count++; + long elpsd = System.currentTimeMillis() - strt; + System.out.println("Found " + count + " primes up to " + n + " in " + elpsd + " milliseconds."); + } + +} diff --git a/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java new file mode 100644 index 0000000000..92cd451293 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Java/sieve-of-eratosthenes-6.java @@ -0,0 +1,78 @@ +import java.util.Iterator; +import java.util.ArrayList; + +// generates all prime numbers up to about 10 ^ 19 if one can wait 100's of years or so... +// practical range is about 10^14 in a week or so... +public class SoEPagedOdds implements Iterator { + private final int BFSZ = 1 << 16; + private final int BFBTS = BFSZ * 32; + private final int BFRNG = BFBTS * 2; + private long bi = -1; + private long lowi = 0; + private final ArrayList bpa = new ArrayList<>(); + private Iterator bps; + private final int[] buf = new int[BFSZ]; + + @Override public boolean hasNext() { return true; } + @Override public Long next() { + if (this.bi < 1) { + if (this.bi < 0) { + this.bi = 0; + return 2L; + } + //this.bi muxt be 0 + long nxt = 3 + (this.lowi << 1) + BFRNG; + if (this.lowi <= 0) { // special culling for first page as no base primes yet: + for (int i = 0, p = 3, sqr = 9; sqr < nxt; i++, p += 2, sqr = p * p) + if ((this.buf[i >>> 5] & (1 << (i & 31))) == 0) + for (int j = (sqr - 3) >> 1; j < BFBTS; j += p) + this.buf[j >>> 5] |= 1 << (j & 31); + } + else { // after the first page: + for (int i = 0; i < this.buf.length; i++) + this.buf[i] = 0; // clear the sieve buffer + if (this.bpa.isEmpty()) { // if this is the first page after the zero one: + this.bps = new SoEPagedOdds(); // initialize separate base primes stream: + this.bps.next(); // advance past the only even prime of two + this.bpa.add(this.bps.next().intValue()); // get the next prime (3 in this case) + } + // get enough base primes for the page range... + for (long p = this.bpa.get(this.bpa.size() - 1), sqr = p * p; sqr < nxt; + p = this.bps.next(), this.bpa.add((int)p), sqr = p * p) ; + for (int i = 0; i < this.bpa.size() - 1; i++) { + long p = this.bpa.get(i); + long s = (p * p - 3) >>> 1; + if (s >= this.lowi) // adjust start index based on page lower limit... + s -= this.lowi; + else { + long r = (this.lowi - s) % p; + s = (r != 0) ? p - r : 0; + } + for (int j = (int)s; j < BFBTS; j += p) + this.buf[j >>> 5] |= 1 << (j & 31); + } + } + } + while ((this.bi < BFBTS) && + ((this.buf[(int)this.bi >>> 5] & (1 << ((int)this.bi & 31))) != 0)) + this.bi++; // find next marker still with prime status + if (this.bi < BFBTS) // within buffer: output computed prime + return 3 + ((this.lowi + this.bi++) << 1); + else { // beyond buffer range: advance buffer + this.bi = 0; + this.lowi += BFBTS; + return this.next(); // and recursively loop + } + } + + public static void main(String[] args) { + long n = 1000000000; + long strt = System.currentTimeMillis(); + Iterator gen = new SoEPagedOdds(); + int count = 0; + while (gen.next() <= n) count++; + long elpsd = System.currentTimeMillis() - strt; + System.out.println("Found " + count + " primes up to " + n + " in " + elpsd + " milliseconds."); + } + +} diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-1.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-1.js new file mode 100644 index 0000000000..a8e73e77ce --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-1.js @@ -0,0 +1,27 @@ +function eratosthenes(limit) { + var primes = []; + if (limit >= 2) { + var sqrtlmt = Math.sqrt(limit) - 2; + var nums = new Array(); // start with an empty Array... + for (var i = 2; i <= limit; i++) // and + nums.push(i); // only initialize the Array once... + for (var i = 0; i <= sqrtlmt; i++) { + var p = nums[i] + if (p) + for (var j = p * p - 2; j < nums.length; j += p) + nums[j] = 0; + } + for (var i = 0; i < nums.length; i++) { + var p = nums[i]; + if (p) + primes.push(p); + } + } + return primes; +} + +var primes = eratosthenes(100); + +if (typeof print == "undefined") + print = (typeof WScript != "undefined") ? WScript.Echo : alert; +print(primes); diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-2.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-2.js new file mode 100644 index 0000000000..e7e8822aba --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-2.js @@ -0,0 +1,22 @@ +function eratosthenes(limit) { + var prms = []; + if (limit >= 2) prms = [2]; + if (limit >= 3) { + var sqrtlmt = (Math.sqrt(limit) - 3) >> 1; + var lmt = (limit - 3) >> 1; + var bfsz = (lmt >> 5) + 1 + var buf = []; + for (var i = 0; i < bfsz; i++) + buf.push(0); + for (var i = 0; i <= sqrtlmt; i++) + if ((buf[i >> 5] & (1 << (i & 31))) == 0) { + var p = i + i + 3; + for (var j = (p * p - 3) >> 1; j <= lmt; j += p) + buf[j >> 5] |= 1 << (j & 31); + } + for (var i = 0; i <= lmt; i++) + if ((buf[i >> 5] & (1 << (i & 31))) == 0) + prms.push(i + i + 3); + } + return prms; +} diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-3.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-3.js new file mode 100644 index 0000000000..e8a60dd321 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-3.js @@ -0,0 +1,42 @@ +var SoEIncClass = (function () { + function SoEIncClass() { + this.n = 0; + } + SoEIncClass.prototype.next = function () { + this.n += 2; + if (this.n < 7) { // initialization of sequence to avoid runaway: + if (this.n < 3) { // only even of two: + this.n = 1; // odds from here... + return 2; + } + if (this.n < 5) + return 3; + this.dict = {}; // n must be 5... + this.bps = new SoEIncClass(); // new source of base primes + this.bps.next(); // advance past the even prime of two... + this.p = this.bps.next(); // first odd prime (3 in this case) + this.q = this.p * this.p; // set guard + return 5; + } else { // past initialization: + var s = this.dict[this.n]; // may or may not be defined... + if (!s) { // not defined: + if (this.n < this.q) // haven't reached the guard: + return this.n; // found a prime + else { // n === q => not prime but at guard, so: + var p2 = this.p << 1; // the span odds-only is twice prime + this.dict[this.n + p2] = p2; // add next composite of prime to dict + this.p = this.bps.next(); + this.q = this.p * this.p; // get next base prime guard + return this.next(); // not prime so advance... + } + } else { // is a found composite of previous base prime => not prime + delete this.dict[this.n]; // advance to next composite of this prime: + var nxt = this.n + s; + while (this.dict[nxt]) nxt += s; // find unique empty slot in dict + this.dict[nxt] = s; // to put the next composite for this base prime + return this.next(); // not prime so advance... + } + } + }; + return SoEIncClass; +})(); diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-4.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-4.js new file mode 100644 index 0000000000..f4f09faf16 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-4.js @@ -0,0 +1,7 @@ +var gen = new SoEIncClass(); +for (var i = 1; i < 1000000; i++, gen.next()); +var prime = gen.next(); + +if (typeof print == "undefined") + print = (typeof WScript != "undefined") ? WScript.Echo : alert; +print(prime); diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-5.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-5.js new file mode 100644 index 0000000000..73924b060f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes-5.js @@ -0,0 +1,57 @@ +var SoEPgClass = (function () { + function SoEPgClass() { + this.bi = -1; // constructor resets the enumeration to start... + } + SoEPgClass.prototype.next = function () { + if (this.bi < 1) { + if (this.bi < 0) { + this.bi++; + this.lowi = 0; // other initialization done here... + this.bpa = []; + return 2; + } else { // bi must be zero: + var nxt = 3 + (this.lowi << 1) + 262144; + this.buf = new Array(); + for (var i = 0; i < 4096; i++) // faster initialization: + this.buf.push(0); + if (this.lowi <= 0) { // special culling for first page as no base primes yet: + for (var i = 0, p = 3, sqr = 9; sqr < nxt; i++, p += 2, sqr = p * p) + if ((this.buf[i >> 5] & (1 << (i & 31))) === 0) + for (var j = (sqr - 3) >> 1; j < 131072; j += p) + this.buf[j >> 5] |= 1 << (j & 31); + } else { // after the first page: + if (!this.bpa.length) { // if this is the first page after the zero one: + this.bps = new SoEPgClass(); // initialize separate base primes stream: + this.bps.next(); // advance past the only even prime of two + this.bpa.push(this.bps.next()); // get the next prime (3 in this case) + } + // get enough base primes for the page range... + for (var p = this.bpa[this.bpa.length - 1], sqr = p * p; sqr < nxt; + p = this.bps.next(), this.bpa.push(p), sqr = p * p) ; + for (var i = 0; i < this.bpa.length; i++) { + var p = this.bpa[i]; + var s = (p * p - 3) >> 1; + if (s >= this.lowi) // adjust start index based on page lower limit... + s -= this.lowi; + else { + var r = (this.lowi - s) % p; + s = (r != 0) ? p - r : 0; + } + for (var j = s; j < 131072; j += p) + this.buf[j >> 5] |= 1 << (j & 31); + } + } + } + } + while (this.bi < 131072 && this.buf[this.bi >> 5] & (1 << (this.bi & 31))) + this.bi++; // find next marker still with prime status + if (this.bi < 131072) // within buffer: output computed prime + return 3 + ((this.lowi + this.bi++) << 1); + else { // beyond buffer range: advance buffer + this.bi = 0; + this.lowi += 131072; + return this.next(); // and recursively loop + } + }; + return SoEPgClass; +})(); diff --git a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js b/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js deleted file mode 100644 index 2e122f5a29..0000000000 --- a/Task/Sieve-of-Eratosthenes/JavaScript/sieve-of-eratosthenes.js +++ /dev/null @@ -1,27 +0,0 @@ -function erasthenes(limit) { - var primes = []; - if (limit >= 2) { - var nums = new Array(limit-1); - for (var i = 2; i <= limit; i++) - nums[i-2] = i; - - var last_prime; - var idx = 0; - while ((last_prime = nums[idx]) <= Math.sqrt(limit)) { - if (last_prime != null) - for (var i = idx + last_prime; i < limit - 1; i += last_prime) - nums[i] = null; - idx++; - } - for (var i = 0; i < nums.length; i++) - if (nums[i] != null) - primes.push(nums[i]); - } - return primes; -} - -var primes = erasthenes(100); - -if (typeof print == "undefined") - print = (typeof WScript != "undefined") ? WScript.Echo : alert; -print(primes); diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua new file mode 100644 index 0000000000..df65311fc8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-1.lua @@ -0,0 +1,10 @@ +function erato(n) + if n < 2 then return {} end + local t = {0} -- clears '1' + local sqrtlmt = math.sqrt(n) + for i = 2, n do t[i] = 1 end + for i = 2, sqrtlmt do if t[i] ~= 0 then for j = i*i, n, i do t[j] = 0 end end end + local primes = {} + for i = 2, n do if t[i] ~= 0 then table.insert(primes, i) end end + return primes +end diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-2.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-2.lua new file mode 100644 index 0000000000..9efef86379 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-2.lua @@ -0,0 +1,14 @@ +function erato2(n) + if n < 2 then return {} end + if n < 3 then return {2} end + local t = {} + local lmt = (n - 3) / 2 + local sqrtlmt = (math.sqrt(n) - 3) / 2 + for i = 0, lmt do t[i] = 1 end + for i = 0, sqrtlmt do if t[i] ~= 0 then + local p = i + i + 3 + for j = (p*p - 3) / 2, lmt, p do t[j] = 0 end end end + local primes = {2} + for i = 0, lmt do if t[i] ~= 0 then table.insert(primes, i + i + 3) end end + return primes +end diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-3.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-3.lua new file mode 100644 index 0000000000..69d370bae9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes-3.lua @@ -0,0 +1,33 @@ +function newEratoInf() + local _cand = 0; local _lstbp = 3; local _lstsqr = 9 + local _composites = {}; local _bps = nil + local _self = {} + function _self.next() + if _cand < 9 then if _cand < 1 then _cand = 1; return 2 + elseif _cand >= 7 then + --advance aux source base primes to 3... + _bps = newEratoInf() + _bps.next(); _bps.next() end end + _cand = _cand + 2 + if _composites[_cand] == nil then -- may be prime + if _cand >= _lstsqr then -- if not the next base prime + local adv = _lstbp + _lstbp -- if next base prime + _composites[_lstbp * _lstbp + adv] = adv -- add cull seq + _lstbp = _bps.next(); _lstsqr = _lstbp * _lstbp -- adv next base prime + return _self.next() + else return _cand end -- is prime + else + local v = _composites[_cand] + _composites[_cand] = nil + local nv = _cand + v + while _composites[nv] ~= nil do nv = nv + v end + _composites[nv] = v + return _self.next() end + end + return _self +end + +gen = newEratoInf() +count = 0 +while gen.next() <= 10000000 do count = count + 1 end -- sieves to 10 million +print(count) diff --git a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua b/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua deleted file mode 100644 index dd1bd150c4..0000000000 --- a/Task/Sieve-of-Eratosthenes/Lua/sieve-of-eratosthenes.lua +++ /dev/null @@ -1,6 +0,0 @@ -function erato(n) - local t = {0, 2} - for i = 3, n, 2 do t[i], t[i+1] = i, 0 end - for i = 3, math.sqrt(n) do for j = i*i, n, 2*i do t[j] = 0 end end - return t -end diff --git a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-2.m b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-2.m index 47f486a29e..b6bed71b17 100644 --- a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-2.m +++ b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-2.m @@ -1,5 +1,14 @@ -sieveOfEratosthenes(30) +function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x -ans = + P = [0 2:x] ; % Create vector with all ints between 2 and x where + % position 1 is hard-coded as 0 since 1 is not a prime. - 2 3 5 7 11 13 17 19 23 29 + for (n=2:sqrt(x)) % All primes factors lie between 2 and sqrt(x). + if P(n) % If the current value is not 0 (i.e. a prime), + P((2*n):n:x) = 0 ; % then replace all further multiples of it with 0. + end + end % At this point P is a vector with only primes and zeroes. + + P = P(P ~= 0) ; % Remove all zeroes from P, leaving only the primes. + +return diff --git a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m index b6bed71b17..1ca6ea091c 100644 --- a/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m +++ b/Task/Sieve-of-Eratosthenes/MATLAB/sieve-of-eratosthenes-3.m @@ -1,14 +1,9 @@ -function P = erato(x) % Sieve of Eratosthenes: returns all primes between 2 and x - - P = [0 2:x] ; % Create vector with all ints between 2 and x where - % position 1 is hard-coded as 0 since 1 is not a prime. - - for (n=2:sqrt(x)) % All primes factors lie between 2 and sqrt(x). - if P(n) % If the current value is not 0 (i.e. a prime), - P((2*n):n:x) = 0 ; % then replace all further multiples of it with 0. - end - end % At this point P is a vector with only primes and zeroes. - - P = P(P ~= 0) ; % Remove all zeroes from P, leaving only the primes. - -return +function P = sieveOfEratosthenes(x) +ISP = [false true(1, x-1)]; % 1 is not prime, but we start off assuming all numbers between 2 and x are +for n = 2:sqrt(x) + if ISP(n) + ISP((2*n):n:x) = false; % Multiples of n that are greater than n are not primes + end +end +% The ISP vector that we have calculated is essentially the output of the ISPRIME function called on 1:x +P = find(ISP); % Convert the ISPRIME output to the values of the primes by finding the locations of the TRUE values in S. diff --git a/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-1.math b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-1.math new file mode 100644 index 0000000000..87bc457be1 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-1.math @@ -0,0 +1,6 @@ +Eratosthenes[n_] := Module[{numbers = Range[n]}, + Do[If[numbers[[i]] != 0, Do[numbers[[i j]] = 0, {j, 2, n/i}]], {i, + 2, Sqrt[n]}]; + Select[numbers, # > 1 &]] + +Eratosthenes[100] diff --git a/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-2.math b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-2.math new file mode 100644 index 0000000000..6a3ddcf012 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-2.math @@ -0,0 +1,5 @@ +Eratosthenes[n_] := Module[{numbers = Range[n]}, + Do[If[numbers[[i]] != 0, Do[numbers[[j]] = 0, {j,i i,n,i}]],{i,2,Sqrt[n]}]; + Select[numbers, # > 1 &]] + +Eratosthenes[100] diff --git a/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-3.math b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-3.math new file mode 100644 index 0000000000..2c689fe2a8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes-3.math @@ -0,0 +1,6 @@ +Eratosthenes2[n_] := Module[{numbers = Range[3, n, 2], limit = (n - 1)/2}, + Do[c = numbers[[i]]; If[c != 0, + Do[numbers[[j]] = 0, {j,(c c - 1)/2,limit,c}]], {i,1,(Sqrt[n] - 1)/2}]; + Prepend[Select[numbers, # > 1 &], 2]] + +Eratosthenes2[100] diff --git a/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes.math b/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes.math deleted file mode 100644 index c5acb9d765..0000000000 --- a/Task/Sieve-of-Eratosthenes/Mathematica/sieve-of-eratosthenes.math +++ /dev/null @@ -1,10 +0,0 @@ -Eratosthenes[n_] := Module[ - {numbers = Range[n]}, - - Do[If[numbers[[i]] != 0, - Do[numbers[[i j]] = 0, {j, 2, n/i}]], - {i, 2, Sqrt[n]}]; - - Select[numbers, # > 1 &]]; - -Eratosthenes[100] diff --git a/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes.pascal b/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-1.pascal similarity index 100% rename from Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes.pascal rename to Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-1.pascal diff --git a/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-2.pascal b/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-2.pascal new file mode 100644 index 0000000000..94e2a1477b --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Pascal/sieve-of-eratosthenes-2.pascal @@ -0,0 +1,130 @@ +program prim(output); +//Sieve of Erathosthenes with fast elimination of multiples of small primes +{$IFNDEF FPC} + {$APPTYPE CONSOLE} +{$ENDIF} +const + PrimeLimit = 100*1000*1000;//1; +type + tLimit = 1..PrimeLimit; +var + //always initialized with 0 => false at startup + primes: array [tLimit] of boolean; + +function BuildWheel: longInt; +//fill primfield with no multiples of small primes +//returns next sieveprime +//speedup ~1/3 +var + //wheelprimes = 2,3,5,7,11... ; + //wheelsize = product [i= 0..wpno-1]wheelprimes[i] > Uint64 i> 13 + wheelprimes :array[0..13] of byte; + wheelSize,wpno, + pr,pw,i, k: LongWord; +begin + //the mother of all numbers 1 ;-) + //the first wheel = generator of numbers + //not divisible by the small primes first found primes + pr := 1; + primes[1]:= true; + WheelSize := 1; + + wpno := 0; + repeat + inc(pr); + //pw = pr projected in wheel of wheelsize + pw := pr; + if pw > wheelsize then + dec(pw,wheelsize); + If Primes[pw] then + begin +// writeln(pr:10,pw:10,wheelsize:16); + k := WheelSize+1; + //turn the wheel (pr-1)-times + for i := 1 to pr-1 do + begin + inc(k,WheelSize); + if k primeLimit then + k := primeLimit; + wheelPrimes[wpno] := pr; + primes[pr] := false; + + inc(wpno); + //the new wheelsize + WheelSize := k; + + //sieve multiples of the new found prime + i:= pr; + i := i*i; + while i <= k do + begin + primes[i] := false; + inc(i,pr); + end; + end; + until WheelSize >= PrimeLimit; + + //re-insert wheel-primes + // 1 still stays prime + while wpno > 0 do + begin + dec(wpno); + primes[wheelPrimes[wpno]] := true; + end; + BuildWheel := pr+1; +end; + +procedure Sieve; +var + sieveprime, + fakt : LongWord; +begin +//primes[1] = true is needed to stop for sieveprime = 2 +// at //Search next smaller possible prime + sieveprime := BuildWheel; +//alternative here + //fillchar(primes,SizeOf(Primes),chr(ord(true)));sieveprime := 2; + repeat + if primes[sieveprime] then + begin + //eliminate 'possible prime' multiples of sieveprime + //must go downwards + //2*2 would unmark 4 -> 4*2 = 8 wouldnt be unmarked + fakt := PrimeLimit DIV sieveprime; + IF fakt < sieveprime then + BREAK; + repeat + //Unmark + primes[sieveprime*fakt] := false; + //Search next smaller possible prime + repeat + dec(fakt); + until primes[fakt]; + until fakt < sieveprime; + end; + inc(sieveprime); + until false; + //remove 1 + primes[1] := false; +end; + +var + prCnt, + i : LongWord; +Begin + Sieve; + {count the primes } + prCnt := 0; + for i:= 1 to PrimeLimit do + inc(prCnt,Ord(primes[i])); + writeln(prCnt,' primes up to ',PrimeLimit); +end. diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl index 9fbe234679..9897dd0ae0 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-1.pl @@ -1,12 +1,16 @@ -$max= $ARGV[0]; -@primes= (); -@tested= (1); -$j= 1; -while ($j < $max) { - next if $tested[$j++]; - push @primes, $j; - for ($k= $j; $k <= $max; $k+=$j) { - $tested[$k-1]= 1; - } +sub sieve { + my $n = shift; + my @composite; + for my $i (2 .. int(sqrt($n))) { + if (!$composite[$i]) { + for (my $j = $i*$i; $j <= $n; $j += $i) { + $composite[$j] = 1; + } + } + } + my @primes; + for my $i (2 .. $n) { + $composite[$i] || push @primes, $i; + } + @primes; } -print "@primes\n"; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl new file mode 100644 index 0000000000..34e6783944 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-10.pl @@ -0,0 +1,54 @@ +use strict; +use warnings; +package Tie::SieveOfEratosthenes; + +sub TIEARRAY { + my $class = shift; + my @primes = (2,3,5,7); + return bless \@primes, $class; +} + +sub prextend { # Extend the given list of primes using a segment sieve + my($primes, $to) = @_; + $to-- unless $to & 1; # Ensure end is odd + return if $to < $primes->[-1]; + my $sqrtn = int(sqrt($to)+0.001); + prextend($primes, $sqrtn) if $primes->[-1] < $sqrtn; + my($segment, $startp) = ('', $primes->[-1]+1); + my($s_beg, $s_len) = ($startp >> 1, ($to>>1) - ($startp>>1)); + for my $p (@$primes) { + last if $p > $sqrtn; + if ($p >= 3) { + my $p2 = $p*$p; + if ($p2 < $startp) { # Bump up to next odd multiple of p >= startp + my $f = 1+int(($startp-1)/$p); + $p2 = $p * ($f | 1); + } + for (my $s = ($p2>>1)-$s_beg; $s <= $s_len; $s += $p) { + vec($segment, $s, 1) = 1; # Mark composites in segment + } + } + } + # Now add all the primes found in the segment to the list + do { push @$primes, 1+2*($_+$s_beg) if !vec($segment,$_,1) } for 0 .. $s_len; +} + +sub FETCHSIZE { 0x7FFF_FFFF } # Allows foreach to work +sub FETCH { + my($primes, $n) = @_; + return if $n < 0; + # Keep expanding the list as necessary, 5% larger each time. + prextend($primes, 1000+int(1.05*$primes->[-1])) while $n > $#$primes; + return $primes->[$n]; +} + +if( !caller ) { + tie my @prime_list, 'Tie::SieveOfEratosthenes'; + my $limit = $ARGV[0] || 100; + print $prime_list[0]; + my $i = 1; + while ($prime_list[$i] < $limit) { print " ", $prime_list[$i++]; } + print "\n"; +} + +1; diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl index d0a9d4c2a9..e8b77c8e15 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-2.pl @@ -1,16 +1,17 @@ -sub simple_sieve { - my($max) = @_; - return () if $max < 2; return (2) if $max < 3; +sub sieve2 { + my($n) = @_; + return @{([],[],[2],[2,3],[2,3])[$n]} if $n <= 4; - my @c; - for(my $t=3; $t*$t<=$max; $t+=2) { - if (!$c[$t]) { - for(my $s=$t*$t; $s<=$max; $s+=$t*2) { $c[$s]++ } + my @composite; + for (my $t = 3; $t*$t <= $n; $t += 2) { + if (!$composite[$t]) { + for (my $s = $t*$t; $s <= $n; $s += $t*2) + { $composite[$s]++ } } } my @primes = (2); - for(my $t=3; $t<=$max; $t+=2) { - $c[$t] || push @primes, $t; + for (my $t = 3; $t <= $n; $t += 2) { + $composite[$t] || push @primes, $t; } @primes; } diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl index 695e79530c..a726e9f6fb 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-3.pl @@ -1,6 +1,6 @@ sub dj_vector { my($end) = @_; - return () if $end < 2; return (2) if $end < 3; + return @{([],[],[2],[2,3],[2,3])[$end]} if $end <= 4; $end-- if ($end & 1) == 0; # Ensure end is odd my ($sieve, $n, $limit, $s_end) = ( '', 3, int(sqrt($end)), $end >> 1 ); diff --git a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl index 0bea95f6c8..e50c825074 100644 --- a/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl +++ b/Task/Sieve-of-Eratosthenes/Perl/sieve-of-eratosthenes-4.pl @@ -1,15 +1,15 @@ sub dj_string { my($end) = @_; - return () if $end < 2; return (2) if $end < 3; + return @{([],[],[2],[2,3],[2,3])[$end]} if $end <= 4; $end-- if ($end & 1) == 0; my $s_end = $end >> 1; my $whole = int( ($end>>1) / 15); # prefill with 3 and 5 marked my $sieve = '100010010010110' . '011010010010110' x $whole; substr($sieve, ($end>>1)+1) = ''; - my ($n, $limit) = ( 7, int(sqrt($end)) ); + my ($n, $limit, $s) = ( 7, int(sqrt($end)), 0 ); while ( $n <= $limit ) { - for (my $s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { + for ($s = ($n*$n) >> 1; $s <= $s_end; $s += $n) { substr($sieve, $s, 1) = '1'; } do { $n += 2 } while substr($sieve, $n>>1, 1); @@ -17,10 +17,11 @@ sub dj_string { # If you just want the count, it's very fast: # my $count = 1 + $sieve =~ tr/0//; my @primes = (2, 3, 5); - $n = 7-2; - foreach my $s (split("0", substr($sieve, 3), -1)) { - $n += 2 + 2 * length($s); - push @primes, $n if $n <= $end; + ($s, $n) = (3, 7-2); + while ( (my $nexts = 1 + index($sieve, "0", $s)) > 0 ) { + $n += 2 * ($nexts - $s); + $s = $nexts; + push @primes, $n; } @primes; } diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py index 428f0fe486..c2b2145b53 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-1.py @@ -1,8 +1,8 @@ -def eratosthenes(n): - multiples = [] - for i in xrange(2, n+1): +def eratosthenes2(n): + multiples = set() + for i in range(2, n+1): if i not in multiples: - print i - multiples.extend(xrange(i*i, n+1, i)) + print(i) + multiples.update(range(i*i, n+1, i)) -eratosthenes(100) +eratosthenes2(100) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py index 8e0d9d5a89..5ada4786d0 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-10.py @@ -1,28 +1,12 @@ -def primes(): - yield 2 ; yield 3 ; yield 5 ; yield 7 ; - ps = (p for p in primes()) # additional primes supply - p = ps.next() and ps.next() # discard 2, then get 3 - q = p*p # 9 - square of next prime to be put - sieve = {} # into sieve dict - n = 9 # the candidate number - while True: - if n not in sieve: # is not a multiple of previously recorded primes - if n < q: # n is prime - yield n - else: - add(sieve, q + 2*p, 2*p) # n==p*p: for prime p, under p*p + 2*p, - p = ps.next() # add 2*p as incremental step - q = p*p - else: - s = sieve.pop(n) - add(sieve, n + s, s) - n += 2 # work on odds only - -def add(sieve,next,step): - while next in sieve: # ensure each entry is unique - next += step - sieve[next] = step # next non-marked multiple of a prime - -import itertools -def primes_up_to(limit): - return list(itertools.takewhile(lambda p: p <= limit, primes())) +>>> primes_upto3(10**6, smallprimes=(2,3)) # Wall time: 0.17 +array([ 2, 3, 5, ..., 999961, 999979, 999983]) +>>> primes_upto3(10**7, smallprimes=(2,3)) # Wall time: '''2.13''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(15) +array([ 2, 3, 5, 7, 11, 13]) +>>> primes_upto3(10**7, smallprimes=primes_upto3(15)) # Wall time: '''1.31''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto2(10**7) # Wall time: '''1.39''' <-- version ''without'' wheels +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +>>> primes_upto3(10**7) # Wall time: '''1.30''' +array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py new file mode 100644 index 0000000000..8022a40075 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-11.py @@ -0,0 +1,28 @@ +import heapq + +# generates all prime numbers +def sieve(): + # priority queue of the sequences of non-primes + # the priority queue allows us to get the "next" non-prime quickly + nonprimes = [] + + i = 2 + while True: + if nonprimes and i == nonprimes[0][0]: # non-prime + while nonprimes[0][0] == i: + # for each sequence that generates this number, + # have it go to the next number (simply add the prime) + # and re-position it in the priority queue + x = nonprimes[0] + x[0] += x[1] + heapq.heapreplace(nonprimes, x) + + else: # prime + # insert a 2-element list into the priority queue: + # [current multiple, prime] + # the first element allows sorting by value of current multiple + # we start with i^2 + heapq.heappush(nonprimes, [i*i, i]) + yield i + + i += 1 diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py new file mode 100644 index 0000000000..1ec9c2285d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-12.py @@ -0,0 +1,24 @@ +def primes(): + yield 2; yield 3; yield 5; yield 7; + bps = (p for p in primes()) # separate supply of "base" primes (b.p.) + p = next(bps) and next(bps) # discard 2, then get 3 + q = p * p # 9 - square of next base prime to keep track of, + sieve = {} # in the sieve dict + n = 9 # n is the next candidate number + while True: + if n not in sieve: # n is not a multiple of any of base primes, + if n < q: # below next base prime's square, so + yield n # n is prime + else: + p2 = p + p # n == p * p: for prime p, add p * p + 2 * p + sieve[q + p2] = p2 # to the dict, with 2 * p as the increment step + p = next(bps); q = p * p # pull next base prime, and get its square + else: + s = sieve.pop(n); nxt = n + s # n's a multiple of some b.p., find next multiple + while nxt in sieve: nxt += s # ensure each entry is unique + sieve[nxt] = s # nxt is next non-marked multiple of this prime + n += 2 # work on odds only + +import itertools +def primes_up_to(limit): + return list(itertools.takewhile(lambda p: p <= limit, primes())) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py new file mode 100644 index 0000000000..e3f2aa1d6c --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-13.py @@ -0,0 +1,30 @@ +def primes(): + for p in [2,3,5,7]: yield p # base wheel primes + gaps1 = [ 2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8 ] + gaps = gaps1 + [ 6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10 ] # wheel2357 + def wheel_prime_pairs(): + yield (11,0); bps = wheel_prime_pairs() # additional primes supply + p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put + sieve = {}; n = 13; ni = 1 # into sieve dict; init cndidate, wheel ndx + while True: + if n not in sieve: # is not a multiple of previously recorded primes + if n < q: yield (n, ni) # n is prime with wheel modulo index + else: + npi = pi + 1 # advance wheel index + if npi > 47: npi = 0 + sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel + p, pi = next(bps); q = p * p # advance next prime and prime square to put + else: + s, si = sieve.pop(n) + nxt = n + s * gaps[si] # move current cull position up the wheel + si = si + 1 # advance wheel index + if si > 47: si = 0 + while nxt in sieve: # ensure each entry is unique by wheel + nxt += s * gaps[si] + si = si + 1 # advance wheel index + if si > 47: si = 0 + sieve[nxt] = (s, si) # next non-marked multiple of a prime + nni = ni + 1 # advance wheel index + if nni > 47: nni = 0 + n += gaps[ni]; ni = nni # advance on the wheel + for p, pi in wheel_prime_pairs(): yield p # strip out indexes diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py new file mode 100644 index 0000000000..6f54e138c7 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-14.py @@ -0,0 +1,40 @@ +def primes(): + whlPrms = [2,3,5,7,11,13,17] # base wheel primes + for p in whlPrms: yield p + def makeGaps(): + buf = [True] * (3 * 5 * 7 * 11 * 13 * 17 + 1) # all odds plus extra for o/f + for p in whlPrms: + if p < 3: + continue # no need to handle evens + strt = (p * p - 19) >> 1 # start position (divided by 2 using shift) + while strt < 0: strt += p + buf[strt::p] = [False] * ((len(buf) - strt - 1) // p + 1) # cull for p + whlPsns = [i + i for i,v in enumerate(buf) if v] + return [whlPsns[i + 1] - whlPsns[i] for i in range(len(whlPsns) - 1)] + gaps = makeGaps() # big wheel gaps + def wheel_prime_pairs(): + yield (19,0); bps = wheel_prime_pairs() # additional primes supply + p, pi = next(bps); q = p * p # adv to get 11 sqr'd is 121 as next square to put + sieve = {}; n = 23; ni = 1 # into sieve dict; init cndidate, wheel ndx + while True: + if n not in sieve: # is not a multiple of previously recorded primes + if n < q: yield (n, ni) # n is prime with wheel modulo index + else: + npi = pi + 1 # advance wheel index + if npi > 92159: npi = 0 + sieve[q + p * gaps[pi]] = (p, npi) # n == p * p: put next cull position on wheel + p, pi = next(bps); q = p * p # advance next prime and prime square to put + else: + s, si = sieve.pop(n) + nxt = n + s * gaps[si] # move current cull position up the wheel + si = si + 1 # advance wheel index + if si > 92159: si = 0 + while nxt in sieve: # ensure each entry is unique by wheel + nxt += s * gaps[si] + si = si + 1 # advance wheel index + if si > 92159: si = 0 + sieve[nxt] = (s, si) # next non-marked multiple of a prime + nni = ni + 1 # advance wheel index + if nni > 92159: nni = 0 + n += gaps[ni]; ni = nni # advance on the wheel + for p, pi in wheel_prime_pairs(): yield p # strip out indexes diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py index b175f484a9..91a2ce29d6 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-2.py @@ -1,8 +1,7 @@ -def eratosthenes2(n): - multiples = set() - for i in xrange(2, n+1): - if i not in multiples: - print i - multiples.update(xrange(i*i, n+1, i)) - -eratosthenes2(100) +def primes_upto(limit): + is_prime = [False] * 2 + [True] * (limit - 1) + for n in range(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)`` + if is_prime[n]: + for i in range(n*n, limit+1, n): + is_prime[i] = False + return [i for i, prime in enumerate(is_prime) if prime] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py index 274d00b5e3..82fe53e36e 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-3.py @@ -1,7 +1,8 @@ -def primes_upto(limit): +def iprimes_upto(limit): is_prime = [False] * 2 + [True] * (limit - 1) for n in xrange(int(limit**0.5 + 1.5)): # stop at ``sqrt(limit)`` if is_prime[n]: - for i in xrange(n*n, limit+1, n): + for i in range(n * n, limit + 1, n): # start at ``n`` squared is_prime[i] = False - return [i for i, prime in enumerate(is_prime) if prime] + for i in xrange(limit + 1): + if is_prime[i]: yield i diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py index d4e7013487..7162985457 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-4.py @@ -1,7 +1,2 @@ -def iprimes_upto(limit): - is_prime = [False] * 2 + [True] * (limit - 1) - for n in range(limit + 1): - if is_prime[n]: - yield n - for i in range(n*n, limit+1, n): # start at ``n`` squared - is_prime[i] = False +>>> list(iprimes_upto(15)) +[2, 3, 5, 7, 11, 13] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py index 7162985457..1ced303894 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-5.py @@ -1,2 +1,11 @@ ->>> list(iprimes_upto(15)) -[2, 3, 5, 7, 11, 13] +def primes2(limit): + if limit < 2: return [] + if limit < 3: return [2] + lmtbf = (limit - 3) // 2 + buf = [True] * (lmtbf + 1) + for i in range((int(limit ** 0.5) - 3) // 2 + 1): + if buf[i]: + p = i + i + 3 + s = p * (i + 1) + i + buf[s::p] = [False] * ((lmtbf - s) // p + 1) + return [2] + [i + i + 3 for i, v in enumerate(buf) if v] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py index 53b4e9ef99..b2b7edbfa3 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-6.py @@ -1,7 +1,12 @@ -import numpy -def primes_upto2(limit): - is_prime = numpy.ones(limit + 1, dtype=numpy.bool) - for n in xrange(2, int(limit**0.5 + 1.5)): - if is_prime[n]: - is_prime[n*n::n] = 0 - return numpy.nonzero(is_prime)[0][2:] +def iprimes2(limit): + yield 2 + if limit < 3: return + lmtbf = (limit - 3) // 2 + buf = [True] * (lmtbf + 1) + for i in range((int(limit ** 0.5) - 3) // 2 + 1): + if buf[i]: + p = i + i + 3 + s = p * (i + 1) + i + buf[s::p] = [False] * ((lmtbf - s) // p + 1) + for i in range(lmtbf + 1): + if buf[i]: yield (i + i + 3) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py index 1cdb64c793..df432360e5 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-7.py @@ -1,20 +1,20 @@ -from numpy import array, bool_, multiply, nonzero, ones, put, resize -# -def makepattern(smallprimes): - pattern = ones(multiply.reduce(smallprimes), dtype=bool_) - pattern[0] = 0 - for p in smallprimes: - pattern[p::p] = 0 - return pattern -# -def primes_upto3(limit, smallprimes=(2,3,5,7,11)): - sp = array(smallprimes) - if limit <= sp.max(): return sp[sp <= limit] - # - isprime = resize(makepattern(sp), limit + 1) - isprime[:2] = 0; put(isprime, sp, 1) - # - for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): - if isprime[n]: - isprime[n*n::n] = 0 - return nonzero(isprime)[0] +def primes235(limit): + yield 2; yield 3; yield 5 + if limit < 7: return + modPrms = [7,11,13,17,19,23,29,31] + gaps = [4,2,4,2,4,6,2,6,4,2,4,2,4,6,2,6] # 2 loops for overflow + ndxs = [0,0,0,0,1,1,2,2,2,2,3,3,4,4,4,4,5,5,5,5,5,5,6,6,7,7,7,7,7,7] + lmtbf = (limit + 23) // 30 * 8 - 1 # integral number of wheels rounded up + lmtsqrt = (int(limit ** 0.5) - 7) + lmtsqrt = lmtsqrt // 30 * 8 + ndxs[lmtsqrt % 30] # round down on the wheel + buf = [True] * (lmtbf + 1) + for i in range(lmtsqrt + 1): + if buf[i]: + ci = i & 7; p = 30 * (i >> 3) + modPrms[ci] + s = p * p - 7; p8 = p << 3 + for j in range(8): + c = s // 30 * 8 + ndxs[s % 30] + buf[c::p8] = [False] * ((lmtbf - c) // p8 + 1) + s += p * gaps[ci]; ci += 1 + for i in range(lmtbf - 6 + (ndxs[(limit - 7) % 30])): # adjust for extras + if buf[i]: yield (30 * (i >> 3) + modPrms[i & 7]) diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py index 5ada4786d0..53b4e9ef99 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-8.py @@ -1,12 +1,7 @@ ->>> primes_upto3(10**6, smallprimes=(2,3)) # Wall time: 0.17 -array([ 2, 3, 5, ..., 999961, 999979, 999983]) ->>> primes_upto3(10**7, smallprimes=(2,3)) # Wall time: '''2.13''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto3(15) -array([ 2, 3, 5, 7, 11, 13]) ->>> primes_upto3(10**7, smallprimes=primes_upto3(15)) # Wall time: '''1.31''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto2(10**7) # Wall time: '''1.39''' <-- version ''without'' wheels -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) ->>> primes_upto3(10**7) # Wall time: '''1.30''' -array([ 2, 3, 5, ..., 9999971, 9999973, 9999991]) +import numpy +def primes_upto2(limit): + is_prime = numpy.ones(limit + 1, dtype=numpy.bool) + for n in xrange(2, int(limit**0.5 + 1.5)): + if is_prime[n]: + is_prime[n*n::n] = 0 + return numpy.nonzero(is_prime)[0][2:] diff --git a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py index 8022a40075..1cdb64c793 100644 --- a/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py +++ b/Task/Sieve-of-Eratosthenes/Python/sieve-of-eratosthenes-9.py @@ -1,28 +1,20 @@ -import heapq - -# generates all prime numbers -def sieve(): - # priority queue of the sequences of non-primes - # the priority queue allows us to get the "next" non-prime quickly - nonprimes = [] - - i = 2 - while True: - if nonprimes and i == nonprimes[0][0]: # non-prime - while nonprimes[0][0] == i: - # for each sequence that generates this number, - # have it go to the next number (simply add the prime) - # and re-position it in the priority queue - x = nonprimes[0] - x[0] += x[1] - heapq.heapreplace(nonprimes, x) - - else: # prime - # insert a 2-element list into the priority queue: - # [current multiple, prime] - # the first element allows sorting by value of current multiple - # we start with i^2 - heapq.heappush(nonprimes, [i*i, i]) - yield i - - i += 1 +from numpy import array, bool_, multiply, nonzero, ones, put, resize +# +def makepattern(smallprimes): + pattern = ones(multiply.reduce(smallprimes), dtype=bool_) + pattern[0] = 0 + for p in smallprimes: + pattern[p::p] = 0 + return pattern +# +def primes_upto3(limit, smallprimes=(2,3,5,7,11)): + sp = array(smallprimes) + if limit <= sp.max(): return sp[sp <= limit] + # + isprime = resize(makepattern(sp), limit + 1) + isprime[:2] = 0; put(isprime, sp, 1) + # + for n in range(sp.max() + 2, int(limit**0.5 + 1.5), 2): + if isprime[n]: + isprime[n*n::n] = 0 + return nonzero(isprime)[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 95dc87796f..f3a56675ea 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-1.rexx @@ -1,12 +1,13 @@ /*REXX program generates primes via the sieve of Eratosthenes algorithm.*/ -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. */ +parse arg H .; if H=='' then H=200 /*was the high limit specified? */ +w=length(H); @prime=right('prime',20) /*W is used for formatting output*/ +@.=. /*assume all numbers are prime. */ #=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*/ + do j=2 for H-1 /*all integers up to H inclusive.*/ + if @.j=='' then iterate /*Composite? Then skip this num.*/ + #=#+1 /*bump the prime number counter. */ + say @prime right(#,w) " ───► " right(j,w) /*show the prime.*/ + do m=j*j to H by j; @.m=; end /*strike all multiples as ¬ prime*/ + end /*j*/ /* ─── */ /*stick a fork in it, we're done.*/ +say; say right(#,w+length(@prime)+1) 'primes found.' 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 be54767a5d..214d0da7b7 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-2.rexx @@ -1,21 +1,22 @@ /*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. */ +parse arg H .; if H=='' then H=200 /*let the highest # be specified.*/ 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) -skip=0 /*skips top part sieve striking. */ -@.=1 /*assume all numbers are prime. */ -#=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) - if skip then iterate /*should the top part be skipped?*/ - if j*j>H then skip=1 /*indicate skipping if j > √ H. */ - 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." +#= w<=H /*number of primes found so far. */ +@.=. /*assume all numbers are prime. */ +!=0 /*skips top part of sieve marking*/ + do j=3 by 2 for (H-2)%2 /*odd integers up to H inclusive.*/ + if @.j=='' then iterate /*composite? Then skip this num.*/ + #=#+1 /*bump the prime number counter. */ + if tell then say right(#,w+20)th(#) 'prime ───► ' right(j,w) + if ! then iterate /*should the top part be skipped?*/ + jj=j*j /*compute the square of J. __ */ + if jj>H then !=1 /*indicate skipping if j > √ H.*/ + do m=jj to H by j+j; @.m=; end /*strike odd multiples as ¬ prime*/ + end /*j*/ /* ─── */ +say +say right(#,w+20) '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*/ -/*──────────────────────────────────TH subroutine───────────────────────*/ -th: procedure;parse arg x;x=abs(x);return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) +/*──────────────────────────────────one─liner subroutines────────────────────────────────────────*/ +s: if arg(1)==1 then return arg(3); return word(arg(2) 's',1) /*pluralizer.*/ +th: procedure; parse arg x; x=abs(x); return word('th st nd rd',1+x//10*(x//100%10\==1)*(x//10<4)) 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 aa9d70aab9..a6d8f95bd1 100644 --- a/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx +++ b/Task/Sieve-of-Eratosthenes/REXX/sieve-of-eratosthenes-3.rexx @@ -1,16 +1,18 @@ /*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) -skip=0 /*skips top part sieve striking. */ -@.=1 /*assume all numbers are prime. */ -#=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*/ - say prime right(#,w) " ───► " right(j,w) /*show.*/ - if skip then iterate /*should the top part be skipped?*/ - if j*j>H then skip=1 /*indicate skipping if j > √ H. */ - 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.*/ +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) +#= 2<=H /*number of primes found so far. */ +@.=. /*assume all numbers are prime. */ +!=0 /*skips top part of sieve marking*/ + do j=3 by 2 for (H-2)%2 /*odd integers up to H inclusive.*/ + if @.j=='' then iterate /*composite? Then skip this num.*/ + #=#+1 /*bump the prime number counter. */ + say @prime right(#,w) " ───► " right(j,w) /*show the prime.*/ + if ! then iterate /*should the top part be skipped?*/ + jj=j*j /*compute the square of J. __ */ + if jj>H then !=1 /*indicate skipping if j > √ H.*/ + do m=jj to H by j+j; @.m=; end /*strike odd multiples as ¬ prime*/ + end /*j*/ /* ─── */ +say /*stick a fork in it, we're done.*/ +say right(#, w+length(@prime)+1) 'primes found.' diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt index 67d6a46e4d..fe790060c7 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-1.rkt @@ -1,6 +1,5 @@ #lang racket -;; ugly imperative version (define (sieve n) (define non-primes '()) (define primes '()) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt new file mode 100644 index 0000000000..2c488f3c3d --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-10.rkt @@ -0,0 +1,5 @@ +(define primes + (cons 2 (diff (ints-from 3 1) + (foldr (λ(p r) (define q (* p p)) + (cons q (union (ints-from (+ q p) p) r))) + '() primes)))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt new file mode 100644 index 0000000000..b2b4ba5221 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-11.rkt @@ -0,0 +1,26 @@ +#lang racket +(define-syntax (define-thread-loop stx) + (syntax-case stx () + [(_ (name . args) expr ...) + (with-syntax ([out! (datum->syntax stx 'out!)]) + #'(define (name . args) + (define out (make-channel)) + (define (out! x) (channel-put out x)) + (thread (λ() (let loop () expr ... (loop)))) + out))])) +(define-thread-loop (ints-from i d) (out! i) (set! i (+ i d))) +(define-thread-loop (merge c1 c2) + (let loop ([x1 (channel-get c1)] [x2 (channel-get c2)]) + (cond [(< x1 x2) (out! x1) (loop (channel-get c1) x2)] + [(> x1 x2) (out! x2) (loop x1 (channel-get c2))] + [else (out! x1) (loop (channel-get c1) (channel-get c2))]))) +(define-thread-loop (sieve l non-primes) + (let loop ([x (channel-get l)] [np (channel-get non-primes)]) + (cond [(< np x) (loop x (channel-get non-primes))] + [(= np x) (loop (channel-get l) (channel-get non-primes))] + [else (out! x) + (set! non-primes (merge (ints-from (* x x) x) non-primes))]))) +(define-thread-loop (cons x l) + (out! x) (let loop () (out! (channel-get l)) (loop))) +(define primes (cons 2 (sieve (ints-from 3 2) (ints-from 2 2)))) +(for/list ([i 25] [x (in-producer channel-get eof primes)]) x) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt new file mode 100644 index 0000000000..4de4f01b06 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-12.rkt @@ -0,0 +1,21 @@ +#lang racket +(require racket/generator) +(define (ints-from i d) + (generator () (let loop ([i i]) (yield i) (loop (+ i d))))) +(define (merge g1 g2) + (generator () + (let loop ([x1 (g1)] [x2 (g2)]) + (cond [(< x1 x2) (yield x1) (loop (g1) x2)] + [(> x1 x2) (yield x2) (loop x1 (g2))] + [else (yield x1) (loop (g1) (g2))])))) +(define (sieve l non-primes) + (generator () + (let loop ([x (l)] [np (non-primes)]) + (cond [(< np x) (loop x (non-primes))] + [(= np x) (loop (l) (non-primes))] + [else (yield x) + (set! non-primes (merge (ints-from (* x x) x) non-primes)) + (loop (l) (non-primes))])))) +(define (cons x l) (generator () (yield x) (let loop () (yield (l)) (loop)))) +(define primes (cons 2 (sieve (ints-from 3 2) (ints-from 2 2)))) +(for/list ([i 25] [x (in-producer primes)]) x) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt index c53a08158f..aa7dd15905 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-2.rkt @@ -1,6 +1,5 @@ #lang racket -;; a little nicer, but still imperative (define (sieve n) (define primes (make-vector (add1 n) #t)) (for* ([i (in-range 2 (add1 n))] diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt index a5f69040cf..da4d0e9628 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-3.rkt @@ -1,11 +1,17 @@ -#lang lazy - -;; infinite list using lazy racket (see the language above) -(define nats (cons 1 (map add1 nats))) -(define (sift n l) (filter (λ(x) (not (zero? (modulo x n)))) l)) -(define (sieve l) (cons (first l) (sieve (sift (first l) (rest l))))) -(define primes (sieve (rest nats))) - -(define (take-upto n l) - (if (<= (car l) n) (cons (car l) (take-upto n (cdr l))) '())) -(!! (take-upto 100 primes)) +#lang racket +(require data/bit-vector) +(define (eratosthenes limit) + " Returns a list of prime numbers up to natural number limit " + (let ((bv (make-bit-vector (+ limit 1) #f))) + (bit-vector-set! bv 0 #t) + (bit-vector-set! bv 1 #t) + (for ((i (in-range (sqrt limit)))) + (when (false? (bit-vector-ref bv i)) + (for ((j (in-range (+ i i) (bit-vector-length bv) i))) + (bit-vector-set! bv j #t)))) + ;; Translate bit-vector into list of primes + ;; the following is extremely ugly/imperative and needs the result list reversed + (let ((to-return null)) + (for ((i (bit-vector-length bv))) + (when (not (bit-vector-ref bv i)) (set! to-return (cons i to-return)))) + (reverse to-return)))) ; NOTE: needs to be reversed diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt index 43440e46b7..0a982bc615 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-4.rkt @@ -1,27 +1,17 @@ #lang racket - -;; infinite list using threads and channels (similar to newsqueak) -(define-syntax (bg-loop stx) - (syntax-case stx () - [(_ expr ...) - (with-syntax ([out! (datum->syntax stx 'out!)]) - #'(let ([out (make-channel)]) - (define (out! x) (channel-put out x)) - (thread (λ() (let loop () expr ... (loop)))) - out))])) -(define nats (bg-loop (for ([i (in-naturals 1)]) (out! i)))) -(define (filter pred? c) - (bg-loop (define x (channel-get c)) - (when (pred? x) (out! x)))) -(define (sift n c) - (filter (λ(x) (not (zero? (modulo x n)))) c)) -(define (sieve c) - (bg-loop (define x (channel-get c)) - (out! x) - (set! c (sift x c)))) -(define primes (begin (channel-get nats) (sieve nats))) - -(define (take-upto n c) - (let loop () - (let ([x (channel-get c)]) (if (<= x n) (cons x (loop)) '())))) -(take-upto 100 primes) +(require data/bit-vector) +(define (eratosthenes limit) + " Returns a list of prime numbers up to natural number limit " + (let ((bv (make-bit-vector (+ limit 1) #f))) + (bit-vector-set! bv 0 #t) + (bit-vector-set! bv 1 #t) + (for ((i (in-range (sqrt limit)))) + (when (false? (bit-vector-ref bv i)) + (for ((j (in-range (+ i i) (bit-vector-length bv) i))) + (bit-vector-set! bv j #t)))) + ;; Translate bit-vector into list of primes using recursion + ;; may as well use the list comprehension from the second version, which does the same thing + (let recur ((i 2)) (cond ((> i limit) '()) + ((false? (bit-vector-ref bv i)) (cons i (recur (+ i 1)))) + (else (recur (+ i 1))))))) +(eratosthenes 100) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt index 00a9f1e242..41bed2d8ca 100644 --- a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-5.rkt @@ -1,18 +1,14 @@ -#lang racket - -;; yet another variation of the same algorithm, this time using generators -(require racket/generator) - -(define nats (generator () (for ([i (in-naturals 1)]) (yield i)))) -(define (filter pred g) - (generator () (for ([i (in-producer g #f)] #:when (pred i)) (yield i)))) -(define (sift n g) (filter (λ(x) (not (zero? (modulo x n)))) g)) -(define (sieve g) - (generator () - (let loop ([g g]) (let ([x (g)]) (yield x) (loop (sift x g)))))) -(define primes (begin (nats) (sieve nats))) - -(define (take-upto n p) - (let loop () - (let ([x (p)]) (if (<= x n) (cons x (loop)) '())))) -(take-upto 100 primes) +#lang lazy +(define (ints-from i d) (cons i (ints-from (+ i d) d))) +(define (after n l f) + (if (< (car l) n) (cons (car l) (after n (cdr l) f)) (f l))) +(define (diff l1 l2) + (let ([x1 (car l1)] [x2 (car l2)]) + (cond [(< x1 x2) (cons x1 (diff (cdr l1) l2 ))] + [(> x1 x2) (diff l1 (cdr l2)) ] + [else (diff (cdr l1) (cdr l2)) ]))) +(define (union l1 l2) ; union of two lists + (let ([x1 (car l1)] [x2 (car l2)]) + (cond [(< x1 x2) (cons x1 (union (cdr l1) l2 ))] + [(> x1 x2) (cons x2 (union l1 (cdr l2)))] + [else (cons x1 (union (cdr l1) (cdr l2)))]))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt new file mode 100644 index 0000000000..0ddb68abf0 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-6.rkt @@ -0,0 +1,5 @@ +(define (sieve l) + (define x (car l)) + (cons x (sieve (diff (cdr l) (ints-from (+ x x) x))))) +(define primes (sieve (ints-from 2 1))) +(!! (take 25 primes)) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt new file mode 100644 index 0000000000..ed1edfb20f --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-7.rkt @@ -0,0 +1,6 @@ +(define (sieve l non-primes) + (let ([x (car l)] [np (car non-primes)]) + (cond [(= x np) (sieve (cdr l) (cdr non-primes))] ; else x < np + [else (cons x (sieve (cdr l) (union (ints-from (* x x) (* 2 x)) + non-primes)))]))) +(define primes (cons 2 (cons 3 (sieve (ints-from 5 2) (ints-from 9 6))))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt new file mode 100644 index 0000000000..1652054e12 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-8.rkt @@ -0,0 +1,5 @@ +(define (sieve l prs) + (define p (car prs)) + (define q (* p p)) + (after q l (λ(t) (sieve (diff t (ints-from q p)) (cdr prs))))) +(define primes (cons 2 (sieve (ints-from 3 1) primes))) diff --git a/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt new file mode 100644 index 0000000000..62409279cf --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Racket/sieve-of-eratosthenes-9.rkt @@ -0,0 +1,6 @@ +(define (composites l q primes) + (after q l (λ(t) (let ([p (car primes)] [r (cadr primes)]) + (composites (union t (ints-from q (* 2 p))) ; q = p*p + (* r r) (cdr primes)))))) +(define primes (cons 2 (cons 3 (diff (ints-from 5 2) + (composites (ints-from 9 6) 25 (cddr primes)))))) diff --git a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust index f51faa5dfe..e6e27524fa 100644 --- a/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust +++ b/Task/Sieve-of-Eratosthenes/Rust/sieve-of-eratosthenes.rust @@ -1,28 +1,28 @@ -use std::vec; -use std::num; use std::iter; fn int_sqrt(n: uint) -> uint { - num::sqrt(n as f64) as uint + (n as f64).sqrt() as uint } -fn simple_sieve(limit: uint) -> ~[uint] { +fn simple_sieve(limit: uint) -> Vec { + if limit < 2 { - return ~[]; + return Vec::new(); } - let mut primes = vec::from_elem(limit + 1, true); + let mut primes: Vec = Vec::from_elem(limit + 1, true); for prime in iter::range_inclusive(2, int_sqrt(limit) + 1) { if primes[prime] { for multiple in iter::range_step(prime * prime, limit + 1, prime) { - primes[multiple] = false + *primes.get_mut(multiple) = false; } } } + iter::range_inclusive(2, limit).filter(|&n| primes[n]).collect() } fn main() { - println!("{:?}", simple_sieve(100)) + println!("{}", simple_sieve(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 ea512ca99b..85c3bbd3d2 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-1.scala @@ -1,10 +1,22 @@ -def sieveOfEratosthenes(nTo: Int) = { - val primes = collection.mutable.BitSet.empty.par ++ (2 +: (3 to nTo by 2)) - for { - candidate <- 3 until Math.sqrt(nTo).toInt - if primes contains candidate - } primes --= candidate * candidate to nTo by candidate - primes +import scala.annotation.tailrec +import scala.collection.parallel.mutable +import scala.compat.Platform + +object GenuineEratosthenesSieve extends App { + def sieveOfEratosthenes(limit: Int) = { + val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt) + @tailrec + def prim(candidate: Int): Unit = { + if (candidate <= sqrtLimit) { + if (primes contains candidate) primes --= candidate * candidate to limit by candidate + prim(candidate + 1) + } + } + prim(2) + primes + } + // BitSet toList is shuffled when using the ParSet version. So it has to be sorted before using it as a sequence. + + assert(sieveOfEratosthenes(15099480).size == 976729) + println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") } -// BitSet toList 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 95676e843d..2cfab39f41 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-2.scala @@ -1,30 +1,9 @@ - import scala.annotation.tailrec - - /* - * 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, "")) - } +object SoEwithBitSet { + def makeSoE_PrimesTo(top: Int): Iterator[Int] = { + val topNdx = (top - 3) / 2 //odds composite BitSet buffer offset down to 3 + val cmpsts = new scala.collection.mutable.BitSet(topNdx + 1) //size includes topNdx + @inline def cullPrmCmpsts(prmNdx: Int) = { + val prm = prmNdx + prmNdx + 3; cmpsts ++= ((prm * prm - 3) >>> 1 to topNdx by prm) } + (0 to (Math.sqrt(top).toInt - 3) / 2).filterNot { cmpsts }.foreach { cullPrmCmpsts } + Iterator.single(2) ++ (0 to topNdx).filterNot { cmpsts }.map { pi => pi + pi + 3 } } +} diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala index 11c3d3277c..4a53172ca4 100644 --- a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-3.scala @@ -1,8 +1,28 @@ -import scala.language.postfixOps +object SoEwithArray { + def makeSoE_PrimesTo(top: Int) = { + import scala.annotation.tailrec + val topNdx = (top - 3) / 2 + 1 //odds composite BitSet buffer offset down to 3 plus 1 for overflow + val (cmpsts, sqrtLmtNdx) = (new Array[Int]((topNdx >>> 5) + 1), (Math.sqrt(top).toInt - 3) / 2) - def sieve(nums: Stream[Int]): Stream[Int] = - Stream.cons(nums.head, sieve((nums.tail) filter (_ % nums.head != 0))) - val primes = 2 #:: sieve(Stream.from(3, 2)) + @inline def isCmpst(ci: Int): Boolean = (cmpsts(ci >>> 5) & (1 << (ci & 31))) != 0 - 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) + @inline def setCmpst(ci: Int): Unit = cmpsts(ci >>> 5) |= 1 << (ci & 31) + + @tailrec def forCndNdxsFrom(cndNdx: Int): Unit = + if (cndNdx <= sqrtLmtNdx) { + if (!isCmpst(cndNdx)) { //is prime + val p = cndNdx + cndNdx + 3 + + @tailrec def cullPrmCmpstsFrom(cmpstNdx: Int): Unit = + if (cmpstNdx <= topNdx) { setCmpst(cmpstNdx); cullPrmCmpstsFrom(cmpstNdx + p) } + + cullPrmCmpstsFrom((p * p - 3) >>> 1) } + + forCndNdxsFrom(cndNdx + 1) }; forCndNdxsFrom(0) + + @tailrec def getNxtPrmFrom(cndNdx: Int): Int = + if ((cndNdx > topNdx) || !isCmpst(cndNdx)) cndNdx + cndNdx + 3 else getNxtPrmFrom(cndNdx + 1) + + Iterator.single(2) ++ Iterator.iterate(3)(p => getNxtPrmFrom(((p + 2) - 3) >>> 1)).takeWhile(_ <= top) + } +} diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-4.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-4.scala new file mode 100644 index 0000000000..422a3836f9 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-4.scala @@ -0,0 +1,10 @@ +object Main extends App { + import SoEwithArray._ + val top_num = 100000000 + val strt = System.nanoTime() + val count = makeSoE_PrimesTo(top_num).size + val end = System.nanoTime() + println(s"Successfully completed without errors. [total ${(end - strt) / 1000000} ms]") + println(f"Found $count primes up to $top_num" + ".") + println("Using one large mutable Array and tail recursive loops.") +} diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-5.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-5.scala new file mode 100644 index 0000000000..61171b4360 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-5.scala @@ -0,0 +1,92 @@ +object APFSoEPagedOdds { + import scala.annotation.tailrec + + private val CACHESZ = 1 << 18 //used cache buffer size + private val PGSZ = CACHESZ / 4 //number of int's in cache + private val PGBTS = PGSZ * 32 //number of bits in buffer + + //processing output type is a tuple of low bit (odds) address, + // bit range size, and the actual culled page segment buffer. + private type Chunk = (Long, Int, Array[Int]) + + //produces an iteration of all the primes from an iteration of Chunks + private def enumChnkPrms(chnks: Stream[Chunk]): Iterator[Long] = { + def iterchnk(chnk: Chunk) = { //iterating primes per Chunk + val (lw, rng, bf) = chnk + @tailrec def nxtpi(i: Int): Int = { //find next prime index not composite + if (i < rng && (bf(i >>> 5) & (1 << (i & 31))) != 0) nxtpi(i + 1) else i } + Iterator.iterate(nxtpi(0))(i => nxtpi(i + 1)).takeWhile { _ < rng } + .map { i => ((lw + i) << 1) + 3 } } //map from index to prime value + chnks.toIterator.flatMap { iterchnk } } + + //culls the composite number bit representations from the bit-packed page buffer + //using a given source of a base primes iterator + private def cullPg(bsprms: Iterator[Long], + lowi: Long, buf: Array[Int]): Unit = { + //cull for all base primes until square >= nxt + val rng = buf.length * 32; val nxt = lowi + rng + @tailrec def cull(bps: Iterator[Long]): Unit = { + //given prime then calculate the base start address for prime squared + val bp = bps.next(); val s = (bp * bp - 3) / 2 + //almost all of the execution time is spent in the following tight loop + @tailrec def cullp(j: Int): Unit = { //cull the buffer for given prime + if (j < rng) { buf(j >>> 5) |= 1 << (j & 31); cullp(j + bp.toInt) } } + if (s < nxt) { //only cull for primes squared less than max + //calculate the start address within this given page segment + val strt = if (s >= lowi) (s - lowi).toInt else { + val b = (lowi - s) % bp + if (b == 0) 0 else (bp - b).toInt } + cullp(strt); if (bps.hasNext) cull(bps) } } //loop for all primes in range + //for the first page, use own bit pattern as a source of base primes + //if another source is not given + if (lowi <= 0 && bsprms.isEmpty) + cull(enumChnkPrms(Stream((0, buf.length << 5, buf)))) + //otherwise use the given source of base primes + else if (bsprms.hasNext) cull(bsprms) } + + //makes a chunk given a low address in (odds) bits + private def mkChnk(lwi: Long): Chunk = { + val rng = PGBTS; val buf = new Array[Int](rng / 32); + val bps = if (lwi <= 0) Iterator.empty else enumChnkPrms(basePrms) + cullPg(bps, lwi, buf); (lwi, rng, buf) } + + //new independent source of base primes in a stream of packed-bit arrays + //memoized by converting it to a Stream and retaining a reference here + private val basePrms: Stream[Chunk] = + Stream.iterate(mkChnk(0)) { case (lw, rng, bf) => { mkChnk(lw + rng) } } + + //produces an infinite iterator over all the chunk results + private def itrRslts[R](rsltf: Chunk => R): Iterator[R] = { + def mkrslt(lwi: Long) = { //makes tuple of result and next low index + val c = mkChnk(lwi); val (_, rng, _) = c; (rsltf(c), lwi + rng) } + Iterator.iterate(mkrslt(0)) { case (_, nlwi) => mkrslt(nlwi) } + .map { case (rslt, _) => rslt} } //infinite iteration of results + + //iterates across the "infinite" produced output primes + def enumSoEPrimes(): Iterator[Long] = //use itrRsltsMP to produce Chunks iteration + Iterator.single(2L) ++ enumChnkPrms(itrRslts { identity }.toStream) + + //counts the number of remaining primes in a page segment buffer + //using a very fast bitcount per integer element + //with special treatment for the last page + private def countpgto(top: Long, b: Array[Int], nlwp: Long) = { + val numbts = b.length * 32; val prng = numbts * 2 + @tailrec def cnt(i: Int, c: Int): Int = { //tight int bitcount loop + if (i >= b.length) c else cnt (i + 1, c - Integer.bitCount(b(i))) } + if (nlwp > top) { //for top in page, calculate int address containing top + val bi = ((top - nlwp + prng) >>> 1).toInt + val w = bi >>> 5; b(w) |= -2 << (bi & 31) //mark all following as composite + for (i <- w + 1 until b.length) b(i) = -1 } //for all int's to end of buffer + cnt(0, numbts) } //counting the entire buffer in every case + + //counts all the primes up to a top value + def countSoEPrimesTo(top: Long): Long = { + if (top < 2) return 0L else if (top < 3) return 1L //no work necessary + //count all Chunks using multi-processing + val gen = itrRslts { case (lwi, rng, bf) => + val nlwp = (lwi + rng) * 2 + 3; (countpgto(top, bf, nlwp), nlwp) } + //a loop to take Chunk's up to including top limit but not past it + @tailrec def takeUpto(acc: Long): Long = { + val (cnt, nlwp) = gen.next(); val nacc = acc + cnt + if (nlwp <= top) takeUpto(nacc) else nacc }; takeUpto(1) } +} diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-6.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-6.scala new file mode 100644 index 0000000000..811eeadacb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-6.scala @@ -0,0 +1,10 @@ +object MainSoEPagedOdds extends App { + import APFSoEPagedOdds._ + countSoEPrimesTo(100) + val top = 1000000000 + val strt = System.currentTimeMillis() + val cnt = enumSoEPrimes().takeWhile { _ <= top }.length +// val cnt = countSoEPrimesTo(top) + val elpsd = System.currentTimeMillis() - strt + println(f"Found $cnt primes up to $top in $elpsd milliseconds.") +} diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-7.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-7.scala new file mode 100644 index 0000000000..59481fea75 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-7.scala @@ -0,0 +1,22 @@ + def birdPrimes() = { + def oddPrimes: Stream[Int] = { + def merge(xs: Stream[Int], ys: Stream[Int]): Stream[Int] = { + val (x, y) = (xs.head, ys.head) + + if (y > x) x #:: merge(xs.tail, ys) else if (x > y) y #:: merge(xs, ys.tail) else x #:: merge(xs.tail, ys.tail) + } + + def primeMltpls(p: Int): Stream[Int] = Stream.iterate(p * p)(_ + p + p) + + def allMltpls(ps: Stream[Int]): Stream[Stream[Int]] = primeMltpls(ps.head) #:: allMltpls(ps.tail) + + def join(ams: Stream[Stream[Int]]): Stream[Int] = ams.head.head #:: merge(ams.head.tail, join(ams.tail)) + + def oddPrms(n: Int, composites: Stream[Int]): Stream[Int] = + if (n >= composites.head) oddPrms(n + 2, composites.tail) else n #:: oddPrms(n + 2, composites) + + //following uses a new recursive source of odd base primes + 3 #:: oddPrms(5, join(allMltpls(oddPrimes))) + } + 2 #:: oddPrimes + } diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-8.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-8.scala new file mode 100644 index 0000000000..665c54a658 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-8.scala @@ -0,0 +1,33 @@ + class CIS[A](val start: A, val continue: () => CIS[A]) + + def primesBirdCIS: Iterator[Int] = { + def merge(xs: CIS[Int], ys: CIS[Int]): CIS[Int] = { + val (x, y) = (xs.start, ys.start) + + if (y > x) new CIS(x, () => merge(xs.continue(), ys)) + else if (x > y) new CIS(y, () => merge(xs, ys.continue())) + else new CIS(x, () => merge(xs.continue(), ys.continue())) + } + + def primeMltpls(p: Int): CIS[Int] = { + def nextCull(cull: Int): CIS[Int] = new CIS[Int](cull, () => nextCull(cull + 2 * p)) + nextCull(p * p) + } + + def allMltpls(ps: CIS[Int]): CIS[CIS[Int]] = + new CIS[CIS[Int]](primeMltpls(ps.start), () => allMltpls(ps.continue())) + def join(ams: CIS[CIS[Int]]): CIS[Int] = { + new CIS[Int](ams.start.start, () => merge(ams.start.continue(), join(ams.continue()))) + } + + def oddPrimes(): CIS[Int] = { + def oddPrms(n: Int, composites: CIS[Int]): CIS[Int] = { //"minua" + if (n >= composites.start) oddPrms(n + 2, composites.continue()) + else new CIS[Int](n, () => oddPrms(n + 2, composites)) + } + //following uses a new recursive source of odd base primes + new CIS(3, () => oddPrms(5, join(allMltpls(oddPrimes())))) + } + + Iterator.single(2) ++ Iterator.iterate(oddPrimes())(_.continue()).map(_.start) + } diff --git a/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-9.scala b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-9.scala new file mode 100644 index 0000000000..cbe809efeb --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scala/sieve-of-eratosthenes-9.scala @@ -0,0 +1,25 @@ + def SoEInc: Iterator[Int] = { + val nextComposites = scala.collection.mutable.HashMap[Int, Int]() + def oddPrimes: Iterator[Int] = { + val basePrimes = SoEInc + basePrimes.next() + basePrimes.next() // skip the two and three prime factors + @tailrec def makePrime(state: (Int, Int, Int)): (Int, Int, Int) = { + val (candidate, nextBasePrime, nextSquare) = state + if (candidate >= nextSquare) { + val adv = nextBasePrime << 1 + nextComposites += ((nextSquare + adv) -> adv) + val np = basePrimes.next() + makePrime((candidate + 2, np, np * np)) + } else if (nextComposites.contains(candidate)) { + val adv = nextComposites(candidate) + nextComposites -= (candidate) += (Iterator.iterate(candidate + adv)(_ + adv) + .dropWhile(nextComposites.contains(_)).next() -> adv) + makePrime((candidate + 2, nextBasePrime, nextSquare)) + } else (candidate, nextBasePrime, nextSquare) + } + Iterator.iterate((5, 3, 9)) { case (c, p, q) => makePrime((c + 2, p, q)) } + .map { case (p, _, _) => p } + } + List(2, 3).toIterator ++ oddPrimes + } diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss new file mode 100644 index 0000000000..3d7ee0eb86 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-10.ss @@ -0,0 +1,9 @@ + (define odd-primes + (s-cons 3 (s-diff (from-By 5 2) + (s-foldr (lambda (p r) (let ((q (* p p))) + (s-cons q (s-union (from-By (+ q (* 2 p)) (* 2 p)) r)))) + '() odd-primes)))) + + (define primes (s-cons 2 odd-primes)) + + ;;;; TODO: implement s-foldr function diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss new file mode 100644 index 0000000000..b9630ac4ad --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-11.ss @@ -0,0 +1,23 @@ +(define (birdPrimes) + (define (mltpls p) + (define pm2 (* p 2)) + (let nxtmltpl ((cmpst (* p p))) + (cons cmpst (lambda () (nxtmltpl (+ cmpst pm2)))))) + (define (allmltpls ps) + (cons (mltpls (car ps)) (lambda () (allmltpls ((cdr ps)))))) + (define (merge xs ys) + (let ((x (car xs)) (xt (cdr xs)) (y (car ys)) (yt (cdr ys))) + (cond ((< x y) (cons x (lambda () (merge (xt) ys)))) + ((> x y) (cons y (lambda () (merge xs (yt))))) + (else (cons x (lambda () (merge (xt) (yt)))))))) + (define (mrgmltpls mltplss) + (cons (car (car mltplss)) + (lambda () (merge ((cdr (car mltplss))) + (mrgmltpls ((cdr mltplss))))))) + (define (minusstrtat n cmps) + (if (< n (car cmps)) + (cons n (lambda () (minusstrtat (+ n 2) cmps))) + (minusstrtat (+ n 2) ((cdr cmps))))) + (define (cmpsts) (mrgmltpls (allmltpls (oddprms)))) ;; internal define's are mutually recursive + (define (oddprms) (cons 3 (lambda () (minusstrtat 5 (cmpsts))))) + (cons 2 (lambda () (oddprms)))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss new file mode 100644 index 0000000000..7e82cae2cc --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-12.ss @@ -0,0 +1,4 @@ +(define (nthPrime n) + (let nxtprm ((cnt 0) (ps (birdPrimes))) + (if (< cnt n) (nxtprm (+ cnt 1) ((cdr ps))) (car ps)))) +(nthPrime 1000000) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss new file mode 100644 index 0000000000..bcc5b06655 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-7.ss @@ -0,0 +1,32 @@ + ;;;; Stream Implementation + (define (head s) (car s)) + (define (tail s) ((cdr s))) + (define-syntax s-cons + (syntax-rules () ((s-cons h t) (cons h (lambda () t))))) + + ;;;; Stream Utility Functions + (define (from-By x s) + (s-cons x (from-By (+ x s) s))) + (define (take n s) + (cond + ((> n 1) (cons (head s) (take (- n 1) (tail s)))) + ((= n 1) (list (head s))) ;; don't force it too soon!! + (else ()))) ;; so (take 4 (s-map / (from-By 4 -1))) works + (define (drop n s) + (cond + ((> n 0) (drop (- n 1) (tail s))) + (else s))) + (define (s-map f s) + (s-cons (f (head s)) (s-map f (tail s)))) + (define (s-diff s1 s2) + (let ((h1 (head s1)) (h2 (head s2))) + (cond + ((< h1 h2) (s-cons h1 (s-diff (tail s1) s2 ))) + ((< h2 h1) (s-diff s1 (tail s2))) + (else (s-diff (tail s1) (tail s2)))))) + (define (s-union s1 s2) + (let ((h1 (head s1)) (h2 (head s2))) + (cond + ((< h1 h2) (s-cons h1 (s-union (tail s1) s2 ))) + ((< h2 h1) (s-cons h2 (s-union s1 (tail s2)))) + (else (s-cons h1 (s-union (tail s1) (tail s2))))))) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss new file mode 100644 index 0000000000..6f02ed0785 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-8.ss @@ -0,0 +1,20 @@ + ;;;; all primes' multiples are removed, merged through a tree of unions + ;;;; runs in ~ n^1.15 run time in producing n = 100K .. 1M primes + (define (primes-stream) + (define (mults p) (from-By (* p p) (* 2 p))) + (define (no-mults-From from) + (s-diff (from-By from 2) + (s-tree-join (s-map mults odd-primes)))) + (define odd-primes + (s-cons 3 (no-mults-From 5))) ;; inner feedback loop + (s-cons 2 (no-mults-From 3))) ;; result stream + + ;;;; join an ordered stream of streams (here, of primes' multiples) + ;;;; into one ordered stream, via an infinite right-deepening tree + (define (s-tree-join sts) ;; sts -> s + (define (join-With of-Tail sts) ;; sts -> s + (s-cons (head (head sts)) + (s-union (tail (head sts)) (of-Tail (tail sts))))) + (define (pairs sts) ;; sts -> sts + (s-cons (join-With head sts) (pairs (tail (tail sts))))) + (join-With (lambda (t) (s-tree-join (pairs t))) sts)) diff --git a/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss new file mode 100644 index 0000000000..b22e3fc6a4 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scheme/sieve-of-eratosthenes-9.ss @@ -0,0 +1,27 @@ +(define (treemergePrimes) + (define (mltpls p) + (define pm2 (* p 2)) + (let nxtmltpl ((cmpst (* p p))) + (cons cmpst (lambda () (nxtmltpl (+ cmpst pm2)))))) + (define (allmltpls ps) + (cons (mltpls (car ps)) (lambda () (allmltpls ((cdr ps)))))) + (define (merge xs ys) + (let ((x (car xs)) (xt (cdr xs)) (y (car ys)) (yt (cdr ys))) + (cond ((< x y) (cons x (lambda () (merge (xt) ys)))) + ((> x y) (cons y (lambda () (merge xs (yt))))) + (else (cons x (lambda () (merge (xt) (yt)))))))) + (define (pairs mltplss) + (let ((tl ((cdr mltplss)))) + (cons (merge (car mltplss) (car tl)) + (lambda () (pairs ((cdr tl))))))) + (define (mrgmltpls mltplss) + (cons (car (car mltplss)) + (lambda () (merge ((cdr (car mltplss))) + (mrgmltpls (pairs ((cdr mltplss)))))))) + (define (minusstrtat n cmps) + (if (< n (car cmps)) + (cons n (lambda () (minusstrtat (+ n 2) cmps))) + (minusstrtat (+ n 2) ((cdr cmps))))) + (define (cmpsts) (mrgmltpls (allmltpls (oddprms)))) ;; internal define's are mutually recursive + (define (oddprms) (cons 3 (lambda () (minusstrtat 5 (cmpsts))))) + (cons 2 (lambda () (oddprms)))) diff --git a/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab b/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab new file mode 100644 index 0000000000..665d1e6da8 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Scilab/sieve-of-eratosthenes.scilab @@ -0,0 +1,13 @@ + clear + n=99 + sieve=ones(1,n+2) + for i=2:n + if sieve(i) then + for j=i*2:i:n + sieve(j)=0 + end + end + end + for i=2:n + if sieve(i) then disp(i); end + end diff --git a/Task/Sieve-of-Eratosthenes/TI-83-BASIC/sieve-of-eratosthenes.ti-83 b/Task/Sieve-of-Eratosthenes/TI-83-BASIC/sieve-of-eratosthenes.ti-83 new file mode 100644 index 0000000000..7ed9f3b9fc --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/TI-83-BASIC/sieve-of-eratosthenes.ti-83 @@ -0,0 +1,20 @@ +Input "Limit:",N +N→Dim(L1) +For(I,2,N) +1→L1(I) +End +For(I,2,SQRT(N)) +If L1(I)=1 +Then +For(J,I*I,N,I) +0→L1(J) +End +End +End +For(I,2,N) +If L1(I)=1 +Then +Disp i +End +End +ClrList L1 diff --git a/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb b/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb new file mode 100644 index 0000000000..1dca87ec02 --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/VBScript/sieve-of-eratosthenes.vb @@ -0,0 +1,20 @@ + Dim sieve() + If WScript.Arguments.Count>=1 Then + n = WScript.Arguments(0) + Else + n = 99 + End If + ReDim sieve(n) + For i = 1 To n + sieve(i) = True + Next + For i = 2 To n + If sieve(i) Then + For j = i * 2 To n Step i + sieve(j) = False + Next + End If + Next + For i = 2 To n + If sieve(i) Then WScript.Echo i + Next diff --git a/Task/Sieve-of-Eratosthenes/Visual-Basic/sieve-of-eratosthenes.vb b/Task/Sieve-of-Eratosthenes/Visual-Basic/sieve-of-eratosthenes.vb new file mode 100644 index 0000000000..cbd8d0a6dd --- /dev/null +++ b/Task/Sieve-of-Eratosthenes/Visual-Basic/sieve-of-eratosthenes.vb @@ -0,0 +1,19 @@ +Sub Eratost() + Dim sieve() As Boolean + Dim n As Integer, i As Integer, j As Integer + n = InputBox("limit:", n) + ReDim sieve(n) + For i = 1 To n + sieve(i) = True + Next i + For i = 2 To n + If sieve(i) Then + For j = i * 2 To n Step i + sieve(j) = False + Next j + End If + Next i + For i = 2 To n + If sieve(i) Then Debug.Print i + Next i +End Sub 'Eratost diff --git a/Task/Simple-database/Bracmat/simple-database.bracmat b/Task/Simple-database/Bracmat/simple-database.bracmat new file mode 100644 index 0000000000..a6e89d34e1 --- /dev/null +++ b/Task/Simple-database/Bracmat/simple-database.bracmat @@ -0,0 +1,79 @@ + whl +' ( arg$:?command + & ( get'db + | (db=1)&lst$(db,db,NEW) + ) + & !command + : ( add + & :?name:?tag:?date + & whl + ' ( arg$:?argmnt + & arg$:?value + & (!argmnt.!value) + : ( (title|name.?name) + | (category|tag.?tag) + | (date.?date) + ) + ) + & ( !name:~ + & !tag:~ + & !date:~ + & ( !db:?*!tag^(?+(!date.!name)+?)*? + & out$"This record already exists" + | !tag^(!date.!name)*!db:?db + & lst$(db,db,NEW) + ) + | out$"invalid data" + ) + | latest + & :?date + & nothing found:?latest + & ( !db + : ? + * ?tag + ^ ( ? + + ( (>!date:?date.?name) + & (!name,!tag,!date):?latest + & ~ + ) + + ? + ) + * ? + | out$!latest + ) + | latest/category + & :?date:?latests:?latest + & ( !db + : ? + * ( ?tag + & !latests !latest:?latests + & :?latest:?date + ) + ^ ( ? + + ( (>!date:?date.?name) + & (!name,!tag,!date):?latest + & ~ + ) + + ? + ) + * ? + | !latests !latest:?latests&out$!latests + ) + | sorted + & 0:?sorted + & ( !db + : ? + * ?tag + ^ ( ? + + ( (?date.?name) + & (!date.!name,!tag,!date)+!sorted:?sorted + & ~ + ) + + ? + ) + * ? + | whl + ' (!sorted:(?.?row)+?sorted&out$!row) + ) + ) + ); diff --git a/Task/Simple-database/D/simple-database.d b/Task/Simple-database/D/simple-database.d index 0e0b050a3f..12ac842bec 100644 --- a/Task/Simple-database/D/simple-database.d +++ b/Task/Simple-database/D/simple-database.d @@ -12,7 +12,7 @@ private { if (item.length < 3) return printUsage(); auto db = load(); - const date = text(cast(DateTime)Clock.currTime); + const date = (cast(DateTime)Clock.currTime).toISOExtString; const cat = (item.length == 4) ? item[3] : "none"; db ~= Item(item[2], date, cat); store(db); diff --git a/Task/Simple-database/Java/simple-database.java b/Task/Simple-database/Java/simple-database.java new file mode 100644 index 0000000000..06ea8d5a2d --- /dev/null +++ b/Task/Simple-database/Java/simple-database.java @@ -0,0 +1,125 @@ +import java.io.*; +import java.text.*; +import java.util.*; + +public class SimpleDatabase { + + final static String filename = "simdb.csv"; + + public static void main(String[] args) { + if (args.length < 1 || args.length > 3) { + printUsage(); + return; + } + + switch (args[0].toLowerCase()) { + case "add": + addItem(args); + break; + case "latest": + printLatest(args); + break; + case "all": + printAll(); + break; + default: + printUsage(); + break; + } + } + + private static class Item implements Comparable{ + final String name; + final String date; + final String category; + + Item(String n, String d, String c) { + name = n; + date = d; + category = c; + } + + @Override + public int compareTo(Item item){ + return date.compareTo(item.date); + } + + @Override + public String toString() { + return String.format("%s,%s,%s%n", name, date, category); + } + } + + private static void addItem(String[] input) { + if (input.length < 2) { + printUsage(); + return; + } + List db = load(); + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + String date = sdf.format(new Date()); + String cat = (input.length == 3) ? input[2] : "none"; + db.add(new Item(input[1], date, cat)); + store(db); + } + + private static void printLatest(String[] a) { + List db = load(); + if (db.isEmpty()) { + System.out.println("No entries in database."); + return; + } + Collections.sort(db); + if (a.length == 2) { + for (Item item : db) + if (item.category.equals(a[1])) + System.out.println(item); + } else { + System.out.println(db.get(0)); + } + } + + private static void printAll() { + List db = load(); + if (db.isEmpty()) { + System.out.println("No entries in database."); + return; + } + Collections.sort(db); + for (Item item : db) + System.out.println(item); + } + + private static List load() { + List db = new ArrayList<>(); + try (Scanner sc = new Scanner(new File(filename))) { + while (sc.hasNext()) { + String[] item = sc.nextLine().split(","); + db.add(new Item(item[0], item[1], item[2])); + } + } catch (IOException e) { + System.out.println(e); + } + return db; + } + + private static void store(List db) { + try (FileWriter fw = new FileWriter(filename)) { + for (Item item : db) + fw.write(item.toString()); + } catch (IOException e) { + System.out.println(e); + } + } + + private static void printUsage() { + System.out.println("Usage:"); + System.out.println(" simdb cmd [categoryName]"); + System.out.println(" add add item, followed by optional category"); + System.out.println(" latest print last added item(s), followed by " + + "optional category"); + System.out.println(" all print all"); + System.out.println(" For instance: add \"some item name\" " + + "\"some category name\""); + } +} diff --git a/Task/Simple-database/REBOL/simple-database.rebol b/Task/Simple-database/REBOL/simple-database.rebol new file mode 100644 index 0000000000..5b93c7b416 --- /dev/null +++ b/Task/Simple-database/REBOL/simple-database.rebol @@ -0,0 +1,15 @@ +rebol [author: "Nick Antonaccio"] +write/append %rdb "" db: load %rdb +switch system/options/args/1 [ + "new" [write/append %rdb rejoin [now " " mold/only next system/options/args newline]] + "latest" [print copy/part tail sort/skip db 4 -4] + "latestcat" [ + foreach cat unique extract at db 3 4 [ + t: copy [] + foreach [a b c d] db [if c = cat [append t reduce [a b c d]]] + print copy/part tail sort/skip t 4 -4 + ] + ] + "sort" [probe sort/skip db 4] +] +halt diff --git a/Task/Simple-database/REXX/simple-database.rexx b/Task/Simple-database/REXX/simple-database.rexx new file mode 100644 index 0000000000..7e5752977e --- /dev/null +++ b/Task/Simple-database/REXX/simple-database.rexx @@ -0,0 +1,77 @@ +/* REXX --------------------------------------------------------------- +* 05.10.2014 +*--------------------------------------------------------------------*/ +x05='05'x +mydb='sidb.txt' +Say 'Enter your commands, ?, or end' +Do Forever + Parse Pull l + Parse Var l command text + Select + When command='?' Then + Call help + When command='add' Then Do + Parse Var text item ',' category ',' date + If date='' Then + date=date('S') /*yyyymmdd*/ + Say 'adding item' item'/'category 'dated' date + Call lineout mydb,date item x05 category + End + When command='latest' Then Do + Call lineout mydb + Parse Var text category + hidt='00000000' + ol='' + Do While lines(mydb)>0 + l=linein(mydb) + Parse Var l dt a (x05) b + If category=''|, + category='-' & b='' |, + b=category Then Do + If dt>>hidt Then Do + ol=l + hidt=dt + End + End + End + If ol>'' Then + Call o ol + Else + Say 'no matching item found' + End + When command='all' Then Do + Call lineout mydb + Parse Var text category + Do While lines(mydb)>0 + l=linein(mydb) + Parse Var l a (x05) b + If category=''|, + category='-' & b=''|, + b=category Then + Call o l + End + End + When command='end' Then + Leave + Otherwise Do + Say 'invalid command ('command')' + Call help + End + End + End +Say 'Bye' +Exit + +o: Parse Value arg(1) With dt text + Say left(dt,8) text + Return + +help: + Say 'add item[,[category][,date]] to add an item' + Say 'latest category to list the latest item of a category' + Say 'latest to list the latest item' + Say 'all category to list all items of a category' + Say 'all to list all items' + Say 'end to end this program' + Say 'Use category - to list items without category' + Return diff --git a/Task/Simple-database/Scala/simple-database.scala b/Task/Simple-database/Scala/simple-database.scala new file mode 100644 index 0000000000..3b4598d6f8 --- /dev/null +++ b/Task/Simple-database/Scala/simple-database.scala @@ -0,0 +1,38 @@ +object SimpleDatabase extends App { + type Entry = Array[String] + def asTSV(e: Entry) = e mkString "\t" + def fromTSV(s: String) = s split "\t" + val header = asTSV(Array("TIMESTAMP", "DESCRIPTION", "CATEGORY", "OTHER")) + + def read(filename: String) = try { + scala.io.Source.fromFile(filename).getLines.drop(1).map(fromTSV) + } catch { + case e: java.io.FileNotFoundException => Nil + } + + def write(filename: String, all: Seq[Entry]) = { + import java.nio.file.{Files,Paths} + import scala.collection.JavaConversions.asJavaIterable + Files.write(Paths.get(filename), asJavaIterable(header +: all.map(asTSV))) + all.size + } + + def add(filename: String, description: String, category: String = "none", optional: Seq[String] = Nil) { + val format = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss") + val e = Array(format.format(new java.util.Date), description, category) ++ optional + println(write(filename, read(filename).toBuffer :+ e) + " entries") + } + + def print(filename: String, filter: Seq[Entry] => TraversableOnce[Entry]) = + filter(read(filename).toList.sortBy(_.headOption)) map(_ mkString ",") foreach println + + args match { + case Array(f, "latest") => print(f, _ takeRight 1) + case Array(f, "latest", cat) => print(f, _ filter(_.lift(2) == Some(cat)) takeRight 1) + case Array(f, "all") => print(f, _.toSeq) + case Array(f, "all", "latest") => print(f, _ groupBy (_ lift 2 getOrElse "") map{case (_, cat) => cat.last}) + case Array(f, "add", desc) => add(f, desc, category = "") + case Array(f, "add", desc, cat, opt @ _*) => add(f, desc, cat, opt) + case _ => println("Usage: SimpleDatabase filename.tsv [all [latest]| latest [CATEGORY] | add [DESCRIPTION [CATEGORY [OPTIONAL]...]]]") + } +} diff --git a/Task/Simple-windowed-application/00DESCRIPTION b/Task/Simple-windowed-application/00DESCRIPTION index 892a2d2d13..7c687d9dc4 100644 --- a/Task/Simple-windowed-application/00DESCRIPTION +++ b/Task/Simple-windowed-application/00DESCRIPTION @@ -1 +1,2 @@ -This task asks to create a window with a label that says "There have been no clicks yet" and a button that says "click me". Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked. +This task asks to create a window with a label that says "There have been no clicks yet" and a button that says "click me". +Upon clicking the button with the mouse, the label should change and show the number of times the button has been clicked. diff --git a/Task/Simple-windowed-application/00META.yaml b/Task/Simple-windowed-application/00META.yaml index 04942ee47c..da9464e4c2 100644 --- a/Task/Simple-windowed-application/00META.yaml +++ b/Task/Simple-windowed-application/00META.yaml @@ -1,6 +1,7 @@ --- category: - Basic language learning +- Simple note: GUI requires: - Graphics diff --git a/Task/Simple-windowed-application/HicEst/simple-windowed-application.hicest b/Task/Simple-windowed-application/HicEst/simple-windowed-application-1.hicest similarity index 100% rename from Task/Simple-windowed-application/HicEst/simple-windowed-application.hicest rename to Task/Simple-windowed-application/HicEst/simple-windowed-application-1.hicest diff --git a/Task/Simple-windowed-application/HicEst/simple-windowed-application-2.hicest b/Task/Simple-windowed-application/HicEst/simple-windowed-application-2.hicest new file mode 100644 index 0000000000..11741903bc --- /dev/null +++ b/Task/Simple-windowed-application/HicEst/simple-windowed-application-2.hicest @@ -0,0 +1,31 @@ +import gui +$include "guih.icn" + +procedure main() + SimpleWindow().show_modal() +end + +class SimpleWindow : Dialog(label, button, count) + method component_setup() + self.set_attribs("size=222,139") + label := Label() + label.set_pos("24", "24") + label.set_internal_alignment("l") + label.set_label("There have been no clicks yet.") + self.add(label) + button := TextButton() + button.set_pos(24, 53) + button.set_label("click me") + button.set_internal_alignment("c") + button.connect(self, "incr", ACTION_EVENT) + self.add(button) + end + + method incr() + /count := 0 + label.set_label("There have been "||(count+:=1)||" clicks.") + end + + initially + self.Dialog.initially() +end diff --git a/Task/Simple-windowed-application/J/simple-windowed-application-1.j b/Task/Simple-windowed-application/J/simple-windowed-application-1.j new file mode 100644 index 0000000000..1258d7c145 --- /dev/null +++ b/Task/Simple-windowed-application/J/simple-windowed-application-1.j @@ -0,0 +1,20 @@ +SIMPLEAPP=: noun define +pc simpleApp; +cc inc button;cn "Click me"; +cc shownText static;cn "There have been no clicks yet."; +) + +simpleApp_run=: verb define + wd SIMPLEAPP + simpleApp_accum=: 0 NB. initialize accumulator + wd 'pshow;' +) + +simpleApp_inc_button=: verb define + wd 'set shownText text ','Button-use count: ',": simpleApp_accum=: >: simpleApp_accum +) + +simpleApp_close=: wd bind 'pclose' +simpleApp_cancel=: simpleApp_close + +simpleApp_run'' diff --git a/Task/Simple-windowed-application/J/simple-windowed-application.j b/Task/Simple-windowed-application/J/simple-windowed-application-2.j similarity index 100% rename from Task/Simple-windowed-application/J/simple-windowed-application.j rename to Task/Simple-windowed-application/J/simple-windowed-application-2.j diff --git a/Task/Simple-windowed-application/Perl-6/simple-windowed-application.pl6 b/Task/Simple-windowed-application/Perl-6/simple-windowed-application.pl6 new file mode 100644 index 0000000000..8bc722a2fe --- /dev/null +++ b/Task/Simple-windowed-application/Perl-6/simple-windowed-application.pl6 @@ -0,0 +1,21 @@ +use GTK::Simple; + +my GTK::Simple::App $app .= new(title => 'Simple Windowed Application'); + +$app.size_request(350, 100); + +$app.set_content( + GTK::Simple::VBox.new( + my $label = GTK::Simple::Label.new( text => 'There have been no clicks yet'), + my $button = GTK::Simple::Button.new(label => 'click me'), + ) +); + +$app.border_width = 40; + +$button.clicked.tap: { + state $clicks += 1; + $label.text = "There has been $clicks click{ 's' if $clicks != 1 }"; +} + +$app.run; diff --git a/Task/Simple-windowed-application/Scala/simple-windowed-application.scala b/Task/Simple-windowed-application/Scala/simple-windowed-application.scala index 28c671b18f..04a66a94f8 100644 --- a/Task/Simple-windowed-application/Scala/simple-windowed-application.scala +++ b/Task/Simple-windowed-application/Scala/simple-windowed-application.scala @@ -1,29 +1,22 @@ -import scala.swing._ -import scala.swing.event._ -import scala.swing.Swing._ +import scala.swing.{ BorderPanel, Button, Label, MainFrame, SimpleSwingApplication } +import scala.swing.event.ButtonClicked object SimpleApp extends SimpleSwingApplication { def top = new MainFrame { - var nClicks = 0 - - val button = new Button { - text = "click me" - } - val label = new Label { - text = "There have been no clicks yet" - } contents = new BorderPanel { + var nClicks = 0 + + val (button, label) = (new Button { text = "click me" }, + new Label { text = "There have been no clicks yet" }) + layout(button) = BorderPanel.Position.South layout(label) = BorderPanel.Position.Center - } - - preferredSize = ((300, 200): Dimension) - - listenTo(button) - reactions += { - case ButtonClicked(_) => - nClicks += 1 - label.text = "There have been %d clicks" format nClicks + listenTo(button) + reactions += { + case ButtonClicked(_) => + nClicks += 1 + label.text = s"There have been ${nClicks} clicks" + } } } } diff --git a/Task/Simulate-input-Keyboard/00DESCRIPTION b/Task/Simulate-input-Keyboard/00DESCRIPTION index 59a70a86d5..6cb948c0a2 100644 --- a/Task/Simulate-input-Keyboard/00DESCRIPTION +++ b/Task/Simulate-input-Keyboard/00DESCRIPTION @@ -1,2 +1,17 @@ +{{omit from|ACL2}} +{{omit from|Batch File}} +{{omit from|Brainf***}} +{{omit from|Maxima}} {{Omit From|Modula-3}} -Send simulated keystrokes to a GUI window, or terminal. You should specify whether the target may be externally created (i.e., if the keystrokes are going to an application other than the application that is creating them). +{{omit from|PARI/GP}} +{{omit from|PHP}} +{{omit from|PostScript}} +{{omit from|R}} +{{omit from|Retro}} +{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} +{{omit from|zkl} + +Send simulated keystrokes to a GUI window, or terminal. +You should specify whether the target may be externally created +(i.e., if the keystrokes are going to an application +other than the application that is creating them). diff --git a/Task/Simulate-input-Keyboard/Python/simulate-input-keyboard.py b/Task/Simulate-input-Keyboard/Python/simulate-input-keyboard.py new file mode 100644 index 0000000000..60bdfaef46 --- /dev/null +++ b/Task/Simulate-input-Keyboard/Python/simulate-input-keyboard.py @@ -0,0 +1,10 @@ +>>> import pyautogui +>>> pyautogui.typewrite('Hello world!') # prints out "Hello world!" instantly +>>> pyautogui.typewrite('Hello world!', interval=0.25) # prints out "Hello world!" with a quarter second delay after each character +>>> pyautogui.press('enter') # press the Enter key +>>> pyautogui.press('f1') # press the F1 key +>>> pyautogui.press('left') # press the left arrow key +>>> pyautogui.keyDown('shift') # hold down the shift key +>>> pyautogui.press('left') # press the left arrow key +>>> pyautogui.keyUp('shift') # release the shift key +>>> pyautogui.hotkey('ctrl', 'shift', 'esc') diff --git a/Task/Simulate-input-Keyboard/Scala/simulate-input-keyboard.scala b/Task/Simulate-input-Keyboard/Scala/simulate-input-keyboard.scala index e56d2d43e9..716c6c52c8 100644 --- a/Task/Simulate-input-Keyboard/Scala/simulate-input-keyboard.scala +++ b/Task/Simulate-input-Keyboard/Scala/simulate-input-keyboard.scala @@ -1,20 +1,26 @@ import java.awt.Robot import java.awt.event.KeyEvent +/** Keystrokes when this function is executed will go to whatever application has focus at the time. + * Special cases may need to be made for certain symbols, but most of + * the VK values in KeyEvent map to the ASCII values of characters. + */ + object Keystrokes extends App { - def Keystroke(str: String) { - val robot = new Robot(); - for (ch <- str.toCharArray()) { + def keystroke(str: String) { + val robot = new Robot() + for (ch <- str) { if (Character.isUpperCase(ch)) { - robot.keyPress(KeyEvent.VK_SHIFT); - robot.keyPress(ch); - robot.keyRelease(ch); - robot.keyRelease(KeyEvent.VK_SHIFT); + robot.keyPress(KeyEvent.VK_SHIFT) + robot.keyPress(ch) + robot.keyRelease(ch) + robot.keyRelease(KeyEvent.VK_SHIFT) } else { - val upCh = Character.toUpperCase(ch); - robot.keyPress(upCh); - robot.keyRelease(upCh); + val upCh = Character.toUpperCase(ch) + robot.keyPress(upCh) + robot.keyRelease(upCh) } } } + keystroke(args(0)) } diff --git a/Task/Simulate-input-Mouse/Scala/simulate-input-mouse.scala b/Task/Simulate-input-Mouse/Scala/simulate-input-mouse.scala new file mode 100644 index 0000000000..065cf531c3 --- /dev/null +++ b/Task/Simulate-input-Mouse/Scala/simulate-input-mouse.scala @@ -0,0 +1,4 @@ + val (p , robot)= (component.location, new Robot()) + robot.mouseMove(p.getX().toInt, p.getY().toInt) //you may want to move a few pixels closer to the center by adding to these values + robot.mousePress(InputEvent.BUTTON1_MASK) //BUTTON1_MASK is the left button + robot.mouseRelease(InputEvent.BUTTON1_MASK) diff --git a/Task/Singleton/00DESCRIPTION b/Task/Singleton/00DESCRIPTION index a8644a830c..c7ef791dfd 100644 --- a/Task/Singleton/00DESCRIPTION +++ b/Task/Singleton/00DESCRIPTION @@ -1 +1,2 @@ -A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance. +A Global Singleton is a class of which only one instance exists within a program. +Any attempt to use non-static members of the class involves performing operations on this one instance. diff --git a/Task/Singleton/Smalltalk/singleton.st b/Task/Singleton/Smalltalk/singleton.st new file mode 100644 index 0000000000..85ec696c9b --- /dev/null +++ b/Task/Singleton/Smalltalk/singleton.st @@ -0,0 +1,4 @@ +SomeClass class>>sharedInstance + + SharedInstance ifNil: [SharedInstance := self basicNew initialize]. + ^ SharedInstance diff --git a/Task/Singly-linked-list-Element-definition/Clojure/singly-linked-list-element-definition.clj b/Task/Singly-linked-list-Element-definition/Clojure/singly-linked-list-element-definition.clj new file mode 100644 index 0000000000..c9c2f8cc5c --- /dev/null +++ b/Task/Singly-linked-list-Element-definition/Clojure/singly-linked-list-element-definition.clj @@ -0,0 +1 @@ +(cons 1 (cons 2 (cons 3 nil))) ; =>(1 2 3) diff --git a/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj b/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj index 0ce2e8a5fe..a388c0fac6 100644 --- a/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj +++ b/Task/Singly-linked-list-Traversal/Clojure/singly-linked-list-traversal.clj @@ -1 +1 @@ -(doseq [x xs] (println x) +(doseq [x xs] (println x)) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp index b061b4bdfe..277dc7e915 100644 --- a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-2.lisp @@ -1,3 +1 @@ -(loop for ref = list then (rest ref) - until (null ref) - do (print (first ref))) +(loop for x in list do (print x)) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-3.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-3.lisp new file mode 100644 index 0000000000..ff2b2af59e --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-3.lisp @@ -0,0 +1 @@ +(mapc #'print list) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-4.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-4.lisp new file mode 100644 index 0000000000..73497ff38c --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-4.lisp @@ -0,0 +1 @@ +(map nil #'print list) diff --git a/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-5.lisp b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-5.lisp new file mode 100644 index 0000000000..b061b4bdfe --- /dev/null +++ b/Task/Singly-linked-list-Traversal/Common-Lisp/singly-linked-list-traversal-5.lisp @@ -0,0 +1,3 @@ +(loop for ref = list then (rest ref) + until (null ref) + do (print (first ref))) diff --git a/Task/Singly-linked-list-Traversal/NewLISP/singly-linked-list-traversal.newlisp b/Task/Singly-linked-list-Traversal/NewLISP/singly-linked-list-traversal.newlisp new file mode 100644 index 0000000000..def2ff8661 --- /dev/null +++ b/Task/Singly-linked-list-Traversal/NewLISP/singly-linked-list-traversal.newlisp @@ -0,0 +1,2 @@ +(dolist (x '(a b c d e)) + (println x)) diff --git a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 index c182b358a2..dfbbbeaa21 100644 --- a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 +++ b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-1.pl6 @@ -1,5 +1,5 @@ my $list = 1 => 2 => 3 => 4 => 5 => 6 => Mu; -loop (my $l = $list; $l; $l = $l.value) { +loop (my $l = $list; $l; $l.=value) { say $l.key; } diff --git a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 index 12193eaa8b..56c0ac8f37 100644 --- a/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 +++ b/Task/Singly-linked-list-Traversal/Perl-6/singly-linked-list-traversal-2.pl6 @@ -1,7 +1,7 @@ use MONKEY_TYPING; augment class Pair { method traverse () { - gather loop (my $l = self; $l; $l = $l.value) { + gather loop (my $l = self; $l; $l.=value) { take $l.key; } } diff --git a/Task/Sleep/360-Assembly/sleep.360 b/Task/Sleep/360-Assembly/sleep.360 new file mode 100644 index 0000000000..dc7ad8cbd3 --- /dev/null +++ b/Task/Sleep/360-Assembly/sleep.360 @@ -0,0 +1,106 @@ + START + PRINT DATA,GEN + YREGS , REGISTER EQUATES (e.g. 0 = R0) +SLEEP CSECT +SLEEP AMODE 31 addressing mode 31 bit +SLEEP RMODE ANY loader determines 31 or 24 +*********************************************************************** +* REENTRANT. Logically swap out a task for a number of seconds +* specified in PARM. Minimum 0, maximum 60 seconds +* +* MVS rexx (the original rexx) does not have a sleep function. This +* program can be called from rexx, assuming this program is in +* LINKLIST, as follows: +* +* /* rexx */ +* wait_time = '6' /* number of seconds to sleep */ +* say 'Sleeping...' +* address LINKMVS "SLEEP wait_time" /* invoke SLEEP */ +* say 'Awake! +*********************************************************************** +PROLOG BAKR R14,0 satck caller's registers + LR R4,R1 save parm pointer + LR R12,R15 entry point addr to R12 + USING SLEEP,R12 tell assembler about that + B AROUND avoid abend S0C1 + DC C'SLEEP ' CSECT NAME + DC C'C=2014.05.10 ' CHANGE DATE + DC C'A=&SYSDATE ' ASSEMBLY DATE + DC C'T=&SYSTIME ' CHANGE TIME + DC C'MarcvdM. ' PROGRAMMER NAME +AROUND L R10,0(0,R4) load parm address in R10 + XR R15,R15 clear R15 + LH R15,0(0,R10) load parm length in R15 + LR R6,R15 save length in R6 + LTR R15,R15 parm length 0? + BZ NOPARM yes, exit before getmain + C R6,F2 parmlength > 2 ? + BH NOPARM yes, exit before getmain + STORAGE OBTAIN,LENGTH=WALEN,LOC=ANY get some storage + LR R9,R1 address of storage in R9 + USING WAREAX,R9 base for data section (DSECT) + MVC EYECAT,=C'**MARC**' make storage easy to find in dump + MVC SECONDS,C00 set field to F0F0 + C R6,F1 parmlength = 1? + BNE COPYSECS no, copy both bytes + MVC SECONDS+1(1),2(R10) yes, just copy one byte. + B TRTEST +COPYSECS MVC SECONDS,2(R10) +* test supplied parameter for valid integer values +TRTEST TRT SECONDS(1),VALINT6 first parm byte no higher as 6? + BNZ NOPARM_REL higher, release storage and return + TRT SECONDS+1(1),VALINT9 second byte valid? + BNZ NOPARM_REL no, release storage and return + CLC SECONDS(1),=C'6' first parm byte < 6? + BNE DOWAIT yes, do wait + CLC SECONDS+1(1),=C'0' first eq. 6, second > 0? + BNE NOPARM_REL yes, release storage and return +DOWAIT DS 0H + MVC WAWTO(DWTOL),DWTO copy WTO list form to obtained st. + MVC WAWTO+18(2),SECONDS copy in nr. of seconds + WTO MF=(E,WAWTO) issue WTO, execute form + MVC HOURS,C00 zero out hours + MVC MINUTS,C00 and minutes + MVC REST,C00 and milliseconds + STIMER WAIT,DINTVL=TIMEVAL SVC 47: logical swap out (sleep) + B EXIT done +NOPARM_REL DS 0H + STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage + LA R15,4 set return code 4 + B RETURN return to caller +EXIT DS 0H + STORAGE RELEASE,ADDR=(R9),LENGTH=WALEN free obtained storage + WTO ' Awake!',ROUTCDE=11 fixed wake-up string +NOPARM EQU * +RETURN PR , return to caller +* +* -------------------------------------------------------------------- +* CONSTANTS +* -------------------------------------------------------------------- +DWTO WTO ' Sleeping... (XX seconds)',ROUTCDE=11,MF=L +DWTOL EQU *-DWTO length of WTO list form +F1 DC F'1' +F2 DC F'2' +C00 DC C'00' +VALINT6 DC 256XL1'01' + ORG *-16 +VALOK6 DC 7XL1'00' F0-F6: OFFSETS 240-246 +VALINT9 DC 256XL1'01' + ORG *-16 +VALOK9 DC 10XL1'00' F0-F9: OFFSETS 240-249 + DS 0D + LTORG , FORCE DISPLACEMENT LITERALS +* -------------------------------------------------------------------- +* DSECT (data section) +* -------------------------------------------------------------------- +WAREAX DSECT , +WAWTO DS CL(DWTOL) reentrant WTO area +EYECAT DS CL8 +TIMEVAL DS 0CL8 +HOURS DS CL2 will be zeroed +MINUTS DS CL2 will be zeroed +SECONDS DS CL2 from parm +REST DS CL2 will be zeroed +WALEN EQU *-WAREAX length of DSECT +* -------------------------------------------------------------------- + END SLEEP diff --git a/Task/Sleep/ALGOL-68/sleep.alg b/Task/Sleep/ALGOL-68/sleep.alg new file mode 100644 index 0000000000..cda9106e74 --- /dev/null +++ b/Task/Sleep/ALGOL-68/sleep.alg @@ -0,0 +1,8 @@ +# using ping to sleep # +INT milliseconds = read int; # ping uses milliseconds # +print ("Sleeping..."); +VOID (system ("ping 0.0.0.1 -n 1 -w " + whole (milliseconds, 0) + " >NUL")); +# 0.0.0.1 is an invalid IP address and cannot be used, so this will never conflict with a real IP address # +# ping -n gives number of tries, -w timeout, and >NUL deletes output so the user does not see it # +print (new line); +print ("Awake!") diff --git a/Task/Sleep/Perl/sleep-3.pl b/Task/Sleep/Perl/sleep-3.pl new file mode 100644 index 0000000000..d0bbb80ce4 --- /dev/null +++ b/Task/Sleep/Perl/sleep-3.pl @@ -0,0 +1,3 @@ +say "Sleeping..."; +select undef, undef, undef, 0.5; +say "Awake!"; diff --git a/Task/Sleep/REXX/sleep.rexx b/Task/Sleep/REXX/sleep-1.rexx similarity index 59% rename from Task/Sleep/REXX/sleep.rexx rename to Task/Sleep/REXX/sleep-1.rexx index 893e9906a7..8d788e9384 100644 --- a/Task/Sleep/REXX/sleep.rexx +++ b/Task/Sleep/REXX/sleep-1.rexx @@ -1,6 +1,7 @@ -/*REXX program to sleep x seconds (base in the argument). */ +/*REXX program sleeps X seconds (the # of seconds supplied by the arg.*/ parse arg secs . /*get a (possible) argument. */ secs=word(secs 0,1) /*if not present, assume 0 (zero)*/ say 'Sleeping' secs "seconds." /*tell 'em what's happening. */ -call delay(secs) /*snooze. Hopefully, a short nap*/ +call delay secs /*snooze. Hopefully, a short nap*/ say 'Awake!' /*and tell 'em we're running. */ + /*stick a fork in it, we're done.*/ diff --git a/Task/Sleep/REXX/sleep-2.rexx b/Task/Sleep/REXX/sleep-2.rexx new file mode 100644 index 0000000000..445985625b --- /dev/null +++ b/Task/Sleep/REXX/sleep-2.rexx @@ -0,0 +1,54 @@ +/*REXX program delays (or SLEEPS) a number of whole seconds. */ +trace off /*suppress REXX error msgs.*/ +parse arg ! /*obtain all the arguments.*/ +if !all(arg()) then exit /*documentation requested? */ +if !cms then address '' /*if CMS, use fast cmd path*/ +signal on halt /*handle HALT gracefully.*/ +signal on noValue /*handle REXX noValue error*/ +signal on syntax /*handle REXX syntax errors*/ + +/*┌────────────────────────────────────────────────────────────────────┐ +┌─┘ The DELAY function is used to delay (wait) a specific amount of └─┐ +│ (wall-clock) time specified in seconds. Any fraction part is ignored.│ +│ │ +│ If the REXX program invoking DELAY function is running under PC/REXX │ +│ or Personal REXX, this REXX program should never be invoked as those │ +└─┐ REXXes have their own built-in function (BIF) named "DELAY". ┌─┘ + └────────────────────────────────────────────────────────────────────┘*/ + +@cpsleep = 'CP SLEEP' /*point to (CP) SLEEP cmd*/ +@ping = 'PING' /*point to the DOS PING cmd*/ + +parse var ! n _ /*parse argument from parms*/ +if _\=='' | arg()>1 then call er 59 /*are there too many args? */ +if n=='' then n=1 /*no arg? Then assume 1 sec*/ +if \isNum(n) then call er 53,n 'delay-seconds' /*is n numeric? */ +n=n%1 /*elide any fractional part*/ +if n<=0 then return 0 + /* ┌────────────────────┐ */ + /* │ delay n seconds. │ */ + /* └────────────────────┘ */ + select + when !cms then @cpsleep n%1 "SEC" /*CMS? Use CP SLEEP*/ + when !tso then call sleep n%1 /*TSO? Use SLEEP*/ + when !regina then call sleep n%1 /*Regina? Use SLEEP*/ + when !dos then @ping '-n' n "127.0.0.1 > NUL" /*DOS? use PING */ + otherwise nop + end /*select*/ + +return 0 /*return a zero value. */ + +/*═════════════════════════════general 1-line subroutines═══════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════════*/ +!all: !!=!;!=space(!);upper !;call !fid;!nt=right(!var('OS'),2)=='NT';!cls=word('CLS VMFCLEAR CLRSCREEN',1+!cms+!tso*2);if arg(1)\==1 then return 0;if wordpos(!,'? ?SAMPLES ?AUTHOR ?FLOW')==0 then return 0;!call=']$H';call '$H' !fn !;!call=;return 1 +!cal: if symbol('!CALL')\=="VAR" then !call=; return !call +!env: !env='ENVIRONMENT'; if !sys=='MSDOS' | !brexx | !r4 | !roo then !env='SYSTEM'; if !os2 then !env='OS2'!env; !ebcdic=1=='f0'x; if !crx then !env='DOS'; return +!fid: parse upper source !sys !fun !fid . 1 . . !fn !ft !fm .; call !sys; if !dos then do; _=lastpos('\',!fn); !fm=left(!fn,_); !fn=substr(!fn,_+1); parse var !fn !fn '.' !ft; end; return word(0 !fn !ft !fm, 1+('0'arg(1))) +!rex: parse upper version !ver !vernum !verdate .; !brexx='BY'==!vernum; !kexx='KEXX'==!ver; !pcrexx='REXX/PERSONAL'==!ver | 'REXX/PC'==!ver; !r4='REXX-R4'==!ver; !regina='REXX-REGINA'==left(!ver,11); !roo='REXX-ROO'==!ver; call !env; return +!sys: !cms=!sys=='CMS'; !os2=!sys=='OS2'; !tso=!sys=='TSO' | !sys=='MVS'; !vse=!sys=='VSE'; !dos=pos('DOS',!sys)\==0 | pos('WIN',!sys)\==0 | !sys=='CMD'; !crx=left(!sys,6)=='DOSCRX'; call !rex; return +!var: call !fid; if !kexx then return space(dosenv(arg(1))); return space(value(arg(1),,!env)) +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 +p: return word(arg(1),1) +halt: call er .1 +isNum: return datatype(arg(1),'N') +noValue: !sigl=sigl; call er 17,!fid(2) !fid(3) !sigl condition('D') sourceline(!sigl) +syntax: !sigl=sigl; call er 13,!fid(2) !fid(3) !sigl !cal() condition('D') sourceline(!sigl) diff --git a/Task/Sleep/RapidQ/sleep.rapidq b/Task/Sleep/RapidQ/sleep.rapidq new file mode 100644 index 0000000000..989161259f --- /dev/null +++ b/Task/Sleep/RapidQ/sleep.rapidq @@ -0,0 +1,4 @@ +input "Enter the number of seconds to sleep: ";s +sleep s +print "I'm awake I think..." +input "Press enter to quit";a$ diff --git a/Task/Sleep/Scala/sleep.scala b/Task/Sleep/Scala/sleep.scala index 66cf544d4d..5a8f7b12aa 100644 --- a/Task/Sleep/Scala/sleep.scala +++ b/Task/Sleep/Scala/sleep.scala @@ -1,9 +1,8 @@ -import java.util.Scanner - -object Sleeper extends Application { - val input = new Scanner(System.in) - val ms = input.nextInt - System.out.println("Sleeping...") - Thread.sleep(ms) - System.out.println("Awake!") +object Sleeper extends App { + print("Enter sleep time in milli sec: ") + val ms = scala.io.StdIn.readInt() + println("Sleeping...") + val sleepStarted = scala.compat.Platform.currentTime + Thread.sleep(ms) + println(s"Awaked after [${scala.compat.Platform.currentTime - sleepStarted} ms]1") } diff --git a/Task/Sockets/Scala/sockets.scala b/Task/Sockets/Scala/sockets.scala new file mode 100644 index 0000000000..2dd89bc583 --- /dev/null +++ b/Task/Sockets/Scala/sockets.scala @@ -0,0 +1,13 @@ +import java.net.Socket + +object sendSocketData { + + def sendData(host: String, msg: String) { + val sock = new Socket(host, 256) + sock.getOutputStream().write(msg.getBytes()) + sock.getOutputStream().flush() + sock.close() + } + + sendData("localhost", "hello socket world") +} diff --git a/Task/Sokoban/C++/sokoban-1.cpp b/Task/Sokoban/C++/sokoban-1.cpp index b876d477cf..1bd2c4ac09 100644 --- a/Task/Sokoban/C++/sokoban-1.cpp +++ b/Task/Sokoban/C++/sokoban-1.cpp @@ -21,24 +21,18 @@ public: int w = 0; vector data; - for(; iter != end; ++iter) - { + for(; iter != end; ++iter){ data.push_back((*iter)[1]); w = max(w, (*iter)[1].length()); } - for(int v = 0; v < data.size(); ++v) - { + for(int v = 0; v < data.size(); ++v){ vector sTemp, dTemp; - for(int u = 0; u < w; ++u) - { - if(u > data[v].size()) - { + for(int u = 0; u < w; ++u){ + if(u > data[v].size()){ sTemp.push_back(' '); dTemp.push_back(' '); - } - else - { + }else{ char s = ' ', d = ' ', c = data[v][u]; if(c == '#') @@ -46,13 +40,11 @@ public: else if(c == '.' || c == '*' || c == '+') s = '.'; - if(c == '@' || c == '+') - { + if(c == '@' || c == '+'){ d = '@'; px = u; py = v; - } - else if(c == '$' || c == '*') + }else if(c == '$' || c == '*') d = '*'; sTemp.push_back(s); @@ -111,32 +103,26 @@ public: dirs[2] = make_tuple(0, 1, 'd', 'D'); dirs[3] = make_tuple(-1, 0, 'l', 'L'); - while(open.size() > 0) - { + while(open.size() > 0){ vector> temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop(); - for(int i = 0; i < 4; ++i) - { + for(int i = 0; i < 4; ++i){ temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]); - if(temp[y+dy][x+dx] == '*') - { - if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())) - { + if(temp[y+dy][x+dx] == '*'){ + if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } - } - else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())) - { + }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); diff --git a/Task/Sokoban/D/sokoban-1.d b/Task/Sokoban/D/sokoban-1.d index 4d180f3337..f8d92ce3fd 100644 --- a/Task/Sokoban/D/sokoban-1.d +++ b/Task/Sokoban/D/sokoban-1.d @@ -9,7 +9,7 @@ const struct Board { private immutable CTable sData, dData; private immutable int playerx, playery; - this(in string[] board) pure nothrow const + this(in string[] board) immutable pure nothrow @safe in { foreach (const row; board) { assert(row.length == board[0].length, @@ -18,8 +18,10 @@ const struct Board { assert(c.inPattern(" #.$@*"), "Not valid input"); } } body { - immutable sMap = [' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; - immutable dMap = [' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; + /*static*/ immutable sMap = + [' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; + /*static*/ immutable dMap = + [' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; ncols = board[0].length; int plx = 0, ply = 0; @@ -43,12 +45,12 @@ const struct Board { private bool move(in int x, in int y, in int dx, in int dy, ref CTable data) - const pure /*nothrow*/ { - if (sData[(y+dy) * ncols + x + dx] == El.wall || - data[(y+dy) * ncols + x + dx] != El.floor) + const pure nothrow /*@safe*/ { + if (sData[(y + dy) * ncols + x + dx] == El.wall || + data[(y + dy) * ncols + x + dx] != El.floor) return false; - auto data2 = data.dup; // Not nothrow. + auto data2 = data.dup; data2[y * ncols + x] = El.floor; data2[(y + dy) * ncols + x + dx] = El.player; data = data2.assumeUnique; // Not enforced. @@ -57,39 +59,40 @@ const struct Board { private bool push(in int x, in int y, in int dx, in int dy, ref CTable data) - const pure /*nothrow*/ { - if (sData[(y + 2*dy) * ncols + x+2*dx] == El.wall || - data[(y + 2*dy) * ncols + x+2*dx] != El.floor) + const pure nothrow /*@safe*/ { + if (sData[(y + 2 * dy) * ncols + x + 2 * dx] == El.wall || + data[(y + 2 * dy) * ncols + x + 2 * dx] != El.floor) return false; - auto data2 = data.dup; // Not nothrow. + auto data2 = data.dup; data2[y * ncols + x] = El.floor; data2[(y + dy) * ncols + x + dx] = El.player; - data2[(y + 2*dy) * ncols + x + 2*dx] = El.boxOnGoal; + data2[(y + 2 * dy) * ncols + x + 2*dx] = El.boxOnGoal; data = data2.assumeUnique; // Not enforced. return true; } - private bool isSolved(in CTable data) const pure nothrow { + private bool isSolved(in CTable data) + const pure nothrow @safe @nogc { foreach (immutable i, immutable d; data) if ((sData[i] == El.goal) != (d == El.boxOnGoal)) return false; return true; } - string solve() pure { + string solve() pure nothrow /*@safe*/ { bool[immutable CTable] visitedSet = [dData: true]; alias Four = Tuple!(CTable, string, int, int); GrowableCircularQueue!Four open; open.push(Four(dData, "", playerx, playery)); - immutable dirs = [tuple( 0, -1, 'u', 'U'), - tuple( 1, 0, 'r', 'R'), - tuple( 0, 1, 'd', 'D'), - tuple(-1, 0, 'l', 'L')]; + static immutable dirs = [tuple( 0, -1, 'u', 'U'), + tuple( 1, 0, 'r', 'R'), + tuple( 0, 1, 'd', 'D'), + tuple(-1, 0, 'l', 'L')]; - while (open.length) { + while (!open.empty) { //immutable (cur, cSol, x, y) = open.pop; immutable item = open.pop; immutable cur = item[0]; @@ -107,14 +110,13 @@ const struct Board { if (push(x, y, dx, dy, temp) && temp !in visitedSet) { if (isSolved(temp)) return cSol ~ di[3]; - open.push(Four(temp, cSol ~ di[3], x+dx, y+dy)); + open.push(Four(temp, cSol ~ di[3], x + dx, y + dy)); visitedSet[temp] = true; } - } else if (move(x, y, dx, dy, temp) && - temp !in visitedSet) { + } else if (move(x, y, dx, dy, temp) && temp !in visitedSet) { if (isSolved(temp)) return cSol ~ di[2]; - open.push(Four(temp, cSol ~ di[2], x+dx, y+dy)); + open.push(Four(temp, cSol ~ di[2], x + dx, y + dy)); visitedSet[temp] = true; } } @@ -126,7 +128,7 @@ const struct Board { void main() { import std.stdio, core.memory; - GC.disable; // Uses about twice the memory + GC.disable; // Uses about twice the memory. immutable level = "####### @@ -138,6 +140,6 @@ void main() { #.# @# #######"; - const b = const(Board)(level.splitLines); + immutable b = immutable(Board)(level.splitLines); writeln(level, "\n\n", b.solve); } diff --git a/Task/Sokoban/D/sokoban-2.d b/Task/Sokoban/D/sokoban-2.d index 5bf8ab8226..13e9949a08 100644 --- a/Task/Sokoban/D/sokoban-2.d +++ b/Task/Sokoban/D/sokoban-2.d @@ -13,15 +13,15 @@ struct State { // Variable length struct. State* prev, next, qNext; CellIndex[0] c_; - CellIndex get(in size_t i) inout pure nothrow { + CellIndex get(in size_t i) inout pure nothrow @nogc { return c_.ptr[i]; } - void set(in size_t i, in CellIndex v) pure nothrow { + void set(in size_t i, in CellIndex v) pure nothrow @nogc { c_.ptr[i] = v; } - CellIndex[] slice(in size_t i, in size_t j) pure nothrow { + CellIndex[] slice(in size_t i, in size_t j) pure nothrow @nogc return { return c_.ptr[i .. j]; } } @@ -35,8 +35,8 @@ __gshared State*[] buckets; __gshared Thash hashSize, fillLimit, filled; -State* newState(State* parent) nothrow { - static State* nextOf(State *s) nothrow { +State* newState(State* parent) nothrow @nogc { + static State* nextOf(State *s) nothrow @nogc { return cast(State*)(cast(ubyte*)s + stateSize); } @@ -64,14 +64,14 @@ State* newState(State* parent) nothrow { } -void unNewState(State* p) nothrow { +void unNewState(State* p) nothrow @nogc { p.next = blockHead; blockHead = p; } /// Mark up positions where a box definitely should not be. -void markLive(in size_t c) nothrow { +void markLive(in size_t c) nothrow @nogc { immutable y = c / w; immutable x = c % w; if (live[c]) @@ -93,8 +93,8 @@ void markLive(in size_t c) nothrow { } -State* parseBoard(in size_t y, in size_t x, in char* s) nothrow { - static T[] myCalloc(T)(in size_t n) nothrow { +State* parseBoard(in size_t y, in size_t x, in char* s) nothrow @nogc { + static T[] myCalloc(T)(in size_t n) nothrow @nogc { auto ptr = cast(T*)calloc(n, T.sizeof); if (ptr == null) exit(1); @@ -150,7 +150,7 @@ State* parseBoard(in size_t y, in size_t x, in char* s) nothrow { /// K&R hash function. -void hash(State* s, in size_t nBoxes) pure nothrow { +void hash(State* s, in size_t nBoxes) pure nothrow @nogc { if (!s.h) { Thash ha = 0; foreach (immutable i; 0 .. nBoxes + 1) @@ -160,7 +160,7 @@ void hash(State* s, in size_t nBoxes) pure nothrow { } -void extendTable() nothrow { +void extendTable() nothrow @nogc { int oldSize = hashSize; if (!oldSize) { @@ -194,7 +194,7 @@ void extendTable() nothrow { } -State* lookup(State *s) nothrow { +State* lookup(State *s) nothrow @nogc { s.hash(nBoxes); auto f = buckets[s.h & (hashSize - 1)]; for (; f; f = f.next) { @@ -206,7 +206,7 @@ State* lookup(State *s) nothrow { } -bool addToTable(State* s) nothrow { +bool addToTable(State* s) nothrow @nogc { if (s.lookup) { s.unNewState; return false; @@ -223,7 +223,7 @@ bool addToTable(State* s) nothrow { } -bool success(in State* s) nothrow { +bool success(in State* s) nothrow @nogc { foreach (immutable i; 1 .. nBoxes + 1) if (!goals[s.get(i)]) return false; @@ -231,7 +231,7 @@ bool success(in State* s) nothrow { } -State* moveMe(State* s, in int dy, in int dx) nothrow { +State* moveMe(State* s, in int dy, in int dx) nothrow @nogc { immutable int y = s.get(0) / w; immutable int x = s.get(0) % w; immutable int y1 = y + dy; @@ -284,7 +284,7 @@ State* moveMe(State* s, in int dy, in int dx) nothrow { } -bool queueMove(State *s) nothrow { +bool queueMove(State *s) nothrow @nogc { if (!s || !s.addToTable) return false; @@ -300,7 +300,7 @@ bool queueMove(State *s) nothrow { } -bool doMove(State* s) nothrow { +bool doMove(State* s) nothrow @nogc { return s.moveMe( 1, 0).queueMove || s.moveMe(-1, 0).queueMove || s.moveMe( 0, 1).queueMove || @@ -308,7 +308,7 @@ bool doMove(State* s) nothrow { } -void showBoard(in State* s) nothrow { +void showBoard(in State* s) nothrow @nogc { static immutable glyphs1 = " #@$", glyphs2 = ".#@$"; auto ptr = cast(ubyte*)alloca(w * h * ubyte.sizeof); @@ -329,19 +329,21 @@ void showBoard(in State* s) nothrow { } -void showMoves(in State* s) nothrow { +void showMoves(in State* s) nothrow @nogc { if (s.prev) s.prev.showMoves; "\n".printf; s.showBoard; } +int main() nothrow @nogc { + // Workaround for @nogc. + alias ctEval(alias expr) = expr; -int main() nothrow { enum uint problem = 0; static if (problem == 0) { - auto s = parseBoard(8, 7, + auto s = parseBoard(8, 7, ctEval!( "#######"~ "# #"~ "# #"~ @@ -349,18 +351,18 @@ int main() nothrow { "#. $$ #"~ "#.$$ #"~ "#.# @#"~ - "#######"); + "#######")); } else static if (problem == 1) { - auto s = parseBoard(5, 13, + auto s = parseBoard(5, 13, ctEval!( "#############"~ "# # #"~ "# $$$$$$$ @#"~ "#....... #" - "#############"); + "#############")); } else static if (problem == 2) { - auto s = parseBoard(11, 19, + auto s = parseBoard(11, 19, ctEval!( " ##### "~ " # # "~ " # # "~ @@ -371,7 +373,7 @@ int main() nothrow { "# $ $ ..#"~ "##### ### #@## .#"~ " # #########"~ - " ####### "); + " ####### ")); } else { asset(0, "Not present problem."); } diff --git a/Task/Sokoban/Haskell/sokoban.hs b/Task/Sokoban/Haskell/sokoban.hs new file mode 100644 index 0000000000..5fcbb518c5 --- /dev/null +++ b/Task/Sokoban/Haskell/sokoban.hs @@ -0,0 +1,132 @@ +import Control.Monad (liftM) +import Data.Array +import Data.List (transpose) +import Data.Maybe (mapMaybe) +import qualified Data.Sequence as Seq +import qualified Data.Set as Set +import Prelude hiding (Left, Right) + +data Field = Space | Wall | Goal + deriving (Eq) + +data Action = Up | Down | Left | Right | PushUp | PushDown | PushLeft | PushRight + +instance Show Action where + show Up = "u" + show Down = "d" + show Left = "l" + show Right = "r" + show PushUp = "U" + show PushDown = "D" + show PushLeft = "L" + show PushRight = "R" + +type Index = (Int, Int) +type FieldArray = Array Index Field +type BoxArray = Array Index Bool +type PlayerPos = Index +type GameState = (BoxArray, PlayerPos) +type Game = (FieldArray, GameState) + +toField :: Char -> Field +toField '#' = Wall +toField ' ' = Space +toField '@' = Space +toField '$' = Space +toField '.' = Goal +toField '+' = Goal +toField '*' = Goal + +toPush :: Action -> Action +toPush Up = PushUp +toPush Down = PushDown +toPush Left = PushLeft +toPush Right = PushRight +toPush n = n + +toMove :: Action -> Index +toMove PushUp = ( 0, -1) +toMove PushDown = ( 0, 1) +toMove PushLeft = (-1, 0) +toMove PushRight = ( 1, 0) +toMove n = toMove $ toPush n + +-- Parse the string-based game board into an easier-to-use format. +-- Assume that the board is valid (rectangular, one player, etc). +parseGame :: [String] -> Game +parseGame fieldStrs = (field, (boxes, player)) + where + width = length $ head fieldStrs + height = length fieldStrs + bound = ((0, 0), (width - 1, height - 1)) + flatField = concat $ transpose fieldStrs + charField = listArray bound flatField + field = fmap toField charField + boxes = fmap (`elem` "$*") charField + player = fst $ head $ filter (flip elem "@+" . snd) $ assocs charField + +add :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b) +add (a, b) (x, y) = (a + x, b + y) + +-- Attempt to perform an action, returning the updated game and adjusted +-- action if the action was legal. +tryAction :: Game -> Action -> Maybe (Game, Action) +tryAction (field, (boxes, player)) action + | field ! vec == Wall = Nothing + | boxes ! vec = + if boxes ! vecB || field ! vecB == Wall + then Nothing + else Just ((field, (boxes // [(vec, False), (vecB, True)], vec)), + toPush action) + | otherwise = Just ((field, (boxes, vec)), action) + where + actionVec = toMove action + vec = player `add` actionVec + vecB = vec `add` actionVec + +-- Search the game for a solution. +solveGame :: Game -> Maybe [Action] +solveGame (field, initState) = + liftM reverse $ bfs (Seq.singleton (initState, [])) (Set.singleton initState) + where + goals = map fst $ filter ((== Goal) . snd) $ assocs field + isSolved st = all (st !) goals + possibleActions = [Up, Down, Left, Right] + + -- Breadth First Search of the game tree. + bfs :: Seq.Seq (GameState, [Action]) -> Set.Set GameState -> Maybe [Action] + bfs queue visited = + case Seq.viewl queue of + Seq.EmptyL -> Nothing + (game@(boxes, _), actions) Seq.:< queueB -> + if isSolved boxes + then Just actions + else + let newMoves = filter (flip Set.notMember visited . fst) $ + map (\((_, g), a) -> (g, a)) $ + mapMaybe (tryAction (field, game)) possibleActions + visitedB = foldl (flip Set.insert) visited $ + map fst newMoves + queueC = foldl (Seq.|>) queueB $ + map (\(g, a) -> (g, a:actions)) newMoves + in bfs queueC visitedB + +exampleA :: [String] +exampleA = + ["#######" + ,"# #" + ,"# #" + ,"#. # #" + ,"#. $$ #" + ,"#.$$ #" + ,"#.# @#" + ,"#######"] + +main :: IO () +main = + case solveGame $ parseGame exampleA of + Nothing -> putStrLn "Unsolvable" + Just solution -> do + mapM_ putStrLn exampleA + putStrLn "" + putStrLn $ concatMap show solution diff --git a/Task/Sokoban/Ruby/sokoban-1.rb b/Task/Sokoban/Ruby/sokoban-1.rb new file mode 100644 index 0000000000..9b0fdd217f --- /dev/null +++ b/Task/Sokoban/Ruby/sokoban-1.rb @@ -0,0 +1,63 @@ +require 'set' + +class Sokoban + def initialize(level) + board = level.each_line.map(&:chomp) + @nrows = board.map(&:size).max + board = board.map{|line| line.ljust(@nrows)} + board.each_with_index do |row, r| + row.each_char.with_index do |ch, c| + @px, @py = c, r if ch == '@' or ch == '+' + end + end + goal = board.join.tr(' .@#$+*', ' . ..') + @goal = goal.each_char.with_index.select{|ch, c| ch == '.'}.map(&:last) + @data = board.join.tr(' .@#$+*', ' @#$ $') + end + + def pos(x, y) + y * @nrows + x + end + + def push(x, y, dx, dy, data) + return data if data[pos(x+2*dx, y+2*dy)] != ' ' + data[pos(x , y )] = ' ' + data[pos(x + dx, y + dy)] = '@' + data[pos(x+2*dx, y+2*dy)] = '$' + data + end + + def solved?(data) + @goal.all?{|i| data[i] == '$'} + end + + DIRS = [[0, -1, 'u', 'U'], [ 1, 0, 'r', 'R'], [0, 1, 'd', 'D'], [-1, 0, 'l', 'L']] + def solve + open = [[@data, "", @px, @py]] + visited = Set[@data] + + until open.empty? + cur, csol, x, y = open.shift + + for dx, dy, cmove, cpush in DIRS + temp = cur.dup + ps = pos(x+dx, y+dy) + if temp[ps] == '$' + temp = push(x, y, dx, dy, temp) + next if visited.include?(temp) + visited.add(temp) + return csol + cpush if solved?(temp) + open << [temp, csol + cpush, x+dx, y+dy] + else + next if @data[ps] == '#' or temp[ps] != ' ' + temp[pos(x, y)] = ' ' + temp[ps] = '@' + next if visited.include?(temp) + visited.add(temp) + open << [temp, csol + cmove, x+dx, y+dy] + end + end + end + "No solution" + end +end diff --git a/Task/Sokoban/Ruby/sokoban-2.rb b/Task/Sokoban/Ruby/sokoban-2.rb new file mode 100644 index 0000000000..900f1b0609 --- /dev/null +++ b/Task/Sokoban/Ruby/sokoban-2.rb @@ -0,0 +1,11 @@ +level = < Success +hidato path = + test path inner + & domain inner 1 40 + & allDifferent inner + & andFD [x `near` y | x <- cells, y <- cells] + & labeling [] (concat path) + where + andFD = solve . foldr1 (#/\#) + cells = enumerate path + inner free + +near :: (Int,Int,Int) -> (Int,Int,Int) -> Constraint +(x,rx,cx) `near` (y,ry,cy) = x #<=# y #/\# dist (y -# x) + #\/# x #># y #/\# dist (x -# y) + #\/# x #=# 0 + #\/# y #=# 0 + where + dist d = abs (rx - ry) #<=# d + #/\# abs (cx - cy) #<=# d + +enumerate :: [[Int]] -> [(Int,Int,Int)] +enumerate xss = [(x,row,col) | (xs,row) <- xss `zip` [1..] + , (x ,col) <- xs `zip` [1..] + ] + +test [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ,[ 0, A, 33, 35, B, C, 0, 0, 0, 0] + ,[ 0, D, E, 24, 22, F, 0, 0, 0, 0] + ,[ 0, G, H, I, 21, J, K, 0, 0, 0] + ,[ 0, L, 26, M, 13, 40, 11, 0, 0, 0] + ,[ 0, 27, N, O, P, 9, Q, 1, 0, 0] + ,[ 0, 0, 0, R, S, 18, T, U, 0, 0] + ,[ 0, 0, 0, 0, 0, V, 7, W, X, 0] + ,[ 0, 0, 0, 0, 0, 0, 0, 5, Y, 0] + ,[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] + ] + [ A, 33, 35, B, C + , D, E, 24, 22, F + , G, H, I, 21, J, K + , L, 26, M, 13, 40, 11 + , 27, N, O, P, 9, Q, 1 + , R, S, 18, T, U + , V, 7, W, X + , 5, Y + ] = success + +main = unpack hidato 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 a908d6971e..41ff56c65f 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 @@ -13,7 +13,7 @@ struct Hidato { Pos[] known; bool[] flood; - this(in string input) @safe pure + this(in string input) pure @safe in { assert(!input.strip.empty); } out { @@ -80,12 +80,12 @@ struct Hidato { } - private Pos idx(in size_t r, in size_t c) const pure nothrow { + private Pos idx(in size_t r, in size_t c) const pure nothrow @safe @nogc { return r * nCols + c; } private uint nNeighbors(in Pos pos, ref Pos[8] neighbours) - const pure nothrow { + const pure nothrow @safe @nogc { immutable r = pos / nCols; immutable c = pos % nCols; typeof(return) n = 0; @@ -110,7 +110,7 @@ struct Hidato { /// Fill all free cells around 'cell' with true and write /// output to variable "flood". - private void floodFill(in Pos pos) pure nothrow { + private void floodFill(in Pos pos) pure nothrow @safe @nogc { Pos[8] n = void; // For all neighbours. @@ -124,7 +124,7 @@ struct Hidato { } /// Check all empty cells are reachable from higher known cells. - private bool checkConnectity(in uint lowerBound) pure nothrow { + private bool checkConnectity(in uint lowerBound) pure nothrow @safe @nogc { flood[] = false; foreach (immutable i; lowerBound + 1 .. boardMax + 1) @@ -139,7 +139,7 @@ struct Hidato { return true; } - private bool fill(in Pos pos, in uint n) pure nothrow { + private bool fill(in Pos pos, in uint n) pure nothrow @safe @nogc { if ((board[pos] && board[pos] != n) || (known[n] && known[n] != pos)) return false; @@ -162,7 +162,7 @@ struct Hidato { return false; } - void solve() pure nothrow + void solve() pure nothrow @safe @nogc in { assert(!known.empty); } body { diff --git a/Task/Solve-a-Hidato-puzzle/Java/solve-a-hidato-puzzle.java b/Task/Solve-a-Hidato-puzzle/Java/solve-a-hidato-puzzle.java new file mode 100644 index 0000000000..964ca3f336 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Java/solve-a-hidato-puzzle.java @@ -0,0 +1,105 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class Hidato { + + private static int[][] board; + private static int[] given, start; + + public static void main(String[] args) { + String[] input = {"_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _"}; + + setup(input); + printBoard(); + System.out.println("\nFound:"); + solve(start[0], start[1], 1, 0); + printBoard(); + } + + private static void setup(String[] input) { + /* This task is not about input validation, so + we're going to trust the input to be valid */ + + String[][] puzzle = new String[input.length][]; + for (int i = 0; i < input.length; i++) + puzzle[i] = input[i].split(" "); + + int nCols = puzzle[0].length; + int nRows = puzzle.length; + + List list = new ArrayList<>(nRows * nCols); + + board = new int[nRows + 2][nCols + 2]; + for (int[] row : board) + for (int c = 0; c < nCols + 2; c++) + row[c] = -1; + + for (int r = 0; r < nRows; r++) { + String[] row = puzzle[r]; + for (int c = 0; c < nCols; c++) { + String cell = row[c]; + switch (cell) { + case "_": + board[r + 1][c + 1] = 0; + break; + case ".": + break; + default: + int val = Integer.parseInt(cell); + board[r + 1][c + 1] = val; + list.add(val); + if (val == 1) + start = new int[]{r + 1, c + 1}; + } + } + } + Collections.sort(list); + given = new int[list.size()]; + for (int i = 0; i < given.length; i++) + given[i] = list.get(i); + } + + private static boolean solve(int r, int c, int n, int next) { + if (n > given[given.length - 1]) + return true; + + if (board[r][c] != 0 && board[r][c] != n) + return false; + + if (board[r][c] == 0 && given[next] == n) + return false; + + int back = board[r][c]; + if (back == n) + next++; + + board[r][c] = n; + for (int i = -1; i < 2; i++) + for (int j = -1; j < 2; j++) + if (solve(r + i, c + j, n + 1, next)) + return true; + + board[r][c] = back; + return false; + } + + private static void printBoard() { + for (int[] row : board) { + for (int c : row) { + if (c == -1) + System.out.print(" . "); + else + System.out.printf(c > 0 ? "%2d " : "__ ", c); + } + System.out.println(); + } + } +} diff --git a/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 b/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 index a57ea26e7f..67ebafa2e5 100644 --- a/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 +++ b/Task/Solve-a-Hidato-puzzle/Perl-6/solve-a-hidato-puzzle.pl6 @@ -1,72 +1,98 @@ -my @grid; -my @known; +my @adjacent = [-1, -1], [-1, 0], [-1, 1], + [ 0, -1], [ 0, 1], + [ 1, -1], [ 1, 0], [ 1, 1]; -sub show_board() { - my $width = $*max.chars; - for @grid -> $r { - say do for @$r { - when Rat { ' ' x $width } - when 0 { '_' x $width } - default { .fmt("%{$width}d") } - } - } -} +solveboard q:to/END/; + __ 33 35 __ __ .. .. .. + __ __ 24 22 __ .. .. .. + __ __ __ 21 __ __ .. .. + __ 26 __ 13 40 11 .. .. + 27 __ __ __ 9 __ 1 .. + .. .. __ __ 18 __ __ .. + .. .. .. .. __ 7 __ __ + .. .. .. .. .. .. 5 __ + END -sub neighbors($y,$x --> List) { - gather for [-1, -1], [-1, 0], [-1, 1], - [ 0, -1], [ 0, 1], - [ 1, -1], [ 1, 0], [ 1, 1] - { - my $y1 = $y + .[0]; - my $x1 = $x + .[1]; - take [$y1,$x1] if defined @grid[$y1][$x1]; - } -} +sub solveboard($board) { + my $max = +$board.comb(/\w+/); + my $width = $max.chars; -sub try_fill($v, $coord [$y,$x] --> Bool) { - return True if $v > $*max; - - my $old = @grid[$y][$x]; - - return False if $old and $old != $v; - return False if @known[$v] and @known[$v] !eqv $coord; - - @grid[$y][$x] = $v; - print "\e[0H"; - show_board(); - - for neighbors($y, $x) { - return True if try_fill $v + 1, $_; - } - - @grid[$y][$x] = $old; - return False; -} - -sub hidato($board) { - my $*max = [max] +«$board.comb(/\d+/); + my @grid; + my @known; + my @neigh; + my @degree; @grid = $board.lines.map: -> $line { - [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] + [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] } + + sub neighbors($y,$x --> List) { + eager gather for @adjacent { + my $y1 = $y + .[0]; + my $x1 = $x + .[1]; + take [$y1,$x1] if defined @grid[$y1][$x1]; + } + } + for ^@grid -> $y { - for ^@grid[$y] -> $x { - if @grid[$y][$x] -> $v { - @known[$v] = [$y,$x]; - } - } + for ^@grid[$y] -> $x { + if @grid[$y][$x] -> $v { + @known[$v] = [$y,$x]; + } + if @grid[$y][$x].defined { + @neigh[$y][$x] = neighbors($y,$x); + @degree[$y][$x] = +@neigh[$y][$x]; + } + } } print "\e[0H\e[0J"; - try_fill 1, @known[1]; -} -hidato q:to/END/; - __ 33 35 __ __ .. .. .. - __ __ 24 22 __ .. .. .. - __ __ __ 21 __ __ .. .. - __ 26 __ 13 40 11 .. .. - 27 __ __ __ 9 __ 1 .. - .. .. __ __ 18 __ __ .. - .. .. .. .. __ 7 __ __ - .. .. .. .. .. .. 5 __ - END + my $tries = 0; + + try_fill 1, @known[1]; + + sub try_fill($v, $coord [$y,$x] --> Bool) { + return True if $v > $max; + $tries++; + + my $old = @grid[$y][$x]; + + return False if $old and $old != $v; + return False if @known[$v] and @known[$v] !eqv $coord; + + @grid[$y][$x] = $v; # conjecture grid value + + print "\e[0H"; # show conjectured board + for @grid -> $r { + say do for @$r { + when Rat { ' ' x $width } + when 0 { '_' x $width } + default { .fmt("%{$width}d") } + } + } + + + my @neighbors = @neigh[$y][$x][]; + + my @degrees; + for @neighbors -> \n [$yy,$xx] { + my $d = --@degree[$yy][$xx]; # conjecture new degrees + push @degrees[$d], n; # and categorize by degree + } + + for @degrees.grep(*.defined) -> @ties { + for @ties.reverse { # reverse works better for this hidato anyway + return True if try_fill $v + 1, $_; + } + } + + for @neighbors -> [$yy,$xx] { + ++@degree[$yy][$xx]; # undo degree conjectures + } + + @grid[$y][$x] = $old; # undo grid value conjecture + return False; + } + + say "$tries tries"; +} diff --git a/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx b/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx index b3617e4710..e4cfe2c04b 100644 --- a/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx +++ b/Task/Solve-a-Hidato-puzzle/REXX/solve-a-hidato-puzzle.rexx @@ -1,9 +1,11 @@ /*REXX pgm solves a Hidato or Numbrix puzzle, displays puzzle & solution*/ -maxr=0; maxc=0; maxx=0; minr=9e9; minc=9e9; minx=9e9; cells=0; @.= +maxr=0; maxc=0; maxx=0; minr=9e9; minc=9e9; minx=9e9; cells=0; @.= parse arg xxx; PZ='Hidato puzzle' /*get cell definitions from C.L. */ +xxx=translate(xxx, , "/\;:_", ',') /*also allow other chars as comma*/ + do while xxx\=''; parse var xxx r c marks ',' xxx do while marks\=''; _=@.r.c - parse var marks x marks + parse var marks x marks if datatype(x,'N') then do; x=x/1 /*normalize X*/ if x<0 then PZ='Numbrix puzzle' x=abs(x) /*use │x│ */ @@ -23,8 +25,9 @@ Nr = '0 1 0 -1 -1 1 1 -1' /*possible row for the next move.*/ Nc = '1 0 -1 0 1 -1 1 -1' /* " col " " " " */ pMoves=words(Nr) -4*(left(PZ,1)=='N') /*is this to be a Numbrix puzzle?*/ do i=1 for pMoves; Nr.i=word(Nr,i); Nc.i=word(Nc,i); end /*fast moves*/ -if \next(2,!r,!c) then call err 'No solution possible.' -say; say 'A solution for the' PZ "exists."; say; call showGrid +if \next(2,!r,!c) then say 'No solution possible for this' PZ "puzzle." + else say 'A solution for the' PZ "exists." +say; call showGrid exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────ERR subroutine──────────────────────*/ err: say; say '***error!*** (from' PZ"): " arg(1); say; exit 13 @@ -48,8 +51,8 @@ return 0 /*This ain't working. */ showGrid: if maxr<1 | maxc<1 then call err 'no legal cell was specified.' if minx<1 then call err 'no 1 was specified for the puzzle start' if maxx\==cells then call err 'no' cells "was specified for the puzzle end" -w=length(maxx); do r=maxr to minr by -1; _= +w=length(cells); do r=maxr to minr by -1; _= do c=minc to maxc; _=_ right(@.r.c,w); end /*c*/ say _ end /*r*/ -return +say; return 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-1.rkt similarity index 100% rename from Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle.rkt rename to Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle-1.rkt diff --git a/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle-2.rkt b/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle-2.rkt new file mode 100644 index 0000000000..f999586830 --- /dev/null +++ b/Task/Solve-a-Hidato-puzzle/Racket/solve-a-hidato-puzzle-2.rkt @@ -0,0 +1,19 @@ +#lang racket +(require "hidato-family-solver.rkt") + +(define moore-neighbour-offsets + '((+1 0) (-1 0) (0 +1) (0 -1) (+1 +1) (-1 -1) (-1 +1) (+1 -1))) + +(define solve-hidato (solve-hidato-family moore-neighbour-offsets)) + +(displayln + (puzzle->string + (solve-hidato + #(#( 0 33 35 0 0) + #( 0 0 24 22 0) + #( 0 0 0 21 0 0) + #( 0 26 0 13 40 11) + #(27 0 0 0 9 0 1) + #( _ _ 0 0 18 0 0) + #( _ _ _ _ 0 7 0 0) + #( _ _ _ _ _ _ 5 0))))) diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb index 964737282b..9c6529f7a7 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-1.rb @@ -1,65 +1,55 @@ # Solve a Hidato Puzzle # -# Nigel_Galloway -# May 5th., 2012. -class Cell - def initialize(row=0, col=0, value=nil) - @adj = [[row-1,col-1],[row,col-1],[row+1,col-1],[row-1,col],[row+1,col],[row-1,col+1],[row,col+1],[row+1,col+1]] - @t = false - $zbl[value] = true unless value.nil? - @value = value - end - def try(value=1) - return false if @value.nil? - return true if value > $end - return false if @t - return false if @value > 0 and @value != value - return false if @value == 0 and $zbl[value] - @t = true - @adj.each do |x,y| - if $board[x][y].try(value+1) - @value = value - return true - end - end - @t = false - end - attr_reader :value -end - class Hidato + Cell = Struct.new(:value, :used, :adj) + ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] + def initialize(board, pout=true) - $end = 0 - $zbl = [] - $board = [] - board.each_line.with_index do |line, x| - $board << line.split.each_with_index.map do |n,y| - begin - n = Integer(n) - @sx, @sy = x, y if n == 1 # start position - $end += 1 - Cell.new(x, y, n) - rescue - Cell.new # frame (Sentinel value) + @board = [] + board.each_line do |line| + @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil] + end + @board << [] # frame (Sentinel value : nil) + @board.each_with_index do |row, x| + row.each_with_index do |cell, y| + if cell + @sx, @sy = x, y if cell.value==1 # start position + cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]} end end end - @xmax = $board.size - 2 - @ymax = $board[1].size - 2 - printout('Problem:') if pout + @xmax = @board.size - 1 + @ymax = @board.map(&:size).max - 1 + @end = @board.flatten.compact.size + puts to_s('Problem:') if pout end + def solve - if $board[@sx][@sy].try(1) - printout('Solution:') - else - puts "no solution" - end + @zbl = Array.new(@end+1, false) + @board.flatten.compact.each{|cell| @zbl[cell.value] = true} + puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution") end - def printout(msg=nil) - puts msg if msg - (1..@xmax).each do |x| - puts (1..@ymax).map{|y| "%3s" % $board[x][y].value}.join + + def try(cell, seq_num) + return true if seq_num > @end + return false if cell.used + value = cell.value + return false if value > 0 and value != seq_num + return false if value == 0 and @zbl[seq_num] + cell.used = true + cell.adj.each do |x, y| + if try(@board[x][y], seq_num+1) + cell.value = seq_num + return true + end end - puts + cell.used = false + end + + def to_s(msg=nil) + str = (0...@xmax).map do |x| + (0...@ymax).map{|y| "%3s" % ((c=@board[x][y]) ? c.value : c)}.join + end + (msg ? [msg] : []) + str + [""] end end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb index 675ade4603..e6aa35721b 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-2.rb @@ -1,35 +1,29 @@ # Which may be used as follows to solve Evil Case 1: board1 = < $end - return false if @t - return false if @value > 0 and @value != value - return false if @value == 0 and $zbl[value] - @t = true - h = Hash.new - @adj.each_with_index do |(x,y), n| - cell = $board[x][y] - h[cell.wdof*10+n] = cell if cell.value +class HLPsolver + attr_reader :board + Cell = Struct.new(:value, :used, :adj) + + def initialize(board, pout=true) + @board = [] + frame = ADJACENT.flatten.map(&:abs).max + board.each_line do |line| + @board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]*frame end - h.sort.each do |key, cell| - if (cell.try(value+1)) - @value = value + frame.times {@board << []} # frame (Sentinel value : nil) + @board.each_with_index do |row, x| + row.each_with_index do |cell, y| + if cell + @sx, @sy = x, y if cell.value==1 # start position + cell.adj = ADJACENT.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]} + end + end + end + @xmax = @board.size - frame + @ymax = @board.map(&:size).max - frame + @end = @board.flatten.compact.size + @format = " %#{@end.to_s.size}s" + puts to_s('Problem:') if pout + end + + def solve + @zbl = Array.new(@end+1, false) + @board.flatten.compact.each{|cell| @zbl[cell.value] = true} + puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution") + end + + def try(cell, seq_num) + value = cell.value + return false if value > 0 and value != seq_num + return false if value == 0 and @zbl[seq_num] + cell.used = true + if seq_num == @end + cell.value = seq_num + return true + end + a = [] + cell.adj.each_with_index do |(x, y), n| + cl = @board[x][y] + a << [wdof(cl.adj)*10+n, x, y] unless cl.used + end + a.sort.each do |key, x, y| + if try(@board[x][y], seq_num+1) + cell.value = seq_num return true end end - @t = false + cell.used = false end - def wdon - (@value.nil? or @value > 0 or @t) ? 0 : 1 + + def wdof(adj) + adj.count {|x,y| not @board[x][y].used} end - def wdof - @adj.inject(0){|res, (x,y)| res += $board[x][y].wdon} + + def to_s(msg=nil) + str = (0...@xmax).map do |x| + (0...@ymax).map{|y| @format % ((c=@board[x][y]) ? c.value : c)}.join + end + (msg ? [msg] : []) + str + [""] end - attr_reader :value end diff --git a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb index 21928b6013..e558211c82 100644 --- a/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb +++ b/Task/Solve-a-Hidato-puzzle/Ruby/solve-a-hidato-puzzle-4.rb @@ -1,16 +1,46 @@ -rows = 8 -cols = 8 -$end = 40 -$zbl = Array.new($end+1,false) -$board = [[Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], - [Cell[], Cell[1,1,0] ,Cell[1,2,33] ,Cell[1,3,35] ,Cell[1,4,0] ,Cell[1,5,0] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], - [Cell[], Cell[2,1,0] ,Cell[2,2,0] ,Cell[2,3,24] ,Cell[2,4,22] ,Cell[2,5,0] ,Cell[] ,Cell[] ,Cell[] ,Cell[]], - [Cell[], Cell[3,1,0] ,Cell[3,2,0] ,Cell[3,3,0] ,Cell[3,4,21] ,Cell[3,5,0] ,Cell[3,6,0] ,Cell[] ,Cell[] ,Cell[]], - [Cell[], Cell[4,1,0] ,Cell[4,2,26] ,Cell[4,3,0] ,Cell[4,4,13] ,Cell[4,5,40] ,Cell[4,6,11] ,Cell[] ,Cell[] ,Cell[]], - [Cell[], Cell[5,1,27] ,Cell[5,2,0] ,Cell[5,3,0] ,Cell[5,4,0] ,Cell[5,5,9] ,Cell[5,6,0] ,Cell[5,7,1] ,Cell[] ,Cell[]], - [Cell[], Cell[] ,Cell[] ,Cell[6,3,0] ,Cell[6,4,0] ,Cell[6,5,18] ,Cell[6,6,0] ,Cell[6,7,0] ,Cell[] ,Cell[]], - [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[7,5,0] ,Cell[7,6,7] ,Cell[7,7,0] ,Cell[7,8,0] ,Cell[]], - [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[8,7,5] ,Cell[8,8,0] ,Cell[]], - [Cell[], Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[] ,Cell[]]] +require 'HLPsolver' -test(rows, cols, 5, 7) +ADJACENT = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] + +# solve Evil Case 1: +board1 = < max(given) then + solved := TRUE; + elsif board[r][c] = 0 and n not in given or board[r][c] = n then + back := board[r][c]; + board[r][c] := n; + for i range -1 to 1 until solved do + for j range -1 to 1 until solved do + solved := solve(r + i, c + j, n + 1); + end for; + end for; + if not solved then + board[r][c] := back; + end if; + end if; + end func; + +const proc: printBoard is func + local + var integer: r is 0; + var integer: c is 0; + begin + for key r range board do + for c range board[r] do + if c = -1 then + write(" . "); + elsif c > 0 then + write(c lpad 2 <& " "); + else + write("__ "); + end if; + end for; + writeln; + end for; + end func; + +const proc: main is func + local + const array string: input is [] ("_ 33 35 _ _ . . .", + "_ _ 24 22 _ . . .", + "_ _ _ 21 _ _ . .", + "_ 26 _ 13 40 11 . .", + "27 _ _ _ 9 _ 1 .", + ". . _ _ 18 _ _ .", + ". . . . _ 7 _ _", + ". . . . . . 5 _"); + begin + setup(input); + printBoard; + writeln; + if solve(startRow, startColumn, 1) then + writeln("Found:"); + printBoard; + end if; + end func; diff --git a/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp b/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp index ab8b1867f7..ffe8f8b2c5 100644 --- a/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp +++ b/Task/Sort-an-array-of-composite-structures/C++/sort-an-array-of-composite-structures.cpp @@ -1,56 +1,28 @@ -#include #include #include +#include -template class less_member -{ -public: - less_member(MemberType Struct::*m): - member(m) - { - } - bool operator()(Struct const& s1, Struct const& s2) const - { - return s1.*member < s2.*member; - } -private: - MemberType Struct::*const member; -}; - -template - less_member make_less_member(MemberType Struct::* m) -{ - return m; -} - -template - void sort_for_member(FwdIter first, FwdIter last, MemberPtrType m) -{ - std::sort(first, last, make_less_member(m)); -} - -struct entry -{ +struct entry { std::string name; std::string value; }; -int main() -{ - entry array[] = { { "grass", "green" }, - { "snow", "white" }, - { "sky", "blue" }, - { "cherry", "red" } }; - std::cout << "before sorting:\n\n"; - for (int i = 0; i < 4; ++i) - std::cout << "index: " << i << ", name: " << array[i].name - << ", value: " << array[i].value << "\n"; +int main() { + entry array[] = { { "grass", "green" }, { "snow", "white" }, + { "sky", "blue" }, { "cherry", "red" } }; - sort_for_member(array, array+4, &entry::name); + std::cout << "Before sorting:\n"; + for (const auto &e : array) { + std::cout << "{" << e.name << ", " << e.value << "}\n"; + } - std::cout << "\nafter sorting:\n\n"; - for (int i = 0; i < 4; ++i) - std::cout << "index: " << i << ", name: " << array[i].name - << ", value: " << array[i].value << "\n"; - return 0; + std::sort(std::begin(array), std::end(array), + [](const entry & a, const entry & b) { + return a.name < b.name; + }); + + std::cout << "After sorting:\n"; + for (const auto &e : array) { + std::cout << "{" << e.name << ", " << e.value << "}\n"; + } } diff --git a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py index 52985061da..f468e2d44d 100644 --- a/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py +++ b/Task/Sort-an-array-of-composite-structures/Python/sort-an-array-of-composite-structures-3.py @@ -1,3 +1,3 @@ from operator import itemgetter people = [(120, 'joe'), (31, 'foo'), (51, 'bar')] -people.sort(key=itemgetter(0)) +people.sort(key=itemgetter(1)) diff --git a/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb b/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb index 4e8eb16efa..9b924416d7 100644 --- a/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb +++ b/Task/Sort-an-array-of-composite-structures/Ruby/sort-an-array-of-composite-structures.rb @@ -1,6 +1,11 @@ -Person = Struct.new(:name,:value) +Person = Struct.new(:name,:value) do + def to_s; "name:#{name}, value:#{value}" end +end + list = [Person.new("Joe",3), Person.new("Bill",4), Person.new("Alice",20), Person.new("Harry",3)] -list.sort_by{|x|x.name} +puts list.sort_by{|x|x.name} +puts +puts list.sort_by(&:value) 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 index c1ab32459d..02457cf7ab 100644 --- 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 @@ -1,6 +1,7 @@ -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) +case class Pair(name:String, value:Double) +val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855)) +input.sortBy(_.name) // Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855)) -//Result: -// Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855)) +// alternative versions: +input.sortBy(struct => (struct.name, struct.value)) // additional sort field (name first, then value) +input.sortWith((a,b) => a.name.compareTo(b.name) < 0) // arbitrary comparison function diff --git a/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp b/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp index a0e37276ad..090eb6de91 100644 --- a/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp +++ b/Task/Sort-an-integer-array/C++/sort-an-integer-array-1.cpp @@ -3,6 +3,6 @@ int main() { int nums[] = {2,4,3,1,2}; - std::sort(nums, nums+5); + std::sort(nums, nums+sizeof(nums)/sizeof(int)); return 0; } diff --git a/Task/Sort-an-integer-array/Frink/sort-an-integer-array.frink b/Task/Sort-an-integer-array/Frink/sort-an-integer-array.frink new file mode 100644 index 0000000000..d87622f9f9 --- /dev/null +++ b/Task/Sort-an-integer-array/Frink/sort-an-integer-array.frink @@ -0,0 +1,2 @@ +a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0] +sort[a] diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx index 5e7c7316a8..bfe0b35540 100644 --- a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-1.rexx @@ -1,47 +1,37 @@ -/*REXX program to sort (E-sort) an array (which contains integers). */ - numeric digits 30 /*handle larger numbers.*/ - a.1= 1 - a.2= 0 - a.3= -1 - a.4= 0 - a.5= 5 - a.6= 0 - a.7= -61 - a.8= 0 - a.9= 1385 -a.10= 0 -a.11= -50521 -a.12= 0 -a.13= 2702765 -a.14= 0 -a.15= -199360981 -a.16= 0 -a.17= 19391512145 -a.18= 0 -a.19= -2404879675441 -a.20= 0 -a.21= 370371188237525 - -size=21 /*have a list of 21 Euler numbers*/ -call tell 'un-sorted' -call esort size -call tell ' sorted' +/*REXX program sorts (E-sort) an arra y (which contains integers). */ +numeric digits 30 /*handle larger Euler numbers. */ + @. = 0 /*default for all Euler numbers. */ + @.1= 1 + @.3= -1 + @.5= 5 + @.7= -61 + @.9= 1385 + @.11= -50521 + @.13= 2702765 + @.15= -199360981 + @.17= 19391512145 + @.19= -2404879675441 + @.21= 370371188237525 +size=21 /*indicate there are 21 Euler #'s*/ +call tell 'un-sorted' /*display the array before sort. */ +call esort size /*sort the array of Euler numbers*/ +call tell ' sorted' /*display the array after sort. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────ESORT subroutine────────────────────*/ -esort: procedure expose a.; parse arg N; h=N - do while h>1; h=h%2 - do i=1 for N-h; j=i; k=h+i - do while a.k=j then leave; j=j-h; k=k-h - end /*while a.k1; h=h%2 + do i=1 for N-h; j=i; k=h+i + do while @.k<@.j + parse value @.j @.k with @.k @.j /*swap two elements.*/ + if h>=j then leave; j=j-h; k=k-h + end /*while @.k<@.j*/ end /*i*/ end /*while h>1*/ return /*──────────────────────────────────TELL subroutine─────────────────────*/ tell: say center(arg(1),50,'─') - do j=1 for size - say arg(1) 'array element' right(j,length(size))'='right(a.j,20) + do j=1 for size + say arg(1) 'array element' right(j,length(size))'='right(@.j,20) end /*j*/ say return diff --git a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx index e3553cd351..031e18dcd1 100644 --- a/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx +++ b/Task/Sort-an-integer-array/REXX/sort-an-integer-array-2.rexx @@ -1,30 +1,29 @@ /*REXX program sorts (using E-sort) a list of some interesting integers.*/ - - /*quotes aren't needed if all elements in a list are non-negative.*/ +/* [↓] quotes aren't needed if all elements in a list are non-negative.*/ bell= 1 1 2 5 15 52 203 877 4140 21147 115975 /*some Bell numbers.*/ bern= '1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617' /*some Bernoulli num*/ -perrin=3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 /*some Perrin nums. */ -list=bell bern perrin /*throw 'em───>a pot*/ -say 'original =' list /*an annoucement... */ +perrin= 3 0 2 3 2 5 5 7 10 12 17 22 29 39 51 68 90 /*some Perrin nums. */ +list=bell bern perrin /*throw 'em───►a pot*/ +say 'unsorted =' list /*an announcement···*/ size=words(list) /*nice to have SIZE.*/ - do j=1 for size /*build an array, 1 */ - a.j=word(list,j) /*element at a time.*/ - end /*j*/ + do j=1 for size /*build an array, 1 */ + @.j=word(list,j) /*element at a time.*/ + end /*j*/ call esort size /*sort the stuff. */ -bList=a.1 /*start with 1st. */ - do k=2 to size /*build a list. */ - bList=bList a.k - end /*k*/ +bList= /*list: null so far.*/ + do k=1 for size /*build a list. */ + bList=strip(bList @.k) /*append it to list.*/ + end /*k*/ say ' sorted =' bList /*show & tell time. */ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────ESORT subroutine────────────────────*/ -esort: procedure expose a.; parse arg N; h=N - do while h>1; h=h%2 - do i=1 for N-h; j=i; k=h+i - do while a.k=j then leave; j=j-h; k=k-h - end /*while a.k1; h=h%2 /*partition array. */ + do i=1 for N-h; j=i; k=h+i + do while @.k<@.j + parse value @.j @.k with @.k @.j /*swap two elements.*/ + if h>=j then leave; j=j-h; k=k-h + end /*while @.k<@.j*/ end /*i*/ end /*while h>1*/ return diff --git a/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust b/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust new file mode 100644 index 0000000000..7116d4e875 --- /dev/null +++ b/Task/Sort-an-integer-array/Rust/sort-an-integer-array.rust @@ -0,0 +1,6 @@ +fn main() { + let mut a = vec!(9, 8, 7, 6, 5, 4, 3, 2, 1, 0); + + a.sort(); + println!("{}", a); +} diff --git a/Task/Sort-an-integer-array/Scala/sort-an-integer-array-1.scala b/Task/Sort-an-integer-array/Scala/sort-an-integer-array-1.scala new file mode 100644 index 0000000000..1cde71f966 --- /dev/null +++ b/Task/Sort-an-integer-array/Scala/sort-an-integer-array-1.scala @@ -0,0 +1,15 @@ +import scala.compat.Platform + +object Sort_an_integer_array extends App { + val array = Array((for (i <- 0 to 10) yield scala.util.Random.nextInt()): + _* /*Sequence is passed as multiple parameters to Array(xs : T*)*/) + + /** Function test the array if it is in order */ + def isSorted[T](arr: Array[T]) = array.sliding(2).forall(pair => pair(0) <= pair(1)) + + assert(!isSorted(array), "Not random") + scala.util.Sorting.quickSort(array) + assert(isSorted(array), "Not sorted") + + println(s"Array in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") +} diff --git a/Task/Sort-an-integer-array/Scala/sort-an-integer-array-2.scala b/Task/Sort-an-integer-array/Scala/sort-an-integer-array-2.scala new file mode 100644 index 0000000000..22067ccb62 --- /dev/null +++ b/Task/Sort-an-integer-array/Scala/sort-an-integer-array-2.scala @@ -0,0 +1,2 @@ +println(List(5,2,78,2,578,-42).sorted) +//--> List(-42, 2, 2, 5, 78, 578) diff --git a/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala b/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala deleted file mode 100644 index 337bb2e7f3..0000000000 --- a/Task/Sort-an-integer-array/Scala/sort-an-integer-array.scala +++ /dev/null @@ -1,2 +0,0 @@ -println(List(5,2,78,2,578,-42).sortWith(_<_)) -//--> List(-42, 2, 2, 5, 78, 578) diff --git a/Task/Sort-disjoint-sublist/00DESCRIPTION b/Task/Sort-disjoint-sublist/00DESCRIPTION index e3fa523ea9..e4964511ee 100644 --- a/Task/Sort-disjoint-sublist/00DESCRIPTION +++ b/Task/Sort-disjoint-sublist/00DESCRIPTION @@ -8,3 +8,6 @@ Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. Note that for one based, rather than the zero-based indexing above, use the indices: {7, 2, 8}. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. + +;Cf. +* [[Order disjoint list items]] diff --git a/Task/Sort-disjoint-sublist/Clojure/sort-disjoint-sublist.clj b/Task/Sort-disjoint-sublist/Clojure/sort-disjoint-sublist.clj new file mode 100644 index 0000000000..33e7a8da8b --- /dev/null +++ b/Task/Sort-disjoint-sublist/Clojure/sort-disjoint-sublist.clj @@ -0,0 +1,4 @@ +(defn disjoint-sort [coll idxs] + (let [val-subset (keep-indexed #(when ((set idxs) %) %2) coll) + replacements (zipmap (set idxs) (sort val-subset))] + (apply assoc coll (flatten (seq replacements))))) diff --git a/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d index acd8f18b83..995a67dba3 100644 --- a/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d +++ b/Task/Sort-disjoint-sublist/D/sort-disjoint-sublist-1.d @@ -4,8 +4,7 @@ void main() { auto data = [7, 6, 5, 4, 3, 2, 1, 0]; auto indices = [6, 1, 7]; - auto idxSet = indices.sort().uniq().array(); - data.indexed(idxSet).sort(); + data.indexed(indices.sort()).sort(); assert(data == [7, 0, 5, 4, 3, 2, 1, 6]); } diff --git a/Task/Sort-disjoint-sublist/Scala/sort-disjoint-sublist.scala b/Task/Sort-disjoint-sublist/Scala/sort-disjoint-sublist.scala new file mode 100644 index 0000000000..9a361b7413 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Scala/sort-disjoint-sublist.scala @@ -0,0 +1,17 @@ +import scala.compat.Platform + +object SortedDisjointSubList extends App { + val (list, subListIndex) = (List(7, 6, 5, 4, 3, 2, 1, 0), List(6, 1, 7)) + + def sortSubList[T: Ordering](indexList: List[Int], list: List[T]) = { + val subListIndex = indexList.sorted + val sortedSubListMap = subListIndex.zip(subListIndex.map(list(_)).sorted).toMap + + list.zipWithIndex.map { case (value, index) => + if (sortedSubListMap.isDefinedAt(index)) sortedSubListMap(index) else value + } + } + + assert(sortSubList(subListIndex, list) == List(7, 0, 5, 4, 3, 2, 1, 6), "Incorrect sort") + println(s"List in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]") +} diff --git a/Task/Sort-disjoint-sublist/Scheme/sort-disjoint-sublist.ss b/Task/Sort-disjoint-sublist/Scheme/sort-disjoint-sublist.ss new file mode 100644 index 0000000000..1873393291 --- /dev/null +++ b/Task/Sort-disjoint-sublist/Scheme/sort-disjoint-sublist.ss @@ -0,0 +1,16 @@ +(use gauche.sequence) +(define num-list '(7 6 5 4 3 2 1 0)) +(define indices '(6 1 7)) +(define table + (alist->hash-table + (map cons + (sort indices) + (sort indices < (lambda (x) (~ num-list x)))))) + +(map last + (sort + (map-with-index + (lambda (i x) (list (hash-table-get table i i) x)) + num-list) + < + car)) diff --git a/Task/Sort-stability/REXX/sort-stability.rexx b/Task/Sort-stability/REXX/sort-stability.rexx new file mode 100644 index 0000000000..a271c27591 --- /dev/null +++ b/Task/Sort-stability/REXX/sort-stability.rexx @@ -0,0 +1,39 @@ +/*REXX program sorts an array using a (stable) bubble-sort algorithm.*/ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call bubbleSort # /*invoke the bubble sort. */ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────BUBBLESORT subroutine───────────────*/ +bubbleSort: procedure expose @.; parse arg n /*N: number of items.*/ + /*diminish # items each time. */ + do until done /*sort until it's done. */ + done=1 /*assume it's done (1 ≡ true). */ + do j=1 for n-1 /*sort M items this time around. */ + k=j+1 /*point to the next item. */ + if @.j>@.k then do /*is it out of order? */ + _=@.j /*assign to a temp variable. */ + @.j=@.k /*swap current item with next ···*/ + @.k=_ /* ··· and the next with _ */ + done=0 /*indicate it's not done, whereas*/ + end /* [↑] 1≡true 0≡false */ + end /*j*/ + end /*until*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: @. = /*assign default value to all @. */ + @.1 = 'UK London' + @.2 = 'US New York' + @.3 = 'US Birmingham' + @.4 = 'UK Birmingham' + + do #=1 while @.# \=='' /*find how many entries in list. */ + end /*#*/ +#=#-1 /*adjust because of DO increment.*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: do j=1 for # /* [↓] display all list elements*/ + say ' element' right(j,length(#)) arg(1)':' @.j + end /*j*/ +say copies('■',50) /*show a separator line. */ +return diff --git a/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.ada b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.ada new file mode 100644 index 0000000000..d9846c6c08 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Ada/sort-using-a-custom-comparator.ada @@ -0,0 +1,108 @@ +with Ada.Text_Io; use Ada.Text_Io; +with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; +with Gnat.Heap_Sort_G; + +procedure Custom_Compare is + + type StringArrayType is array (Natural range <>) of Unbounded_String; + + Strings : StringArrayType := (Null_Unbounded_String, + To_Unbounded_String("this"), + To_Unbounded_String("is"), + To_Unbounded_String("a"), + To_Unbounded_String("set"), + To_Unbounded_String("of"), + To_Unbounded_String("strings"), + To_Unbounded_String("to"), + To_Unbounded_String("sort"), + To_Unbounded_String("This"), + To_Unbounded_String("Is"), + To_Unbounded_String("A"), + To_Unbounded_String("Set"), + To_Unbounded_String("Of"), + To_Unbounded_String("Strings"), + To_Unbounded_String("To"), + To_Unbounded_String("Sort")); + + procedure Move (From, To : in Natural) is + + begin + Strings(To) := Strings(From); + end Move; + + function UpCase (Char : in Character) return Character is + Temp : Character; + begin + if Char >= 'a' and Char <= 'z' then + Temp := Character'Val(Character'Pos(Char) + - Character'Pos('a') + + Character'Pos('A')); + else + Temp := Char; + end if; + return Temp; + end UpCase; + + function Lt (Op1, Op2 : Natural) + return Boolean is + Temp, Len : Natural; + begin + Len := Length(Strings(Op1)); + Temp := Length(Strings(Op2)); + if Len < Temp then + return False; + elsif Len > Temp then + return True; + end if; + + declare + S1, S2 : String(1..Len); + begin + S1 := To_String(Strings(Op1)); + S2 := To_String(Strings(Op2)); + Put("Same size: "); + Put(S1); + Put(" "); + Put(S2); + Put(" "); + for I in S1'Range loop + Put(UpCase(S1(I))); + Put(UpCase(S2(I))); + if UpCase(S1(I)) = UpCase(S2(I)) then + null; + elsif UpCase(S1(I)) < UpCase(S2(I)) then + Put(" LT"); + New_Line; + return True; + else + return False; + end if; + end loop; + Put(" GTE"); + New_Line; + return False; + end; + end Lt; + + procedure Put (Arr : in StringArrayType) is + begin + for I in 1..Arr'Length-1 loop + Put(To_String(Arr(I))); + New_Line; + end loop; + end Put; + + package Heap is new Gnat.Heap_Sort_G(Move, + Lt); + use Heap; + + +begin + Put_Line("Unsorted list:"); + Put(Strings); + New_Line; + Sort(16); + New_Line; + Put_Line("Sorted list:"); + Put(Strings); +end Custom_Compare; diff --git a/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d b/Task/Sort-using-a-custom-comparator/D/sort-using-a-custom-comparator-2.d index a04eb1ff64..d0420b16c9 100644 --- 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 @@ -2,8 +2,6 @@ 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.multiSort!(q{a.length > b.length}, q{a.toUpper < b.toUpper}); parts.writeln; } diff --git a/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua b/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua index 2210d8fc72..9faf9c5d41 100644 --- a/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua +++ b/Task/Sort-using-a-custom-comparator/Lua/sort-using-a-custom-comparator.lua @@ -1,7 +1,12 @@ -function pair(a, b) return a[1] < b[1] end +test = { "Here", "we", "have", "some", "sample", "strings", "to", "be", "sorted" } -t = { -{2, 5}, {1, 6}, {4, 8}, {3, 2} -} -table.sort(t, pair) -for i, v in ipairs(t) do print(unpack(v)) end +function stringSorter(a, b) + if string.len(a) == string.len(b) then + return string.lower(a) < string.lower(b) + end + return string.len(a) > string.len(b) +end +table.sort(test, stringSorter) + +-- print sorted table +for k,v in pairs(test) do print(v) end diff --git a/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-3.ss b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-3.ss new file mode 100644 index 0000000000..63aead0313 --- /dev/null +++ b/Task/Sort-using-a-custom-comparator/Scheme/sort-using-a-custom-comparator-3.ss @@ -0,0 +1,11 @@ +(define strings '( + "This" "Is" "A" "Set" "Of" "Strings" "To" "Sort" "duplicated" + "this" "is" "a" "set" "of" "strings" "to" "sort" "duplicated")) + +(print + (sort strings + (lambda two + (define sizes (map string-length two)) + (if (apply = sizes) + (apply string-ci sizes))))) diff --git a/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d b/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d index 02d80945c1..ac5321c01e 100644 --- a/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d +++ b/Task/Sorting-algorithms-Bead-sort/D/sorting-algorithms-bead-sort.d @@ -3,7 +3,7 @@ import std.stdio, std.algorithm, std.range, std.array, std.functional; alias repeat0 = curry!(repeat, 0); // Currenty std.range.transposed doesn't work. -auto columns(R)(R m) /*pure nothrow*/ { +auto columns(R)(R m) pure /*nothrow*/ @safe /*@nogc*/ { return m .map!walkLength .reduce!max @@ -11,7 +11,7 @@ auto columns(R)(R m) /*pure nothrow*/ { .map!(i => m.filter!(s => s.length > i).walkLength.repeat0); } -auto beadSort(in uint[] data) /*pure nothrow*/ { +auto beadSort(in uint[] data) pure /*nothrow @nogc*/ { return data.map!repeat0.columns.columns.map!walkLength; } diff --git a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e new file mode 100644 index 0000000000..1fdb130674 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-1.e @@ -0,0 +1,61 @@ +class + BEAD_SORT +feature + bead_sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER] + local + max, count, i, j, k: INTEGER + sorted: ARRAY[INTEGER] + do + max:= max_item(ar) + create sorted.make_filled(0,1, ar.count) + from + i:= 1 + until + i> max + loop + count:= 0 + from + k:= 1 + until + k> ar.count + loop + if ar.item (k) >= i then + count:= count+1 + end + k:= k+1 + end + from + j:= 1 + until + j>count + loop + sorted[j]:= i + j:= j+1 + end + i:= i+1 + end + RESULT:= sorted + end + +feature{NONE} + max_item(ar: ARRAY [INTEGER]):INTEGER + require + ar_not_void: ar/= Void + local + i, max: INTEGER + do + from + i:=1 + until + i > ar.count + loop + if ar.item(i) > max then + max := ar.item(i) + end + i := i + 1 + end + Result := max + ensure + result_is_set: Result /= Void + end +end diff --git a/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e new file mode 100644 index 0000000000..72204af86e --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Eiffel/sorting-algorithms-bead-sort-2.e @@ -0,0 +1,20 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + test:= <<1, 5, 99, 2, 95, 7, 7>> + create beadsort + io.put_string ("unsorted:"+"%N") + across test as ar loop io.put_string(ar.item.out + "%T") end + io.put_string ("%N"+"sorted:"+"%N") + test:= beadsort.bead_sort (test) + across test as ar loop io.put_string(ar.item.out + "%T") end + end + beadsort: BEAD_SORT + test: ARRAY[INTEGER] +end diff --git a/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort.pli b/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-1.pli similarity index 100% rename from Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort.pli rename to Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-1.pli diff --git a/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-2.pli b/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-2.pli new file mode 100644 index 0000000000..1e27934b2b --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/PL-I/sorting-algorithms-bead-sort-2.pli @@ -0,0 +1,46 @@ +*process source attributes xref; + /* Handles both negative and positive values. */ + Beadsort: Proc Options(main); + Dcl sysprint Print; + Dcl (hbound,max,min) Builtin; + + Dcl z(10) Bin Fixed(31) Init(10,-12,1,0,999,8,2,2,4,4); + Dcl s(10) Bin Fixed(31); + Dcl (init,lo,hi) Bin Fixed(31) Init(0); + Dcl (i,j) Bin Fixed(31) Init(0); + + Call minmax(z,init,lo,hi); + + Begin; + Dcl beads(lo:hi) Bin Fixed(31); + beads=0; + Do i=1 To hbound(z); + beads(z(i))+=1; + End; + Do i=lo To hi; + Do While(beads(i)>0); + j+=1; + s(j)=i; + beads(i)-=1; + End; + End; + Put Edit(' Input:',(z(i) Do i=1 To hbound(z)))(skip,a,99(f(4))); + Put Edit('Sorted:',(s(i) Do i=1 To hbound(s)))(skip,a,99(f(4))); + End; + + minmax: Proc(z,init,lo,hi); + Dcl z(*) Bin Fixed(31); + Dcl (init,lo,hi) Bin Fixed(31); + Do i=1 To hbound(z); + If init=0 Then Do; + init=1; + lo,hi=z(i); + End; + Else Do; + lo=min(lo,z(i)); + hi=max(hi,z(i)); + End; + End; + End; + + End; diff --git a/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx index 557421447d..a3b495889d 100644 --- a/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx +++ b/Task/Sorting-algorithms-Bead-sort/REXX/sorting-algorithms-bead-sort.rexx @@ -1,62 +1,46 @@ -/*REXX program sorts a list of integers using a bead sort algorithm. */ - /*get some grassHopper numbers. */ -grasshopper=, +/*REXX program sorts a list of integers using a bead sort algorithm.*/ +grasshopper=, /*get 2 dozen grasshopper numbers*/ 1 4 10 12 22 26 30 46 54 62 66 78 94 110 126 134 138 158 162 186 190 222 254 270 - /*GreeenGrocer numbers are also called hexagonal pyramidal */ - /* numbers. */ -greengrocer=, + /*Green Grocer numbers are also */ +greenGrocer=, /*called hexagonal pyramidal nums*/ 0 4 16 40 80 140 224 336 480 660 880 1144 1456 1820 2240 2720 3264 3876 4560 - /*get some Bernoulli numerator numbers. */ + /*get 23 Bernoulli numerator nums*/ bernN='1 -1 1 0 -1 0 1 0 -1 0 5 0 -691 0 7 0 -3617 0 43867 0 -174611 0 854513' - /*Psi is also called the Reduced Totient function, and */ - /* is also called Carmichale lambda, or LAMBDA function.*/ -psi=, + /*Psi is also called the Reduced Totient function, and is*/ +psi=, /*also called Carmichale lambda, or the LAMBDA function.*/ 1 1 2 2 4 2 6 2 6 4 10 2 12 6 4 4 16 6 18 4 6 10 22 2 20 12 18 6 28 4 30 8 10 16 -list=grasshopper greengrocer bernN psi /*combine the four lists into one*/ - -call showL 'before sort',list /*show the list before sorting. */ -$=beadSort(list) /*invoke the bead sort. */ -call showL ' after sort',$ /*show the after array elements.*/ +#s=grasshopper greenGrocer bernN psi /*combine the four lists into one*/ +call show 'before sort', #s /*show the list before sorting.*/ +call show ' after sort', beadSort(#s) /*show the list after sorting.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -beadSort: procedure expose @.; parse arg z -$= /*this'll be the sorted list. */ -low=999999999; high=-low /*define the low and high numbers*/ -@.=0 /*define all beads to zero. */ - - do j=1 until z=='' /*pick the meat off the bone. */ - parse var z x z - if \datatype(x,'Whole') then do - say; say '*** error! ***'; say - say 'element' j "in list isn't numeric:" x - say - exit 13 - end - x=x/1 /*normalize number, it could be: */ - /* +4 007 5. 2e3 etc.*/ - @.x=@.x+1 /*indicate this bead has a number*/ - low=min(low,x) /*keep track of the lowest number*/ - high=max(high,x) /* " " " " highest " */ - end /*j*/ - /*now, collect the beads and */ +beadSort: procedure; parse arg low . 1 high . 1 z,$ /*$: the list to be*/ +@.=0 /*set all beads (@.) to zero. */ + do j=1 until z==''; parse var z x z /*pick the meat off the bone.*/ + if \datatype(x,'W') then do; say '*** error! ***' + say 'element' j "in list isn't numeric:" x + say; exit 13 + end /* [↑] exit program with RC=13. */ + x=x/1 /*normalize X: 4. 004 +4 .4e0 ···*/ + @.x=@.x+1 /*indicate this bead has a number*/ + low=min(low,x); high=max(high,x) /*track the lowest & highest num.*/ + end /*j*/ + /* [↓] now, collect the beads and*/ do m=low to high /*let them fall (to zero). */ - if @.m==0 then iterate /*No bead here? Then keep looking*/ - do n=1 for @.m /*let the beads fall to 0. */ - $=$ m /*add it to the sorted list. */ - end /*n*/ - end /*m*/ + if @.m\==0 then do n=1 for @.m /*have we found a bead here? */ + $=$ m /*add it to the sorted list. */ + end /*n*/ /* [↑] let beads fall to zero. */ + end /*m*/ return $ -/*──────────────────────────────────SHOWL subroutine────────────────────*/ -showL: widthH=length(words(arg(2))) /*maximum width of the index. */ - - do j=1 for words(arg(2)) - say 'element' right(j,widthH) arg(1)":" right(word(arg(2),j),10) - end /*j*/ - -say copies('─',79) /*show a separator line. */ +/*──────────────────────────────────SHOW subroutine─────────────────────*/ +show: parse arg txt,y; _=left('', 20) +w=length(words(y)); do k=1 for words(y) /* [↑] twenty blanks.*/ + say _ 'element' right(k,w) txt":" right(word(y,k),9) + end /*k*/ +say copies('─',70) /*show a long separator line. */ return diff --git a/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb index dcaf4c5fe0..9a667ec570 100644 --- a/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb +++ b/Task/Sorting-algorithms-Bead-sort/Ruby/sorting-algorithms-bead-sort.rb @@ -1,11 +1,11 @@ class Array def beadsort - map {|e| [1] * e}.columns.columns.map {|e| e.length} + map {|e| [1] * e}.columns.columns.map(&:length) end def columns y = length - x = map {|l| l.length}.max + x = map(&:length).max Array.new(x) do |row| Array.new(y) { |column| self[column][row] }.compact # Remove nils. end diff --git a/Task/Sorting-algorithms-Bead-sort/Seed7/sorting-algorithms-bead-sort.seed7 b/Task/Sorting-algorithms-Bead-sort/Seed7/sorting-algorithms-bead-sort.seed7 new file mode 100644 index 0000000000..a307e4bc97 --- /dev/null +++ b/Task/Sorting-algorithms-Bead-sort/Seed7/sorting-algorithms-bead-sort.seed7 @@ -0,0 +1,46 @@ +$ include "seed7_05.s7i"; + +const proc: beadSort (inout array integer: a) is func + local + var integer: max is 0; + var integer: sum is 0; + var array bitset: beads is 0 times {}; + var integer: i is 0; + var integer: j is 0; + begin + beads := length(a) times {}; + for i range 1 to length(a) do + if a[i] > max then + max := a[i]; + end if; + beads[i] := {1 .. a[i]}; + end for; + for j range 1 to max do + sum := 0; + for i range 1 to length(a) do + sum +:= ord(j in beads[i]); + excl(beads[i], j); + end for; + for i range length(a) - sum + 1 to length(a) do + incl(beads[i], j); + end for; + end for; + for i range 1 to length(a) do + for j range 1 to max until j not in beads[i] do + noop; + end for; + a[i] := pred(j); + end for; + end func; + +const proc: main is func + local + var array integer: a is [] (5, 3, 1, 7, 4, 1, 1, 20); + var integer: num is 0; + begin + beadSort(a); + for num range a do + write(num <& " "); + end for; + writeln; + end func; diff --git a/Task/Sorting-algorithms-Bogosort/00DESCRIPTION b/Task/Sorting-algorithms-Bogosort/00DESCRIPTION index 6cf7feb777..7d540766c6 100644 --- a/Task/Sorting-algorithms-Bogosort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Bogosort/00DESCRIPTION @@ -1,7 +1,9 @@ {{Sorting Algorithm}} -[[wp:Bogosort|Bogosort]] a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. +[[wp:Bogosort|Bogosort]] a list of numbers. +Bogosort simply shuffles a collection randomly until it is sorted. -"Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in ''n'' factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is O(n) since a single pass through the elements may suffice to order them. +"Bogosort" is a perversely inefficient algorithm only used as an in-joke. +Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in ''n'' factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is O(n) since a single pass through the elements may suffice to order them. Pseudocode: '''while not''' InOrder(list) '''do''' diff --git a/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort.cpp b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort.cpp new file mode 100644 index 0000000000..666b501486 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/C++/sorting-algorithms-bogosort.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +template +void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end, + Predicate p) { + std::random_device rd; + std::mt19937 generator(rd()); + while (!std::is_sorted(begin, end, p)) { + std::shuffle(begin, end, generator); + } +} + +template +void bogo_sort(RandomAccessIterator begin, RandomAccessIterator end) { + bogo_sort( + begin, end, + std::less< + typename std::iterator_traits::value_type>()); +} + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + bogo_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; +} diff --git a/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj b/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj index 1454754a52..342e91322f 100644 --- a/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj +++ b/Task/Sorting-algorithms-Bogosort/Clojure/sorting-algorithms-bogosort.clj @@ -1,17 +1,9 @@ -(ns bogosort - (:use [clojure.contrib.seq-utils :only (shuffle)])) - -(defn in-order? [less xs] +(defn in-order? [order xs] (or (empty? xs) - (empty? (next xs)) - (and (less (first xs) (second xs)) - (recur less (next xs))))) + (apply order xs))) -(defn bogosort - ([xs] - (bogosort < xs)) - ([less xs] - (if (in-order? less xs) xs - (recur less (shuffle xs))))) +(defn bogosort [order xs] + (if (in-order? order xs) xs + (recur order (shuffle xs)))) -(println (bogosort [7,5,12,1,4,2,23,18])) +(println (bogosort < [7 5 12 1 4 2 23 18])) diff --git a/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-1.e b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-1.e new file mode 100644 index 0000000000..e441638ea4 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-1.e @@ -0,0 +1,58 @@ +class + BOGO_SORT +feature + bogo_sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER] + do + from + until + is_sorted (ar) = TRUE + loop + Result:= shuffel(ar) + end + end +feature{NONE} + is_sorted (ar:ARRAY[INTEGER]): BOOLEAN + require + not_void: ar /= Void + local + i: INTEGER + do + Result := True + from + i := 1+ 1 + invariant + i >= 1 + 1 and i <= ar.count + 1 + until + i > ar.count + loop + Result := Result and ar [i - 1] <= ar [i] + i := i + 1 + variant + ar.count + 1 - i + end + end + + shuffel(ar:ARRAY[INTEGER]): ARRAY[INTEGER] + require + not_void: ar/= Void + local + i,j:INTEGER + ith: INTEGER + random: V_RANDOM + do + create random + from + i:=ar.count + until + i<2 + loop + j:=random.bounded_item (1, i) + ith:= ar[i] + ar[i]:= ar[j] + ar[j]:= ith + random.forth + i:=i-1 + end + Result:= ar + end +end diff --git a/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e new file mode 100644 index 0000000000..d4dd10b837 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Eiffel/sorting-algorithms-bogosort-2.e @@ -0,0 +1,24 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} -- Initialization + + make + do + test:= <<3,2,5,7,1>> + io.put_string ("Unsorted: ") + across test as t loop io.put_string (t.item.out + " ") end + create sorter + test:= sorter.bogo_sort (test) + io.put_string ("%NSorted: ") + across test as t loop io.put_string (t.item.out + " ") end + end + test: ARRAY[INTEGER] + sorter: BOGO_SORT +end diff --git a/Task/Sorting-algorithms-Bogosort/PL-I/sorting-algorithms-bogosort.pli b/Task/Sorting-algorithms-Bogosort/PL-I/sorting-algorithms-bogosort.pli new file mode 100644 index 0000000000..dd10061427 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/PL-I/sorting-algorithms-bogosort.pli @@ -0,0 +1,54 @@ +*process source xref; + bogosort: Proc Options(main); + Dcl SYSPRINT Print; + Dcl (HBOUND,RANDOM,TIME) Builtin; + Dcl tim Pic'(9)9'; + Dcl timms Pic'(3)9' def tim pos(7); + tim=time(); + x=random(timms); + Dcl a(5) Dec Fixed(5,1) Init(-21,333,0,444.4,1); + Dcl (x,y,temp) Dec Fixed(5,1); + Dcl (n,bogo,j,u,v) Bin Fixed(31); + n=hbound(a); + Call tell('un-bogoed'); + loop: + Do bogo=1 By 1; + Do j=1 To n-1; + jp=j+1; + x=a(j); + y=a(jp); + if y>=x Then + Iterate; + u=rand(1,n); + Do Until v^=u + v=rand(1,n); + End; + Temp=a(u); + a(u)=a(v); + a(v)=temp; + Iterate loop; + End; + Leave; + End; + + Put Edit('number of bogo sorts performed =',bogo)(Skip,a,f(4)); + call tell(' bogoed'); + Return; + + tell: Proc(txt); + Dcl txt Char(*); + Dcl t Bin Fixed(31); + Put Edit(txt)(skip,a); + Do t=1 to n; + Put Edit(a(t))(Skip,f(6,1)); + End; + End; + + rand: Proc(lo,hi) Returns(Bin Fixed(31)); + Dcl (lo,hi,res) Bin Fixed(31); + Dcl r Bin Float(31); + r=random(); + res=r*(hi-lo+1)+lo; + Return(res); + End; + End; diff --git a/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-4.py b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-4.py new file mode 100644 index 0000000000..4935148561 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/Python/sorting-algorithms-bogosort-4.py @@ -0,0 +1,12 @@ +import operator +import random +from itertools import dropwhile, imap, islice, izip, repeat, starmap + +def shuffled(x): + x = x[:] + random.shuffle(x) + return x + +bogosort = lambda l: next(dropwhile( + lambda l: not all(starmap(operator.le, izip(l, islice(l, 1, None)))), + imap(shuffled, repeat(l)))) diff --git a/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-1.rexx b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-1.rexx new file mode 100644 index 0000000000..444273ddd0 --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-1.rexx @@ -0,0 +1,31 @@ +/*REXX program performs a type of bogo sort on numbers in an array. */ +parse arg list /*obtain optional list from C.L. */ +if list='' then list=-21 333 0 444.4 /*Not defined? Then use default.*/ +#=words(list) /*the number of numbers in list. */ + do i=1 for words(list); @.i=word(list,i); end /*create an array.*/ +call tell 'before bogo sort' + + do bogo=1 + + do j=1 for #-1; jp=j+1 /* [↓] compare a # with the next*/ + if @.jp>=@.j then iterate /*so far, so good; keep looking.*/ + /*get 2 unique random #s for swap*/ + do until a\==b; a=random(1, #); b=random(1, #); end + + parse value @.a @.b with @.b @.a /*swap 2 random numbers in array.*/ + iterate bogo /*go and try another bogo sort. */ + end /*j*/ + + leave /*we're finished with bogo sort. */ + end /*bogo*/ /* [↓] show the # of bogo sorts.*/ + +say 'number of bogo sorts performed =' bogo +call tell ' after bogo sort' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: say; say center(arg(1), 50, '─') + do t=1 for # + say arg(1) 'element'right(t, length(#))'='right(@.t, 18) + end /*t*/ +say +return diff --git a/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-2.rexx b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-2.rexx new file mode 100644 index 0000000000..e97f6d219e --- /dev/null +++ b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort-2.rexx @@ -0,0 +1,42 @@ +/*REXX program performs a type of bogo sort on numbers in an array. */ +@.1 = 0 ; @.11= -64 ; @.21= 4096 ; @.31= 6291456 +@.2 = 0 ; @.12= 64 ; @.22= 40960 ; @.32= 5242880 +@.3 = 1 ; @.13= 256 ; @.23= 16384 ; @.33= -15728640 +@.4 = 2 ; @.14= 0 ; @.24= -114688 ; @.34= -27262976 +@.5 = 0 ; @.15= -768 ; @.25= -131072 ; @.35= 29360128 +@.6 = -4 ; @.16= -512 ; @.26= 262144 ; @.36= 104857600 +@.7 = 0 ; @.17= 2048 ; @.27= 589824 ; @.37= -16777216 +@.8 = 16 ; @.18= 3072 ; @.28= -393216 ; @.38= -335544320 +@.9 = 16 ; @.19= -4096 ; @.29= -2097152 ; @.39= -184549376 +@.10= -32 ; @.20= -12288 ; @.30= -262144 ; @.40= 905969664 + /* [↑] @.1 is really the 0th Berstel number*/ +#=40 /*we have a list of two score Berstel numbers.*/ +call tell 'before bogo sort' + + do bogo=1 + + do j=1 for #; ?=@.j /*? is the next number in array.*/ + + do k=j+1 to # + if @.k>=? then iterate /*is this # in order? Get next. */ + /*get 2 unique random #s for swap*/ + do until a\==b; a=random(j, k); b=random(j, k); end + + parse value @.a @.b with @.b @.a /*swap 2 random #s in array.*/ + iterate bogo /*go and try another bogo sort. */ + end /*k*/ + end /*j*/ + + leave /*we're finished with bogo sort. */ + end /*bogo*/ /* [↓] show the # of bogo sorts.*/ + +say 'number of bogo sorts performed =' bogo +call tell ' after bogo sort' +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────TELL subroutine─────────────────────*/ +tell: say; say center(arg(1), 50, '─') + do t=1 for # + say arg(1) 'element'right(t, length(#))'='right(@.t, 18) + end /*t*/ +say +return diff --git a/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx b/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx deleted file mode 100644 index 6eaeb26696..0000000000 --- a/Task/Sorting-algorithms-Bogosort/REXX/sorting-algorithms-bogosort.rexx +++ /dev/null @@ -1,46 +0,0 @@ -/*REXX program;to perform a type of bogo sort on an array. */ - /*a.1 is really the 0th Berstel number... */ -a.1 = 0 ; a.11= -64 ; a.21= 4096 ; a.31= 6291456 -a.2 = 0 ; a.12= 64 ; a.22= 40960 ; a.32= 5242880 -a.3 = 1 ; a.13= 256 ; a.23= 16384 ; a.33= -15728640 -a.4 = 2 ; a.14= 0 ; a.24= -114688 ; a.34= -27262976 -a.5 = 0 ; a.15= -768 ; a.25= -131072 ; a.35= 29360128 -a.6 = -4 ; a.16= -512 ; a.26= 262144 ; a.36= 104857600 -a.7 = 0 ; a.17= 2048 ; a.27= 589824 ; a.37= -16777216 -a.8 = 16 ; a.18= 3072 ; a.28= -393216 ; a.38= -335544320 -a.9 = 16 ; a.19= -4096 ; a.29= -2097152 ; a.39= -184549376 -a.10= -32 ; a.20= -12288 ; a.30= -262144 ; a.40= 905969664 - -size=40 /*we have a list of two score Berstel numbers.*/ -call tell 'un-bogoed' - - do bogo=1 - - do j=1 for size - _=a.j - - do k=j+1 to size - if a.k>=_ then iterate - n=random(j,k) /*we have an num out of order.get rand*/ - do forever; m=random(j,k) /*get another random number.*/ - if m\==n then leave /*ensure we're not swapping the same #*/ - end /*forever*/ - parse value a.n a.m with a.m a.n /*swap 2 random nums*/ - iterate bogo - end /*k*/ - end /*j*/ - - leave - end /*bogo*/ - -say 'number of bogo sorts performed =' bogo-1 -call tell ' bogoed' -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────TELL subroutine─────────────────────*/ -tell: say; say center(arg(1),40,'─') - - do j=1 to size - say arg(1) 'element'right(j,length(size))'='right(a.j,20) - end /*j*/ -say -return diff --git a/Task/Sorting-algorithms-Bubble-sort/00DESCRIPTION b/Task/Sorting-algorithms-Bubble-sort/00DESCRIPTION index 81ec113000..2406e612a1 100644 --- a/Task/Sorting-algorithms-Bubble-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Bubble-sort/00DESCRIPTION @@ -1,9 +1,13 @@ {{Sorting Algorithm}} In this task, the goal is to sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers. -The bubble sort is generally considered to be the simplest sorting algorithm. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. +The bubble sort is generally considered to be the simplest sorting algorithm. +Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. +Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. -The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them). Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. +The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them). +Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass. +A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudocode as follows (assuming 1-based indexing): '''repeat''' diff --git a/Task/Sorting-algorithms-Bubble-sort/360-Assembly/sorting-algorithms-bubble-sort.360 b/Task/Sorting-algorithms-Bubble-sort/360-Assembly/sorting-algorithms-bubble-sort.360 new file mode 100644 index 0000000000..851ce1fd54 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/360-Assembly/sorting-algorithms-bubble-sort.360 @@ -0,0 +1,83 @@ +* Bubble Sort +BUBBLE CSECT + USING BUBBLE,R13,R12 +SAVEAREA B STM-SAVEAREA(R15) skip savearea + DC 17F'0' + DC CL8'BUBBLE' +STM STM R14,R12,12(R13) save calling context + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 set addessability + LA R12,4095(R13) + LA R12,1(R12) +MORE EQU * + LA R8,0 R8=no more + LA R1,A R1=Addr(A(I)) + LA R2,2(R1) R2=Addr(A(I+1)) + LA R4,0 to start at 1 + LA R6,1 increment + L R7,N R7=N + BCTR R7,0 R7=N-1 +LOOP BXH R4,R6,ENDLOOP for R4=1 to N-1 + LH R3,0(R1) R3=A(I) + CH R3,0(R2) A(I)::A(I+1) + BNH NOSWAP if A(I)<=A(I+1) then goto NOSWAP + LH R9,0(R1) R9=A(I) + LH R3,0(R2) R3=A(I+1) + STH R3,0(R1) A(I)=R3 + STH R9,0(R2) A(I+1)=R9 + LA R8,1 R8=more +NOSWAP EQU * + LA R1,2(R1) next A(I) + LA R2,2(R2) next A(I+1) + B LOOP +ENDLOOP EQU * + LTR R8,R8 + BNZ MORE + LA R3,A R3=Addr(A(I)) + LA R4,0 to start at 1 + LA R6,1 increment + L R7,N +PRNT BXH R4,R6,ENDPRNT for R4=1 to N + LH R5,0(R3) R5=A(I) + CVD R4,P Store I to packed P + UNPK Z,P Z=P + MVC C,Z C=Z + OI C+L'C-1,X'F0' ZAP SIGN + MVC BUFFER(4),C+12 + CVD R5,P Store A(I) to packed P + UNPK Z,P Z=P + MVC C,Z C=Z + OI C+L'C-1,X'F0' ZAP SIGN + MVC BUFFER+10(6),C+10 + WTO MF=(E,WTOMSG) + LA R3,2(R3) next A(I) + B PRNT +ENDPRNT EQU * + CNOP 0,4 + L R13,4(0,R13) + LM R14,R12,12(R13) restore context + XR R15,R15 set return code to 0 + BR R14 return to caller +N DC A((AEND-A)/2) number of items in A, so N=F'80' +A DC H'223',H'356',H'018',H'820',H'664',H'845',H'927',H'198' 8 + DC H'261',H'802',H'523',H'982',H'242',H'192',H'913',H'230' 16 + DC H'353',H'565',H'195',H'174',H'665',H'807',H'050',H'539' 24 + DC H'436',H'249',H'848',H'010',H'006',H'794',H'100',H'433' 32 + DC H'782',H'728',H'259',H'358',H'206',H'081',H'701',H'997' 40 + DC H'880',H'520',H'780',H'293',H'861',H'942',H'735',H'091' 48 + DC H'503',H'582',H'716',H'836',H'135',H'653',H'856',H'142' 56 + DC H'919',H'498',H'303',H'894',H'536',H'211',H'539',H'986' 64 + DC H'356',H'796',H'644',H'552',H'771',H'443',H'035',H'780' 72 + DC H'474',H'278',H'332',H'949',H'351',H'282',H'558',H'904' 80 +AEND EQU * +P DS PL8 packed +Z DS ZL16 zoned +C DS CL16 character +WTOMSG CNOP 0,4 + DC H'80' length of WTO buffer + DC H'0' must be binary zeroes +BUFFER DC 80C' ' + LTORG + YREGS + END BUBBLE diff --git a/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp b/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp index 7097064050..ee46f24e35 100644 --- a/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp +++ b/Task/Sorting-algorithms-Bubble-sort/C++/sorting-algorithms-bubble-sort.cpp @@ -1,42 +1,24 @@ -#include #include +#include +#include -template< typename ARRAY_TYPE, typename INDEX_TYPE > -void bubble_sort(ARRAY_TYPE array[], INDEX_TYPE size) -{ - bool done = false; - - while ( ! done) - { - done = true; - for (INDEX_TYPE i = 0 ; i < size-1 ; i++) - { - if (array[i] > array[i+1]) - { - done = false; - std::swap(array[i], array[i+1]); - } - } - size--; +template +void bubble_sort(RandomAccessIterator begin, RandomAccessIterator end) { + bool swapped = true; + while (begin != end-- && swapped) { + swapped = false; + for (auto i = begin; i != end; ++i) { + if (*(i + 1) < *i) { + std::iter_swap(i, i + 1); + swapped = true; + } } + } } -template< typename TYPE > -void print(TYPE val) -{ - std::cout << val << " "; -} - -int main() -{ - int array[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; - bubble_sort(array, 10); - std::for_each (&array[0], &array[10], print); - std::cout << std::endl; - - //But in real life... - int data[] = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 }; - std::sort(data, data+10); - std::for_each (data, data+10, print); - std::cout << std::endl; +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + bubble_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; } diff --git a/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c b/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c index 009ff225e7..5a5513e829 100644 --- a/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c +++ b/Task/Sorting-algorithms-Bubble-sort/C/sorting-algorithms-bubble-sort.c @@ -1,16 +1,28 @@ -void bubble_sort(int *a, int n) { - int j, t = 1; - while (n-- && t) - for (j = t = 0; j < n; j++) { - if (a[j] <= a[j + 1]) continue; - t = a[j], a[j] = a[j + 1], a[j + 1] = t; - t=1; - } +#include + +void bubble_sort (int *a, int n) { + int i, t, s = 1; + while (s) { + s = 0; + for (i = 1; i < n; i++) { + if (a[i] < a[i - 1]) { + t = a[i]; + a[i] = a[i - 1]; + a[i - 1] = t; + s = 1; + } + } + } } -int main(void) { - int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; - bubble_sort(a, sizeof(a) / sizeof(a[0])); - - return 0; +int main () { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); + bubble_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); + return 0; } diff --git a/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol index 8944734d50..ec1be92241 100644 --- a/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol +++ b/Task/Sorting-algorithms-Bubble-sort/COBOL/sorting-algorithms-bubble-sort.cobol @@ -1,145 +1,54 @@ - IDENTIFICATION DIVISION. - PROGRAM-ID. BUBBLESORT. - AUTHOR. DAVE STRATFORD. - DATE-WRITTEN. MARCH 2010. - INSTALLATION. HEXAGON SYSTEMS LIMITED. - - ENVIRONMENT DIVISION. - CONFIGURATION SECTION. - SOURCE-COMPUTER. ICL VME. - OBJECT-COMPUTER. ICL VME. - - INPUT-OUTPUT SECTION. - FILE-CONTROL. - SELECT FA-INPUT-FILE ASSIGN FL01. - SELECT FB-OUTPUT-FILE ASSIGN FL02. - - DATA DIVISION. - FILE SECTION. - - FD FA-INPUT-FILE. - 01 FA-INPUT-REC. - 03 FA-DATA PIC S9(6). - - FD FB-OUTPUT-FILE. - 01 FB-OUTPUT-REC PIC S9(6). - - WORKING-STORAGE SECTION. - 01 WA-IDENTITY. - 03 WA-PROGNAME PIC X(10) VALUE "BUBBLESORT". - 03 WA-VERSION PIC X(6) VALUE "000001". - - 01 WB-TABLE. - 03 WB-ENTRY PIC 9(8) COMP SYNC OCCURS 100000 - INDEXED BY WB-IX-1. - - 01 WC-VARS. - 03 WC-SIZE PIC S9(8) COMP SYNC. - 03 WC-TEMP PIC S9(8) COMP SYNC. - 03 WC-END PIC S9(8) COMP SYNC. - 03 WC-LAST-CHANGE PIC S9(8) COMP SYNC. - - 01 WF-CONDITION-FLAGS. - 03 WF-EOF-FLAG PIC X. - 88 END-OF-FILE VALUE "Y". - 03 WF-EMPTY-FILE-FLAG PIC X. - 88 EMPTY-FILE VALUE "Y". - - PROCEDURE DIVISION. - A-MAIN SECTION. - A-000. - PERFORM B-INITIALISE. - IF NOT EMPTY-FILE - PERFORM C-SORT. - PERFORM D-FINISH. - - A-999. - STOP RUN. - - B-INITIALISE SECTION. - B-000. - DISPLAY "*** " WA-PROGNAME " VERSION " - WA-VERSION " STARTING ***". - - MOVE ALL "N" TO WF-CONDITION-FLAGS. - OPEN INPUT FA-INPUT-FILE. - SET WB-IX-1 TO 0. - - READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG - WF-EMPTY-FILE-FLAG. - - PERFORM BA-READ-INPUT UNTIL END-OF-FILE. - - CLOSE FA-INPUT-FILE. - - SET WC-SIZE TO WB-IX-1. - - B-999. - EXIT. - - BA-READ-INPUT SECTION. - BA-000. - SET WB-IX-1 UP BY 1. - MOVE FA-DATA TO WB-ENTRY(WB-IX-1). - - READ FA-INPUT-FILE AT END MOVE "Y" TO WF-EOF-FLAG. - - BA-999. - EXIT. - - C-SORT SECTION. - C-000. - DISPLAY "SORT STARTING". - - MOVE WC-SIZE TO WC-END. - PERFORM E-BUBBLE UNTIL WC-END = 1. - - DISPLAY "SORT FINISHED". - - C-999. - EXIT. - - D-FINISH SECTION. - D-000. - OPEN OUTPUT FB-OUTPUT-FILE. - SET WB-IX-1 TO 1. - - PERFORM DA-WRITE-OUTPUT UNTIL WB-IX-1 > WC-SIZE. - - CLOSE FB-OUTPUT-FILE. - - DISPLAY "*** " WA-PROGNAME " FINISHED ***". - - D-999. - EXIT. - - DA-WRITE-OUTPUT SECTION. - DA-000. - WRITE FB-OUTPUT-REC FROM WB-ENTRY(WB-IX-1). - SET WB-IX-1 UP BY 1. - - DA-999. - EXIT. - - E-BUBBLE SECTION. - E-000. - MOVE 1 TO WC-LAST-CHANGE. - - PERFORM F-PASS VARYING WB-IX-1 FROM 1 BY 1 - UNTIL WB-IX-1 = WC-END. - - MOVE WC-LAST-CHANGE TO WC-END. - - E-999. - EXIT. - - F-PASS SECTION. - F-000. - IF WB-ENTRY(WB-IX-1) > WB-ENTRY(WB-IX-1 + 1) - SET WC-LAST-CHANGE TO WB-IX-1 - MOVE WB-ENTRY(WB-IX-1) TO WC-TEMP - MOVE WB-ENTRY(WB-IX-1 + 1) TO WB-ENTRY(WB-IX-1) - MOVE WC-TEMP TO WB-ENTRY(WB-IX-1 + 1). - - F-999. - EXIT. + identification division. + program-id. BUBBLSRT. + data division. + working-storage section. + 01 changed-flag pic x. + 88 hasChanged value 'Y'. + 88 hasNOTChanged value 'N'. + 01 itemCount pic 99. + 01 tempItem pic 99. + 01 itemArray. + 03 itemArrayCount pic 99. + 03 item pic 99 occurs 99 times + indexed by itemIndex. + * + procedure division. + main. + * place the values to sort into itemArray + move 10 to itemArrayCount + move 28 to item (1) + move 44 to item (2) + move 46 to item (3) + move 24 to item (4) + move 19 to item (5) + move 2 to item (6) + move 17 to item (7) + move 11 to item (8) + move 24 to item (9) + move 4 to item (10) + * store the starting count in itemCount and perform the sort + move itemArrayCount to itemCount + perform bubble-sort + * output the results + perform varying itemIndex from 1 by 1 + until itemIndex > itemArrayCount + display item (itemIndex) ';' with no advancing + end-perform + * thats it! + stop run. + * + bubble-sort. + perform with test after until hasNOTchanged + set hasNOTChanged to true + subtract 1 from itemCount + perform varying itemIndex from 1 by 1 + until itemIndex > itemCount + if item (itemIndex) > item (itemIndex + 1) + move item (itemIndex) to tempItem + move item (itemIndex + 1) to item (itemIndex) + move tempItem to item (itemIndex + 1) + set hasChanged to true + end-if + end-perform + end-perform + . diff --git a/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f b/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f index c15ef80f14..886364f5ad 100644 --- a/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f +++ b/Task/Sorting-algorithms-Bubble-sort/Fortran/sorting-algorithms-bubble-sort.f @@ -2,7 +2,7 @@ SUBROUTINE Bubble_Sort(a) REAL, INTENT(in out), DIMENSION(:) :: a REAL :: temp INTEGER :: i, j - LOGICAL :: swapped = .TRUE. + LOGICAL :: swapped DO j = SIZE(a)-1, 1, -1 swapped = .FALSE. diff --git a/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-3.hs b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-3.hs new file mode 100644 index 0000000000..7752565930 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Haskell/sorting-algorithms-bubble-sort-3.hs @@ -0,0 +1,16 @@ +import Data.Maybe (fromMaybe) +import Control.Monad + +bubbleSortBy :: (a -> a -> Bool) -> [a] -> [a] +bubbleSortBy f as = case innerSort $ reverse as of + Nothing -> as + Just v -> let (x:xs) = reverse v + in x : bubbleSortBy f xs + where innerSort (a:b:cs) = if b `f` a + then liftM (a:) $ innerSort (b:cs) + else Just $ b : fromMaybe (a:cs) + (innerSort $ a:cs) + innerSort _ = Nothing + +bsort :: Ord a => [a] -> [a] +bsort = bubbleSortBy (<) diff --git a/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort.m b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort.m new file mode 100644 index 0000000000..2598b65718 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/MATLAB/sorting-algorithms-bubble-sort.m @@ -0,0 +1,20 @@ +function list = bubbleSort(list) + + hasChanged = true; + itemCount = numel(list); + + while(hasChanged) + + hasChanged = false; + itemCount = itemCount - 1; + + for index = (1:itemCount) + + if(list(index) > list(index+1)) + list([index index+1]) = list([index+1 index]); %swap + hasChanged = true; + end %if + + end %for + end %while +end %bubbleSort diff --git a/Task/Sorting-algorithms-Bubble-sort/Objective-C/sorting-algorithms-bubble-sort.m b/Task/Sorting-algorithms-Bubble-sort/Objective-C/sorting-algorithms-bubble-sort.m new file mode 100644 index 0000000000..ad9f7cea03 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Objective-C/sorting-algorithms-bubble-sort.m @@ -0,0 +1,15 @@ +- (NSArray *) bubbleSort:(NSMutableArray *)unsorted { + BOOL done = false; + + while (!done) { + done = true; + for (int i = 1; i < unsorted.count; i++) { + if ( [[unsorted objectAtIndex:i-1] integerValue] > [[unsorted objectAtIndex:i] integerValue] ) { + [unsorted exchangeObjectAtIndex:i withObjectAtIndex:i-1]; + done = false; + } + } + } + + return unsorted; +} diff --git a/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort.pro b/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-1.pro similarity index 100% rename from Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort.pro rename to Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-1.pro diff --git a/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-2.pro b/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-2.pro new file mode 100644 index 0000000000..80e05d21b1 --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Prolog/sorting-algorithms-bubble-sort-2.pro @@ -0,0 +1,22 @@ +:- initialization(main). + + +bubble_sort(Xs,Res) :- + write(Xs), nl + , bubble_pass(Xs,Ys,Changed) + , ( Changed == true -> bubble_sort(Ys,Res) ; Res = Xs ) + . + +bubble_pass(Xs,Res,Changed) :- + Xs = [X|Ys], Ys = [Y|Zs] + , ( X > Y -> H = Y, T = [X|Zs], Changed = true + ; H = X, T = Ys + ) + , Res = [H|R], !, bubble_pass(T,R,Changed) + ; Res = Xs + . + + +test([8,9,1,3,4,2,6,5,4]). + +main :- test(T), bubble_sort(T,_), halt. 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 index 544d7851fc..3eaa445d7a 100644 --- a/Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic +++ b/Task/Sorting-algorithms-Bubble-sort/REALbasic/sorting-algorithms-bubble-sort.realbasic @@ -1,7 +1,7 @@ Dim sortable() As Integer ' assume the array is populated sortable.Shuffle() ' sortable is now randomized + Dim swapped As Boolean Do - Dim swapped As Boolean Dim index, bound As Integer bound = sortable.Ubound @@ -15,6 +15,5 @@ index = index + 1 Wend - If not swapped Then Exit Do - Loop + Loop Until Not swapped 'sortable is now sorted diff --git a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx index 4242bf1835..55df1d7216 100644 --- a/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx +++ b/Task/Sorting-algorithms-Bubble-sort/REXX/sorting-algorithms-bubble-sort.rexx @@ -1,50 +1,48 @@ -/*REXX program sorts an array using the bubble-sort method. */ - +/*REXX program sorts an array using the bubble-sort algorithm. */ call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call bubbleSort highItem /*invoke the bubble sort. */ -call show@ ' after sort' /*show the after array elements.*/ +call show@ 'before sort' /*show the before array elements.*/ +call bubbleSort # /*invoke the bubble sort. */ +call show@ ' after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────BUBBLESORT subroutine───────────────*/ -bubbleSort: procedure expose @.; parse arg n /* n = number of items. */ +bubbleSort: procedure expose @.; parse arg n /*N: number of items.*/ /*diminish # items each time. */ - do until done /*sort until it's done. */ - done=1 /*assume it's done (1 = true). */ - do j=1 for n-1 /*sort M items this time. */ + do until done /*sort until it's done. */ + done=1 /*assume it's done (1 ≡ true). */ + do j=1 for n-1 /*sort M items this time around. */ k=j+1 /*point to the next item. */ - if @.j>@.k then do /*is it out of order ? */ - _=@.j /*assign to a temp variable. */ - @.j=@.k /*swap current with next. */ - @.k=_ /*... and next with _ */ - done=0 /*indicate it's not done. */ - end /* 1=true 0=false */ + if @.j>@.k then do /*is it out of order? */ + _=@.j /*assign to a temp variable. */ + @.j=@.k /*swap current item with next ···*/ + @.k=_ /* ··· and the next with _ */ + done=0 /*indicate it's not done, whereas*/ + end /* [↑] 1≡true 0≡false */ end /*j*/ end /*until done*/ return /*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign some default values. */ -@.1 ='---letters of the Hebrew alphabet---' ; @.13='kaph [kaf]' -@.2 ='====================================' ; @.14='lamed' -@.3 ='aleph [alef]' ; @.15='mem' -@.4 ='beth [bet]' ; @.16='nun' -@.5 ='gimel' ; @.17='samekh' -@.6 ='daleth [dalet]' ; @.18='ayin' -@.7 ='he' ; @.19='pe' -@.8 ='waw [vav]' ; @.20='sadhe [tsadi]' -@.9 ='zayin' ; @.21='qoph [qof]' -@.10='heth [het]' ; @.22='resh' -@.11='teth [tet]' ; @.23='shin' -@.12='yod' ; @.24='taw [tav]' +gen@: @.= /*assign default value to all @. */ +@.1 = '---letters of the Hebrew alphabet---' ; @.13 = 'kaph [kaf]' +@.2 = '====================================' ; @.14 = 'lamed' +@.3 = 'aleph [alef]' ; @.15 = 'mem' +@.4 = 'beth [bet]' ; @.16 = 'nun' +@.5 = 'gimel' ; @.17 = 'samekh' +@.6 = 'daleth [dalet]' ; @.18 = 'ayin' +@.7 = 'he' ; @.19 = 'pe' +@.8 = 'waw [vav]' ; @.20 = 'sadhe [tsadi]' +@.9 = 'zayin' ; @.21 = 'qoph [qof]' +@.10 = 'heth [het]' ; @.22 = 'resh' +@.11 = 'teth [tet]' ; @.23 = 'shin' +@.12 = 'yod' ; @.24 = 'taw [tav]' - do highItem=1 while @.highItem\=='' /*find how many entries. */ - end /*highitem*/ - -highItem=highItem-1 /*adjust highItem slightly. */ + do #=1 while @.# \=='' /*find how many entries in list. */ + end /*#*/ +#=#-1 /*adjust because of DO increment.*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*maximum width of any line. */ - do j=1 for highItem - say 'element' right(j,widthH) arg(1)':' @.j - end -say copies('-',80) /*show a separator line. */ +show@: widthH=length(#) /*maximum width of any line. */ + do j=1 for # + say 'element' right(j,widthH) arg(1)':' @.j + end /*j*/ +say copies('─',80) /*show a separator line. */ return diff --git a/Task/Sorting-algorithms-Bubble-sort/Scilab/sorting-algorithms-bubble-sort.scilab b/Task/Sorting-algorithms-Bubble-sort/Scilab/sorting-algorithms-bubble-sort.scilab new file mode 100644 index 0000000000..d29ebca1cd --- /dev/null +++ b/Task/Sorting-algorithms-Bubble-sort/Scilab/sorting-algorithms-bubble-sort.scilab @@ -0,0 +1,16 @@ +function b=BubbleSort(a) + n=length(a) + swapped=%T + while swapped + swapped=%F + for i=1:1:n-1 + if a(i)>a(i+1) then + temp=a(i) + a(i)=a(i+1) + a(i+1)=temp + swapped=%T + end + end + end + b=a +endfunction BubbleSort diff --git a/Task/Sorting-algorithms-Cocktail-sort/00DESCRIPTION b/Task/Sorting-algorithms-Cocktail-sort/00DESCRIPTION index 227d415668..03adf697a7 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Cocktail-sort/00DESCRIPTION @@ -1,5 +1,6 @@ {{Sorting Algorithm}}{{wikipedia|Cocktail sort}} -The cocktail shaker sort is an improvement on the [[Bubble Sort]]. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from [[wp:Cocktail sort|wikipedia]]): +The cocktail shaker sort is an improvement on the [[Bubble Sort]]. +The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from [[wp:Cocktail sort|wikipedia]]): '''function''' ''cocktailSort''( A : list of sortable items ) '''do''' swapped := false diff --git a/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-1.cpp similarity index 78% rename from Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp rename to Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-1.cpp index de45c091a3..20c70d2d9a 100644 --- a/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort.cpp +++ b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-1.cpp @@ -1,10 +1,8 @@ #include #include -//-------------------------------------------------------------------------------------------------- const int EL_COUNT = 77, LLEN = 11; -//-------------------------------------------------------------------------------------------------- class cocktailSort { public: @@ -44,13 +42,13 @@ private: a = b; b = t; } }; -//-------------------------------------------------------------------------------------------------- + int main( int argc, char* argv[] ) { srand( GetTickCount() ); cocktailSort cs; int arr[EL_COUNT]; - + for( int x = 0; x < EL_COUNT; x++ ) arr[x] = rand() % EL_COUNT + 1; @@ -66,7 +64,7 @@ int main( int argc, char* argv[] ) //DWORD now = GetTickCount(); cs.sort( arr, EL_COUNT ); //now = GetTickCount() - now; - + std::cout << std::endl << std::endl << "Sorted: " << std::endl << "========" << std::endl; for( int x = 0; x < EL_COUNT; x += LLEN ) { @@ -78,8 +76,5 @@ int main( int argc, char* argv[] ) std::cout << std::endl << std::endl << std::endl << std::endl; //std::cout << now << std::endl << std::endl; - system( "pause" ); - return 0; } -//-------------------------------------------------------------------------------------------------- diff --git a/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-2.cpp b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-2.cpp new file mode 100644 index 0000000000..358c6e35a3 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/C++/sorting-algorithms-cocktail-sort-2.cpp @@ -0,0 +1,35 @@ +#include +#include +#include + +template +void cocktail_sort(RandomAccessIterator begin, RandomAccessIterator end) { + bool swapped = true; + while (begin != end-- && swapped) { + swapped = false; + for (auto i = begin; i != end; ++i) { + if (*(i + 1) < *i) { + std::iter_swap(i, i + 1); + swapped = true; + } + } + if (!swapped) { + break; + } + swapped = false; + for (auto i = end - 1; i != begin; --i) { + if (*i < *(i - 1)) { + std::iter_swap(i, i - 1); + swapped = true; + } + } + ++begin; + } +} + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + cocktail_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-1.d b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-1.d new file mode 100644 index 0000000000..75f5b2c464 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-1.d @@ -0,0 +1,37 @@ +// Written in the D programming language. +module rosettaCode.sortingAlgorithms.cocktailSort; + +import std.range; + +Range cocktailSort(Range)(Range data) +if (isRandomAccessRange!Range && hasLvalueElements!Range) { + import std.algorithm : swap; + bool swapped = void; + void trySwap(E)(ref E lhs, ref E rhs) { + if (lhs > rhs) { + swap(lhs, rhs); + swapped = true; + } + } + + if (data.length > 0) do { + swapped = false; + foreach (i; 0 .. data.length - 1) + trySwap(data[i], data[i + 1]); + if (!swapped) + break; + swapped = false; + foreach_reverse (i; 0 .. data.length - 1) + trySwap(data[i], data[i + 1]); + } while(swapped); + return data; +} + +unittest { + assert (cocktailSort([3, 1, 5, 2, 4]) == [1, 2, 3, 4, 5]); + assert (cocktailSort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]); + assert (cocktailSort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]); + assert (cocktailSort((int[]).init) == []); + assert (cocktailSort(["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]) == + ["Alice", "Jane", "Joe", "John", "Kate", "Zerg"]); +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-2.d b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-2.d new file mode 100644 index 0000000000..f141131484 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort-2.d @@ -0,0 +1,7 @@ +import rosettaCode.sortingAlgorithms.cocktailSort; + +void main() { + import std.stdio, std.algorithm, std.range, std.random; + //generate 10 sorted random numbers in [0 .. 10) + rndGen.take(10).map!(a=>a%10).array.cocktailSort.writeln(); +} diff --git a/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d b/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d deleted file mode 100644 index 54f03b84e4..0000000000 --- a/Task/Sorting-algorithms-Cocktail-sort/D/sorting-algorithms-cocktail-sort.d +++ /dev/null @@ -1,26 +0,0 @@ -import std.stdio, std.algorithm; - -void cocktailSort(Range)(Range data) { - bool swapped = false; - do { - foreach (i; 0 .. data.length - 1) - if (data[i] > data[i + 1]) { - swap(data[i], data[i + 1]); - swapped = true; - } - if (!swapped) - break; - swapped = false; - foreach_reverse (i; 0 .. data.length - 1) - if (data[i] > data[i + 1]) { - swap(data[i], data[i + 1]); - swapped = true; - } - } while(swapped); -} - -void main() { - auto array = ["John", "Kate", "Zerg", "Alice", "Joe", "Jane"]; - cocktailSort(array); - writeln(array); -} diff --git a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e new file mode 100644 index 0000000000..5c0b0435e5 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-1.e @@ -0,0 +1,50 @@ +class + COCKTAIL_SORT[G -> COMPARABLE] +feature +cocktail_sort(ar: ARRAY[G]): ARRAY[G] + require + ar_not_empty: ar.count>=1 + local + swapped, finished: BOOLEAN + sol: ARRAY[G] + i,j : INTEGER + t: G + do + create sol.make_from_array (ar) + from + until finished= TRUE + loop + swapped := FALSE + from + i:= 1 + until + i= ar.count-1 + loop + if ar[i]> ar[i+1] then + t:= ar[i] + ar[i]:= ar[i+1] + ar[i+1]:= t + swapped:= true + end + i:= i+1 + end + + from j:= ar.count-1 + until j= 1 + loop + if ar[j]> ar[j+1] then + t:= ar[j] + ar[j]:= ar[j+1] + ar[j+1]:= t + swapped:= TRUE + end + j:= j-1 + end + if swapped= FALSE then + finished:= TRUE + sol:= ar + end + end + Result:= sol + end +end diff --git a/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e new file mode 100644 index 0000000000..ec76e37587 --- /dev/null +++ b/Task/Sorting-algorithms-Cocktail-sort/Eiffel/sorting-algorithms-cocktail-sort-2.e @@ -0,0 +1,18 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + test:= <<5,1,99,3,2>> + across test as t loop io.put_string (t.item.out + "%T") end + create cs + test:= cs.cocktail_sort(test) + across test as ar loop io.put_string (ar.item.out+"%T") end + end + cs: COCKTAIL_SORT[INTEGER] + test: ARRAY[INTEGER] +end diff --git a/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d b/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d index d8cdd6271e..fa808225e5 100644 --- a/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d +++ b/Task/Sorting-algorithms-Comb-sort/D/sorting-algorithms-comb-sort.d @@ -1,22 +1,22 @@ import std.stdio, std.algorithm; -void combSort(T)(T[] input) { +void combSort(T)(T[] input) pure nothrow @safe @nogc { int gap = input.length; bool swaps = true; while (gap > 1 || swaps) { gap = max(1, cast(int)(gap / 1.2473)); swaps = false; - foreach (i; 0 .. input.length - gap) + foreach (immutable i; 0 .. input.length - gap) if (input[i] > input[i + gap]) { - swap(input[i], input[i + gap]); + input[i].swap(input[i + gap]); swaps = true; } } } void main() { - auto array = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; - combSort(array); - writeln(array); + auto data = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; + data.combSort; + data.writeln; } diff --git a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e new file mode 100644 index 0000000000..aeeeb39124 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-1.e @@ -0,0 +1,44 @@ +class + COMB_SORT[G -> COMPARABLE] +feature + combsort (ar: ARRAY[G]): ARRAY[G] + require + array_not_empty: ar.count >0 + local + gap, i: INTEGER + swap: G + swapped: BOOLEAN + shrink: REAL_64 + do + gap:= ar.count + from + + until + gap= 1 and swapped = false + loop + from + i:= 1 + swapped:= false + until + i+gap > ar.count + loop + if ar[i]> ar[i+gap] then + swap:= ar[i] + ar[i]:= ar[i+gap] + ar[i+gap]:= swap + swapped:= TRUE + end + i:= i+1 + end + shrink:= gap/1.3 + gap:= shrink.floor + if gap <1 then + gap:= 1 + end + end + RESULT:= ar + ensure + RESULT_is_set: Result /= VOID + + end +end diff --git a/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e new file mode 100644 index 0000000000..f26caf6d1c --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/Eiffel/sorting-algorithms-comb-sort-2.e @@ -0,0 +1,24 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature + make + + do + test:= <<1,5,99,2,95, 7,-7>> + io.put_string ("unsorted"+"%N") + across test as ar loop io.put_string(ar.item.out + "%T") end + io.put_string ("%N"+"sorted:"+"%N") + create combsort + test:=combsort.combsort(test) + across test as ar loop io.put_string (ar.item.out + "%T") end + end + combsort: COMB_SORT[INTEGER] + test: ARRAY[INTEGER] +end diff --git a/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-1.max b/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-1.max new file mode 100644 index 0000000000..6295b4f9bc --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-1.max @@ -0,0 +1,28 @@ +fn combSort arr = +( + local gap = arr.count + local swaps = 1 + while not (gap == 1 and swaps == 0) do + ( + gap = (gap / 1.25) as integer + if gap < 1 do + ( + gap = 1 + ) + local i = 1 + swaps = 0 + while not (i + gap > arr.count) do + ( + if arr[i] > arr[i+gap] do + ( + swap arr[i] arr[i+gap] + swaps = 1 + ) + i += 1 + + ) + + + ) + return arr +) diff --git a/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-2.max b/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-2.max new file mode 100644 index 0000000000..19e9910783 --- /dev/null +++ b/Task/Sorting-algorithms-Comb-sort/MAXScript/sorting-algorithms-comb-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 10 collect random 1 10 +#(2, 6, 5, 9, 10, 7, 2, 6, 1, 4) +combsort a +#(1, 2, 2, 4, 5, 6, 6, 7, 9, 10) diff --git a/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx index 58ec22c33b..dcde047a63 100644 --- a/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx +++ b/Task/Sorting-algorithms-Comb-sort/REXX/sorting-algorithms-comb-sort.rexx @@ -1,44 +1,36 @@ -/*REXX program sorts an array using the comb-sort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call combSort highItem /*invoke the comb sort. */ -call show@ ' after sort' /*show the after array elements.*/ +/*REXX program sorts a stemmed array using the comb-sort algorithm. */ +call gen@; w=length(#) /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call combSort # /*invoke the comb sort. */ +call show@ ' after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────COMBSORT subroutine─────────────────*/ -combSort: procedure expose @.; parse arg n -s=n-1 /*S = spread between COMBs. */ - - do until s<=1 & done - s=trunc(s*.8) /* ÷ is slow, * is better. */ - done=1 - do j=1 until j+s>=n - jps=j+s - if @.j>@.jps then do; _=@.j; @.j=@.jps; @.jps=_; done=0; end - end /*j*/ - end /*until*/ - +combSort: procedure expose @.; parse arg N /*N: is number of elements.*/ +s=N-1 /*S: is the spread between COMBs.*/ + do until s<=1 & done; done=1 /*assume sort is done (so far). */ + s=trunc(s*.8) /* ÷ is slow, * is better.*/ + do j=1 until js>=N; js=j+s + if @.j>@.js then do; _=@.j; @.j=@.js; @.js=_; done=0; end + end /*j*/ + end /*until*/ return /*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign the default value. */ -@.1 ='--- polygon sides' -@.2 ='============== =====' -@.3 ='triangle 3' -@.4 ='quadrilateral 4' -@.5 ='pentagon 5' -@.6 ='hexagon 6' -@.7 ='heptagon 7' -@.8 ='octagon 8' -@.9 ='nonagon 9' -@.10='decagon 10' -@.11='dodecagon 12' - do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ - end -highItem=highItem-1 /*adjust highItem slightly. */ +gen@: @. = ; @.12 = 'dodecagon 12' + @.1 = '----polygon--- sides' ; @.13 = 'tridecagon 13' + @.2 = '============== =======' ; @.14 = 'tetradecagon 14' + @.3 = 'triangle 3' ; @.15 = 'pentadecagon 15' + @.4 = 'quadrilateral 4' ; @.16 = 'hexadecagon 16' + @.5 = 'pentagon 5' ; @.17 = 'heptadecagon 17' + @.6 = 'hexagon 6' ; @.18 = 'octadecagon 18' + @.7 = 'heptagon 7' ; @.19 = 'enneadecagon 19' + @.8 = 'octagon 8' ; @.20 = 'icosagon 20' + @.9 = 'nonagon 9' ; @.21 = 'hectogon 100' + @.10 = 'decagon 10' ; @.22 = 'chiliagon 1000' + @.11 = 'hendecagon 11' ; @.23 = 'myriagon 10000' + do #=1 while @.#\==''; end; #=#-1 /*find how many entries in array.*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*the maximum width of any line. */ - do j=1 for highItem - say 'element' right(j,widthH) arg(1)":" @.j - end -say copies('─',79) /*show a nice separator line. */ +show@: say copies('▒',60); do j=1 for # /*display array elements.*/ + say ' element' right(j,w) arg(1)":" @.j + end /*j*/ return diff --git a/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-1.cpp similarity index 99% rename from Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp rename to Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-1.cpp index 5a0d12cb93..cdcedc76d5 100644 --- a/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort.cpp +++ b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-1.cpp @@ -48,7 +48,7 @@ int main( int argc, char* argv[] ) srand( time( NULL ) ); int arr[MAX]; for( int i = 0; i < MAX; i++ ) arr[i] = rand() % 140 - rand() % 40 + 1; - + for( int i = 0; i < MAX; i++ ) cout << arr[i] << ", "; cout << endl << endl; diff --git a/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-2.cpp b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-2.cpp new file mode 100644 index 0000000000..ec943629bb --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/C++/sorting-algorithms-counting-sort-2.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +template void counting_sort(ForwardIterator begin, + ForwardIterator end) { + auto min_max = std::minmax_element(begin, end); + if (min_max.first == min_max.second) { // empty range + return; + } + auto min = *min_max.first; + auto max = *min_max.second; + std::vector count((max - min) + 1, 0u); + for (auto i = begin; i != end; ++i) { + ++count[*i - min]; + } + for (auto i = min; i <= max; ++i) { + for (auto j = 0; j < count[i - min]; ++j) { + *begin++ = i; + } + } +} + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + counting_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; +} diff --git a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e new file mode 100644 index 0000000000..1295132c97 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-1.e @@ -0,0 +1,34 @@ +class + COUNTING_SORT +feature +sort(ar: ARRAY[INTEGER]; min, max: INTEGER): ARRAY[INTEGER] + local + count: ARRAY[INTEGER] + i, j, z: INTEGER + do + create count.make_filled (0, 0, max-min) + from + i:= 0 + until + i= ar.count + loop + count[ar[i]-min]:= count[ar[i]-min]+1 + i:= i+1 + end + across count as c loop io.put_string (c.item.out + "%T") end + z:= 0 + from i:= min + until i>max + loop + from j:= 0 + until j= count[i-min] + loop + ar[z]:=i + z:= z+1 + j:= j+1 + end + i:= i+1 + end + Result:= ar + end +end diff --git a/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e new file mode 100644 index 0000000000..68ca47029c --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/Eiffel/sorting-algorithms-counting-sort-2.e @@ -0,0 +1,24 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + create test.make_filled(0,0,5) + test[0]:=-7 + test[1]:=4 + test[2]:=2 + test[3]:=6 + test[4]:=1 + test[5]:=3 + across test as t loop io.put_string (t.item.out + "%T") end + create count + test:=count.sort (test, -7, 6) + across test as ar loop io.put_string (ar.item.out+"%T") end + end + count: COUNTING_SORT + test: ARRAY[INTEGER] +end diff --git a/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-1.max b/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-1.max new file mode 100644 index 0000000000..d263b7a830 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-1.max @@ -0,0 +1,23 @@ +fn countingSort arr = +( + if arr.count < 2 do return arr + local minVal = amin arr + local maxVal = amax arr + local count = for i in 1 to (maxVal-minVal+1) collect 0 + for i in arr do + ( + count[i-minVal+1] = count[i-minVal+1] + 1 + ) + local z = 1 + for i = minVal to maxVal do + ( + while (count[i-minVal+1]>0) do + ( + arr[z] = i + z += 1 + count[i-minVal+1] = count[i-minVal+1] - 1 + ) + + ) + return arr +) diff --git a/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-2.max b/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-2.max new file mode 100644 index 0000000000..13d2201291 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/MAXScript/sorting-algorithms-counting-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 15 collect random 1 30 +#(7, 1, 6, 16, 27, 11, 24, 16, 25, 11, 22, 7, 28, 15, 17) +countingSort a +#(1, 6, 7, 7, 11, 11, 15, 16, 16, 17, 22, 24, 25, 27, 28) diff --git a/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-1.rexx b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-1.rexx new file mode 100644 index 0000000000..22789addb3 --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-1.rexx @@ -0,0 +1,32 @@ +/*REXX program sorts an array using the count-sort algorithm. */ +call gen@ /*generate the array elements. */ +call show@ 'before sort' /*show the before array elements.*/ +call countSort # /*sort N entries of the @. array.*/ +call show@ ' after sort' /*show the after array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────COUNTSORT subroutine────────────────*/ +countSort: procedure expose @.; parse arg N; h=@.1; L=h + + do i=2 to N; L=min(L,@.i); h=max(h,@.i); end /*i*/ + +_.=0; do j=1 for N; x=@.j; _.x=_.x+1; end /*j*/ + +x=1; do k=L to h; if _.k\==0 then do x=x for _.k + @.x=k + end /*x*/ + end /*k*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: $=1 3 6 2 7 13 20 12 21 11 22 10 23 9 24 8 25 43 62 42 63 41 18 42 17 43 16 44 15 45 14 46 79 113 78 114 77 39 78 38 +#=words($) + do j=1 for # /* [↓] assign 40 Recaman numbers.*/ + @.j=word($,j) /*assign a Recaman # from a list.*/ + end /*j*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: do s=1 for # + say left('',9) "element" right(s,length(#)) arg(1)': ' @.s + end /*s*/ + +say copies('─',50) /*show a pretty separator line. */ +return diff --git a/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-2.rexx b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-2.rexx new file mode 100644 index 0000000000..9a0655378b --- /dev/null +++ b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort-2.rexx @@ -0,0 +1,43 @@ +/* REXX --------------------------------------------------------------- +* 13.07.2014 Walter Pachl translated from PL/I +*--------------------------------------------------------------------*/ +alist='999 888 777 1 5 13 15 17 19 21 5' +Parse Var alist lo hi . +Do i=1 By 1 While alist<>'' + Parse Var alist a.i alist; + lo=min(lo,a.i) + hi=max(hi,a.i) + End +a.0=i-1 + +Call show 'before count_sort' +Call count_sort +Call show 'after count_sort' +Exit + +count_sort: procedure Expose a. lo hi + t.=0 + do i=1 to a.0 + j=a.i + t.j=t.j+1 + end + k=1 + do i=lo to hi + if t.i<>0 then Do + do j=1 to t.i + a.k=i + k=k+1 + end + end + end + Return + +show: Procedure Expose a. +Parse Arg head +Say head +ol='' +Do i=1 To a.0 + ol=ol right(a.i,3) + End +Say ol +Return diff --git a/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx b/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx deleted file mode 100644 index 7a5f74d9fd..0000000000 --- a/Task/Sorting-algorithms-Counting-sort/REXX/sorting-algorithms-counting-sort.rexx +++ /dev/null @@ -1,41 +0,0 @@ -/*REXX program sorts an array using the count-sort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call countSort N /*sort N entries of the @. array.*/ -call show@ ' after sort' /*show the after array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────countSort subroutine────────────────*/ -countSort: procedure expose @.; parse arg N; h=@.1; L=h - - do i=2 to N; L=min(L,@.i); h=max(h,@.i) - end /*i*/ - -_.=0; do j=1 for N; x=@.j; _.x=_.x+1 - end /*j*/ - -#=1; do k=L to h; if _.k\==0 then do #=# for _.k - @.#=k - end /*#*/ - end /*k*/ -return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign 40 Recaman numbers. */ -@.1 = 1 ; @.9 = 21 ; @.17= 25 ; @.25= 17 ; @.33= 79 -@.2 = 3 ; @.10= 11 ; @.18= 43 ; @.26= 43 ; @.34= 113 -@.3 = 6 ; @.11= 22 ; @.19= 62 ; @.27= 16 ; @.35= 78 -@.4 = 2 ; @.12= 10 ; @.20= 42 ; @.28= 44 ; @.36= 114 -@.5 = 7 ; @.13= 23 ; @.21= 63 ; @.29= 15 ; @.37= 77 -@.6 = 13 ; @.14= 9 ; @.22= 41 ; @.30= 45 ; @.38= 39 -@.7 = 20 ; @.15= 24 ; @.23= 18 ; @.31= 14 ; @.39= 78 -@.8 = 12 ; @.16= 8 ; @.24= 42 ; @.32= 46 ; @.40= 38 - - do N=1 while @.N\==''; end /*determine the number of entries*/ -N=N-1 /*adjust highItem slightly. */ -return -/*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(N) /*max width of any element number*/ -pad=left('',9); do s=1 for N - say pad 'element' right(s,widthH) arg(1)": " @.s - end /*s*/ -say copies('─',40) /*show a pretty separator line. */ -return diff --git a/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat b/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat new file mode 100644 index 0000000000..edf095005f --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Batch-File/sorting-algorithms-gnome-sort.bat @@ -0,0 +1,60 @@ +@ECHO OFF +SETLOCAL EnableExtensions EnableDelayedExpansion +:: GnomeSort.cmd in WinNT Batch using pseudo array. +:: Set the number of random elements to sort. +SET numElements=100 +:: Decrement numElements for use in zero-based loops as in (0, 1, %numElements% - 1). +SET /A tmpElements=%numElements% - 1 + +:: Create array of random numbers and output to file. +ECHO GnomeSort Random Input 0 to %tmpElements%:>%~n0.txt +FOR /L %%X IN (0, 1, %tmpElements%) DO ( + SET array[%%X]=!RANDOM! + ECHO !array[%%X]!>>%~n0.txt +) + +:GnomeSort +:: Initialize the pointers i-1, i, and j. +SET gs1=0 +SET gs2=1 +SET gs3=2 +:GS_Loop +:: Implementing a WHILE loop in WinNT batch using GOTO. It only executes +:: if the condition is true and continues until the condition is false. +:: First, display [i-1][j - 2] to the Title Bar. +SET /A gsTmp=%gs3% - 2 +TITLE GnomeSort:[%gs1%][%gsTmp%] of %tmpElements% +:: ...then start Main Loop. It's a direct implementation of the +:: pseudo code supplied by Rosetta Code. I had to add an additional +:: pointer to represent i-1, because of limitations in WinNT Batch. +IF %gs2% LSS %numElements% ( + REM if i-1 <= i advance pointers to next unchecked element, then loop. + IF !array[%gs1%]! LEQ !array[%gs2%]! ( + SET /A gs1=%gs3% - 1 + SET /A gs2=%gs3% + SET /A gs3=%gs3% + 1 + ) ELSE ( + REM ... else swap i-1 and i, decrement pointers to check previous element, then loop. + SET gsTmp=!array[%gs1%]! + SET array[%gs1%]=!array[%gs2%]! + SET array[%gs2%]=!gsTmp! + SET /A gs1-=1 + SET /A gs2-=1 + REM if first element has been reached, set pointers to next unchecked element. + IF !gs2! EQU 0 ( + SET /A gs1=%gs3% - 1 + SET /A gs2=%gs3% + SET /A gs3=%gs3% + 1 + ) + ) + GOTO :GS_Loop +) +TITLE GnomeSort:[%gs1%][%gsTmp%] - Done! + +:: write sorted elements out to file +ECHO.>>%~n0.txt +ECHO GnomeSort Sorted Output 0 to %tmpElements%:>>%~n0.txt +FOR /L %%X IN (0, 1, %tmpElements%) DO ECHO !array[%%X]!>>%~n0.txt + +ENDLOCAL +EXIT /B 0 diff --git a/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp b/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp index 02c28adf66..f8ffe22c2a 100644 --- a/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp +++ b/Task/Sorting-algorithms-Gnome-sort/C++/sorting-algorithms-gnome-sort.cpp @@ -1,22 +1,30 @@ #include #include +#include template -void gnomeSort(RandomAccessIterator begin, RandomAccessIterator end) { - RandomAccessIterator i = begin + 1; - RandomAccessIterator j = begin + 2; +void gnome_sort(RandomAccessIterator begin, RandomAccessIterator end) { + auto i = begin + 1; + auto j = begin + 2; - while(i < end) { - if(*(i - 1) <= *i) { + while (i < end) { + if (!(*i < *(i - 1))) { i = j; ++j; } else { std::iter_swap(i - 1, i); --i; - if(i == begin) { + if (i == begin) { i = j; ++j; } } } } + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + gnome_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; +} diff --git a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e new file mode 100644 index 0000000000..7eff8e357c --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-1.e @@ -0,0 +1,38 @@ +class + GNOME_SORT + +feature + sort(ar: ARRAY[INTEGER]): ARRAY[INTEGER] + -- sort array ar with gnome sort + require + array_not_void: ar/= VOID + local + i,j, ith: INTEGER + do + from + i:= 2 + j:= 3 + until + i>ar.count + loop + if ar[i-1] <= ar[i] then + i:= j + j:= j+1 + else + ith := ar[i-1] + ar[i-1] := ar[i] + ar[i] := ith + i:= i-1 + if i=1 then + i:=j + j:= j+1 + end + end + end + Result := ar + ensure + same_length: ar.count = Result.count + same_items: Result.same_items (ar) + end + +end diff --git a/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e new file mode 100644 index 0000000000..ccae0061d0 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/Eiffel/sorting-algorithms-gnome-sort-2.e @@ -0,0 +1,21 @@ +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature + make + do + test:= <<7, 99, -7, 1, 0, 25, -10>> + create gnome + test:= gnome.sort (test) + across test as ar loop io.put_string( ar.item.out + "%T") end + end + + test: ARRAY[INTEGER] + gnome: GNOME_SORT[INTEGER] +end diff --git a/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max new file mode 100644 index 0000000000..4a5c144f17 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-1.max @@ -0,0 +1,24 @@ +fn gnomeSort arr = +( + local i = 2 + local j = 3 + while i <= arr.count do + ( + if arr[i-1] <= arr[i] then + ( + i = j + j += 1 + ) + else + ( + swap arr[i-1] arr[i] + i -= 1 + if i == 1 then + ( + i = j + j += 1 + ) + ) + ) + return arr +) diff --git a/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-2.max b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-2.max new file mode 100644 index 0000000000..24b6422c4c --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/MAXScript/sorting-algorithms-gnome-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 10 collect random 1 20 +#(20, 10, 16, 2, 19, 12, 11, 3, 5, 16) +gnomesort a +#(2, 3, 5, 10, 11, 12, 16, 16, 19, 20) diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx new file mode 100644 index 0000000000..f14311d2f5 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-1.rexx @@ -0,0 +1,31 @@ +/*REXX program sorts a stemmed array using the gnome-sort algorithm.*/ +call gen@ /*generate the @. array elements.*/ +call show@ 'before sort' /*show "before" array elements.*/ +call gnomeSort # /*invoke the infamous gnome sort.*/ +call show@ ' after sort' /*show "after" array elements.*/ +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────GNOMESORT subroutine────────────────*/ +gnomeSort: procedure expose @.; parse arg n; k=2 /*n=num items.*/ + do j=3 while k<=n; km=k-1 /*KM=prev item*/ + if @.km<<=@.k then do; k=j; iterate; end /*OK so far···*/ + _=@.km; @.km=@.k; @.k=_ /*swap 2 entries in the @. array.*/ + k=k-1; if k==1 then k=j; else j=j-1 /*test index 1*/ + end /*j*/ /* [↑] perform gnome sort on @.*/ +return +/*──────────────────────────────────GEN@ subroutine─────────────────────*/ +gen@: !=... 'deadbeef'x ...; @.=! /*default none-value; allows null*/ +@.1 = '---the seven virtues---' /* [↓] indent the seven virtues.*/ +@.2 = '=======================' ; @.6 = 'Fortitude' +@.3 = 'Faith' ; @.7 = 'Justice' +@.4 = 'Hope' ; @.8 = 'Prudence' +@.5 = 'Charity [Love]' ; @.9 = 'Temperance' + + do #=1 while @.#\==!; end /*find the # of items in @ array.*/ +#=#-1 /*adjust the numer of items by 1.*/ +return +/*──────────────────────────────────SHOW@ subroutine────────────────────*/ +show@: do j=1 for # /* [↓] display all items for @. */ + say ' element' right(j,length(#)) arg(1)":" @.j + end /*j*/ /* [↑] right justify the J num.*/ +say copies('■',60) /*show a separator line that fits*/ +return diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-2.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-2.rexx new file mode 100644 index 0000000000..d878766319 --- /dev/null +++ b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort-2.rexx @@ -0,0 +1,46 @@ +/* REXX --------------------------------------------------------------- +* 28.06.2014 Walter Pachl cf ooRexx version 2 +* only style changes (reformatting) and adapt for ooRexx compatibility +* NOTE that leading blanks are ignored in the comparison (' Justice') +* unless strict comparison is used (i.e., 'If x.km<<=x.k Then') +* 30.06.2014 WP added the missing else clause +*--------------------------------------------------------------------*/ + /* generate the array elements. */ + Call gen '---the seven virtues---','=======================',, + 'Faith','Hope','Charity [Love]','Fortitude',' Justice',, + 'Prudence','Temperance' + Call show 'before sort' /* show "before" array elements.*/ + Call gnomeSort /* invoke the infamous gnome sort.*/ + Call show ' after sort' /* show "after" array elements.*/ + Exit /* done. */ + +gnomesort: Procedure Expose x. + k=2 + Do j=3 While k<=x.0 + km=k-1 + If x.km<=x.k Then + k=j + Else Do + t=x.km; x.km=x.k; x.k=t /* swap two entries in the array. */ + k=k-1 + If k==1 Then + k=j + Else + j=j-1 + End + End + Return + +gen: Procedure Expose x. + Do i=1 To arg() + x.i=arg(i) + End + x.0=arg() + Return + +show: Procedure Expose x. + Say arg(1) + Do i=1 To x.0 + Say 'element' right(i,2) x.i + End + Return diff --git a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx b/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx deleted file mode 100644 index 2b1178bb79..0000000000 --- a/Task/Sorting-algorithms-Gnome-sort/REXX/sorting-algorithms-gnome-sort.rexx +++ /dev/null @@ -1,41 +0,0 @@ -/*REXX program sorts an array using the gnome-sort method. */ -call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show "before" array elements.*/ -call gnomeSort highItem /*invoke the infamous gnome sort.*/ -call show@ ' after sort' /*show "after" array elements.*/ -exit /*stick a fork in it, we're done.*/ -/*─────────────────────────────────────gnomeSORT subroutine─────────────*/ -gnomeSort: procedure expose @.; parse arg n; k=2 - - do j=3 while k<=n; km=k-1 - if @.km<=@.k then k=j - else do - _=@.km /*swap two entries in the array. */ - @.km=@.k - @.k=_ - k=k-1; if k==1 then k=j - end - end /*j*/ -return -/*─────────────────────────────────────GEN@ subroutine──────────────────*/ -gen@: @.= /*assign a default value (null). */ -@.1='---the seven virtues---' -@.2='=======================' -@.3='Faith' -@.4='Hope' -@.5='Charity [Love]' -@.6='Fortitude' -@.7='Justice' -@.8='Prudence' -@.9='Temperance' - do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ - end /*not much of a DO loop, eh? */ -highItem=highItem-1 /*because of DO, adjust highItem.*/ -return -/*─────────────────────────────────────SHOW@ subroutine─────────────────*/ -show@: widthH=length(highItem) /*the maximum width of any line. */ - do j=1 for highItem /*show and tell time for array. */ - say 'element' right(j,widthH) arg(1)":" @.j /*make it pretty.*/ - end /*j*/ -say copies('─',60) /*show a separator line that fits*/ -return diff --git a/Task/Sorting-algorithms-Heapsort/00DESCRIPTION b/Task/Sorting-algorithms-Heapsort/00DESCRIPTION index c4a0b76ef6..3482da4f4c 100644 --- a/Task/Sorting-algorithms-Heapsort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Heapsort/00DESCRIPTION @@ -1,4 +1,9 @@ -{{Sorting Algorithm}}{{wikipedia|Heapsort}}[[wp:Heapsort|Heapsort]] is an in-place sorting algorithm with worst case and average complexity of O(''n'' log''n''). The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. Heapsort requires random access, so can only be used on an array-like data structure. + {{Sorting Algorithm}} {{wikipedia|Heapsort}} +{{omit from|GUISS}} +[[wp:Heapsort|Heapsort]] is an in-place sorting algorithm with worst case and average complexity of O(''n'' log''n''). +The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element. +We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front. +Heapsort requires random access, so can only be used on an array-like data structure. Pseudocode: '''function''' heapSort(a, count) '''is''' diff --git a/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp new file mode 100644 index 0000000000..5fb4a92699 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/C++/sorting-algorithms-heapsort.cpp @@ -0,0 +1,16 @@ +#include +#include +#include + +template +void heap_sort(RandomAccessIterator begin, RandomAccessIterator end) { + std::make_heap(begin, end); + std::sort_heap(begin, end); +} + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + heap_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; +} 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 a58b4e3a06..8def121c19 100644 --- a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-1.d @@ -1,6 +1,6 @@ import std.stdio, std.container; -void heapSort(T)(T[] data) /*pure nothrow*/ { +void heapSort(T)(T[] data) /*pure nothrow @safe @nogc*/ { for (auto h = data.heapify; !h.empty; h.removeFront) {} } 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 69cfd7288c..b6ddc72986 100644 --- a/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d +++ b/Task/Sorting-algorithms-Heapsort/D/sorting-algorithms-heapsort-2.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm; -void inplaceHeapSort(R)(R seq) pure nothrow { +void heapSort(R)(R seq) pure nothrow @safe @nogc { static void siftDown(R seq, in size_t start, - in size_t end) pure nothrow { + in size_t end) pure nothrow @safe @nogc { for (size_t root = start; root * 2 + 1 <= end; ) { auto child = root * 2 + 1; if (child + 1 <= end && seq[child] < seq[child + 1]) @@ -16,17 +16,17 @@ void inplaceHeapSort(R)(R seq) pure nothrow { } if (seq.length > 1) - foreach_reverse (start; 1 .. (seq.length - 2) / 2 + 2) + foreach_reverse (immutable start; 1 .. (seq.length - 2) / 2 + 2) siftDown(seq, start - 1, seq.length - 1); - foreach_reverse (end; 1 .. seq.length) { + foreach_reverse (immutable end; 1 .. seq.length) { swap(seq[end], seq[0]); siftDown(seq, 0, end - 1); } } void main() { - auto arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; - inplaceHeapSort(arr); - writeln(arr); + auto data = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]; + data.heapSort; + data.writeln; } diff --git a/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort.fth b/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-1.fth similarity index 100% rename from Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort.fth rename to Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-1.fth diff --git a/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-2.fth b/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-2.fth new file mode 100644 index 0000000000..060740f41c --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Forth/sorting-algorithms-heapsort-2.fth @@ -0,0 +1,83 @@ +\ Written in ANS-Forth; tested under VFX. +\ Requires the novice package: http://www.forth.org/novice.html +\ The following should already be done: +\ include novice.4th + +\ This is already in the novice package, so it is not really necessary to compile the code provided here. + +\ ****** +\ ****** This is our array sort. We are using the heap-sort because it provides consistent times and it is not recursive. +\ ****** This code was ported from C++ at: http://www.snippets.24bytes.com/2010/06/heap-sort.html +\ ****** Our array record size must be a multiple of W. This is assured if FIELD is used for creating the record. +\ ****** The easiest way to speed this up is to rewrite EXCHANGE in assembly language. +\ ****** + +marker HeapSort.4th + +macro: exchange ( adrX adrY size -- ) \ the size of the record must be a multiple of W + begin dup while \ -- adrX adrY remaining + over @ fourth @ \ -- adrX adrY remaining Y X + fourth ! fourth ! \ -- adrX adrY remaining + rot w + rot w + rot w - + repeat + 3drop ; + +\ All of these macros use the locals from SORT, and can only be called from SORT. + +macro: adr ( index -- adr ) + recsiz * array + ; + +macro: left ( x -- y ) 2* 1+ ; + +macro: right ( x -- y ) 2* 2 + ; + +macro: heapify ( x -- ) + dup >r begin \ r: -- great + dup left dup limit < if dup adr rover adr 'comparer execute if rdrop dup >r then then drop + dup right dup limit < if dup adr r@ adr 'comparer execute if rdrop dup >r then then drop + dup r@ <> while + adr r@ adr recsiz exchange + r@ repeat + drop rdrop ; + +macro: build-max-heap ( -- ) + limit 1- 2/ begin dup 0>= while dup heapify 1- repeat drop ; + +: sort { array limit recsiz 'comparer -- } + recsiz [ w 1- ] literal and abort" *** SORT: record size must be a multiple of the cell size ***" + build-max-heap + begin limit while -1 +to limit + 0 adr limit adr recsiz exchange + 0 heapify repeat ; + +\ The SORT locals: +\ array \ the address of the 0th element +\ limit \ the number of records in the array +\ recsiz \ the size of a record in the array \ this must be a multiple of W (FIELD assures this) +\ 'comparer \ adrX adrY -- X>Y? + +\ Note for the novice: +\ This code was originally written with colon words rather than macros, and using items rather than local variables. +\ After it was debugged, it was changed to use macros and locals so that it would be fast and reentrant. +\ One of the reasons why the heap-sort was chosen is because it is not recursive, which allows macros to be used. +\ Using macros allows the data (array, limit, recsiz, 'comparer) to be held in locals rather than items, which is reentrant. + + +\ ****** +\ ****** This tests SORT. +\ ****** + +create aaa 2 , 9 , 3 , 6 , 1 , 4 , 5 , 7 , 0 , 8 , + +: print-aaa ( limit -- ) + cells aaa + aaa do I @ . w +loop ; + +: int> ( adrX adrY -- X>Y? ) + swap @ swap @ > ; + +: test-sort ( limit -- ) + cr dup print-aaa + aaa over w ['] int> sort + cr print-aaa ; + +10 test-sort diff --git a/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-1.max b/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-1.max new file mode 100644 index 0000000000..6db574dd38 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-1.max @@ -0,0 +1,43 @@ +fn heapify arr count = +( + local s = count /2 + while s > 0 do + ( + arr = siftDown arr s count + s -= 1 + ) + return arr +) +fn siftDown arr s end = +( + local root = s + while root * 2 <= end do + ( + local child = root * 2 + if child < end and arr[child] < arr[child+1] do + ( + child += 1 + ) + if arr[root] < arr[child] then + ( + swap arr[root] arr[child] + root = child + ) + else return arr + ) + return arr +) +fn heapSort arr = +( + local count = arr.count + arr = heapify arr count + local end = count + while end >= 1 do + ( + swap arr[1] arr[end] + + end -= 1 + arr = siftDown arr 1 end + ) + +) diff --git a/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-2.max b/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-2.max new file mode 100644 index 0000000000..6fde51997d --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/MAXScript/sorting-algorithms-heapsort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 10 collect random 0 9 +#(7, 2, 5, 6, 1, 5, 4, 0, 1, 6) +heapSort a +#(0, 1, 1, 2, 4, 5, 5, 6, 6, 7) diff --git a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx index f24e4b4565..61b7048ae9 100644 --- a/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx +++ b/Task/Sorting-algorithms-Heapsort/REXX/sorting-algorithms-heapsort-1.rexx @@ -1,44 +1,42 @@ -/*REXX program sorts an array using the heapsort method. */ +/*REXX program sorts an array using the heapsort algorithm. */ call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements*/ -call heapSort highItem /*invoke the heap sort. */ -call show@ ' after sort' /*show tge after array elements*/ +call show@ 'before sort' /*show the before array elements*/ +call heapSort # /*invoke the heap sort. */ +call show@ ' after sort' /*show the after array elements*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────HEAPSORT subroutine─────────────────*/ heapSort: procedure expose @.; parse arg n; do j=n%2 by -1 to 1 - call shuffle j,n + call shuffle j,n end /*j*/ do n=n by -1 to 2 _=@.1; @.1=@.n; @.n=_; call shuffle 1,n-1 /*swap and shuffle.*/ end /*n*/ return /*──────────────────────────────────SHUFFLE subroutine──────────────────*/ -shuffle: procedure expose @.; parse arg i,n; _=@.i +shuffle: procedure expose @.; parse arg i,n; _=@.i do while i+i<=n; j=i+i; k=j+1 if k<=n then if @.k>@.j then j=k - if _>=@.j then leave - @.i=@.j; i=j - end /*while i+i≤n*/ + if _>=@.j then leave + @.i=@.j; i=j + end /*while*/ @.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. */ +gen@: @.=; @.1='---modern Greek alphabet letters---' /*default; title.*/ + @.2= copies('=', length(@.1)) /*match sep with ↑*/ +@.3='alpha' ; @.9 ='eta' ; @.15='nu' ; @.21='tau' +@.4='beta' ; @.10='theta' ; @.16='xi' ; @.22='upsilon' +@.5='gamma' ; @.11='iota' ; @.17='omicron' ; @.23='phi' +@.6='delta' ; @.12='kappa' ; @.18='pi' ; @.24='chi' +@.7='epsilon' ; @.13='lambd' ; @.19='rho' ; @.25='psi' +@.8='zeta' ; @.14='mu' ; @.20='sigma' ; @.26='omega' + + do #=1 while @.#\==''; end /*find how many entries in list. */ +#=#-1 /*adjust highItem slightly. */ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: do j=1 for highItem - say 'element' right(j,length(highItem)) arg(1)':' @.j +show@: do j=1 for # /* [↓] display elements in array.*/ + say ' element' right(j,length(#)) arg(1)':' @.j end /*j*/ -say copies('─', 79) /*show a separator line. */ +say copies('■', 70) /*show a separator line. */ return diff --git a/Task/Sorting-algorithms-Heapsort/Standard-ML/sorting-algorithms-heapsort.ml b/Task/Sorting-algorithms-Heapsort/Standard-ML/sorting-algorithms-heapsort.ml new file mode 100644 index 0000000000..b085a44fd9 --- /dev/null +++ b/Task/Sorting-algorithms-Heapsort/Standard-ML/sorting-algorithms-heapsort.ml @@ -0,0 +1,54 @@ +(* Pairing heap - http://en.wikipedia.org/wiki/Pairing_heap *) +functor PairingHeap(type t + val cmp : t * t -> order) = +struct + datatype 'a heap = Empty + | Heap of 'a * 'a heap list; + + (* merge, O(1) + * Merges two heaps *) + fun merge (Empty, h) = h + | merge (h, Empty) = h + | merge (h1 as Heap(e1, s1), h2 as Heap(e2, s2)) = + case cmp (e1, e2) of LESS => Heap(e1, h2 :: s1) + | _ => Heap(e2, h1 :: s2) + + (* insert, O(1) + * Inserts an element into the heap *) + fun insert (e, h) = merge (Heap (e, []), h) + + (* findMin, O(1) + * Returns the smallest element of the heap *) + fun findMin Empty = raise Domain + | findMin (Heap(e, _)) = e + + (* deleteMin, O(lg n) amortized + * Deletes the smallest element of the heap *) + local + fun mergePairs [] = Empty + | mergePairs [h] = h + | mergePairs (h1::h2::hs) = merge (merge(h1, h2), mergePairs hs) + in + fun deleteMin Empty = raise Domain + | deleteMin (Heap(_, s)) = mergePairs s + end + + (* build, O(n) + * Builds a heap from a list *) + fun build es = foldl insert Empty es; +end + +local + structure IntHeap = PairingHeap(type t = int; val cmp = Int.compare); + open IntHeap + + fun heapsort' Empty = [] + | heapsort' h = findMin h :: (heapsort' o deleteMin) h; +in + fun heapsort ls = (heapsort' o build) ls + + val test_0 = heapsort [] = [] + val test_1 = heapsort [1,2,3] = [1, 2, 3] + val test_2 = heapsort [1,3,2] = [1, 2, 3] + val test_3 = heapsort [6,2,7,5,8,1,3,4] = [1, 2, 3, 4, 5, 6, 7, 8] +end; diff --git a/Task/Sorting-algorithms-Insertion-sort/00DESCRIPTION b/Task/Sorting-algorithms-Insertion-sort/00DESCRIPTION index ff4b56fd38..4cf82f29aa 100644 --- a/Task/Sorting-algorithms-Insertion-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Insertion-sort/00DESCRIPTION @@ -1,8 +1,13 @@ {{Sorting Algorithm}} {{wikipedia|Insertion sort}} -An [[O]](''n''2) sorting algorithm which moves elements one at a time into the correct position. The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. +{{omit from|GUISS}} +An [[O]](''n''2) sorting algorithm which moves elements one at a time into the correct position. +The algorithm consists of inserting one element at a time into the previously sorted part of the array, moving higher ranked elements up as necessary. +To start off, the first (or smallest, or any arbitrary) element of the unsorted array is considered to be the sorted part. -Although insertion sort is an [[O]](''n''2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases (i) small ''n'', (ii) as the final finishing-off algorithm for [[O]](''n'' log''n'') algorithms such as [[Merge sort|mergesort]] and [[quicksort]]. +Although insertion sort is an [[O]](''n''2) algorithm, its simplicity, low overhead, good locality of reference and efficiency make it a good choice in two cases:
    +(i) small ''n'',
    +(ii) as the final finishing-off algorithm for [[O]](''n'' log''n'') algorithms such as [[Merge sort|mergesort]] and [[quicksort]]. The algorithm is as follows (from [[wp:Insertion_sort#Algorithm|wikipedia]]): '''function''' ''insertionSort''(array A) diff --git a/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp b/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp index d74faf7d47..a45c7ebd09 100644 --- a/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp +++ b/Task/Sorting-algorithms-Insertion-sort/C++/sorting-algorithms-insertion-sort.cpp @@ -1,8 +1,26 @@ #include +#include +#include -template -void insertion_sort(Iter beg, Iter end) -{ - for (Iter i = beg; i != end; ++i) - std::rotate(std::upper_bound(beg, i, *i), i, i+1); +template +void insertion_sort(RandomAccessIterator begin, RandomAccessIterator end, + Predicate p) { + for (auto i = begin; i != end; ++i) { + std::rotate(std::upper_bound(begin, i, *i, p), i, i + 1); + } +} + +template +void insertion_sort(RandomAccessIterator begin, RandomAccessIterator end) { + insertion_sort( + begin, end, + std::less< + typename std::iterator_traits::value_type>()); +} + +int main() { + int a[] = { 100, 2, 56, 200, -52, 3, 99, 33, 177, -199 }; + insertion_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; } diff --git a/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c b/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c index ce7c5944e2..725ef7f776 100644 --- a/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c +++ b/Task/Sorting-algorithms-Insertion-sort/C/sorting-algorithms-insertion-sort.c @@ -1,19 +1,24 @@ -#include +#include -static void insertion_sort(int *a, const size_t n) { - size_t i, j; - int value; +void insertion_sort (int *a, int n) { + int i, j, t; for (i = 1; i < n; i++) { - value = a[i]; - for (j = i; j > 0 && value < a[j - 1]; j--) { + t = a[i]; + for (j = i; j > 0 && t < a[j - 1]; j--) { a[j] = a[j - 1]; } - a[j] = value; + a[j] = t; } } -int main(void) { +int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; - insertion_sort(a, sizeof a / sizeof a[0]); + int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); + insertion_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; } diff --git a/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort.lisp b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-1.lisp similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort.lisp rename to Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-1.lisp diff --git a/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-2.lisp b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-2.lisp new file mode 100644 index 0000000000..fecbf5fe15 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/Common-Lisp/sorting-algorithms-insertion-sort-2.lisp @@ -0,0 +1,18 @@ +(defun insertion-sort (sequence &optional (predicate #'<)) + (if (cdr sequence) + (insert (car sequence) ;; insert the current item into + (insertion-sort (cdr sequence) ;; the already-sorted + predicate) ;; remainder of the list + predicate) + sequence)) ; a list of one element is already sorted + +(defun insert (item sequence predicate) + (cond ((null sequence) (list item)) + ((funcall (complement predicate) ;; if the first element of the list + (car sequence) ;; isn't better than the item, + item) ;; cons the item onto + (cons item sequence)) ;; the front of the list + (t (cons (car sequence) ;; otherwise cons the first element onto the front of + (insert item ;; the list of the item sorted with the rest of the list + (cdr sequence) + predicate))))) diff --git a/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-1.d similarity index 61% rename from Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d rename to Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-1.d index 684fdd8467..7219c6ae9c 100644 --- a/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort.d +++ b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-1.d @@ -1,5 +1,5 @@ -void insertionSort(T)(T[] data) pure nothrow { - foreach (i, value; data[1 .. $]) { +void insertionSort(T)(T[] data) pure nothrow @safe @nogc { + foreach (immutable i, value; data[1 .. $]) { auto j = i + 1; for ( ; j > 0 && value < data[j - 1]; j--) data[j] = data[j - 1]; @@ -10,6 +10,6 @@ void insertionSort(T)(T[] data) pure nothrow { void main() { import std.stdio; auto items = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; - items.insertionSort(); - writeln(items); + items.insertionSort; + items.writeln; } diff --git a/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-2.d b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-2.d new file mode 100644 index 0000000000..a067e6be44 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/D/sorting-algorithms-insertion-sort-2.d @@ -0,0 +1,31 @@ +import std.stdio, std.range, std.algorithm, std.traits; + +void insertionSort(R)(R arr) +if (hasLength!R && isRandomAccessRange!R && hasSlicing!R) { + foreach (immutable i; 1 .. arr.length) + bringToFront(arr[0 .. i].assumeSorted.upperBound(arr[i]), arr[i .. i + 1]); +} + +void main() { + import std.random, std.container; + + auto arr1 = [28, 44, 46, 24, 19, 2, 17, 11, 25, 4]; + arr1.insertionSort; + assert(arr1.isSorted); + writeln("arr1 sorted: ", arr1); + + auto arr2 = Array!int([28, 44, 46, 24, 19, 2, 17, 11, 25, 4]); + arr2[].insertionSort; + assert(arr2[].isSorted); + writeln("arr2 sorted: ", arr2[]); + + // Random data test. + int[10] buf; + foreach (immutable _; 0 .. 100_000) { + auto arr3 = buf[0 .. uniform(0, $)]; + foreach (ref x; arr3) + x = uniform(-6, 6); + arr3.insertionSort; + assert(arr3.isSorted); + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-1.max b/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-1.max new file mode 100644 index 0000000000..cbf9416527 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-1.max @@ -0,0 +1,14 @@ +fn inSort arr = +( + arr = deepcopy arr + for i = 1 to arr.count do + ( + j = i + while j > 1 and arr[j-1] > arr[j] do + ( + swap arr[j] arr[j-1] + j -= 1 + ) + ) + return arr +) diff --git a/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-2.max b/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-2.max new file mode 100644 index 0000000000..df728fcd17 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/MAXScript/sorting-algorithms-insertion-sort-2.max @@ -0,0 +1,4 @@ +b = for i in 1 to 20 collect random 1 40 +#(2, 28, 35, 31, 27, 24, 2, 22, 15, 34, 9, 10, 22, 40, 26, 5, 23, 6, 18, 33) +a = insort b +#(2, 2, 5, 6, 9, 10, 15, 18, 22, 22, 23, 24, 26, 27, 28, 31, 33, 34, 35, 40) diff --git a/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort.r b/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-1.r similarity index 100% rename from Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort.r rename to Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-1.r diff --git a/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-2.r b/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-2.r new file mode 100644 index 0000000000..93f31dde25 --- /dev/null +++ b/Task/Sorting-algorithms-Insertion-sort/R/sorting-algorithms-insertion-sort-2.r @@ -0,0 +1,17 @@ +insertion_sort <- function(x) { + for (j in 2:length(x)) { + key <- x[j] + bp <- which.max(x[1:j] > key) + # 'bp' stands for breakpoint + if (bp == 1) { + if (key < ar[1]){ + x <- c(key, ar[-j]) + } + } + else { + x <- x[-j] + x <- c(ar[1:bp - 1], key, x[bp : (s-1)]) + } + return(x) + } +} diff --git a/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx index a99a1b05b2..75bfc38f19 100644 --- a/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx +++ b/Task/Sorting-algorithms-Insertion-sort/REXX/sorting-algorithms-insertion-sort.rexx @@ -1,38 +1,38 @@ -/*REXX program sorts a stemmed array using the insertion-sort method.*/ +/*REXX program sorts a stemmed array using the insertion-sort algoritm.*/ call gen@ /*generate the array's elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call insertionSort highItem /*invoke the insertion sort. */ -call show@ ' after sort' /*show the after array elements.*/ +call show@ 'before sort' /*show the before array elements.*/ +call insertionSort # /*invoke the insertion sort. */ +call show@ ' after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign default value to array. */ -@.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" -@.2 = "Monday's child is fair of face;" -@.3 = "Tuesday's child is full of grace;" -@.4 = "Wednesday's child is full of woe;" -@.5 = "Thursday's child has far to go;" -@.6 = "Friday's child is loving and giving;" -@.7 = "Saturday's child works hard for a living;" -@.8 = "But the child that is born on the Sabbath day" -@.9 = "Is blithe and bonny, good and gay." - do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ - end /*short and sweet DO loop, eh? */ -highItem=highItem-1 /*because of DO, adjust highItem.*/ +gen@: @. = /*assign default value to array. */ + @.1 = "---Monday's Child Is Fair of Face (by Mother Goose)---" + @.2 = "Monday's child is fair of face;" + @.3 = "Tuesday's child is full of grace;" + @.4 = "Wednesday's child is full of woe;" + @.5 = "Thursday's child has far to go;" + @.6 = "Friday's child is loving and giving;" + @.7 = "Saturday's child works hard for a living;" + @.8 = "But the child that is born on the Sabbath day" + @.9 = "Is blithe and bonny, good and gay." + + do #=1 while @.#\=='' /*find how many entries in array.*/ + end /*#*/ /*short and sweet DO loop, eh? */ +#=#-1 /*because of DO, adjust # entries*/ return /*──────────────────────────────────INSERTIONSORT subroutine────────────*/ -insertionSort: procedure expose @.; parse arg highItem - do i=2 to highItem; value=@.i - do j=i-1 by -1 while j\==0 & @.j>value - jp=j+1; @.jp=@.j - end /*j*/ +insertionSort: procedure expose @. # + do i=2 to # + value=@.i; do j=i-1 by -1 while j\==0 & @.j>value + jp=j+1; @.jp=@.j + end /*j*/ jp=j+1 @.jp=value end /*i*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*the maximum width of any line. */ - do j=1 for highItem - say 'element' right(j,widthH) arg(1)': ' @.j - end /*j*/ +show@: do j=1 for # + say 'element' right(j,length(#)) arg(1)': ' @.j + end /*j*/ say copies('─',79) /*show a separator line that fits*/ return diff --git a/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt b/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt index 164fca7e69..1156fcf505 100644 --- a/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt +++ b/Task/Sorting-algorithms-Insertion-sort/Racket/sorting-algorithms-insertion-sort.rkt @@ -1,13 +1,9 @@ -(require racket/match) +#lang racket -(define (sort pred l) +(define (sort < l) (define (insert x y) - (match (list x y) - [(list x '()) (list x)] - [(list x (cons y ys)) - (if (pred x y) - (cons x (cons y ys)) - (cons y (f x ys)))])) - (match l - ['() '()] - [(cons x xs) (insert x (sort pred xs))])) + (match* (x y) + [(x '()) (list x)] + [(x (cons y ys)) (cond [(< x y) (list* x y ys)] + [else (cons y (insert x ys))])])) + (foldl insert '() l)) diff --git a/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala b/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala index 24e5d60ccb..2be331175d 100644 --- a/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala +++ b/Task/Sorting-algorithms-Insertion-sort/Scala/sorting-algorithms-insertion-sort.scala @@ -1,4 +1,6 @@ -def insert(list: List[Int], value: Int) = list.span(_ < value) match { - case (lower, upper) => lower ::: value :: upper +def insertSort[X](list: List[X])(implicit ord: Ordering[X]) = { + def insert(list: List[X], value: X) = list.span(x => ord.lt(x, value)) match { + case (lower, upper) => lower ::: value :: upper + } + list.foldLeft(List.empty[X])(insert) } -def insertSort(list: List[Int]) = list.foldLeft(List[Int]())(insert) diff --git a/Task/Sorting-algorithms-Merge-sort/00DESCRIPTION b/Task/Sorting-algorithms-Merge-sort/00DESCRIPTION index 9fa86aaed1..a23fa523ed 100644 --- a/Task/Sorting-algorithms-Merge-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Merge-sort/00DESCRIPTION @@ -1,6 +1,12 @@ -{{Sorting Algorithm}}[[Category:Recursion]]The '''merge sort''' is a recursive sort of order n*log(n). It is notable for having a worst case and average complexity of ''O(n*log(n))'', and a best case complexity of ''O(n)'' (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups). Then merge the groups back together so that their elements are in order. This is how the algorithm gets its "divide and conquer" description. +{{Sorting Algorithm}}[[Category:Recursion]]The '''merge sort''' is a recursive sort of order n*log(n). +It is notable for having a worst case and average complexity of ''O(n*log(n))'', and a best case complexity of ''O(n)'' (for pre-sorted input). +The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups). +Then merge the groups back together so that their elements are in order. +This is how the algorithm gets its "divide and conquer" description. -Write a function to sort a collection of integers using the merge sort. The merge sort algorithm comes in two parts: a sort function and a merge function. The functions in pseudocode look like this: +Write a function to sort a collection of integers using the merge sort. +The merge sort algorithm comes in two parts: a sort function and a merge function. +The functions in pseudocode look like this: '''function''' ''mergesort''(m) '''var''' list left, right, result '''if''' length(m) ≤ 1 @@ -35,3 +41,5 @@ Write a function to sort a collection of integers using the merge sort. The merg '''return''' result For more information see [[wp:Merge_sort|Wikipedia]] + +Note: better performance can be expected if, rather than recursing until length(m) ≤ 1, an insertion sort is used for length(m) smaller than some threshold larger than 1. However, this complicates example code, so is not shown here. 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 index c225f386c9..9e31a830bc 100644 --- a/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c +++ b/Task/Sorting-algorithms-Merge-sort/C/sorting-algorithms-merge-sort.c @@ -1,102 +1,38 @@ #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 merge (int *a, int n, int m) { + int i, j, k; + int *x = malloc(n * sizeof (int)); + for (i = 0, j = m, k = 0; k < n; k++) { + x[k] = j == n ? a[i++] + : i == m ? a[j++] + : a[j] < a[i] ? a[j++] + : a[i++]; + } + for (i = 0; i < n; i++) { + a[i] = x[i]; + } + free(x); } -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 merge_sort (int *a, int n) { + if (n < 2) + return; + int m = n / 2; + merge_sort(a, m); + merge_sort(a + m, n - m); + merge(a, n, m); } -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; +int main () { + int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; + int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); + merge_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); + 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 9641aefc10..16f5908ae0 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 @@ -1,6 +1,6 @@ import std.stdio, std.algorithm, std.array, std.range; -T[] mergeSorted(T)(in T[] D) /*pure nothrow*/ { +T[] mergeSorted(T)(in T[] D) /*pure nothrow @safe*/ { if (D.length < 2) return D.dup; return [D[0 .. $ / 2].mergeSorted, D[$ / 2 .. $].mergeSorted] diff --git a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e new file mode 100644 index 0000000000..b292c9d68f --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-1.e @@ -0,0 +1,117 @@ +class + MERGE_SORT [G -> COMPARABLE] +create + sort +feature + sort(ar: ARRAY[G]) + -- sort array ar with mergesort and save it in sorted_array + require + ar_not_empty: ar.is_empty= FALSE + do + create sorted_array.make_empty + mergesort(ar, 1, ar.count) + sorted_array:= ar + ensure + sorted_array_not_empty: sorted_array.is_empty = FALSE + sorted: is_sorted(sorted_array, 1, sorted_array.count)= TRUE + end + sorted_array: ARRAY[G] +feature {NONE} + mergesort(ar:ARRAY[G]; l,r:INTEGER) + local + m: INTEGER + do + if l=1 + positive_index_m: m>=1 + positive_index_r: r>=1 + ar_not_empty: ar.is_empty= FALSE + local + merged: ARRAY[G] + h,i,j,k: INTEGER + do + i := l + j := m+1 + k := l + create merged.make_empty + from + until + i > m or j > r + loop + if ar.item (i) <= ar.item (j) then + merged.force(ar.item(i),k) + i := i +1 + elseif ar.item (i) > ar.item (j) then + merged.force(ar.item(j),k) + j := j+1 + end + k := k+1 + end + if i > m then + from + h := j + until + h > r + loop + merged.force(ar.item(h),k+h-j) + h := h+1 + end + elseif j > m then + from + h := i + until + h > m + loop + merged.force(ar.item(h),k+h-i) + h := h+1 + end + end + from + h := l + until + h > r + loop + ar.item (h) := merged.item (h) + h := h+1 + end + ensure + is_partially_sorted: is_sorted(ar, l,r)= TRUE + end + + is_sorted(ar: ARRAY[G];l, r: INTEGER): BOOLEAN + --- feature is not required for mergesort but is used for contracts + require + ar_not_empty: ar.is_empty= FALSE + l_in_range: l >= 1 + r_in_range: r <= ar.count + local + smaller : BOOLEAN + i: INTEGER + do + smaller:= TRUE + from + i:= l + until + i=r + loop + if ar[i]> ar[i+1] then + smaller:= FALSE + end + i:= i+1 + end + if smaller = TRUE then + RESULT := TRUE + else + RESULT:= FALSE + end + end +end diff --git a/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e new file mode 100644 index 0000000000..8e7c456ca6 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Eiffel/sorting-algorithms-merge-sort-2.e @@ -0,0 +1,19 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + test:= <<2,5,66,-2, 0, 7>> + io.put_string ("unsorted"+ "%N") + across test as ar loop io.put_string (ar.item.out + "%T") end + io.put_string ("%N"+"sorted"+ "%N") + create merge.sort (test) + across merge.sorted_array as ar loop io.put_string (ar.item.out + "%T") end + end + test: ARRAY[INTEGER] + merge: MERGE_SORT[INTEGER] +end diff --git a/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java b/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java index bead13c08d..6e236adf3a 100644 --- a/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java +++ b/Task/Sorting-algorithms-Merge-sort/Java/sorting-algorithms-merge-sort.java @@ -2,9 +2,9 @@ import java.util.List; import java.util.ArrayList; import java.util.Iterator; -public class Merge { - public static > List mergeSort(List m) { - if (m.size() <= 1) return m; +public class Merge{ + public static > List mergeSort(List m){ + if(m.size() <= 1) return m; int middle = m.size() / 2; List left = m.subList(0, middle); @@ -17,33 +17,35 @@ public class Merge { return result; } - public static > List merge(List left, List right) { + public static > List merge(List left, List right){ List result = new ArrayList(); Iterator it1 = left.iterator(); Iterator it2 = right.iterator(); E x = it1.next(); E y = it2.next(); - while (true) { + while (true){ //change the direction of this comparison to change the direction of the sort - if (x.compareTo(y) <= 0) { + if(x.compareTo(y) <= 0){ result.add(x); - if (it1.hasNext()) + if(it1.hasNext()){ x = it1.next(); - else { + }else{ result.add(y); - while (it2.hasNext()) + while(it2.hasNext()){ result.add(it2.next()); + } break; } - } else { + }else{ result.add(y); - if (it2.hasNext()) + if(it2.hasNext()){ y = it2.next(); - else { + }else{ result.add(x); - while (it1.hasNext()) + while (it1.hasNext()){ result.add(it1.next()); + } break; } } diff --git a/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js index 2f535386e0..bb828800d2 100644 --- a/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js +++ b/Task/Sorting-algorithms-Merge-sort/JavaScript/sorting-algorithms-merge-sort.js @@ -1,22 +1,22 @@ -function merge(left,right,arr){ - var a=0; - while(left.length&&right.length) - arr[a++]=right[0] 0 and b.count > 0 do + ( + if a[1] <= b[1] then + ( + append result a[1] + a = for i in 2 to a.count collect a[i] + ) + else + ( + append result b[1] + b = for i in 2 to b.count collect b[i] + ) + ) + if a.count > 0 do + ( + join result a + ) + if b.count > 0 do + ( + join result b + ) + return result +) diff --git a/Task/Sorting-algorithms-Merge-sort/MAXScript/sorting-algorithms-merge-sort-2.max b/Task/Sorting-algorithms-Merge-sort/MAXScript/sorting-algorithms-merge-sort-2.max new file mode 100644 index 0000000000..4d53146a9c --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/MAXScript/sorting-algorithms-merge-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 15 collect random -5 20 +#(-3, 13, 2, -2, 13, 9, 17, 7, 16, 19, 0, 0, 20, 18, 1) +mergeSort a +#(-3, -2, 0, 0, 1, 2, 7, 9, 13, 13, 16, 17, 18, 19, 20) diff --git a/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort.pascal b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-1.pascal similarity index 100% rename from Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort.pascal rename to Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-1.pascal diff --git a/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal new file mode 100644 index 0000000000..221a92e049 --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/Pascal/sorting-algorithms-merge-sort-2.pascal @@ -0,0 +1,168 @@ +{$IFDEF FPC} + {$MODE DELPHI} + {$OPTIMIZATION ON,Regvar,ASMCSE,CSE,PEEPHOLE} +{$ELSE} + {$APPTYPE CONSOLE} +{$ENDIF} +uses + sysutils; //for timing +type + tDataElem = record + myX, + myY : double; + myTag, + myOrgIdx : LongInt; + end; + tpDataElem = ^tDataElem; + tData = array of tDataElem; + + tSortData = array of tpDataElem; + tCompFunc = function(A,B:tpDataElem):integer; +var + Data : tData; + Sortdata, + tmpData : tSortData; + +procedure InitData(var D:tData;cnt: LongWord); +var + i,k: LongInt; +begin + Setlength(D,cnt); + Setlength(SortData,cnt); + Setlength(tmpData,cnt shr 1 +1 ); + k := 10*cnt; + For i := cnt-1 downto 0 do + Begin + Sortdata[i] := @D[i]; + with D[i] do + Begin + myX := Random*k; + myY := Random*k; + myTag := Random(k); + myOrgIdx := i; + end; + end; +end; + +procedure FreeData(var D:tData); +begin + Setlength(tmpData,0); + Setlength(SortData,0); + Setlength(D,0); +end; + +function myCompX(A,B:tpDataElem):integer; +//same as sign without jumps in assembler code +Begin + result := ORD(A^.myX > B^.myX)-ORD(A^.myX < B^.myX); +end; + +function myCompY(A,B:tpDataElem):integer; +Begin + result := ORD(A^.myY > B^.myY)-ORD(A^.myY < B^.myY); +end; + +function myCompTag(A,B:tpDataElem):integer; +Begin + result := ORD(A^.myTag > B^.myTag)-ORD(A^.myTag < B^.myTag); +end; + +procedure InsertionSort(left,right:integer;var a: tSortData;CompFunc: tCompFunc); +var + Pivot : tpDataElem; + i,j : LongInt; +begin + for i:=left+1 to right do + begin + j :=i; + Pivot := A[j]; + while (j>left) AND (CompFunc(A[j-1],Pivot)>0) do + begin + A[j] := A[j-1]; + dec(j); + end; + A[j] :=PiVot;// s.o. + end; +end; + + +procedure mergesort(left,right:integer;var a: tSortData;CompFunc: tCompFunc); +var + i,j,k,mid :integer; +begin +{// without insertion sort + If right>left then +} +//{ test insertion sort + If right-left<=14 then + InsertionSort(left,right,a,CompFunc) + else +//} + begin + //recursion + mid := (right+left) div 2; + mergesort(left, mid,a,CompFunc); + mergesort(mid+1, right,a,CompFunc); + //already sorted ? + IF CompFunc(A[Mid],A[Mid+1])<0 then + exit; + + //########## Merge ########## + //copy lower half to temporary array + move(A[left],tmpData[0],(mid-left+1)*SizeOf(Pointer)); + i := 0; + j := mid+1; + k := left; + // re-integrate + while (k@.h then do; _=@.h; @.h=@.L; @.L=_; end - return - end -m=n%2 -call mergeTo@ L+m,n-m -call mergeTo! L,m,1 -i=1; j=L+m; do k=L while k@.h then do; _=@.h; @.h=@.L; @.L=_; end + return + end +m=n%2 /*cut N in half (integer div.)*/ +call mergeTo@ L+m,n-m /*divide items to the left ···*/ +call mergeTo! L,m,1 /* " " " " right ···*/ +i=1; j=L+m; do k=L while k@.h then do; q=_; _=q+1; end - !._=@.L; !.q=@.h - return - end -m=n%2 -call mergeTo@ L,m -call mergeTo! L+m,n-m,m+_ -i=L; j=m+_ - do k=_ while k@.h then do; q=_; _=q+1; end + !._=@.L; !.q=@.h + return /*done with special case of N=2.*/ + end +m=n%2 /*cut N in half (integer div).*/ +call mergeTo@ L,m /*divide items to the left ···*/ +call mergeTo! L+m,n-m,m+_ /* " " " " right ···*/ +i=L; j=m+_; do k=_ while k b} middle = length / 2 - left = self[0, middle].mergesort(&comparitor) + left = self[0..middle - 1].mergesort(&comparitor) right = self[middle..-1].mergesort(&comparitor) merge(left, right, comparitor) end diff --git a/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed new file mode 100644 index 0000000000..ef24e8c56b --- /dev/null +++ b/Task/Sorting-algorithms-Merge-sort/ZED/sorting-algorithms-merge-sort.zed @@ -0,0 +1,86 @@ +(append) list1 list2 +comment: +#true +(003) "append" list1 list2 + +(car) pair +comment: +#true +(002) "car" pair + +(cdr) pair +comment: +#true +(002) "cdr" pair + +(cons) one two +comment: +#true +(003) "cons" one two + +(map) function list +comment: +#true +(003) "map" function list + +(merge) comparator list1 list2 +comment: +#true +(merge1) comparator list1 list2 nil + +(merge1) comparator list1 list2 collect +comment: +(null?) list2 +(append) (reverse) collect list1 + +(merge1) comparator list1 list2 collect +comment: +(null?) list1 +(append) (reverse) collect list2 + +(merge1) comparator list1 list2 collect +comment: +(003) comparator (car) list2 (car) list1 +(merge1) comparator list1 (cdr) list2 (cons) (car) list2 collect + +(merge1) comparator list1 list2 collect +comment: +#true +(merge1) comparator (cdr) list1 list2 (cons) (car) list1 collect + +(null?) value +comment: +#true +(002) "null?" value + +(reverse) list +comment: +#true +(002) "reverse" list + +(sort) comparator jumble +comment: +#true +(car) (sort11) comparator (sort1) jumble + +(sort1) jumble +comment: +#true +(map) "list" jumble + +(sort11) comparator jumble +comment: +(null?) jumble +nil + +(sort11) comparator jumble +comment: +(null?) (cdr) jumble +jumble + +(sort11) comparator jumble +comment: +#true +(sort11) comparator + (cons) (merge) comparator (car) jumble (002) "cadr" jumble + (sort11) comparator (002) "cddr" jumble diff --git a/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d b/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d index 8947b09a5b..9804d9fe29 100644 --- a/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d +++ b/Task/Sorting-algorithms-Pancake-sort/D/sorting-algorithms-pancake-sort.d @@ -1,8 +1,8 @@ import std.stdio, std.algorithm; void pancakeSort(bool tutor=false, T)(T[] data) { - foreach_reverse (i; 2 .. data.length + 1) { - immutable maxIndex = i - data[0 .. i].minPos!q{a > b}().length; + foreach_reverse (immutable i; 2 .. data.length + 1) { + immutable maxIndex = i - data[0 .. i].minPos!q{a > b}.length; if (maxIndex + 1 != i) { if (maxIndex != 0) { static if (tutor) @@ -18,7 +18,7 @@ void pancakeSort(bool tutor=false, T)(T[] data) { } void main() { - char[] data = "769248135".dup; - pancakeSort!true(data); - writeln(data); + auto data = "769248135".dup; + data.pancakeSort!true; + data.writeln; } diff --git a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e new file mode 100644 index 0000000000..76ee5e9ec2 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-1.e @@ -0,0 +1,87 @@ +class + PANCAKE_SORT +create + make +feature{NONE} + arraymax(array: ARRAY [INTEGER]; upper: INTEGER):INTEGER + require + upper_index_positive: upper >=0 + array_exists: array/= void + local + i, cur_max, index: INTEGER + do + from + i:=1 + cur_max := array.item (i) + index := i + until + i+1 > upper + loop + if array.item(i+1) > cur_max then + cur_max := array.item(i+1) + index := i+1 + end + i := i + 1 + end + Result:=index + ensure + Index_positive: Result > 0 + end + + reverse_array(ar:ARRAY[INTEGER]; upper:INTEGER):ARRAY[INTEGER] + require + upper_positive: upper >0 + ar_not_void: ar /= void + local + i,j:INTEGER + new_array: ARRAY[INTEGER] + do + create new_array.make_empty + new_array.copy (ar) + from + i:= 1 + j:=upper + until + i>j + loop + new_array[i]:=ar[j] + new_array[j]:=ar[i] + i:=i+1 + j:=j-1 + end + Result:= new_array + ensure + same_length: ar.count = Result.count + end + + sort(ar:ARRAY[INTEGER]):ARRAY[INTEGER] + local + i:INTEGER + do + my_array:=ar + from + i:=ar.count + until + i=1 + loop + my_array:=reverse_array(reverse_array(my_array, arraymax(my_array,i)),i) + i:=i-1 + end + Result := my_array + ensure + same_length: ar.count= Result.count + end + + my_array:ARRAY[INTEGER] + +feature + make(ar:ARRAY[INTEGER]) + do + create my_array.make_from_array(ar) + end + + pancake_sort:ARRAY[INTEGER] + do + Result:= sort(my_array) + end +end diff --git a/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e new file mode 100644 index 0000000000..7ec3a5616c --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/Eiffel/sorting-algorithms-pancake-sort-2.e @@ -0,0 +1,21 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + test := <<1, 27, 32, 99, 1, -7, 3, 5>> + create sorter.make(test) + io.put_string ("Unsorted: ") + across test as ar loop io.put_string (ar.item.out + " ") end + io.put_string ("%NSorted: ") + test:= sorter.pancake_sort + across test as ar loop io.put_string (ar.item.out + " ") end + end + + test: ARRAY[INTEGER] + sorter: PANCAKE_SORT +end diff --git a/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-1.max b/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-1.max new file mode 100644 index 0000000000..0530a26b00 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-1.max @@ -0,0 +1,29 @@ +fn flipArr arr index = +( + local new = #() + for i = index to 1 by -1 do + ( + append new arr[i] + ) + join new (for i in (index+1) to arr.count collect arr[i]) + return new +) + +fn pancakeSort arr = +( + if arr.count < 2 then return arr + else + ( + for i = arr.count to 1 by -1 do + ( + local newArr = for n in 1 to i collect arr[n] + local oldArr = for o in (i+1) to arr.count collect arr[o] + local maxIndices = for m in 1 to (newArr.count) where (newArr[m] == amax newArr) collect m + local lastMaxIndex = maxIndices[maxIndices.count] + newArr = flipArr newArr lastMaxIndex + newArr = flipArr newArr newArr.count + arr = join newArr oldArr + ) + return arr + ) +) diff --git a/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-2.max b/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-2.max new file mode 100644 index 0000000000..f222887a86 --- /dev/null +++ b/Task/Sorting-algorithms-Pancake-sort/MAXScript/sorting-algorithms-pancake-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 15 collect random 0 20 +#(8, 13, 2, 0, 10, 8, 1, 15, 4, 7, 6, 9, 11, 3, 5) +pancakeSort a +#(0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 13, 15) diff --git a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx index e7e3e32197..381b4cac95 100644 --- a/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx +++ b/Task/Sorting-algorithms-Pancake-sort/REXX/sorting-algorithms-pancake-sort.rexx @@ -1,59 +1,38 @@ -/*REXX program sorts/shows an array using the pancake sort algorithm.*/ +/*REXX program sorts & shows an array using the pancake sort algorithm.*/ call gen@ /*generate elements in the array.*/ call show@ 'before sort' /*show the BEFORE array elements.*/ -call pancakeSort #items /*invoke the pancake sort. Yummy.*/ +call pancakeSort # /*invoke the pancake sort. Yummy.*/ call show@ ' after sort' /*show the AFTER array elements.*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────PANCAKESORT subroutine──────────────*/ -pancakeSort: procedure expose @.; parse arg n - - do n-1 /*perform this loop N-1 times.*/ - !=@.1; ?=1 - do j=2 to n - if @.j<=! then iterate - !=@.j; ?=j - end /*j*/ - call flip ?; call flip n - n=n-1 - end /*n-1*/ -return /*──────────────────────────────────FLIP subroutine─────────────────────*/ -flip: procedure expose @.; parse arg w - do i=1 for (w+1)%2 /*In REXX, % is integer divide.*/ - kmip1=w-i+1; _=@.i; @.i=@.kmip1; @.kmip1=_ - end /*i*/ +flip: procedure expose @.; parse arg y + do i=1 for (y+1)%2 + ymp=y-i+1; _=@.i; @.i=@.ymp; @.ymp=_ + end /*i*/ return -/*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.='' /*assign a default value. */ - /*Generate some bread primes which are primes of the*/ - /*form: (p-3)÷2 and 2∙p+3 where p is a prime.*/ - /*Bread primes are related to sandwich & meat primes.*/ +/*──────────────────────────────────GEN@ subroutine──────────────────────────────────────────────────────────────────*/ +gen@: /*a few sorted bread primes which are primes of the form: (p-3)÷2 and 2∙p+3 */ + /*where p is a prime. Bread primes are related to sandwich and meat primes. */ +bp=2 17 5 29 7 37 13 61 43 181 47 197 67 277 97 397 113 461 137 557 167 677 173 701 797 1117 307 1237 1597 463 1861 467 +fb='-55 -21 -1 -8 -8 -21 -55 0 0' /*some non-positive Fibonacci #s,*/ +$=bp fb /* most of which are repeated.*/ +#=words($) /*get number of items in $ list. */ + /* [↓] populate @ array with #s.*/ + do j=1 for #; @.j=word($,j); end /*obtain a number of the $ list.*/ +return +/*──────────────────────────────────PANCAKESORT subroutine──────────────*/ +pancakeSort: procedure expose @.; parse arg N - @.1= 2 ; @.17= 113 ; @.33= -55 - @.2= 17 ; @.18= 461 ; @.34= -21 - @.3= 5 ; @.19= 137 ; @.35= -1 - @.4= 29 ; @.20= 557 ; @.36= -8 - @.5= 7 ; @.21= 167 ; @.37= -8 - @.6= 37 ; @.22= 677 ; @.38= -21 - @.7= 13 ; @.23= 173 ; @.39= -55 - @.8= 61 ; @.24= 701 ; @.40= 0 - @.9= 43 ; @.25= 797 ; @.41= 0 -@.10= 181 ; @.26= 1117 -@.11= 47 ; @.27= 307 /*The non-positive numbers*/ -@.12= 197 ; @.28= 1237 /*above are some negative */ -@.13= 67 ; @.29= 1597 /*Fibonacci numbers, some */ -@.14= 277 ; @.30= 463 /*of which where specified*/ -@.15= 97 ; @.31= 1861 /*twice just 'cause I felt*/ -@.16= 397 ; @.32= 467 /*like it. Also, added */ - /*two zeroes, just 'cause.*/ - do #items=1 while @.#items\==''; end /*find how many entries in array.*/ - -#items=#items-1 /*adjust the #items slightly. */ + do N=N by -1 for N-1 + !=@.1; ?=1; do j=2 to N; if @.j<=! then iterate + !=@.j; ?=j + end /*j*/ + call flip ?; call flip N + end /*N*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(#items) /*the maximum width of any line. */ - do k=1 for #items - say 'element' right(k,widthH) arg(1)':' @.k - end /*k*/ -say copies('─',79) /*show an eyeball separator line.*/ +show@: w=length(#); do k=1 for # + say ' element' right(k,w) arg(1)':' right(@.k,9) + end /*k*/ +say copies('█',40) /*show an eyeball separator line.*/ return diff --git a/Task/Sorting-algorithms-Permutation-sort/00DESCRIPTION b/Task/Sorting-algorithms-Permutation-sort/00DESCRIPTION index b09a7263fd..f8fbab014b 100644 --- a/Task/Sorting-algorithms-Permutation-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Permutation-sort/00DESCRIPTION @@ -1,4 +1,7 @@ -{{Sorting Algorithm}}Permutation sort, which proceeds by generating the possible permutations of the input array/list until discovering the sorted one. +{{Sorting Algorithm}} +{{omit from|GUISS}} +Permutation sort, which proceeds by generating the possible permutations +of the input array/list until discovering the sorted one. Pseudocode: '''while not''' InOrder(list) '''do''' 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 3a1545f37d..669e23b4cb 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,11 +1,9 @@ import std.stdio, std.algorithm, permutations2; -void permutationSort(T)(T[] items) pure /*nothrow*/ { +void permutationSort(T)(T[] items) pure nothrow @safe @nogc { foreach (const perm; items.permutations!false) - if (perm.isSorted) { - items[] = perm[]; + if (perm.isSorted) break; - } } void main() { 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 906f5d75b4..50f2595b38 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,6 +1,6 @@ import std.stdio, std.algorithm; -void permutationSort(T)(T[] items) pure nothrow { +void permutationSort(T)(T[] items) pure nothrow @safe @nogc { while (items.nextPermutation) {} } diff --git a/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-1.max b/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-1.max new file mode 100644 index 0000000000..89c54cadd0 --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-1.max @@ -0,0 +1,29 @@ +fn inOrder arr = +( + if arr.count < 2 then return true + else + ( + local i = 1 + while i < arr.count do + ( + if arr[i+1] < arr[i] do return false + i += 1 + ) + return true + ) +) + +fn permutations arr = +( + if arr.count <= 1 then return arr + else + ( + for i = 1 to arr.count do + ( + local rest = for r in 1 to arr.count where r != i collect arr[r] + local permRest = permutations rest + local new = join #(arr[i]) permRest + if inOrder new do return new + ) + ) +) diff --git a/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-2.max b/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-2.max new file mode 100644 index 0000000000..2a66e6e72c --- /dev/null +++ b/Task/Sorting-algorithms-Permutation-sort/MAXScript/sorting-algorithms-permutation-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 9 collect random 1 20 +#(10, 20, 17, 15, 17, 15, 3, 11, 15) +permutations a +#(3, 10, 11, 15, 15, 15, 17, 17, 20) diff --git a/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx index f148ca319a..07b60270ac 100644 --- a/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx +++ b/Task/Sorting-algorithms-Permutation-sort/REXX/sorting-algorithms-permutation-sort.rexx @@ -1,22 +1,22 @@ /*REXX program sorts an array using the permutation-sort method. */ call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call permsets items /*generate items! permutations.*/ -call permSort items /*invoke the permutation sort. */ -call show@ ' after sort' /*show after array elements*/ +call show@ 'before sort' /*show the before array elements.*/ +call permsets L /*generate items! permutations.*/ +call permSort L /*invoke the permutation sort. */ +call show@ ' after sort' /*show the after array elements.*/ say; say 'Permutation sort took' ? "permutations to find the sorted list." exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────GEN@ subroutine─────────────────────*/ -gen@: @.= /*assign default value. */ -@.1 = '---Four_horsemen_of_the_Apocalypse---' -@.2 = '=====================================' -@.3 = 'Famine───black_horse' -@.4 = 'Death───pale_horse' -@.5 = 'Pestilence_[Slaughter]───red_horse' -@.6 = 'Conquest_[War]───white_horse' -list= /*[↓] find # of entries in array.*/ - do items=1 while @.items\==''; @@.items=@.items; end /*items*/ -items=items-1 /*adjust items slightly. */ +gen@: @. = /*assign default value. */ + @.1 = '---Four_horsemen_of_the_Apocalypse---' + @.2 = '=====================================' + @.3 = 'Famine───black_horse' + @.4 = 'Death───pale_horse' + @.5 = 'Pestilence_[Slaughter]───red_horse' + @.6 = 'Conquest_[War]───white_horse' + /*[↓] find # of entries in array.*/ + do L=1 while @.L\==''; @@.L=@.L; end /*L*/ +L=L-1 /*adjust number of items by one. */ return /*──────────────────────────────────INORDER subroutine──────────────────*/ inOrder: parse arg q /*see if list Q is in order. */ @@ -24,12 +24,13 @@ _=word(q,1); do j=2 to words(q); x=word(q,j) if x<_ then return 0 /*Out of order? Then not sorted.*/ _=x end /*j*/ - do k=1 for items; _=word(#.?,k); @.k=@@._; end /*k*/ /*here it is*/ + do k=1 for #; _=word(#.?,k); @.k=@@._; end /*k*/ /*here it is*/ return 1 /*they're all in order finally. */ /*──────────────────────────────────PERMSETS subroutine─────────────────*/ -permsets: procedure expose !. # #.; parse arg n,#.; #=0 - do f=1 for n; !.f=f; end /*f*/; call .permAdd /*populate 1st perm*/ - do while .permNext(n,0); call .permAdd; end /*while ···*/ +permsets: procedure expose !. # #.; parse arg n,#.; #=0 + do f=1 for n; !.f=f; end /*f*/ +call .permAdd /*populate 1st perm*/ + do while .permNext(n,0); call .permAdd; end /*while*/ return # .permNext: procedure expose !.; parse arg n,i; nm=n-1 do k=nm by -1 for nm; kp=k+1 @@ -39,14 +40,15 @@ return # if i==0 then return 0; do j=i+1 while !.je)/⍵} - qsort 1 3 5 7 9 8 6 4 2 -1 2 3 4 5 6 7 8 9 + qsort ← {1≥⍴⍵:⍵ ⋄ e←⍵[?⍴⍵] ⋄ (∇(⍵e)/⍵)} + qsort 31 4 1 5 9 2 6 5 3 5 8 +1 2 3 4 5 5 5 6 8 9 31 diff --git a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c index 0d3695d4a7..03ee92736c 100644 --- a/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c +++ b/Task/Sorting-algorithms-Quicksort/C/sorting-algorithms-quicksort.c @@ -1,29 +1,33 @@ +#include + void quick_sort (int *a, int n) { + int i, j, p, t; if (n < 2) return; - int p = a[n / 2]; - int *l = a; - int *r = a + n - 1; - while (l <= r) { - if (*l < p) { - l++; - continue; - } - if (*r > p) { - r--; - continue; // we need to check the condition (l <= r) every time we change the value of l or r - } - int t = *l; - *l++ = *r; - *r-- = t; + p = a[n / 2]; + for (i = 0, j = n - 1;; i++, j--) { + while (a[i] < p) + i++; + while (p < a[j]) + j--; + if (i >= j) + break; + t = a[i]; + a[i] = a[j]; + a[j] = t; } - quick_sort(a, r - a + 1); - quick_sort(l, a + n - l); + quick_sort(a, i); + quick_sort(a + i, n - i); } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); quick_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; } 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 58d537e67e..5803ffa814 100644 --- a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-1.d @@ -1,9 +1,9 @@ import std.stdio, std.algorithm, std.range, std.array; -auto quickSort(T)(T[] items) /*pure*/ nothrow { +auto quickSort(T)(T[] items) pure nothrow @safe { if (items.length < 2) return items; - auto pivot = items[0]; + immutable pivot = items[0]; return items[1 .. $].filter!(x => x < pivot).array.quickSort ~ pivot ~ items[1 .. $].filter!(x => x >= pivot).array.quickSort; diff --git a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d index 5afc1947b9..ba064456c1 100644 --- a/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d +++ b/Task/Sorting-algorithms-Quicksort/D/sorting-algorithms-quicksort-3.d @@ -1,6 +1,6 @@ import std.stdio, std.algorithm; -void quickSort(T)(T[] items) pure nothrow { +void quickSort(T)(T[] items) pure nothrow @safe @nogc { if (items.length >= 2) { auto parts = partition3(items, items[$ / 2]); parts[0].quickSort; diff --git a/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth b/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth index 32a653412c..cf05aab820 100644 --- a/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth +++ b/Task/Sorting-algorithms-Quicksort/Forth/sorting-algorithms-quicksort.fth @@ -1,5 +1,3 @@ -defer lessthan ( a@ b@ -- ? ) ' < is lessthan - : mid ( l r -- mid ) over - 2/ -cell and + ; : exch ( addr1 addr2 -- ) dup @ >r over @ swap ! r> swap ! ; @@ -7,8 +5,8 @@ defer lessthan ( a@ b@ -- ? ) ' < is lessthan : partition ( l r -- l r r2 l2 ) 2dup mid @ >r ( r: pivot ) 2dup begin - swap begin dup @ r@ lessthan while cell+ repeat - swap begin r@ over @ lessthan while cell- repeat + swap begin dup @ r@ < while cell+ repeat + swap begin r@ over @ < while cell- repeat 2dup <= if 2dup exch >r cell+ r> cell- then 2dup > until r> drop ; diff --git a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-1.julia b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-1.julia new file mode 100644 index 0000000000..7472fbdd96 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-1.julia @@ -0,0 +1 @@ +sort!(A, alg=QuickSort) diff --git a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-2.julia b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-2.julia new file mode 100644 index 0000000000..3d8d7a26f0 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-2.julia @@ -0,0 +1,22 @@ +function quicksort!(A,i=1,j=length(A)) + if j > i + pivot = A[rand(i:j)] # random element of A + left, right = i, j + while left <= right + while A[left] < pivot + left += 1 + end + while A[right] > pivot + right -= 1 + end + if left <= right + A[left], A[right] = A[right], A[left] + left += 1 + right -= 1 + end + end + quicksort!(A,i,right) + quicksort!(A,left,j) + end + return A +end diff --git a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-3.julia b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-3.julia new file mode 100644 index 0000000000..f1d7de750d --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort-3.julia @@ -0,0 +1 @@ +qsort(L) = isempty(L) ? L : vcat(qsort(filter(x -> x < L[1], L[2:end])), L[1:1], qsort(filter(x -> x >= L[1], L[2:end]))) diff --git a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia b/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia deleted file mode 100644 index cacb76baf7..0000000000 --- a/Task/Sorting-algorithms-Quicksort/Julia/sorting-algorithms-quicksort.julia +++ /dev/null @@ -1,29 +0,0 @@ -function modes(values) - dict = Dict() # Values => Number of repetitions - modesArray = typeof(values[1])[] # Array of the modes so far - max = 0 # Max of repetitions so far - - for v in values - # Add one to the dict[v] entry (create one if none) - if v in keys(dict) - dict[v] += 1 - else - dict[v] = 1 - end - - # Update modesArray if the number of repetitions - # of v reaches or surpasses the max value - if dict[v] >= max - if dict[v] > max - empty!(modesArray) - max += 1 - end - append!(modesArray, [v]) - end - end - - return modesArray -end - -println(modes([1,3,6,6,6,6,7,7,12,12,17])) -println(modes((1,1,2,4,4))) diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k index 95a4bfeafe..a3caf9086b 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-3.k @@ -1 +1 @@ -1 2 3 4 5 6 7 8 9 + _f() diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k index a3caf9086b..0aef1c1c3a 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-4.k @@ -1 +1 @@ - _f() + :[....] diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k index 0aef1c1c3a..bb65ec570f 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-5.k @@ -1 +1 @@ - :[....] + f:*x@1?#x diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k index bb65ec570f..3a21fcbaf3 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-6.k @@ -1 +1,9 @@ - f:*x@1?#x + :[ + 0=#x; / if length of x is zero + x; / then return x + / else + ,/( / join the results of: + _f x@&xf) / sort (recursively) elements greater than f + ] diff --git a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k index 3a21fcbaf3..38d72b5d2a 100644 --- a/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k +++ b/Task/Sorting-algorithms-Quicksort/K/sorting-algorithms-quicksort-7.k @@ -1,9 +1 @@ - :[ - 0=#x; / if length of x is zero - x; / then return x - / else - ,/( / join the results of: - _f x@&xf) / sort (recursively) elements greater than f - ] + t@= $p, @a); } diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-6.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-6.py new file mode 100644 index 0000000000..2333684177 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-6.py @@ -0,0 +1,7 @@ +def qsort(array): + if len(array) < 2: + return array + head, *tail = array + less = qsort([i for i in tail if i < head]) + more = qsort([i for i in tail if i >= head]) + return less + [head] + more diff --git a/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-7.py b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-7.py new file mode 100644 index 0000000000..a2c5c55cc2 --- /dev/null +++ b/Task/Sorting-algorithms-Quicksort/Python/sorting-algorithms-quicksort-7.py @@ -0,0 +1,17 @@ +def quicksort(array): + _quicksort(array, 0, len(array) - 1) + +def _quicksort(array, start, stop): + if stop - start > 0: + pivot, left, right = array[start], start, stop + while left <= right: + while array[left] < pivot: + left += 1 + while array[right] > pivot: + right -= 1 + if left <= right: + array[left], array[right] = array[right], array[left] + left += 1 + right -= 1 + _quicksort(array, start, right) + _quicksort(array, left, stop) diff --git a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx index a3bc7dd9be..5541edf79a 100644 --- a/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx +++ b/Task/Sorting-algorithms-Quicksort/REXX/sorting-algorithms-quicksort-1.rexx @@ -1,119 +1,114 @@ -/*REXX program sorts a stemmed array using the quicksort method. */ +/*REXX program sorts a stemmed array using the quicksort algorithm.*/ call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show before array elements.*/ -call quickSort highItem /*here come da judge, here come..*/ -call show@ ' after sort' /*show after array elements.*/ +call show@ 'before sort' /*show before array elements.*/ +call quickSort # /*invoke the quicksort routine.*/ +call show@ ' after sort' /*show after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────QUICKSORT subroutine────────────────*/ quickSort: procedure expose @. /*access the caller's local var. */ a.1=1; b.1=arg(1); $=1 - do while $\==0; l=a.$; t=b.$; $=$-1 - if t<2 then iterate - h=l+t-1 - ?=l+t%2 - if @.h<@.l then if @.?<@.h then do; p=@.h; @.h=@.l; end - else if @.?>@.l then p=@.l - else do; p=@.?; @.?=@.l; end - else if @.?<@.l then p=@.l - else if @.?>@.h then do; p=@.h; @.h=@.l; end - else do; p=@.?; @.?=@.l; end - j=l+1 + do while $\==0; L=a.$; t=b.$; $=$-1; if t<2 then iterate + h=L+t-1 + ?=L+t%2 + if @.h<@.L then if @.?<@.h then do; p=@.h; @.h=@.L; end + else if @.?>@.L then p=@.L + else do; p=@.?; @.?=@.L; end + else if @.?<@.l then p=@.L + else if @.?>@.h then do; p=@.h; @.h=@.L; end + else do; p=@.?; @.?=@.L; end + j=L+1 k=h do forever - do j=j while j<=k & @.j<=p; end /*a tinie-tiny loop*/ - do k=k by -1 while j =p; end /*another tiny loop*/ - if j>=k then leave - _=@.j; @.j=@.k; @.k=_ + do j=j while j<=k & @.j<=p; end /*a tinie-tiny loop*/ + do k=k by -1 while j =p; end /*another " " */ + if j>=k then leave /*segment finished?*/ + _=@.j; @.j=@.k; @.k=_ /*swap j&k elements*/ end /*forever*/ - k=j-1; @.l=@.k; @.k=p - $=$+1 - if j<=? then do; a.$=j; b.$=h-j+1; $=$+1; a.$=l; b.$=k-l; end - else do; a.$=l; b.$=k-l; $=$+1; a.$=j; b.$=h-j+1; end - end /*while $\==0*/ + k=j-1; @.L=@.k; @.k=p; $=$+1 + if j<=? then do; a.$=j; b.$=h-j+1; $=$+1; a.$=L; b.$=k-L; end + eLse do; a.$=L; b.$=k-L; $=$+1; a.$=j; b.$=h-j+1; end + end /*whiLe $¬==0*/ return /*──────────────────────────────────GEN@ subroutine─────────────────────*/ gen@: @.=; maxL=0 /*assign default value for array.*/ -@.1 =" Rivers that form part of a state's (USA) border " /*adj. later,*/ -@.2 ='=' /*this value is expanded later. */ -@.3 ="Perdido River: Alabama, Florida" -@.4 ="Chattahoochee River: Alabama, Georgia" -@.5 ="Tennessee River: Alabama, Kentucky, Mississippi, Tennessee" -@.6 ="Colorado River: Arizona, California, Nevada, Baja California (Mexico)" -@.7 ="Mississippi River: Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennesse, Louisiana, Wisconsin" -@.8 ="St. Francis River: Arkansas, Missouri" -@.9 ="Poteau River: Arkansas, Oklahoma" -@.10="Arkansas River: Arkansas, Oklahoma" -@.11="Red River (Mississippi watershed): Arkansas, Oklahoma, Texas" -@.12="Byram River: Connecticut, New York" -@.13="Pawcatuck River: Connecticut, Rhode Island" -@.14="Delaware River: Delaware, New Jersey, New York, Pennsylvania" -@.15="Potomac River: District of Columbia, Maryland, Virginia, West Virginia" -@.16="St. Marys River: Florida, Georgia" -@.17="Chattooga River: Georgia, South Carolina" -@.18="Tugaloo River: Georgia, South Carolina" -@.19="Savannah River: Georgia, South Carolina" -@.20="Snake River: Idaho, Oregon, Washington" -@.21="Wabash River: Illinois, Indiana" -@.22="Ohio River: Illinois, Indiana, Kentucky, Ohio, West Virginia" -@.23="Great Miami River (mouth only): Indiana, Ohio" -@.24="Des Moines River: Iowa, Missouri" -@.25="Big Sioux River: Iowa, South Dakota" -@.26="Missouri River: Kansas, Iowa, Missouri, Nebraska, South Dakota" -@.27="Tug Fork River: Kentucky, Virginia, West Virginia" -@.28="Big Sandy River: Kentucky, West Virginia" -@.29="Pearl River: Louisiana, Mississippi" -@.30="Sabine River: Louisiana, Texas" -@.31="Monument Creek: Maine, New Brunswick (Canda)" -@.32="St. Croix River: Maine, New Brunswick (Canda)" -@.33="Piscataqua River: Maine, New Hampshire" -@.34="St. Francis River: Maine, Quebec (Canada)" -@.35="St. John River: Maine, Quebec (Canada)" -@.36="Pocomoke River: Maryland, Virginia" -@.37="Palmer River: Massachusetts, Rhode Island" -@.38="Runnins River: Massachusetts, Rhode Island" -@.39="Montreal River: Michigan (upper peninsula), Wisconsin" -@.40="Detroit River: Michigan, Ontario (Canada)" -@.41="St. Clair River: Michigan, Ontario (Canada)" -@.42="St. Marys River: Michigan, Ontario (Canada)" -@.43="Brule River: Michigan, Wisconsin" -@.44="Menominee River: Michigan, Wisconsin" -@.45="Red River of the North: Minnesota, North Dakota" -@.46="Bois de Sioux River: Minnesota, North Dakota, South Dakota" -@.47="Pigeon River: Minnesota, Ontario (Canada)" -@.48="Rainy River: Minnesota, Ontario (Canada)" -@.49="St. Croix River: Minnesota, Wisconsin" -@.50="St. Louis River: Minnesota, Wisconsin" -@.51="Halls Stream: New Hampshire, Canada" -@.52="Salmon Falls River: New Hampshire, Maine" -@.53="Connecticut River: New Hampshire, Vermont" -@.54="Arthur Kill: New Jersey, New York (tidal strait)" -@.55="Kill Van Kull: New Jersey, New York (tidal strait)" -@.56="Hudson River (lower part only): New Jersey, New York" -@.57="Rio Grande: New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila De Zaragoza (Mexico), Chihuahua (Mexico)" -@.58="Niagara River: New York, Ontario (Canada)" -@.59="St. Lawrence River: New York, Ontario (Canada)" -@.60="Poultney River: New York, Vermont" -@.61="Catawba River: North Carolina, South Carolina" -@.62="Blackwater River: North Carolina, Virginia" -@.63="Columbia River: Oregon, Washington" +@.1 = " Rivers that form part of a (USA) state's border " /*this value is adjusted later to include a prefix & suffix.*/ +@.2 = '=' /*this value is expanded later. */ +@.3 = "Perdido River Alabama, Florida" +@.4 = "Chattahoochee River Alabama, Georgia" +@.5 = "Tennessee River Alabama, Kentucky, Mississippi, Tennessee" +@.6 = "Colorado River Arizona, California, Nevada, Baja California (Mexico)" +@.7 = "Mississippi River Arkansas, Illinois, Iowa, Kentucky, Minnesota, Mississippi, Missouri, Tennessee, Louisiana, Wisconsin" +@.8 = "St. Francis River Arkansas, Missouri" +@.9 = "Poteau River Arkansas, Oklahoma" +@.10 = "Arkansas River Arkansas, Oklahoma" +@.11 = "Red River (Mississippi watershed) Arkansas, Oklahoma, Texas" +@.12 = "Byram River Connecticut, New York" +@.13 = "Pawcatuck River Connecticut, Rhode Island and Providence Plantations" +@.14 = "Delaware River Delaware, New Jersey, New York, Pennsylvania" +@.15 = "Potomac River District of Columbia, Maryland, Virginia, West Virginia" +@.16 = "St. Marys River Florida, Georgia" +@.17 = "Chattooga River Georgia, South Carolina" +@.18 = "Tugaloo River Georgia, South Carolina" +@.19 = "Savannah River Georgia, South Carolina" +@.20 = "Snake River Idaho, Oregon, Washington" +@.21 = "Wabash River Illinois, Indiana" +@.22 = "Ohio River Illinois, Indiana, Kentucky, Ohio, West Virginia" +@.23 = "Great Miami River (mouth only) Indiana, Ohio" +@.24 = "Des Moines River Iowa, Missouri" +@.25 = "Big Sioux River Iowa, South Dakota" +@.26 = "Missouri River Kansas, Iowa, Missouri, Nebraska, South Dakota" +@.27 = "Tug Fork River Kentucky, Virginia, West Virginia" +@.28 = "Big Sandy River Kentucky, West Virginia" +@.29 = "Pearl River Louisiana, Mississippi" +@.30 = "Sabine River Louisiana, Texas" +@.31 = "Monument Creek Maine, New Brunswick (Canada)" +@.32 = "St. Croix River Maine, New Brunswick (Canada)" +@.33 = "Piscataqua River Maine, New Hampshire" +@.34 = "St. Francis River Maine, Quebec (Canada)" +@.35 = "St. John River Maine, Quebec (Canada)" +@.36 = "Pocomoke River Maryland, Virginia" +@.37 = "Palmer River Massachusetts, Rhode Island and Providence Plantations" +@.38 = "Runnins River Massachusetts, Rhode Island and Providence Plantations" +@.39 = "Montreal River Michigan (upper peninsula), Wisconsin" +@.40 = "Detroit River Michigan, Ontario (Canada)" +@.41 = "St. Clair River Michigan, Ontario (Canada)" +@.42 = "St. Marys River Michigan, Ontario (Canada)" +@.43 = "Brule River Michigan, Wisconsin" +@.44 = "Menominee River Michigan, Wisconsin" +@.45 = "Red River of the North Minnesota, North Dakota" +@.46 = "Bois de Sioux River Minnesota, North Dakota, South Dakota" +@.47 = "Pigeon River Minnesota, Ontario (Canada)" +@.48 = "Rainy River Minnesota, Ontario (Canada)" +@.49 = "St. Croix River Minnesota, Wisconsin" +@.50 = "St. Louis River Minnesota, Wisconsin" +@.51 = "Halls Stream New Hampshire, Canada" +@.52 = "Salmon Falls River New Hampshire, Maine" +@.53 = "Connecticut River New Hampshire, Vermont" +@.54 = "Arthur Kill New Jersey, New York (tidal strait)" +@.55 = "Kill Van Kull New Jersey, New York (tidal strait)" +@.56 = "Hudson River (lower part only) New Jersey, New York" +@.57 = "Rio Grande New Mexico, Texas, Tamaulipas (Mexico), Nuevo Leon (Mexico), Coahuila de Zaragoza (Mexico), Chihuahua (Mexico)" +@.58 = "Niagara River New York, Ontario (Canada)" +@.59 = "St. Lawrence River New York, Ontario (Canada)" +@.60 = "Poultney River New York, Vermont" +@.61 = "Catawba River North Carolina, South Carolina" +@.62 = "Blackwater River North Carolina, Virginia" +@.63 = "Columbia River Oregon, Washington" - do highItem=1 while @.highItem\=='' /*find how many entries, and also*/ - maxL=max(maxL,length(@.highItem)) /* find the maximum width entry.*/ - end /*highItem*/ - -highItem=highItem-1 /*adjust highItem slightly. */ -@.1=centre(@.1,maxL,'-') /*adjust the header information. */ -@.2=copies(@.2,maxL) /*adjust the header separator. */ + do #=1 while @.#\=='' /*find how many entries, and also*/ + maxL=max(maxL, length(@.#)) /* find the maximum width entry.*/ + end /*#*/ +#=#-1 /*adjust the highest element #. */ +@.1=centre(@.1, maxL, '-') /*adjust the header information. */ +@.2=copies(@.2, maxL) /*adjust the header separator. */ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*maximum width of any line. */ - - do j=1 for highItem /*display each item in the array.*/ - say 'element' right(j,widthH) arg(1)':' @.j - end /*j*/ - -say copies('█',maxL+widthH+22) /*display a separator line. */ +show@: widthH=length(#) /*maximum width of any line. */ + do j=1 for # /*display each item in the array.*/ + say 'element' right(j,widthH) arg(1)':' @.j + end /*j*/ +say copies('▒', maxL + widthH + 22) /*display a separator line. */ return diff --git a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt index c0fd84dde1..5b9c836589 100644 --- a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt +++ b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-1.rkt @@ -1,9 +1,9 @@ #lang racket -(define (quicksort a-list (compare <)) - (match a-list - ((list) - (list)) - ((cons x xs) - (append (quicksort (filter (lambda (element) (compare element x)) xs) compare) - (list x) - (quicksort (filter (lambda (element) (not (compare element x))) xs) compare))))) +(define (quicksort < l) + (match l + ['() '()] + [(cons x xs) + (let-values ([(xs-gte xs-lt) (partition (curry < x) xs)]) + (append (quicksort < xs-lt) + (list x) + (quicksort < xs-gte)))])) diff --git a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt index 339b6867e4..0ecf9a2f2b 100644 --- a/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt +++ b/Task/Sorting-algorithms-Quicksort/Racket/sorting-algorithms-quicksort-2.rkt @@ -1,4 +1,4 @@ - (quicksort '(8 7 5 6 4 3 2)) +(quicksort < '(8 7 3 6 4 5 2)) ;returns '(2 3 4 5 6 7 8) -(quicksort '("Quicksort" "Mergesort" "Bubblesort") string(v: &mut[T]) { + let len = v.len(); + if len < 2 { + return; + } + + let pivot_index = partition(v); + + // Sort the left side + quick_sort(v.mut_slice(0, pivot_index)); + + // Sort the right side + quick_sort(v.mut_slice(pivot_index + 1, len)); +} + +// Reorders the slice with values lower than the pivot at the left side, +// and values bigger than it at the right side. +// Also returns the store index. +fn partition(v: &mut [T]) -> uint { + let len = v.len(); + let pivot_index = len / 2; + + v.swap(pivot_index, len - 1); + + let mut store_index = 0; + for i in range(0, len - 1) { + if v[i] <= v[len - 1] { + v.swap(i, store_index); + store_index += 1; + } + } + + v.swap(store_index, len - 1); + store_index +} + +fn main() { + // Sort numbers + let mut numbers = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]; + println!("Before: {}", numbers.as_slice()); + + quick_sort(numbers); + println!("After: {}", numbers.as_slice()); + + // Sort strings + let mut strings = ["beach", "hotel", "airplane", "car", "house", "art"]; + println!("Before: {}", strings.as_slice()); + + quick_sort(strings); + println!("After: {}", strings.as_slice()); +} diff --git a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala index be7a82ec30..037306b269 100644 --- a/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala +++ b/Task/Sorting-algorithms-Quicksort/Scala/sorting-algorithms-quicksort-5.scala @@ -1,6 +1,7 @@ def quicksortInt(list: List[Int]): List[Int] = list match { + case List(head) => list case head :: tail => val (smaller, bigger) = tail partition (_ < head) quicksortInt(smaller) ::: head :: quicksortInt(bigger) - case list => list + case _ => list } diff --git a/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java index 4d9f5b4f27..beba857e9f 100644 --- a/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java +++ b/Task/Sorting-algorithms-Radix-sort/Java/sorting-algorithms-radix-sort-1.java @@ -1,38 +1,34 @@ public static int[] sort(int[] old) { - - for(int shift = Integer.SIZE-1; shift > -1; shift--) { //Loop for every bit in the integers - - int[] tmp = new int[old.length]; //the array to put the partially sorted array into - int j = 0; //The number of 0s + // Loop for every bit in the integers + for (int shift = Integer.SIZE - 1; shift > -1; shift--) { + // The array to put the partially sorted array into + int[] tmp = new int[old.length]; + // The number of 0s + int j = 0; - - for(int i = 0; i < old.length; i++) { //Move the 0s to the new array, and the 1s to the old one - - boolean move = old[i] << shift >= 0; //If there is a 1 in the bit we are testing, the number will be negative - - if(shift == 0 ? !move : move) { //If this is the last bit, negative numbers are actually lower - - tmp[j] = old[i]; - j++; - - } else { //It's a 1, so stick it in the old array for now - - old[i-j] = old[i]; - - } - - } - - for(int i = j; i < tmp.length; i++) { //Copy over the 1s from the old array - - tmp[i] = old[i-j]; - - } - - old = tmp; //And now the tmp array gets switched for another round of sorting - - } - - return old; - + // Move the 0s to the new array, and the 1s to the old one + for (int i = 0; i < old.length; i++) { + // If there is a 1 in the bit we are testing, the number will be negative + boolean move = old[i] << shift >= 0; + + // If this is the last bit, negative numbers are actually lower + if (shift == 0 ? !move : move) { + tmp[j] = old[i]; + j++; + } else { + // It's a 1, so stick it in the old array for now + old[i - j] = old[i]; + } + } + + // Copy over the 1s from the old array + for (int i = j; i < tmp.length; i++) { + tmp[i] = old[i - j]; + } + + // And now the tmp array gets switched for another round of sorting + old = tmp; + } + + return old; } diff --git a/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-1.math b/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-1.math new file mode 100644 index 0000000000..08b754a430 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-1.math @@ -0,0 +1,17 @@ +ClearAll[SortByPos, RadixSort] +SortByPos[data : {_List ..}, pos_Integer] := Module[{digs, order}, + digs = data[[All, pos]]; + order = Ordering[digs]; + data[[order]] + ] +RadixSort[x : {_Integer ..}] := Module[{y, digs, maxlen, offset}, + offset = Min[x]; + y = x - offset; + digs = IntegerDigits /@ y; + maxlen = Max[Length /@ digs]; + digs = IntegerDigits[#, 10, maxlen] & /@ y; + digs = Fold[SortByPos, digs, -Range[maxlen]]; + digs = FromDigits /@ digs; + digs += offset; + digs + ] diff --git a/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-2.math b/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-2.math new file mode 100644 index 0000000000..63e2599c18 --- /dev/null +++ b/Task/Sorting-algorithms-Radix-sort/Mathematica/sorting-algorithms-radix-sort-2.math @@ -0,0 +1,2 @@ +RadixSort[{170,45,75,-90,-802,24,2,66}] +RadixSort[{170,45,75,90,802,2,24,66}] diff --git a/Task/Sorting-algorithms-Selection-sort/00DESCRIPTION b/Task/Sorting-algorithms-Selection-sort/00DESCRIPTION index 7ab15ff371..6d2a50816b 100644 --- a/Task/Sorting-algorithms-Selection-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Selection-sort/00DESCRIPTION @@ -2,6 +2,7 @@ In this task, the goal is to sort an [[array]] (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. -Its asymptotic complexity is [[O]](n2) making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg writing to flash memory or EEPROM. No other sorting algorithm has less data movement. +Its asymptotic complexity is [[O]](n2) making it inefficient on large arrays. Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM. +No other sorting algorithm has less data movement. For more information see the article on [[wp:Selection_sort|Wikipedia]]. diff --git a/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp b/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp index 74e722815a..694e229966 100644 --- a/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp +++ b/Task/Sorting-algorithms-Selection-sort/C++/sorting-algorithms-selection-sort.cpp @@ -1,8 +1,17 @@ #include #include +#include -template -void selectionSort(ForwardIterator begin, ForwardIterator end) { - for(ForwardIterator i = begin; i != end; ++i) - std::iter_swap(i, std::min_element(i, end)); +template void selection_sort(ForwardIterator begin, + ForwardIterator end) { + for(auto i = begin; i != end; ++i) { + std::iter_swap(i, std::min_element(i, end)); + } +} + +int main() { + int a[] = {100, 2, 56, 200, -52, 3, 99, 33, 177, -199}; + selection_sort(std::begin(a), std::end(a)); + copy(std::begin(a), std::end(a), std::ostream_iterator(std::cout, " ")); + std::cout << "\n"; } diff --git a/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c b/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c index 7a9e675083..6cdb825c24 100644 --- a/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c +++ b/Task/Sorting-algorithms-Selection-sort/C/sorting-algorithms-selection-sort.c @@ -1,9 +1,12 @@ +#include + void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { - if (a[j] < a[m]) + if (a[j] < a[m]) { m = j; + } } t = a[i]; a[i] = a[m]; @@ -14,6 +17,11 @@ void selection_sort (int *a, int n) { int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); selection_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; } diff --git a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e new file mode 100644 index 0000000000..df8538f3c6 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-1.e @@ -0,0 +1,62 @@ +class + SELECTION_SORT[G -> COMPARABLE] + + + +feature {NONE} +index_of_min(ar: ARRAY [G]; lower: INTEGER):INTEGER + --find index of smallest element in array ar in the range of lower and the max index. + require + lower_positiv : lower >=1 + lower_in_range: lower <= ar.count + ar_not_void: ar/= Void + local + i, index: INTEGER + min: G + do + from + i:=lower + min := ar.item (i) + index := i + until + i+1 > ar.count + loop + if ar.item(i+1) < min then + min := ar.item(i+1) + index := i+1 + end + i := i + 1 + end + Result := index + ensure + result_is_set: Result /= Void + end + + + +sort (ar: ARRAY [G]):ARRAY[G] + -- sort array ar with selectionsort + require + ar_not_void: ar/=VOID + local + min_index: INTEGER + ith: G + do + across ar as ic loop + min_index := index_of_min(ar,ic.cursor_index) + ith:=ar[ic.cursor_index] + ar[ic.cursor_index]:= ar[min_index] + ar[min_index]:=ith + end + Result:= ar + ensure + Result_is_set: Result /= Void + end + + +feature +selectionsort(ar: ARRAY[G]):ARRAY[G] + do + Result:= sort(ar) + end +end diff --git a/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e new file mode 100644 index 0000000000..ac85664410 --- /dev/null +++ b/Task/Sorting-algorithms-Selection-sort/Eiffel/sorting-algorithms-selection-sort-2.e @@ -0,0 +1,23 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make + +feature + make + + do + test := <<1, 27, 32, 99, 1, -7, 3, 5, 7>> + io.put_string ("Unsorted: ") + across test as ic loop io.put_string (ic.item.out + " ") end + create selection + io.put_string ("%NSorted: ") + test:= selectionsort.selectionsort(test) + across test as ar loop io.put_string (ar.item.out + " ") end + end + + test: ARRAY[INTEGER] + selection: SELECTION_SORT[INTEGER] +end diff --git a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs index 23afec4ad8..c126b5add5 100644 --- a/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs +++ b/Task/Sorting-algorithms-Selection-sort/Haskell/sorting-algorithms-selection-sort.hs @@ -1,7 +1,7 @@ -import Data.List (unfoldr) - -selectionSort = unfoldr selectionSort' where - selectionSort' [] = Nothing - selectionSort' (first:lst) = Just $ foldl f (first, []) lst - f (small, output) x | x < small = (x, small:output) - | otherwise = (small, x:output) +selSort :: (Ord a) => [a] -> [a] +selSort [] = [] +selSort xs = let x = maximum xs in selSort (remove x xs) ++ [x] + where remove _ [] = [] + remove a (x:xs) + | x == a = xs + | otherwise = x : remove a xs diff --git a/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx b/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx index 9f6c830407..3ffe26c8fc 100644 --- a/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx +++ b/Task/Sorting-algorithms-Selection-sort/REXX/sorting-algorithms-selection-sort.rexx @@ -1,31 +1,31 @@ -/*REXX program sorts an array using the selection-sort method. */ -@.='' /*assign a default value to stem.*/ -@.1='---The seven hills of Rome:---' -@.2='==============================' -@.3='Caelian' -@.4='Palatine' -@.5='Capitoline' -@.6='Virminal' -@.7='Esquiline' -@.8='Quirinal' -@.9='Aventine' - do items=1 until @.items=='' /*find # items.*/ - end -items=items-1 /*adjust the # of items slightly.*/ -call show@ 'before sort' /*show the before array elements,*/ -call selectionSort items /*invoke the selection sort. */ -call show@ ' after sort' /*show the after array elements.*/ +/*REXX program sorts a stemmed array using the selection-sort algorithm.*/ +@. = /*assign a default value to stem.*/ +@.1 = '---The seven hills of Rome:---' +@.2 = '==============================' +@.3 = 'Caelian' +@.4 = 'Palatine' +@.5 = 'Capitoline' +@.6 = 'Virminal' +@.7 = 'Esquiline' +@.8 = 'Quirinal' +@.9 = 'Aventine' + do k=1 until @.k=='' /*find the number of array items.*/ + end /*k*/ /* [↑] find the "null" item. */ +items=k-1 /*adjust the # of items slightly.*/ +call show@ 'before sort' /*show the before array elements,*/ +call selectionSort items /*invoke the selection sort. */ +call show@ ' after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SELECTIONSORT subroutine────────────*/ selectionSort: procedure expose @.; parse arg n - do j=1 for n-1 - _=@.j; p=j; do k=j+1 to n - if @.k<_ then do; _=@.k; p=k; end - end /*k*/ - if p==j then iterate - _=@.j; @.j=@.p; @.p=_ - end /*j*/ + do j=1 for n-1 + _=@.j; p=j; do k=j+1 to n + if @.k<_ then do; _=@.k; p=k; end + end /*k*/ + if p==j then iterate /*if the same, order of items OK.*/ + _=@.j; @.j=@.p; @.p=_ /*swap two items out-of-sequence.*/ + end /*j*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ show@: w=length(items); do i=1 for items diff --git a/Task/Sorting-algorithms-Shell-sort/00DESCRIPTION b/Task/Sorting-algorithms-Shell-sort/00DESCRIPTION index 427e510d99..7e8bde9ccb 100644 --- a/Task/Sorting-algorithms-Shell-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Shell-sort/00DESCRIPTION @@ -1,3 +1,8 @@ {{Sorting Algorithm}} -In this task, the goal is to sort an array of elements using the [[wp:Shell sort|Shell sort]] algorithm, a diminishing increment sort. The Shell sort is named after its inventor, Donald Shell, who published the algorithm in 1959. Shellsort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. +In this task, the goal is to sort an array of elements using the [[wp:Shell sort|Shell sort]] algorithm, a diminishing increment sort. +The Shell sort is named after its inventor, Donald Shell, who published the algorithm in 1959. +Shellsort is a sequence of interleaved insertion sorts based on an increment sequence. +The increment size is reduced after each pass until the increment size is 1. +With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". +Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [http://www.cs.princeton.edu/~rs/shell/] Other good sequences are found at the [https://oeis.org/search?q=shell+sort On-Line Encyclopedia of Integer Sequences]. diff --git a/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c b/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c index 220e3c2b74..43b3a6e1d1 100644 --- a/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c +++ b/Task/Sorting-algorithms-Shell-sort/C/sorting-algorithms-shell-sort.c @@ -1,12 +1,14 @@ +#include + void shell_sort (int *a, int n) { - int h, i, j, k; + int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { - k = a[i]; - for (j = i; j >= h && k < a[j - h]; j -= h) { + t = a[i]; + for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } - a[j] = k; + a[j] = t; } } } @@ -14,6 +16,11 @@ void shell_sort (int *a, int n) { int main (int ac, char **av) { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; + int i; + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); shell_sort(a, n); + for (i = 0; i < n; i++) + printf("%d%s", a[i], i == n - 1 ? "\n" : " "); return 0; } diff --git a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx index 693d34bbf0..eb0de4af9b 100644 --- a/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx +++ b/Task/Sorting-algorithms-Shell-sort/REXX/sorting-algorithms-shell-sort.rexx @@ -1,56 +1,54 @@ /*REXX program sorts an (stemmed) array using the shellsort method. */ call gen@ /*generate the array elements. */ -call show@ 'before sort' /*show the before array elements.*/ -call shellSort highItem /*invoke the shell sort. */ -call show@ ' after sort' /*show the after array elements.*/ +call show@ 'before sort' /*show the before array elements.*/ +call shellSort # /*invoke the shell sort. */ +call show@ ' after sort' /*show the after array elements.*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────GEN@ subroutine─────────────────────*/ gen@: @.= /*assign default value to stem. */ @.1='3 character abbreviations for states of the USA' /*predates ZIP.*/ @.2='===============================================' - @.3='RHO Rhode Island and Providence Plantations' ; @.36='NMX New Mexico' - @.4='CAL California' ; @.20='NEV Nevada' ; @.37='IND Indiana' - @.5='KAN Kansas' ; @.21='TEX Texas' ; @.38='MOE Missouri' - @.6='MAS Massachusetts' ; @.22='VGI Virginia' ; @.39='COL Colorado' - @.7='WAS Washington' ; @.23='OHI Ohio' ; @.40='CON Connecticut' - @.8='HAW Hawaii' ; @.24='NHM New Hampshire'; @.41='MON Montana' - @.9='NCR North Carolina'; @.25='MAE Maine' ; @.42='LOU Louisiana' -@.10='SCR South Carolina'; @.26='MIC Michigan' ; @.43='IOW Iowa' -@.11='IDA Idaho' ; @.27='MIN Minnesota' ; @.44='ORE Oregon' -@.12='NDK North Dakota' ; @.28='MIS Mississippi' ; @.45='ARK Arkansas' -@.13='SDK South Dakota' ; @.29='WIS Wisconsin' ; @.46='ARZ Arizona' -@.14='NEB Nebraska' ; @.30='OKA Oklahoma' ; @.47='UTH Utah' -@.15='DEL Delaware' ; @.31='ALA Alabama' ; @.48='KTY Kentucky' -@.16='PEN Pennsylvania' ; @.32='FLA Florida' ; @.49='WVG West Virginia' -@.17='TEN Tennessee' ; @.33='MLD Maryland' ; @.50='NWJ New Jersey' -@.18='GEO Georgia' ; @.34='ALK Alaska' ; @.51='NYK New York' -@.19='VER Vermont' ; @.35='ILL Illinois' ; @.52='WYO Wyoming' + @.3='RHO Rhode Island and Providence Plantations' ; @.36='NMX New Mexico' + @.4='CAL California' ; @.20='NEV Nevada' ; @.37='IND Indiana' + @.5='KAN Kansas' ; @.21='TEX Texas' ; @.38='MOE Missouri' + @.6='MAS Massachusetts' ; @.22='VGI Virginia' ; @.39='COL Colorado' + @.7='WAS Washington' ; @.23='OHI Ohio' ; @.40='CON Connecticut' + @.8='HAW Hawaii' ; @.24='NHM New Hampshire'; @.41='MON Montana' + @.9='NCR North Carolina'; @.25='MAE Maine' ; @.42='LOU Louisiana' +@.10='SCR South Carolina'; @.26='MIC Michigan' ; @.43='IOW Iowa' +@.11='IDA Idaho' ; @.27='MIN Minnesota' ; @.44='ORE Oregon' +@.12='NDK North Dakota' ; @.28='MIS Mississippi' ; @.45='ARK Arkansas' +@.13='SDK South Dakota' ; @.29='WIS Wisconsin' ; @.46='ARZ Arizona' +@.14='NEB Nebraska' ; @.30='OKA Oklahoma' ; @.47='UTH Utah' +@.15='DEL Delaware' ; @.31='ALA Alabama' ; @.48='KTY Kentucky' +@.16='PEN Pennsylvania' ; @.32='FLA Florida' ; @.49='WVG West Virginia' +@.17='TEN Tennessee' ; @.33='MLD Maryland' ; @.50='NWJ New Jersey' +@.18='GEO Georgia' ; @.34='ALK Alaska' ; @.51='NYK New York' +@.19='VER Vermont' ; @.35='ILL Illinois' ; @.52='WYO Wyoming' - do highItem=1 while @.highItem\=='' /*find how many entries in array.*/ - end - -highItem=highItem-1 /*adjust the highItem slightly.*/ + do #=1 while @.#\=='' /*find how many entries in array.*/ + end /*#*/ +#=#-1 /*adjust # of entries slightly.*/ return -/*──────────────────────────────────SHELLSORT subroutine───────---──────*/ -shellSort: procedure expose @.; parse arg highItem -i=highItem%2 +/*──────────────────────────────────SHELLSORT subroutine────────────────*/ +shellSort: procedure expose @.; parse arg N +i=N%2 /*integer divide N by two. */ do while i\==0 - do j=i+1 to highItem; k=j; kmi=k-i - _=@.j - do while k>=i+1 & @.kmi>_; @.k=@.kmi - k=k-i; kmi=k-i - end /*while k>=i+1 & ...*/ - @.k=_ - end /*j*/ + do j=i+1 to N; k=j; kmi=k-i + _=@.j + do while k>=i+1 & @.kmi>_; @.k=@.kmi + k=k-i; kmi=k-i + end /*while k>=i+1 & ···*/ + @.k=_ + end /*j*/ if i==2 then i=1 else i=i*5%11 end /*while i\==0*/ return /*──────────────────────────────────SHOW@ subroutine────────────────────*/ -show@: widthH=length(highItem) /*maximum width of any line. */ - do j=1 for highItem - say 'element' right(j,widthH) arg(1)': ' @.j - end /*j*/ +show@: do j=1 for # + say 'element' right(j,length(#)) arg(1)': ' @.j + end /*j*/ say copies('─',79) /*show a separator line (a fence)*/ return diff --git a/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt b/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt index b7a2e0fbb9..f15dbd2f37 100644 --- a/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt +++ b/Task/Sorting-algorithms-Shell-sort/Racket/sorting-algorithms-shell-sort.rkt @@ -1,14 +1,14 @@ #lang racket (define (shell-sort! xs) - (define (ref i) (vector-ref xs i)) - (define (new Δ) (if (= Δ 2) 1 (exact-floor (/ (* Δ 5) 11)))) + (define ref (curry vector-ref xs)) + (define (new Δ) (if (= Δ 2) 1 (quotient (* Δ 5) 11))) (let loop ([Δ (quotient (vector-length xs) 2)]) (unless (= Δ 0) - (for ([xi (in-vector xs)] [i (in-naturals)]) + (for ([xᵢ (in-vector xs)] [i (in-naturals)]) (let while ([i i]) - (cond [(and (>= i Δ) (> (ref (- i Δ)) xi)) + (cond [(and (>= i Δ) (> (ref (- i Δ)) xᵢ)) (vector-set! xs i (ref (- i Δ))) (while (- i Δ))] - [(vector-set! xs i xi)]))) + [else (vector-set! xs i xᵢ)]))) (loop (new Δ)))) xs) diff --git a/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp b/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp new file mode 100644 index 0000000000..9651d32169 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/C++/sorting-algorithms-sleep-sort.cpp @@ -0,0 +1,38 @@ +#include +#include +#include +#include + +using namespace std; + +void sortThread( int x ) +{ + usleep( 10000 * x ); + cout << x << " "; +} + +int main() +{ + vector threads; + + srand( ( unsigned )time( NULL ) ); + + cout << "unsorted:" << endl; + for( int x = 0; x < 15; x++ ) + { + int r = rand() % 20 + 5; + cout << r << " "; + thread* t = new thread( sortThread, r ); + threads.push_back( t ); + } + cout << endl << endl << "sorted:" << endl; + + for( vector::iterator t = threads.begin(); t != threads.end(); t++ ) + { + ( *t )->join(); + delete ( *t ); + } + + cout << endl << endl; + return 0; +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Clojure/sorting-algorithms-sleep-sort-1.clj b/Task/Sorting-algorithms-Sleep-sort/Clojure/sorting-algorithms-sleep-sort-1.clj new file mode 100644 index 0000000000..af5fbdd5d4 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Clojure/sorting-algorithms-sleep-sort-1.clj @@ -0,0 +1,9 @@ +(ns sleepsort.core + (require [clojure.core.async :as async :refer [chan go ! timeout]])) + +(defn sleep-sort [l] + (let [c (chan (count l))] + (doseq [i l] + (go (! c i))) + ( [1 2 3 4 5 6 7] diff --git a/Task/Sorting-algorithms-Sleep-sort/Common-Lisp/sorting-algorithms-sleep-sort.lisp b/Task/Sorting-algorithms-Sleep-sort/Common-Lisp/sorting-algorithms-sleep-sort.lisp new file mode 100644 index 0000000000..1a7e26dfd7 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Common-Lisp/sorting-algorithms-sleep-sort.lisp @@ -0,0 +1,8 @@ +(defun sleeprint(n) + (sleep (/ n 10)) + (format t "~a~%" n)) + +(loop for arg in (cdr sb-ext:*posix-argv*) doing + (sb-thread:make-thread (lambda() (sleeprint (parse-integer arg))))) + +(loop while (not (null (cdr (sb-thread:list-all-threads))))) 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 a846b88e9d..57d89a40e9 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 @@ -1,9 +1,9 @@ -import std.stdio, std.conv, std.datetime, core.thread; +import std.stdio, std.conv, std.datetime, std.array, core.thread; final class SleepSorter: Thread { private immutable uint val; - this(in uint n) /*pure nothrow*/ { + this(in uint n) /*pure nothrow @safe*/ { super(&run); val = n; } @@ -15,7 +15,7 @@ final class SleepSorter: Thread { } void main(in string[] args) { - if (args.length > 1) - foreach (arg; args[1 .. $]) + if (!args.empty) + foreach (const arg; args[1 .. $]) new SleepSorter(arg.to!uint).start; } diff --git a/Task/Sorting-algorithms-Sleep-sort/Dart/sorting-algorithms-sleep-sort.dart b/Task/Sorting-algorithms-Sleep-sort/Dart/sorting-algorithms-sleep-sort.dart new file mode 100644 index 0000000000..253cbc3a21 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Dart/sorting-algorithms-sleep-sort.dart @@ -0,0 +1,18 @@ +import 'dart:async'; + +Future> sleepsort(List input) { + List> tasks = []; + List result = []; + for (int i in input) { + tasks.add(new Future.delayed(new Duration(seconds: i), () { + result.add(i); + })); + } + return Future.wait(tasks).then((_) { + return result; + }); +} + +sleepsort.sleepsort([3, 1, 2]).then((List sorted) { + print(sorted); +}); diff --git a/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go b/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go index 3062bcdf30..276ad139d0 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go +++ b/Task/Sorting-algorithms-Sleep-sort/Go/sorting-algorithms-sleep-sort.go @@ -1,27 +1,26 @@ package main import ( - "log" - "os" - "strconv" - "sync" - "time" + "fmt" + "log" + "os" + "strconv" + "time" ) func main() { - lg := log.New(os.Stdout, "", 0) - var wg sync.WaitGroup - wg.Add(len(os.Args) - 1) - for _, a := range os.Args[1:] { - if i, err := strconv.ParseInt(a, 10, 64); err != nil { - lg.Print(err) - wg.Done() - } else { - time.AfterFunc(time.Duration(i*int64(time.Second)), func() { - lg.Print(i) - wg.Done() - }) - } - } - wg.Wait() + out := make(chan uint64) + for _, a := range os.Args[1:] { + i, err := strconv.ParseUint(a, 10, 64) + if err != nil { + log.Fatal(err) + } + go func(n uint64) { + time.Sleep(time.Duration(n) * time.Millisecond) + out <- n + }(i) + } + for _ = range os.Args[1:] { + fmt.Println(<-out) + } } diff --git a/Task/Sorting-algorithms-Sleep-sort/Groovy/sorting-algorithms-sleep-sort.groovy b/Task/Sorting-algorithms-Sleep-sort/Groovy/sorting-algorithms-sleep-sort.groovy new file mode 100644 index 0000000000..4274e28449 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Groovy/sorting-algorithms-sleep-sort.groovy @@ -0,0 +1,9 @@ +@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1') +import groovyx.gpars.GParsPool + +GParsPool.withPool args.size(), { + args.eachParallel { + sleep(it.toInteger() * 10) + println it + } +} diff --git a/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-1.lua b/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-1.lua new file mode 100644 index 0000000000..e13a1e7238 --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-1.lua @@ -0,0 +1,27 @@ +function sleeprint(n) + local t0 = os.time() + while os.time() - t0 <= n do + coroutine.yield(false) + end + print(n) + return true +end + +coroutines = {} +for i=1, #arg do + wrapped = coroutine.wrap(sleeprint) + table.insert(coroutines, wrapped) + wrapped(tonumber(arg[i])) +end + +done = false +while not done do + done = true + for i=#coroutines,1,-1 do + if coroutines[i]() then + table.remove(coroutines, i) + else + done = false + end + end +end diff --git a/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-2.lua b/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-2.lua new file mode 100644 index 0000000000..ac58e082ad --- /dev/null +++ b/Task/Sorting-algorithms-Sleep-sort/Lua/sorting-algorithms-sleep-sort-2.lua @@ -0,0 +1,29 @@ +socket = require 'socket' + +function sleeprint(n) + local t0 = socket.gettime() + while (socket.gettime() - t0)*100 <= n do + coroutine.yield(false) + end + print(n) + return true +end + +coroutines = {} +for i=1, #arg do + wrapped = coroutine.wrap(sleeprint) + table.insert(coroutines, wrapped) + wrapped(tonumber(arg[i])) +end + +done = false +while not done do + done = true + for i=#coroutines,1,-1 do + if coroutines[i]() then + table.remove(coroutines, i) + else + done = false + end + end +end diff --git a/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 b/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 index aab08a11d5..467746bb5d 100644 --- a/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 +++ b/Task/Sorting-algorithms-Sleep-sort/Perl-6/sorting-algorithms-sleep-sort.pl6 @@ -1,7 +1,2 @@ -use MuEvent; - -for <6 8 1 12 2 14 5 2 1 0> -> $item { - MuEvent::timer( after => $item, cb => sub { say $item } ); -} - -MuEvent::run; +await map -> $delay { start { sleep $delay ; say $delay } }, + <6 8 1 12 2 14 5 2 1 0>; diff --git a/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx b/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx index 9489ea84b2..6a92432fcd 100644 --- a/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx +++ b/Task/Sorting-algorithms-Sleep-sort/REXX/sorting-algorithms-sleep-sort.rexx @@ -1,46 +1,46 @@ -/*REXX program implements a sleep sort (with numbers entered from C.L.)*/ +/*REXX program implements a sleep sort (with numbers entered from C.L.).*/ numeric digits 300 /*over the top, but what the hey!*/ - /* (above) ... from vaudeville.*/ + /* (above) ··· from vaudeville.*/ #.= /*placeholder for the array of #s*/ -stuff='1e9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0' /*alphabetically*/ +stuff= 1e9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0 /*alphabetically*/ parse arg numbers /*let the user specify on the CL.*/ -if numbers='' then numbers=stuff /*Not specified? Then use default*/ +if numbers='' then numbers=stuff /*Not specified? Then use default*/ N=words(numbers) /*N is the number of numbers. */ w=length(N) /*width of N (for nice output).*/ say N 'numbers to be sorted:' numbers /*informative informational info.*/ - do j=1 for N /*let's start to boogie-woogie. */ + do j=1 for N /*let's start to boogie-woogie. */ #.j=word(numbers,j) /*plug in one number at a time. */ - if datatype(#.j,'Numeric') then #.j = #.j/1 /*normalize it if num.*/ - call fork /*REGINA REXX supports FORK func.*/ + if datatype(#.j,'N') then #.j=#.j/1 /*normalize it if a number.*/ + call fork /*only REGINA REXX supports FORK.*/ call sortItem j /*start a sort for array number. */ end /*j*/ - do forever while \inOrder(N) /*wait for the sorts to complete.*/ - call sleep 1 /*1 sec is the min effective time*/ + do forever while \inOrder(N) /*wait for the sorts to complete.*/ + call sleep 1 /*1 sec is minimum effective time*/ end /*forever while*/ /*well, other than zero seconds. */ m=max(length(#.1),length(#.N)) /*width of smallest | largest num*/ -say; say 'after sort:'; indent=left('',20) /*same as: COPIES(' ',20) */ - /*∙∙∙but LEFT pads [much faster]*/ - do k=1 for N /*list (sorted) array's elements.*/ - say indent 'array element' right(k,w) '───>' right(#.k,m) - end /*k*/ +say; say 'after sort:' /*display blank line and a title.*/ + + do k=1 for N /*list (sorted) array's elements.*/ + say left('',20) 'array element' right(k,w) '───►' right(#.k,m) + end /*k*/ exit /*stick a fork in it, we're done.*/ /*───────────────────────────────────SortItem subroutine────────────────*/ -sortItem: procedure expose #.; parse arg ? /*sorts single item.*/ - do Asort=1 until \switched /*cook until cooked.*/ - switched=0 /*honky-dorey so far*/ - do i=1 while #.i\=='' & \switched - if #.? >= #.i then iterate /*this one ok*/ - parse value #.? #.i with #.i #.? - switched=1 /*yup, we done switched one.*/ - end /*i*/ - if Asort//?==0 then call sleep switched /*sleep if last*/ - end /*Asort*/ +sortItem: procedure expose #.; parse arg ? /*sorts single item.*/ + do Asort=1 until \switched /*cook until cooked.*/ + switched=0 /*hunky-dorey so far*/ + do i=1 while #.i\=='' & \switched + if #.? >= #.i then iterate /*this one ok*/ + parse value #.? #.i with #.i #.? + switched=1 /* [↑] swapped one.*/ + end /*i*/ + if Asort//?==0 then call sleep switched /*sleep if last*/ + end /*Asort*/ return /*Sleeping Beauty awakes. Not to worry: (c) = circa 1697.*/ /*───────────────────────────────────InOrder subroutine─────────────────*/ inOrder: procedure expose #.; parse arg howMany /*is array in order? */ - do m=1 for howMany-1; next=m+1; if #.m>#.next then return 0 + do m=1 for howMany-1; next=m+1; if #.m>#.next then return 0 end /*m*/ /*keep looking for fountain of yut*/ return 1 /*yes, indicate with an indicator.*/ diff --git a/Task/Sorting-algorithms-Stooge-sort/00DESCRIPTION b/Task/Sorting-algorithms-Stooge-sort/00DESCRIPTION index 0068f7b411..ee953c4a31 100644 --- a/Task/Sorting-algorithms-Stooge-sort/00DESCRIPTION +++ b/Task/Sorting-algorithms-Stooge-sort/00DESCRIPTION @@ -1,4 +1,8 @@ -{{sorting Algorithm}}{{wikipedia|Stooge sort}}Show the [[wp:Stooge sort|Stooge Sort]] for an array of integers. The Stooge Sort algorithm is as follows: +{{sorting Algorithm}}{{wikipedia|Stooge sort}} +{{omit from|GUISS}} +Show the [[wp:Stooge sort|Stooge Sort]] for an array of integers. + +The Stooge Sort algorithm is as follows: algorithm stoogesort(array L, i = 0, j = length(L)-1) if L[j] < L[i] then L[i] L[j] diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e new file mode 100644 index 0000000000..73e1861b98 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-1.e @@ -0,0 +1,28 @@ +class + STOOGE_SORT +feature + stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER) + require + ar_not_empty: ar.count >= 0 + i_in_range: i>=1 + j_in_range: j <= ar.count + boundary_set: i<=j + local + t: REAL_64 + third: INTEGER + swap: INTEGER + do + if ar[j]< ar[i] then + swap:= ar[i] + ar[i]:=ar[j] + ar[j]:= swap + end + if j-i >1 then + t:= (j-i+1)/3 + third:= t.floor + stoogesort(ar, i, j-third) + stoogesort(ar, i+third, j) + stoogesort(ar, i, j-third) + end + end +end diff --git a/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e new file mode 100644 index 0000000000..bd968fbbe8 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/Eiffel/sorting-algorithms-stooge-sort-2.e @@ -0,0 +1,20 @@ +class + APPLICATION +inherit + ARGUMENTS +create + make +feature + make + do + test:= <<2,5,66,-2, 0, 7>> + io.put_string ("%Nunsorted:%N") + across test as ar loop io.put_string (ar.item.out + "%T") end + create stoogesort + stoogesort.stoogesort (test, 1, test.count) + io.put_string ("%Nsorted:%N") + across test as ar loop io.put_string (ar.item.out + "%T") end + end + test: ARRAY[INTEGER] + stoogesort: STOOGE_SORT +end diff --git a/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max new file mode 100644 index 0000000000..cfd35c1508 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-1.max @@ -0,0 +1,18 @@ +fn stoogeSort arr i: j: = +( + if i == unsupplied do i = 1 + if j == unsupplied do j = arr.count + + if arr[j] < arr[i] do + ( + swap arr[j] arr[i] + ) + if j - i > 1 do + ( + local t = (j - i+1)/3 + arr = stoogeSort arr i:i j:(j-t) + arr = stoogeSort arr i:(i+t) j:j + arr = stoogeSort arr i:i j:(j-t) + ) + return arr +) diff --git a/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-2.max b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-2.max new file mode 100644 index 0000000000..6a81d1cbf2 --- /dev/null +++ b/Task/Sorting-algorithms-Stooge-sort/MAXScript/sorting-algorithms-stooge-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 15 collect random 1 20 +#(10, 2, 1, 19, 18, 20, 18, 5, 13, 2, 13, 9, 7, 10, 6) +stoogeSort a +#(1, 2, 2, 5, 6, 7, 9, 10, 10, 13, 13, 18, 18, 19, 20) diff --git a/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-1.max b/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-1.max new file mode 100644 index 0000000000..f9b852220d --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-1.max @@ -0,0 +1,25 @@ +fn strandSort arr = +( + arr = deepcopy arr + local sub = #() + local results = #() + while arr.count > 0 do + ( + sub = #() + append sub (amax arr) + deleteitem arr (for i in 1 to arr.count where arr[i] == amax arr collect i)[1] + local i = 1 + while i <= arr.count do + ( + if arr[i] > sub[sub.count] do + ( + append sub arr[i] + deleteitem arr i + ) + i += 1 + ) + results = join sub results + ) + return results + +) diff --git a/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-2.max b/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-2.max new file mode 100644 index 0000000000..33c4f1c254 --- /dev/null +++ b/Task/Sorting-algorithms-Strand-sort/MAXScript/sorting-algorithms-strand-sort-2.max @@ -0,0 +1,4 @@ +a = for i in 1 to 20 collect random 1 40 +#(19, 26, 14, 31, 11, 33, 2, 14, 32, 28, 12, 38, 2, 37, 27, 18, 31, 24, 39, 28) +strandSort a +#(2, 2, 11, 12, 14, 14, 18, 19, 24, 26, 27, 28, 28, 31, 31, 32, 33, 37, 38, 39) diff --git a/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx index 0be8a3d765..7bb4c0afac 100644 --- a/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx +++ b/Task/Sorting-algorithms-Strand-sort/REXX/sorting-algorithms-strand-sort.rexx @@ -1,30 +1,30 @@ -/*REXX program uses a strand sort to sort a random list of words | nums.*/ +/*REXX pgm sorts a random list of words using the strand sort algorithm.*/ parse arg size minv maxv,old /*get options from command line. */ -if size=='' then size=20 /*no size? Then use the default.*/ -if minv=='' then minv=0 /*no minV? " " " " */ -if maxv=='' then maxv=size /*no maxV? " " " " */ - do i=1 for size /*generate random # list*/ - old=old random(0,maxv-minv)+minv +if size=='' then size=20 /*no size? Then use the default.*/ +if minv=='' then minv=0 /*no minV? " " " " */ +if maxv=='' then maxv=size /*no maxV? " " " " */ + do i=1 for size /*generate random # list*/ + old=old random(0,maxv-minv)+minv end /*i*/ old=space(old) /*remove any extraneous blanks. */ -say center('unsorted list',length(old),"="); say old; say +say center('unsorted list',length(old),"─"); say old; say new=strand_sort(old) /*sort the list of random numbers*/ -say center('sorted list' ,length(new),"="); say new +say center('sorted list' ,length(new),"─"); say new exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────STRAND_SORT subroutine──────────────*/ strand_sort: procedure; parse arg x; y= - do while words(x)\==0; w=words(x) - do j=1 for w-1 /*any number|word out of order?*/ - if word(x,j)>word(x,j+1) then do; w=j; leave; end - end /*j*/ + do while words(x)\==0; w=words(x) + do j=1 for w-1 /*any number | word out of order?*/ + if word(x,j)>word(x,j+1) then do; w=j; leave; end + end /*j*/ y=merge(y,subword(x,1,w)); x=subword(x,w+1) - end /*while words(x)\==0*/ + end /*while*/ return y /*──────────────────────────────────MERGE subroutine────────────────────*/ merge: procedure; parse arg a.1,a.2; p= do forever /*keep at it while 2 lists exist.*/ - do i=1 to 2; w.i=words(a.i); end /*find number of entries in lists*/ - if w.1*w.2==0 then leave /*if any list is empty, then stop*/ + do i=1 for 2; w.i=words(a.i); end /*find number of entries in lists*/ + if w.1*w.2==0 then leave /*if any list is empty, then stop*/ if word(a.1,w.1) <= word(a.2,1) then leave /*lists are now sorted?*/ if word(a.2,w.2) <= word(a.1,1) then return space(p a.2 a.1) #=1+(word(a.1,1) >= word(a.2,1)); p=p word(a.#,1); a.#=subword(a.#,2) diff --git a/Task/Soundex/00DESCRIPTION b/Task/Soundex/00DESCRIPTION index 01957a1e49..7369dc29ce 100644 --- a/Task/Soundex/00DESCRIPTION +++ b/Task/Soundex/00DESCRIPTION @@ -1 +1,2 @@ -Soundex is an algorithm for creating indices for words based on their pronunciation. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from [[wp:soundex|the WP article]]). +Soundex is an algorithm for creating indices for words based on their pronunciation. +The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from [[wp:soundex|the WP article]]). diff --git a/Task/Soundex/Ada/soundex.ada b/Task/Soundex/Ada/soundex.ada index 25378b9318..e3199e5b29 100644 --- a/Task/Soundex/Ada/soundex.ada +++ b/Task/Soundex/Ada/soundex.ada @@ -6,10 +6,10 @@ procedure Soundex is function "+"(S:String) return Unbounded_String renames To_Unbounded_String; function toSoundex (instr : String) return String is - str : String := To_Upper(instr); + str : String := To_Upper(instr); output : String := "0000"; spos : Integer := str'First+1; opos : Positive := 2; - map : array(0..255) of Character := (others => ' '); + map : array(0..255) of Character := (others => ' '); last : Integer := str'First; begin map(65..90) := " 123 12- 22455 12623 1-2 2"; diff --git a/Task/Soundex/REXX/soundex.rexx b/Task/Soundex/REXX/soundex.rexx index 73f894c377..b33472ae4c 100644 --- a/Task/Soundex/REXX/soundex.rexx +++ b/Task/Soundex/REXX/soundex.rexx @@ -1,81 +1,81 @@ /*REXX program demonstrates Soundex codes from some words | commandLine.*/ -_=; @.= +_=; @.= /*set a couple of vars to "null".*/ parse arg @.0 . /*allow input from command line. */ - @.1 ='12346' ; #.1 ='0000' - @.4 ='4-H' ; #.4 ='H000' - @.11 ='Ashcraft' ; #.11 ='A261' - @.12 ='Ashcroft' ; #.12 ='A261' - @.18 ='auerbach' ; #.18 ='A612' - @.20 ='Baragwanath' ; #.20 ='B625' - @.22 ='bar' ; #.22 ='B600' - @.23 ='barre' ; #.23 ='B600' - @.20 ='Baragwanath' ; #.20 ='B625' - @.28 ='Burroughs' ; #.28 ='B620' - @.29 ='Burrows' ; #.29 ='B620' - @.30 ='C.I.A.' ; #.30 ='C000' - @.37 ='coöp' ; #.37 ='C100' - @.43 ='D-day' ; #.43 ='D000' - @.44 ='d jay' ; #.44 ='D200' - @.45 ='de la Rosa' ; #.45 ='D462' - @.46 ='Donnell' ; #.46 ='D540' - @.47 ='Dracula' ; #.47 ='D624' - @.48 ='Drakula' ; #.48 ='D624' - @.49 ='Du Pont' ; #.49 ='D153' - @.50 ='Ekzampul' ; #.50 ='E251' - @.51 ='example' ; #.51 ='E251' - @.55 ='Ellery' ; #.55 ='E460' - @.59 ='Euler' ; #.59 ='E460' - @.60 ='F.B.I.' ; #.60 ='F000' - @.70 ='Gauss' ; #.70 ='G200' - @.71 ='Ghosh' ; #.71 ='G200' - @.72 ='Gutierrez' ; #.72 ='G362' - @.80 ='he' ; #.80 ='H000' - @.81 ='Heilbronn' ; #.81 ='H416' - @.84 ='Hilbert' ; #.84 ='H416' - @.100='Jackson' ; #.100='J250' - @.104='Johnny' ; #.104='J500' - @.105='Jonny' ; #.105='J500' - @.110='Kant' ; #.110='K530' - @.116='Knuth' ; #.116='K530' - @.120='Ladd' ; #.120='L300' - @.124='Llyod' ; #.124='L300' - @.125='Lee' ; #.125='L000' - @.126='Lissajous' ; #.126='L222' - @.128='Lukasiewicz' ; #.128='L222' - @.130='naïve' ; #.130='N100' - @.141='Miller' ; #.141='M460' - @.143='Moses' ; #.143='M220' - @.146='Moskowitz' ; #.146='M232' - @.147='Moskovitz' ; #.147='M213' - @.150="O'Conner" ; #.150='O256' - @.151="O'Connor" ; #.151='O256' - @.152="O'Hara" ; #.152='O600' - @.153="O'Mally" ; #.153='O540' - @.161='Peters' ; #.161='P362' - @.162='Peterson' ; #.162='P362' - @.165='Pfister' ; #.165='P236' - @.180='R2-D2' ; #.180='R300' - @.182='rÄ≈sumÅ∙' ; #.182='R250' - @.184='Robert' ; #.184='R163' - @.185='Rupert' ; #.185='R163' - @.187='Rubin' ; #.187='R150' - @.191='Soundex' ; #.191='S532' - @.192='sownteks' ; #.192='S532' - @.199='Swhgler' ; #.199='S460' - @.202="'til" ; #.202='T400' - @.208='Tymczak' ; #.208='T522' - @.216='Uhrbach' ; #.216='U612' - @.221='Van de Graaff' ; #.221='V532' - @.222='VanDeusen' ; #.222='V532' - @.230='Washington' ; #.230='W252' - @.233='Wheaton' ; #.233='W350' - @.234='Williams' ; #.234='W452' - @.236='Woolcock' ; #.236='W422' + @.1 = "12346" ; #.1 = '0000' + @.4 = "4-H" ; #.4 = 'H000' + @.11 = "Ashcraft" ; #.11 = 'A261' + @.12 = "Ashcroft" ; #.12 = 'A261' + @.18 = "auerbach" ; #.18 = 'A612' + @.20 = "Baragwanath" ; #.20 = 'B625' + @.22 = "bar" ; #.22 = 'B600' + @.23 = "barre" ; #.23 = 'B600' + @.20 = "Baragwanath" ; #.20 = 'B625' + @.28 = "Burroughs" ; #.28 = 'B620' + @.29 = "Burrows" ; #.29 = 'B620' + @.30 = "C.I.A." ; #.30 = 'C000' + @.37 = "coöp" ; #.37 = 'C100' + @.43 = "D-day" ; #.43 = 'D000' + @.44 = "d jay" ; #.44 = 'D200' + @.45 = "de la Rosa" ; #.45 = 'D462' + @.46 = "Donnell" ; #.46 = 'D540' + @.47 = "Dracula" ; #.47 = 'D624' + @.48 = "Drakula" ; #.48 = 'D624' + @.49 = "Du Pont" ; #.49 = 'D153' + @.50 = "Ekzampul" ; #.50 = 'E251' + @.51 = "example" ; #.51 = 'E251' + @.55 = "Ellery" ; #.55 = 'E460' + @.59 = "Euler" ; #.59 = 'E460' + @.60 = "F.B.I." ; #.60 = 'F000' + @.70 = "Gauss" ; #.70 = 'G200' + @.71 = "Ghosh" ; #.71 = 'G200' + @.72 = "Gutierrez" ; #.72 = 'G362' + @.80 = "he" ; #.80 = 'H000' + @.81 = "Heilbronn" ; #.81 = 'H416' + @.84 = "Hilbert" ; #.84 = 'H416' + @.100 = "Jackson" ; #.100 = 'J250' + @.104 = "Johnny" ; #.104 = 'J500' + @.105 = "Jonny" ; #.105 = 'J500' + @.110 = "Kant" ; #.110 = 'K530' + @.116 = "Knuth" ; #.116 = 'K530' + @.120 = "Ladd" ; #.120 = 'L300' + @.124 = "Llyod" ; #.124 = 'L300' + @.125 = "Lee" ; #.125 = 'L000' + @.126 = "Lissajous" ; #.126 = 'L222' + @.128 = "Lukasiewicz" ; #.128 = 'L222' + @.130 = "naïve" ; #.130 = 'N100' + @.141 = "Miller" ; #.141 = 'M460' + @.143 = "Moses" ; #.143 = 'M220' + @.146 = "Moskowitz" ; #.146 = 'M232' + @.147 = "Moskovitz" ; #.147 = 'M213' + @.150 = "O'Conner" ; #.150 = 'O256' + @.151 = "O'Connor" ; #.151 = 'O256' + @.152 = "O'Hara" ; #.152 = 'O600' + @.153 = "O'Mally" ; #.153 = 'O540' + @.161 = "Peters" ; #.161 = 'P362' + @.162 = "Peterson" ; #.162 = 'P362' + @.165 = "Pfister" ; #.165 = 'P236' + @.180 = "R2-D2" ; #.180 = 'R300' + @.182 = "rÄ≈sumÅ∙" ; #.182 = 'R250' + @.184 = "Robert" ; #.184 = 'R163' + @.185 = "Rupert" ; #.185 = 'R163' + @.187 = "Rubin" ; #.187 = 'R150' + @.191 = "Soundex" ; #.191 = 'S532' + @.192 = "sownteks" ; #.192 = 'S532' + @.199 = "Swhgler" ; #.199 = 'S460' + @.202 = "'til" ; #.202 = 'T400' + @.208 = "Tymczak" ; #.208 = 'T522' + @.216 = "Uhrbach" ; #.216 = 'U612' + @.221 = "Van de Graaff" ; #.221 = 'V532' + @.222 = "VanDeusen" ; #.222 = 'V532' + @.230 = "Washington" ; #.230 = 'W252' + @.233 = "Wheaton" ; #.233 = 'W350' + @.234 = "Williams" ; #.234 = 'W452' + @.236 = "Woolcock" ; #.236 = 'W422' - do k=0 to 300; if @.k=='' then iterate ; $=soundex(@.k) - say word('nope [ok]',1+($==#.k|k==0)) _ $ 'is the Soundex for' @.k - if k==0 then leave - end /*k*/ + do k=0 for 300; if @.k=='' then iterate; $=soundex(@.k) + say word('nope [ok]',1+($==#.k | k==0)) _ $ 'is the Soundex for' @.k + if k==0 then leave + end /*k*/ exit /*stick a fork in it, we're done.*/ /*───────────────────────────────────SOUNDEX subroutine─────────────────*/ soundex: procedure; arg thing /*ARG automatically uppercases it*/ @@ -83,18 +83,18 @@ old_alphabet = 'AEIOUYHWBFPVCGJKQSXZDTLMNR' new_alphabet = '@@@@@@**111122222222334556' word= do i=1 for length(thing) /*handle special chars: - ' _ etc*/ - _=substr(thing,i,1) + _=substr(thing, i, 1) if datatype(_,'M') then word=word || _ /*it's a letter, then OK*/ end /*i*/ -value=strip(left(word,1)) /*first character is left alone. */ +value=strip(left(word, 1)) /*first character is left alone. */ word=translate(word, new_alphabet, old_alphabet) prev=translate(value,new_alphabet, old_alphabet) /*the previous code.*/ - do j=2 to length(word) /*process remainder of the word. */ - ?=substr(word,j,1) - if ?\==prev & datatype(?,'W') then do; value=value || ?; prev=?; end - else if ?=='@' then prev=? - end /*j*/ + do j=2 to length(word) /*process remainder of the word. */ + ?=substr(word, j, 1) + if ?\==prev & datatype(?,'W') then do; value=value || ?; prev=?; end + else if ?=='@' then prev=? + end /*j*/ return left(value,4,0) /*return padded value with zeroes*/ diff --git a/Task/Soundex/Standard-ML/soundex.ml b/Task/Soundex/Standard-ML/soundex.ml new file mode 100644 index 0000000000..3ca85dab9c --- /dev/null +++ b/Task/Soundex/Standard-ML/soundex.ml @@ -0,0 +1,66 @@ +(* There are 3 kinds of letters: + * h and w are ignored completely (letters separated by h or w are considered + * adjacent, or merged together) + * vowels are ignored, but letters separated by a vowel are split apart. + * All consonants but h and w map to a digit *) +datatype code = + Merge + | Split + | Digit of char + +(* Encodes which characters map to which codes *) +val codeTable = + [([#"H", #"W"], Merge), + ([#"A",#"E",#"I", #"O",#"U",#"Y"], Split), + ([#"B",#"F",#"P",#"V"], Digit #"1"), + ([#"C",#"G",#"J",#"K",#"Q",#"S",#"X",#"Z"], Digit #"2"), + ([#"D",#"T"], Digit #"3"), + ([#"L"], Digit #"4"), + ([#"M",#"N"], Digit #"5"), + ([#"R"], Digit #"6")] + +(* Find the code that matches a given character *) +fun codeOf (c : char) = + #2 (valOf (List.find (fn (L,_) => isSome(List.find (fn c' => c = c') L)) codeTable)) + +(* Remove all the non-digit codes, combining like digits when appropriate. *) +fun collapse (c :: Merge :: cs) = collapse (c :: cs) + | collapse (Digit d :: Split :: cs) = Digit d :: collapse cs + | collapse (Digit d :: (cs' as Digit d' :: cs)) = + if d = d' then collapse (Digit d :: cs) + else Digit d :: collapse cs' + | collapse [Digit d] = [Digit d] + | collapse (c::cs) = collapse cs + | collapse _ = [] + +(* dropWhile f L removes the initial elements of L that satisfy f and returns + * the rest *) +fun dropWhile f [] = [] + | dropWhile f (x::xs) = + if f x then dropWhile f xs + else x::xs + +fun soundex (s : string) = + let + (* Normalize the string to uppercase letters only *) + val c::cs = map (Char.toUpper) (filter Char.isAlpha(String.explode s)) + fun first3 L = map (fn Digit c => c) (List.take(L,3)) + val padding = [Digit #"0", Digit #"0", Digit #"0"] + (* Remove any initial section that has the same code as the first character. + * This comes up in the "Pfister" test case. *) + val codes = dropWhile (fn Merge => true | Digit d => Digit d = codeOf c | Split => false) + (map codeOf (c::cs)) + in + String.implode(c::first3(collapse codes@padding)) + end + +(* Some test cases from Wikipedia *) +fun test input output = + if soundex input = output then () + else raise Fail ("Soundex of " ^ input ^ " should be " ^ output ^ ", not " ^ soundex input) + +val () = test "Rupert" "R163" +val () = test "Robert" "R163" +val () = test "Rubin" "R150" +val () = test "Tymczak" "T522" +val () = test "Pfister" "P236" diff --git a/Task/Soundex/TXR/soundex-2.txr b/Task/Soundex/TXR/soundex-2.txr index 19c0428bd6..7f2bcf958b 100644 --- a/Task/Soundex/TXR/soundex-2.txr +++ b/Task/Soundex/TXR/soundex-2.txr @@ -1,12 +1,11 @@ -@(next :args) @(do (defun get-code (c) - (cond ((memq c '(#\B #\F #\P #\V)) #\1) - ((memq c '(#\C #\G #\J #\K - #\Q #\S #\X #\Z)) #\2) - ((memq c '(#\D #\T)) #\3) - ((eql c #\L) #\4) - ((memq c '(#\M #\N)) #\5) - ((eq c #\R) #\6))) + (caseq c + ((#\B #\F #\P #\V) #\1) + ((#\C #\G #\J #\K #\Q #\S #\X #\Z) #\2) + ((#\D #\T) #\3) + (#\L #\4) + ((#\M #\N) #\5) + (#\R #\6))) (defun soundex (s) (if (zerop (length s)) @@ -14,12 +13,13 @@ (let* ((su (upcase-str s)) (o (chr-str su 0))) (for ((i 1) (l (length su)) cp cg) - ((< i l) (sub-str (cat-str '(,o "000") nil) 0 4)) + ((< i l) (sub-str (cat-str ^(,o "000") nil) 0 4)) ((inc i) (set cp cg)) (set cg (get-code (chr-str su i))) (if (and cg (null (eql cg cp))) - (set o (cat-str '(,o ,cg) nil)))))))) -@(collect) + (set o (cat-str ^(,o ,cg) nil)))))))) +@(next :args) +@(repeat) @arg @ (output) @arg -> @(soundex arg) diff --git a/Task/Special-characters/Scala/special-characters.scala b/Task/Special-characters/Scala/special-characters.scala new file mode 100644 index 0000000000..60fee8410b --- /dev/null +++ b/Task/Special-characters/Scala/special-characters.scala @@ -0,0 +1 @@ +val n = 1 + 2 diff --git a/Task/Special-variables/Clojure/special-variables.clj b/Task/Special-variables/Clojure/special-variables.clj new file mode 100644 index 0000000000..c42e743ba3 --- /dev/null +++ b/Task/Special-variables/Clojure/special-variables.clj @@ -0,0 +1 @@ +(apply str (interpose " " (sort (filter #(.startsWith % "*") (map str (keys (ns-publics 'clojure.core))))))) diff --git a/Task/Special-variables/Common-Lisp/special-variables.lisp b/Task/Special-variables/Common-Lisp/special-variables.lisp new file mode 100644 index 0000000000..61d48271b8 --- /dev/null +++ b/Task/Special-variables/Common-Lisp/special-variables.lisp @@ -0,0 +1,12 @@ +(defun special-variables () + (flet ((special-var-p (s) + (and (char= (aref s 0) #\*) + (find-if-not (lambda (x) (char= x #\*)) s) + (char= (aref s (1- (length s))) #\*)))) + (let ((lst '())) + (do-symbols (s (find-package 'cl)) + (when (special-var-p (symbol-name s)) + (push s lst))) + lst))) + +(format t "~a~%" (sort (special-variables) #'string<)) diff --git a/Task/Special-variables/Julia/special-variables.julia b/Task/Special-variables/Julia/special-variables.julia new file mode 100644 index 0000000000..7431213f29 --- /dev/null +++ b/Task/Special-variables/Julia/special-variables.julia @@ -0,0 +1 @@ +join(sort(filter(sym -> let n=eval(sym); !(isa(n, Function) || isa(n, Type) || isa(n, Module)); end, names(Base))), ", ") diff --git a/Task/Special-variables/Lua/special-variables.lua b/Task/Special-variables/Lua/special-variables.lua new file mode 100644 index 0000000000..f6b64a51cd --- /dev/null +++ b/Task/Special-variables/Lua/special-variables.lua @@ -0,0 +1 @@ +for n in pairs(_G) do print(n) end diff --git a/Task/Special-variables/REXX/special-variables-1.rexx b/Task/Special-variables/REXX/special-variables-1.rexx new file mode 100644 index 0000000000..83d783117e --- /dev/null +++ b/Task/Special-variables/REXX/special-variables-1.rexx @@ -0,0 +1,29 @@ +/*REXX program demonstrates REXX special variables: RC, RESULT, SIGL */ + /*line two. */ + /*line three.*/ say copies('═',79) +rc=1/3 /*line four. */ +signal youWho /*line five. */ +myLoo='this got skipped' /*line six. */ +youwho: /*line seven.*/ +sep=copies('─', 9) /*line eight.*/ +say sep 'SIGL=' sigl /*line nine. */ +say sep 'REXX source statement' SIGL '=' sourceline(sigl) + say copies('═',79) +g=44 +call halve g +say sep 'rc=' rc +say sep 'result=' result + say copies('═',79) +h=66 +hh=halve(h) +say sep 'rc=' rc +say sep 'result=' result +say sep 'hh=' hh + say copies('═',79) +'DIR /ad /b' /*display the directories (Bare).*/ +say sep 'rc=' rc +say sep 'result=' result + say copies('═',79) +exit /*stick a fork in it, we're done.*/ +/*──────────────────────────────────HALVE subroutine────────────────────*/ +halve: return arg(1) / 2 /*a simple halving function. */ diff --git a/Task/Special-variables/REXX/special-variables-2.rexx b/Task/Special-variables/REXX/special-variables-2.rexx new file mode 100644 index 0000000000..b1153cc9a7 --- /dev/null +++ b/Task/Special-variables/REXX/special-variables-2.rexx @@ -0,0 +1,23 @@ +'dir a2.txt' +Say 'rc='rc +'dir 33.*' +Say 'rc='rc + +Call square 5 +Say 'RESULT='result +Say 'SIGL='sigl + +x2=square(3) /* just a simle example */ +Say '3**2='||x2 + +Signal On Novalue +x=y /* y was not yet assigned a value */ + +Exit +square: Procedure Expose sigl +Say 'square was invoked from line' sigl':' sourceline(sigl) +Return arg(1)**2 + +Novalue: +Say 'NOVALUE encountered in line' sigl':' sourceline(sigl) +Exit diff --git a/Task/Special-variables/REXX/special-variables.rexx b/Task/Special-variables/REXX/special-variables.rexx deleted file mode 100644 index bd615b0449..0000000000 --- a/Task/Special-variables/REXX/special-variables.rexx +++ /dev/null @@ -1,28 +0,0 @@ -/*REXX program to demonstrate REXX special variables: RC, RESULT, SIGL. */ - /*line two. */ - /*line three.*/ say copies('=',75) -rc=1/3 /*line four. */ -signal youWho /*line five. */ -myLoo='this got skipped' /*line six. */ -youwho: /*line seven.*/ -say 'SIGL=' sigl -say 'REXX source statement' SIGL '=' sourceline(sigl) - say copies('=',75) -g=44 -call someFunc g -say 'rc=' rc -say 'result=' result - say copies('=',75) -h=66 -hh=someFunc(h) -say 'rc=' rc -say 'result=' result -say 'hh=' hh - say copies('=',75) -'DIR C:\ /ad | find /i /v "Volume " ' -say 'rc=' rc -say 'result=' result - say copies('=',75) -exit /*stick a fork in it, we're done.*/ -/*───────────────────────────────────someFunc subroutine.───────────────*/ -someFunc: procedure; parse arg x; return x/2 diff --git a/Task/Special-variables/Tcl/special-variables-1.tcl b/Task/Special-variables/Tcl/special-variables-1.tcl new file mode 100644 index 0000000000..39128cce71 --- /dev/null +++ b/Task/Special-variables/Tcl/special-variables-1.tcl @@ -0,0 +1 @@ +__DATE__, __DEBUG__, __FILE__, __LINE__, __NAME__, __TIME__ diff --git a/Task/Special-variables/Tcl/special-variables.tcl b/Task/Special-variables/Tcl/special-variables-2.tcl similarity index 100% rename from Task/Special-variables/Tcl/special-variables.tcl rename to Task/Special-variables/Tcl/special-variables-2.tcl diff --git a/Task/Speech-synthesis/Clojure/speech-synthesis.clj b/Task/Speech-synthesis/Clojure/speech-synthesis.clj new file mode 100644 index 0000000000..820dbbb81e --- /dev/null +++ b/Task/Speech-synthesis/Clojure/speech-synthesis.clj @@ -0,0 +1,2 @@ +(use 'speech-synthesis.say) +(say "This is an example of speech synthesis.") diff --git a/Task/Speech-synthesis/Perl-6/speech-synthesis.pl6 b/Task/Speech-synthesis/Perl-6/speech-synthesis.pl6 new file mode 100644 index 0000000000..e4e1b6a32d --- /dev/null +++ b/Task/Speech-synthesis/Perl-6/speech-synthesis.pl6 @@ -0,0 +1 @@ +run 'espeak', 'This is an example of speech synthesis.'; diff --git a/Task/Speech-synthesis/Scala/speech-synthesis.scala b/Task/Speech-synthesis/Scala/speech-synthesis.scala index 11ba1869dd..4981852651 100644 --- a/Task/Speech-synthesis/Scala/speech-synthesis.scala +++ b/Task/Speech-synthesis/Scala/speech-synthesis.scala @@ -1,31 +1,50 @@ -import java.util.Locale import javax.speech.Central -import javax.speech.synthesis.{ Synthesizer, SynthesizerModeDesc } +import javax.speech.synthesis.{Synthesizer, SynthesizerModeDesc} object ScalaSpeaker extends App { def speech(text: String) = { - if (!text.trim.isEmpty()) { + if (!text.trim.isEmpty) { + val VOICENAME = "kevin16" + + System.setProperty("freetts.voices", "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory") + Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral") + + val synth = Central.createSynthesizer(null) + synth.allocate() + + val desc = synth.getEngineModeDesc match {case g2: SynthesizerModeDesc => g2} + + synth.getSynthesizerProperties.setVoice(desc.getVoices.find(_.toString == VOICENAME).get) synth.speakPlainText(text, null) + synth.waitEngineState(Synthesizer.QUEUE_EMPTY) + synth.deallocate() } } - val voiceName = "kevin16" - - System.setProperty("freetts.voices", - "com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory") - - Central.registerEngineCentral("com.sun.speech.freetts.jsapi.FreeTTSEngineCentral") - val synth = Central.createSynthesizer(new SynthesizerModeDesc(Locale.ENGLISH)) - synth.allocate() - val desc = synth.getEngineModeDesc() match { - case g2: SynthesizerModeDesc => g2 - case _ => throw new ClassCastException - } - synth.getSynthesizerProperties() - .setVoice(desc.getVoices().find(_.toString() == voiceName).get) - - speech("If it ain't Dutch, It ain't much.") - synth.deallocate() + speech( """Thinking of Holland + |I see broad rivers + |slowly chuntering + |through endless lowlands, + |rows of implausibly + |airy poplars + |standing like tall plumes + |against the horizon; + |and sunk in the unbounded + |vastness of space + |homesteads and boweries + |dotted across the land, + |copses, villages, + |couchant towers, + |churches and elm-trees, + |bound in one great unity. + |There the sky hangs low, + |and steadily the sun + |is smothered in a greyly + |iridescent smirr, + |and in every province + |the voice of water + |with its lapping disasters + |is feared and hearkened.""".stripMargin) } diff --git a/Task/Spiral-matrix/00DESCRIPTION b/Task/Spiral-matrix/00DESCRIPTION index 9b6d76fc4c..cdddba99ac 100644 --- a/Task/Spiral-matrix/00DESCRIPTION +++ b/Task/Spiral-matrix/00DESCRIPTION @@ -1,4 +1,8 @@ -Produce a spiral array. A spiral array is a square arrangement of the first N2 natural numbers, where the numbers increase sequentially as you go around the edges of the array spiralling inwards. +Produce a spiral array.
    +A spiral array is a square arrangement of the +first N2 natural numbers, +where the numbers increase sequentially +as you go around the edges of the array spiralling inwards. For example, given 5, produce this array:
    @@ -8,3 +12,5 @@ For example, given 5, produce this array:
     13 22 21 20  7
     12 11 10  9  8
     
    + +;See also [[Zig-zag matrix]] diff --git a/Task/Spiral-matrix/360-Assembly/spiral-matrix.360 b/Task/Spiral-matrix/360-Assembly/spiral-matrix.360 new file mode 100644 index 0000000000..78949cdc0a --- /dev/null +++ b/Task/Spiral-matrix/360-Assembly/spiral-matrix.360 @@ -0,0 +1,120 @@ +SPIRALM CSECT + USING SPIRALM,R13 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'SPIRALM' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 +* ---- CODE + LA R0,0 + LA R1,1 + LH R12,N n + LR R4,R1 Row=1 + LR R5,R1 Col=1 + LR R6,R1 BotRow=1 + LR R7,R1 BotCol=1 + LR R8,R12 TopRow=n + LR R9,R12 TopCol=n + LR R10,R0 Dir=0 + LR R15,R12 n + MR R14,R12 R15=n*n + LA R11,1 k=1 +LOOP CR R11,R15 + BH ENDLOOP + LR R1,R4 + BCTR R1,0 + MH R1,N + AR R1,R5 + LR R2,R11 k + BCTR R2,0 + BCTR R1,0 + SLA R1,1 + STH R2,MATRIX(R1) Matrix(Row,Col)=k-1 + CH R10,=H'0' + BE DIR0 + CH R10,=H'1' + BE DIR1 + CH R10,=H'2' + BE DIR2 + CH R10,=H'3' + BE DIR3 + B DIRX +DIR0 CR R5,R9 if ColBotCol + BNH DIR2S + BCTR R5,0 Col=Col-1 + B DIRX +DIR2S LA R10,3 Dir=3 + BCTR R4,0 Row=Row-1 + BCTR R8,0 TopRow=TopRow-1 + B DIRX +DIR3 CR R4,R6 if Row>BotRow + BNH DIR3S + BCTR R4,0 Row=Row-1 + B DIRX +DIR3S LA R10,0 Dir=0 + LA R5,1(R5) Col=Col+1 + LA R7,1(R7) BotCol=BotCol+1 +DIRX EQU * + LA R11,1(R11) k=k+1 + B LOOP +ENDLOOP EQU * + LA R4,1 i +LOOPI CR R4,R12 + BH ENDLOOPI + XR R10,R10 + LA R5,1 j +LOOPJ CR R5,R12 + BH ENDLOOPJ + LR R1,R4 + BCTR R1,0 + MH R1,N + AR R1,R5 + BCTR R1,0 + SLA R1,1 + LH R2,MATRIX(R1) Matrix(i,j) + LA R3,BUF + AR R3,R10 + CVD R2,P8 + MVC 0(4,R3),=X'40202120' + ED 0(4,R3),P8+6 + LA R10,4(R10) + LA R5,1(R5) + B LOOPJ +ENDLOOPJ EQU * + WTO MF=(E,WTOMSG) + LA R4,1(R4) + B LOOPI +ENDLOOPI EQU * +* ---- END CODE + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 +* ---- DATA +N DC H'5' max=20 (20*4=80) + LTORG +P8 DS PL8 +WTOMSG DS 0F + DC H'80',XL2'0000' +BUF DC CL80' ' +MATRIX DS H Matrix(n,n) + YREGS + END SPIRALM diff --git a/Task/Spiral-matrix/C++/spiral-matrix.cpp b/Task/Spiral-matrix/C++/spiral-matrix-1.cpp similarity index 100% rename from Task/Spiral-matrix/C++/spiral-matrix.cpp rename to Task/Spiral-matrix/C++/spiral-matrix-1.cpp diff --git a/Task/Spiral-matrix/C++/spiral-matrix-2.cpp b/Task/Spiral-matrix/C++/spiral-matrix-2.cpp new file mode 100644 index 0000000000..a9db818c4d --- /dev/null +++ b/Task/Spiral-matrix/C++/spiral-matrix-2.cpp @@ -0,0 +1,17 @@ +#include +#include +using namespace std; +int main() { + const int n = 5; + const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0}; + int x = 0, y = -1, c = 0; + vector> m(n, vector(n)); + for (int i = 0, im = 0; i < n + n - 1; ++i, im = i % 4) + for (int j = 0, jlen = (n + n - i) / 2; j < jlen; ++j) + m[x += dx[im]][y += dy[im]] = ++c; + for (auto & r : m) { + for (auto & v : r) + cout << v << ' '; + cout << endl; + } +} diff --git a/Task/Spiral-matrix/C/spiral-matrix.c b/Task/Spiral-matrix/C/spiral-matrix-1.c similarity index 100% rename from Task/Spiral-matrix/C/spiral-matrix.c rename to Task/Spiral-matrix/C/spiral-matrix-1.c diff --git a/Task/Spiral-matrix/C/spiral-matrix-2.c b/Task/Spiral-matrix/C/spiral-matrix-2.c new file mode 100644 index 0000000000..17a04e9056 --- /dev/null +++ b/Task/Spiral-matrix/C/spiral-matrix-2.c @@ -0,0 +1,18 @@ +#include +#include + +int spiral(int w, int h, int x, int y) +{ + return y ? w + spiral(h - 1, w, y - 1, w - x - 1) : x; +} + +int main(int argc, char **argv) +{ + int w = atoi(argv[1]), h = atoi(argv[2]), i, j; + for (i = 0; i < h; i++) { + for (j = 0; j < w; j++) + printf("%4d", spiral(w, h, j, i)); + putchar('\n'); + } + return 0; +} diff --git a/Task/Spiral-matrix/Clojure/spiral-matrix.clj b/Task/Spiral-matrix/Clojure/spiral-matrix.clj index f4dc7fb303..23ed0ae869 100644 --- a/Task/Spiral-matrix/Clojure/spiral-matrix.clj +++ b/Task/Spiral-matrix/Clojure/spiral-matrix.clj @@ -1,8 +1,16 @@ (defn spiral [n] - (let [fmt (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%") - counts (cons n (mapcat #(repeat 2 %) (range (dec n) 0 -1))) - ones-and-ns (mapcat #(repeat %1 %2) counts (cycle [1 n -1 (- n)]))] - (->> (map vector (range 0 (* n n)) (reductions + ones-and-ns)) + (let [cyc (cycle [1 n -1 (- n)])] + (->> (range (dec n) 0 -1) + (mapcat #(repeat 2 %)) + (cons n) + #(mapcat repeat % cyc) + (reductions +) + (map vector (range 0 (* n n))) (sort-by second) - (map first) - (clojure.pprint/cl-format true fmt)))) + (map first))) + +(let [n 5] + (clojure.pprint/cl-format + true + (str " ~{~<~%~," (* n 3) ":;~2d ~>~}~%") + (spiral n))) diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix.hs b/Task/Spiral-matrix/Haskell/spiral-matrix-1.hs similarity index 79% rename from Task/Spiral-matrix/Haskell/spiral-matrix.hs rename to Task/Spiral-matrix/Haskell/spiral-matrix-1.hs index a2c752b8bb..004c35d0cd 100644 --- a/Task/Spiral-matrix/Haskell/spiral-matrix.hs +++ b/Task/Spiral-matrix/Haskell/spiral-matrix-1.hs @@ -1,12 +1,9 @@ -module Spiral where - import Data.List import Control.Monad -import Control.Monad.Instances - grade xs = map snd. sort $ zip xs [0..] values n = cycle [1,n,-1,-n] counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1] reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs)) - spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n) +displayRow = putStrLn . intercalate " " . map show +main = mapM displayRow $ spiral 5 diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix-2.hs b/Task/Spiral-matrix/Haskell/spiral-matrix-2.hs new file mode 100644 index 0000000000..5f3a052571 --- /dev/null +++ b/Task/Spiral-matrix/Haskell/spiral-matrix-2.hs @@ -0,0 +1,9 @@ +import Data.List +import Control.Applicative +counts = tail . reverse . concat . map (replicate 2) . enumFromTo 1 +values = cycle . ((++) <$> map id <*> map negate) . (1 :) . (: []) +grade = map snd . sort . flip zip [0..] +copies = grade . scanl1 (+) . concat . map (uncurry replicate) . (zip <$> counts <*> values) +parts = (<*>) take $ (.) <$> (map . take) <*> (iterate . drop) <*> copies +disp = (>> return ()) . mapM (putStrLn . intercalate " " . map show) . parts +main = disp 5 diff --git a/Task/Spiral-matrix/Haskell/spiral-matrix-3.hs b/Task/Spiral-matrix/Haskell/spiral-matrix-3.hs new file mode 100644 index 0000000000..5f5542bf28 --- /dev/null +++ b/Task/Spiral-matrix/Haskell/spiral-matrix-3.hs @@ -0,0 +1,10 @@ +import Data.List (transpose) +import Text.Printf (printf) + +-- spiral is the first row plus a smaller spiral rotated 90 deg +spiral 0 _ _ = [[]] +spiral h w s = [[s .. s+w-1]] ++ rot90 (spiral w (h-1) (s+w)) + where rot90 = (map reverse).transpose + +-- this is sort of hideous, someone may want to fix it +main = mapM_ (\row->mapM_ ((printf "%4d").toInteger) row >> putStrLn "") (spiral 10 9 1) diff --git a/Task/Spiral-matrix/J/spiral-matrix.j b/Task/Spiral-matrix/J/spiral-matrix.j index 1c13caeecf..a9990bc960 100644 --- a/Task/Spiral-matrix/J/spiral-matrix.j +++ b/Task/Spiral-matrix/J/spiral-matrix.j @@ -1,4 +1,4 @@ -spiral =. ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,) +spiral =: ,~ $ [: /: }.@(2 # >:@i.@-) +/\@# <:@+: $ (, -)@(1&,) spiral 5 0 1 2 3 4 diff --git a/Task/Spiral-matrix/Pascal/spiral-matrix.pascal b/Task/Spiral-matrix/Pascal/spiral-matrix.pascal new file mode 100644 index 0000000000..bdcc94faf0 --- /dev/null +++ b/Task/Spiral-matrix/Pascal/spiral-matrix.pascal @@ -0,0 +1,70 @@ +program Spiralmat; +type + tDir = (left,down,right,up); + tdxy = record + dx,dy: longint; + end; + tdeltaDir = array[tDir] of tdxy; +const + Nextdir : array[tDir] of tDir = (down,right,up,left); + cDir : tDeltaDir = ((dx:1;dy:0),(dx:0;dy:1),(dx:-1;dy:0),(dx:0;dy:-1)); + cMaxN = 32; +type + tSpiral = array[0..cMaxN,0..cMaxN] of LongInt; + +function FillSpiral(n:longint):tSpiral; +var + b,i,k, dn,x,y : longInt; + dir : tDir; + tmpSp : tSpiral; +BEGIN + b := 0; + x := 0; + y := 0; + //only for the first line + k := -1; + dn := n-1; + tmpSp[x,y] := b; + dir := left; + repeat + i := 0; + while i < dn do + begin + inc(b); + tmpSp[x,y] := b; + inc(x,cDir[dir].dx); + inc(y,cDir[dir].dy); + inc(i); + end; + Dir:= NextDir[dir]; + inc(k); + IF k > 1 then + begin + k := 0; + //shorten the line every second direction change + dn := dn-1; + if dn <= 0 then + BREAK; + end; + until false; + //the last + tmpSp[x,y] := b+1; + FillSpiral := tmpSp; +end; + +var + a : tSpiral; + x,y,n : LongInt; +BEGIN + For n := 1 to 5{cMaxN} do + begin + A:=FillSpiral(n); + For y := 0 to n-1 do + begin + For x := 0 to n-1 do + write(A[x,y]:4); + writeln; + end; + writeln; + end; +END. diff --git a/Task/Spiral-matrix/Python/spiral-matrix-3.py b/Task/Spiral-matrix/Python/spiral-matrix-3.py index 1446ba9429..79946d6466 100644 --- a/Task/Spiral-matrix/Python/spiral-matrix-3.py +++ b/Task/Spiral-matrix/Python/spiral-matrix-3.py @@ -1,16 +1,18 @@ -def spiral(n): - dat = [[None] * n for i in range(n)] - le = [[i + 1, i + 1] for i in reversed(range(n))] - le = sum(le, [])[1:] # for n = 5 le will be [5, 4, 4, 3, 3, 2, 2, 1, 1] - dxdy = [[1, 0], [0, 1], [-1, 0], [0, -1]] * ((len(le) + 4) / 4) # long enough - x, y, val = -1, 0, -1 - for steps, (dx, dy) in zip(le, dxdy): - x, y, val = x + dx, y + dy, val + 1 - for j in range(steps): - dat[y][x] = val - if j != steps-1: - x, y, val = x + dx, y + dy, val + 1 - return dat +def rot_right(a): + return zip(*a[::-1]) -for row in spiral(5): # calc spiral and print it - print ' '.join('%3s' % x for x in row) +def sp(m, n, start = 0): + """ Generate number range spiral of dimensions m x n + """ + if n == 0: + yield () + else: + yield tuple(range(start, m + start)) + for row in rot_right(list(sp(n - 1, m, m + start))): + yield row + +def spiral(m): + return sp(m, m) + +for row in spiral(5): + print(''.join('%3i' % i for i in row)) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-4.py b/Task/Spiral-matrix/Python/spiral-matrix-4.py index f1e525cb2a..1446ba9429 100644 --- a/Task/Spiral-matrix/Python/spiral-matrix-4.py +++ b/Task/Spiral-matrix/Python/spiral-matrix-4.py @@ -1,19 +1,16 @@ -import itertools +def spiral(n): + dat = [[None] * n for i in range(n)] + le = [[i + 1, i + 1] for i in reversed(range(n))] + le = sum(le, [])[1:] # for n = 5 le will be [5, 4, 4, 3, 3, 2, 2, 1, 1] + dxdy = [[1, 0], [0, 1], [-1, 0], [0, -1]] * ((len(le) + 4) / 4) # long enough + x, y, val = -1, 0, -1 + for steps, (dx, dy) in zip(le, dxdy): + x, y, val = x + dx, y + dy, val + 1 + for j in range(steps): + dat[y][x] = val + if j != steps-1: + x, y, val = x + dx, y + dy, val + 1 + return dat -concat = itertools.chain.from_iterable -def partial_sums(items): - s = 0 - for x in items: - s += x - yield s - -grade = lambda xs: sorted(range(len(xs)), key=xs.__getitem__) -values = lambda n: itertools.cycle([1,n,-1,-n]) -counts = lambda n: concat([i,i-1] for i in range(n,0,-1)) -reshape = lambda n, xs: zip(*([iter(xs)] * n)) - -spiral = lambda n: reshape(n, grade(list(partial_sums(concat( - [v]*c for c,v in zip(counts(n), values(n))))))) - -for row in spiral(5): - print(' '.join('%3s' % x for x in row)) +for row in spiral(5): # calc spiral and print it + print ' '.join('%3s' % x for x in row) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-5.py b/Task/Spiral-matrix/Python/spiral-matrix-5.py new file mode 100644 index 0000000000..f1e525cb2a --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-5.py @@ -0,0 +1,19 @@ +import itertools + +concat = itertools.chain.from_iterable +def partial_sums(items): + s = 0 + for x in items: + s += x + yield s + +grade = lambda xs: sorted(range(len(xs)), key=xs.__getitem__) +values = lambda n: itertools.cycle([1,n,-1,-n]) +counts = lambda n: concat([i,i-1] for i in range(n,0,-1)) +reshape = lambda n, xs: zip(*([iter(xs)] * n)) + +spiral = lambda n: reshape(n, grade(list(partial_sums(concat( + [v]*c for c,v in zip(counts(n), values(n))))))) + +for row in spiral(5): + print(' '.join('%3s' % x for x in row)) diff --git a/Task/Spiral-matrix/Python/spiral-matrix-6.py b/Task/Spiral-matrix/Python/spiral-matrix-6.py new file mode 100644 index 0000000000..808efedb51 --- /dev/null +++ b/Task/Spiral-matrix/Python/spiral-matrix-6.py @@ -0,0 +1,11 @@ +n = 5 +dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] +x, y, c = 0, -1, 1 +m = [[0 for i in range(n)] for j in range(n)] +for i in range(n + n - 1): + for j in range((n + n - i) // 2): + x += dx[i % 4] + y += dy[i % 4] + m[x][y] = c + c += 1 +print('\n'.join([' '.join([str(v) for v in r]) for r in m])) diff --git a/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx b/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx new file mode 100644 index 0000000000..5aaf573bef --- /dev/null +++ b/Task/Spiral-matrix/REXX/spiral-matrix-1.rexx @@ -0,0 +1,22 @@ +/*REXX program displays a spiral in a square array (of any size). */ +parse arg size . /*get the array size from the CL.*/ +if size=='' then size=5 /*No argument? Then use default.*/ +tot=size**2 /*total # of elements in spiral.*/ +k=size /*K is the counter for the spiral*/ +row=1; col=0; start=0 /*start at row 1, col 0, with 0.*/ +/*──────────────────────────────────────────────construct the spiral #s.*/ + do n=start for k; col=col+1; @.col.row=n; end; if k==0 then exit + /* [↑] build first row of spiral*/ + do until n>=tot /*spiral matrix.*/ + do one=1 to -1 by -2 until n>=tot; k=k-1 /*perform twice.*/ + do n=n for k; row=row+one; @.col.row=n; end /*for the row···*/ + do n=n for k; col=col-one; @.col.row=n; end /* " " col···*/ + end /*one*/ /* ↑↓ direction.*/ + end /*until n≥tot*/ /* [↑] done with matrix spiral.*/ +/*──────────────────────────────────────────────display spiral to screen*/ + do row=1 for size; _= /*construct display row by row.*/ + do col=1 for size /*construct a line col by col.*/ + _=_ right(@.col.row, length(tot)) /*construct a line for display. */ + end /*col*/ /* [↑] line has an extra blank.*/ + say substr(_,2) /*SUBSTR ignores the first blank.*/ + end /*row*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx b/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx new file mode 100644 index 0000000000..5e2382bf7a --- /dev/null +++ b/Task/Spiral-matrix/REXX/spiral-matrix-2.rexx @@ -0,0 +1,25 @@ +/*REXX program displays a spiral in a square array (of any size). */ +parse arg size . /*get the array size from the CL.*/ +if size=='' then size=5 /*No argument? Then use default.*/ +tot=size**2 /*total # of elements in spiral.*/ +k=size /*K is the counter for the spiral*/ +row=1; col=0; start=0 /*start at row 1, col 0, with 0.*/ +/*──────────────────────────────────────────────construct the spiral #s.*/ + do n=start for k; col=col+1; @.col.row=n; end; if k==0 then exit + /* [↑] build first row of spiral*/ + do until n>=tot /*spiral matrix.*/ + do one=1 to -1 by -2 until n>=tot; k=k-1 /*perform twice.*/ + do n=n for k; row=row+one; @.col.row=n; end /*for the row···*/ + do n=n for k; col=col-one; @.col.row=n; end /* " " col···*/ + end /*one*/ /* ↑↓ direction.*/ + end /*until n≥tot*/ /* [↑] done with matrix spiral.*/ +/*──────────────────────────────────────────────display spiral to screen*/ + do twice=0 for 2; if \twice then !.=0 /*1st time? Find max col width.*/ + do row=1 for size; _= /*construct display row by row. */ + do col=1 for size; x=@.col.row /*construct a line col by col. */ + if twice then _=_ right(x,!.col) /*construct a line for display.*/ + else !.col=max(!.col,length(x)) /*find width of column*/ + end /*col*/ /* [↓] line has an extra blank.*/ + if twice then say substr(_,2) /*SUBSTR ignores the 1st blank. */ + end /*row*/ /*stick a fork in it, we're done*/ + end /*twice*/ diff --git a/Task/Spiral-matrix/REXX/spiral-matrix.rexx b/Task/Spiral-matrix/REXX/spiral-matrix.rexx deleted file mode 100644 index 12b8e49759..0000000000 --- a/Task/Spiral-matrix/REXX/spiral-matrix.rexx +++ /dev/null @@ -1,27 +0,0 @@ -/*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; 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 - - 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 - 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 /*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 /*col*/ - /*stick a fork in it, we're done.*/ diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix.rb b/Task/Spiral-matrix/Ruby/spiral-matrix-1.rb similarity index 79% rename from Task/Spiral-matrix/Ruby/spiral-matrix.rb rename to Task/Spiral-matrix/Ruby/spiral-matrix-1.rb index 0feeced787..5673565624 100644 --- a/Task/Spiral-matrix/Ruby/spiral-matrix.rb +++ b/Task/Spiral-matrix/Ruby/spiral-matrix-1.rb @@ -11,8 +11,8 @@ def spiral(n) end def print_matrix(m) - max = m.flatten.map{|x| x.to_s.size}.max - m.each {|row| puts row.map {|x| "%#{max}s " % x}.join} + width = m.flatten.map{|x| x.to_s.size}.max + m.each {|row| puts row.map {|x| "%#{width}s " % x}.join} end print_matrix spiral(5) diff --git a/Task/Spiral-matrix/Ruby/spiral-matrix-2.rb b/Task/Spiral-matrix/Ruby/spiral-matrix-2.rb new file mode 100644 index 0000000000..7f8bddb839 --- /dev/null +++ b/Task/Spiral-matrix/Ruby/spiral-matrix-2.rb @@ -0,0 +1,13 @@ +n = 5 +m = Array.new(n){Array.new(n)} +pos, side = -1, n +for i in 0 .. (n-1)/2 + (0...side).each{|j| m[i][i+j] = (pos+=1) } + (1...side).each{|j| m[i+j][n-1-i] = (pos+=1) } + side -= 2 + side.downto(0) {|j| m[n-1-i][i+j] = (pos+=1) } + side.downto(1) {|j| m[i+j][i] = (pos+=1) } +end + +fmt = "%#{(n*n-1).to_s.size}d " * n +puts m.map{|row| fmt % row} diff --git a/Task/Spiral-matrix/Scilab/spiral-matrix.scilab b/Task/Spiral-matrix/Scilab/spiral-matrix.scilab new file mode 100644 index 0000000000..7f684df1bc --- /dev/null +++ b/Task/Spiral-matrix/Scilab/spiral-matrix.scilab @@ -0,0 +1,22 @@ +// Spiral Matrix +n=10 +mat=zeros(n,n); +botcol=1; topcol=n +botrow=1; toprow=n +ndir=0; col=1; row=1; +for i=0:n*n-1 + mat(row,col)=i; + if ndir==0 + if colbotcol then col=col-1; else ndir=3, row=row-1; toprow=toprow-1; end + elseif ndir==3 + if row>botrow then row=row-1; else ndir=0, col=col+1; botcol=botcol+1; end + end +end i +printf("n=%4d\n",n); +for i=1:n; + for j=1:n; printf("%4d",mat(i,j)); end j; printf("\n"); +end i; diff --git a/Task/Spiral-matrix/TI-83-BASIC/spiral-matrix.ti-83 b/Task/Spiral-matrix/TI-83-BASIC/spiral-matrix.ti-83 new file mode 100644 index 0000000000..841434e134 --- /dev/null +++ b/Task/Spiral-matrix/TI-83-BASIC/spiral-matrix.ti-83 @@ -0,0 +1,40 @@ +5->N +DelVar [F] +{N,N}→dim([F]) +1→A: N→B +1→C: N→D +0→E: E→G +1→I: 1→J +For(K,1,N*N) +K-1→[F](I,J) +If E=0: Then +If JC: Then +J-1→J +Else: 3→G +I-1→I: B-1→B +End +End +If E=3: Then +If I>A: Then +I-1→I +Else: 0→G +J+1→J: C+1→C +End +End +G→E +End +[F] diff --git a/Task/Spiral-matrix/Visual-Basic/spiral-matrix-4.vb b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-4.vb new file mode 100644 index 0000000000..21fcded522 --- /dev/null +++ b/Task/Spiral-matrix/Visual-Basic/spiral-matrix-4.vb @@ -0,0 +1,55 @@ +Module modSpiralArray + Sub Main() + print2dArray(getSpiralArray(5)) + End Sub + + Function getSpiralArray(dimension As Integer) As Object + Dim spiralArray(,) As Integer + Dim numConcentricSquares As Integer + + ReDim spiralArray(dimension - 1, dimension - 1) + numConcentricSquares = dimension \ 2 + If (dimension Mod 2) Then numConcentricSquares = numConcentricSquares + 1 + + Dim j As Integer, sideLen As Integer, currNum As Integer + sideLen = dimension + + Dim i As Integer + For i = 0 To numConcentricSquares - 1 + ' do top side + For j = 0 To sideLen - 1 + spiralArray(i, i + j) = currNum + currNum = currNum + 1 + Next + ' do right side + For j = 1 To sideLen - 1 + spiralArray(i + j, dimension - 1 - i) = currNum + currNum = currNum + 1 + Next + ' do bottom side + For j = sideLen - 2 To 0 Step -1 + spiralArray(dimension - 1 - i, i + j) = currNum + currNum = currNum + 1 + Next + ' do left side + For j = sideLen - 2 To 1 Step -1 + spiralArray(i + j, i) = currNum + currNum = currNum + 1 + Next + sideLen = sideLen - 2 + Next + getSpiralArray = spiralArray + End Function + + Sub print2dArray(arr) + Dim row As Integer, col As Integer, s As String + For row = 0 To UBound(arr, 1) + s = "" + For col = 0 To UBound(arr, 2) + s = s & " " & Right(" " & arr(row, col), 3) + Next + Debug.Print(s) + Next + End Sub + +End Module diff --git a/Task/Stable-marriage-problem/00DESCRIPTION b/Task/Stable-marriage-problem/00DESCRIPTION index 0ddfbc8498..4326c48945 100644 --- a/Task/Stable-marriage-problem/00DESCRIPTION +++ b/Task/Stable-marriage-problem/00DESCRIPTION @@ -43,3 +43,5 @@ And a complete list of ranked preferences, where the most liked is to the left: # [http://www.cs.columbia.edu/~evs/intro/stable/writeup.html The Stable Marriage Problem]. (Eloquent description and background information). # [http://sephlietz.com/gale-shapley/ Gale-Shapley Algorithm Demonstration]. # [http://mathsite.math.berkeley.edu/smp/smp.html Another Gale-Shapley Algorithm Demonstration]. +# [https://www.youtube.com/watch?v=Qcv1IqHWAzg Stable Marriage Problem - Numberphile] (Video). +# [https://www.youtube.com/watch?v=LtTV6rIxhdo Stable Marriage Problem (the math bit)] (Video). diff --git a/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-1.cfm b/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-1.cfm new file mode 100644 index 0000000000..5d7a705807 --- /dev/null +++ b/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-1.cfm @@ -0,0 +1,121 @@ +PERSON.CFC + +component displayName="Person" accessors="true" { + property name="Name" type="string"; + property name="MrOrMrsGoodEnough" type="Person"; + property name="UnrealisticExpectations" type="array"; + property name="PersonalHistory" type="array"; + + public Person function init( required String name ) { + setName( arguments.name ); + setPersonalHistory([ getName() & " is on the market." ]); + this.HotnessScale = 0; + return this; + } + + public Boolean function hasSettled() { + // if we have settled, return true; + return isInstanceOf( getMrOrMrsGoodEnough(), "Person" ); + } + + public Person function getBestOfWhatIsLeft() { + // increment the hotness scale...1 is best, 10 is...well...VERY settling. + this.HotnessScale++; + // get the match from the current rung in the barrel + var bestChoice = getUnrealisticExpectations()[ this.HotnessScale ]; + return bestChoice; + } + + public Boolean function wouldRatherBeWith( required Person person ) { + // only compare if we've already settled on a potential mate + if( isInstanceOf( this.getMrOrMrsGoodEnough(), "Person" ) ) { + // if the new person's hotness is greater (numerically smaller) than our current beau... + return getHotness( this, arguments.person ) < getHotness( this, this.getMrOrMrsGoodEnough() ); + } + return false; + } + + public Void function settle( required Person person ) { + if( person.hasSettled() ) { + // this is the match we want. Force a break up of a previous relationship (sorry!) + dumpLikeATonOfBricks( person ); + } + person.setMrOrMrsGoodEnough( this ); + if( hasSettled() ) { + // this is the match we want, so write a dear john to our current match + dumpLikeATonOfBricks( this ); + } + logHookup( arguments.person ); + // we've found the mate of our dreams! + setMrOrMrsGoodEnough( arguments.person ); + } + + public Void function swing( required Person person ) { + // get our spouses + var mySpouse = getMrOrMrsGoodEnough(); + var notMySpouse = arguments.person.getMrOrMrsGoodEnough(); + // swap em' + setMrOrMrsGoodEnough( notMySpouse ); + person.setMrOrMrsGoodEnough( mySpouse ); + } + + public Void function dumpLikeATonOfBricks( required Person person ) { + logBreakup( arguments.person ); + person.getMrOrMrsGoodEnough().setMrOrMrsGoodEnough( JavaCast( "null", "" ) ); + } + + public String function psychoAnalyze() { + logNuptuals(); + logRegrets(); + var personalJourney = ""; + for( var entry in getPersonalHistory() ) { + personalJourney = personalJourney & entry & "
    "; + } + return personalJourney; + } + + private Numeric function getHotness( required Person pursuer, required Person pursued ) { + var pursuersExpectations = pursuer.getUnrealisticExpectations(); + var hotnessFactor = 1; + for( var hotnessFactor=1; hotnessFactor<=arrayLen( pursuersExpectations ); hotnessFactor++ ) { + if( pursuersExpectations[ hotnessFactor ].getName()==arguments.pursued.getName() ) { + return hotnessFactor; + } + } + } + + private Void function logRegrets() { + var spouse = getMrOrMrsGoodEnough(); + var spouseHotness = getHotness( this, spouse ); + var myHotness = getHotness( spouse, this ); + if( spouseHotness == 1 && myHotness == 1 ) { + arrayAppend( getPersonalHistory(), "Yes, yes, the beautiful people always find happy endings: #getName()# (her ###myHotness#), #spouse.getName()# (his ###spouseHotness#)"); + } + else if( spouseHotness == myHotness ) { + arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) was made for #spouse.getName()# (his ###spouseHotness#). How precious."); + } + else if( spouseHotness > myHotness ) { + arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) could have done better than #spouse.getName()# (his ###spouseHotness#). Poor slob."); + } + else { + arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) is a lucky bastard to have landed #spouse.getName()# (his ###spouseHotness#)."); + } + } + + private Void function logNuptuals() { + arrayAppend( getPersonalHistory(), "#getName()# has settled for #getMrOrMrsGoodEnough().getName()#." ); + } + + private Void function logHookup( required Person person ) { + var winnerHotness = getHotness( this, arguments.person ); + var myHotness = getHotness( arguments.person, this ); + arrayAppend( getPersonalHistory(), "#getName()# (her ###myHotness#) is checking out #arguments.person.getName()# (his ###winnerHotness#), but wants to keep his options open."); + } + + private Void function logBreakup( required Person person ) { + var scrub = person.getMrOrMrsGoodEnough(); + var scrubHotness = getHotness( person, scrub ); + var myHotness = getHotness( person, this ); + arrayAppend( getPersonalHistory(), "#getName()# is so hot (her ###myHotness#) that #person.getName()# is dumping #scrub.getName()# (her ###scrubHotness#)"); + } +} diff --git a/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-2.cfm b/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-2.cfm new file mode 100644 index 0000000000..83ebb152b3 --- /dev/null +++ b/Task/Stable-marriage-problem/ColdFusion/stable-marriage-problem-2.cfm @@ -0,0 +1,113 @@ +INDEX.CFM + + + /** + * Let's get these crazy kids married! + * @men.hint The men who want to get married + */ + function doCreepyMassMarriages( required Array men ) { + marriagesAreStable = false; + while( !marriagesAreStable ) { + marriagesAreStable = true; + for( man in men ) { + if( !man.hasSettled() ) { + marriagesAreStable = false; + sexyLady = man.getBestOfWhatIsLeft(); + if( !sexyLady.hasSettled() || sexyLady.wouldRatherBeWith( man ) ) { + man.settle( sexyLady ); + } + } + } + } + return men; + } + + /** + * We played God...now let's see if society is going to survive + * @men.hint The married men + * @women.hint The married women + */ + function isSocietyStable( required Array men, required Array women ) { + // loop over married men + for( var man in arguments.men ) { + // loop over married women + for( var woman in arguments.women ) { + // if the man does not prefer this woman to his current spouse, and the women + // doesn't prefer the man to her current spouse, this is the best possible match + if( man.wouldRatherBeWith( woman ) && woman.wouldRatherBeWith( man ) ) { + return false; + } + } + } + return true; + } + + // the men + abe = new Person( "Abe" ); + bob = new Person( "Bob" ); + col = new Person( "Col" ); + dan = new Person( "Dan" ); + ed = new Person( "Ed" ); + fred = new Person( "Fred" ); + gav = new Person( "Gav" ); + hal = new Person( "Hal" ); + ian = new Person( "Ian" ); + jon = new Person( "Jon" ); + + men = [ abe, bob, col, dan, ed, fred, gav, hal, ian, jon ]; + + // the women + abi = new Person( "Abi" ); + bea = new Person( "Bea" ); + cath = new Person( "Cath" ); + dee = new Person( "Dee" ); + eve = new Person( "Eve" ); + fay = new Person( "Fay" ); + gay = new Person( "Gay" ); + hope = new Person( "Hope" ); + ivy = new Person( "Ivy" ); + jan = new Person( "Jan" ); + + women = [ abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan ]; + + // set unrealistic expectations for the men + abe.setUnrealisticExpectations([ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ]); + bob.setUnrealisticExpectations([ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ]); + col.setUnrealisticExpectations([ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ]); + dan.setUnrealisticExpectations([ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ]); + ed.setUnrealisticExpectations([ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ]); + fred.setUnrealisticExpectations([ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ]); + gav.setUnrealisticExpectations([ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ]); + hal.setUnrealisticExpectations([ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ]); + ian.setUnrealisticExpectations([ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ]); + jon.setUnrealisticExpectations([ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ]); + // set unrealistic expectations for the women + abi.setUnrealisticExpectations([ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ]); + bea.setUnrealisticExpectations([ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ]); + cath.setUnrealisticExpectations([ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ]); + dee.setUnrealisticExpectations([ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ]); + eve.setUnrealisticExpectations([ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ]); + fay.setUnrealisticExpectations([ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ]); + gay.setUnrealisticExpectations([ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ]); + hope.setUnrealisticExpectations([ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ]); + ivy.setUnrealisticExpectations([ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ]); + jan.setUnrealisticExpectations([ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ]); + + // here comes the bride, duhn, duhn, duh-duhn + possiblyHappilyMarriedMen = doCreepyMassMarriages( men ); + // let's see who shacked up! + for( man in possiblyHappilyMarriedMen ) { + writeoutput( man.psychoAnalyze() & "
    " ); + } + // check if society is stable + if( isSocietyStable( men, women ) ) { + writeoutput( "Hey, look at that. Creepy social engineering works. Sort of...

    " ); + } + // what happens if couples start swingin'? + jon.swing( fred ); + writeoutput( "Swapping Jon and Fred's wives...will society survive?

    " ); + // check if society is still stable after the swingers + if( !isSocietyStable( men, women ) ) { + writeoutput( "Nope, now everything is broken. Sharing spouses doesn't work, kids.
    " ); + } +
    diff --git a/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d b/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d index 4f6cd57c49..fe200aaef0 100644 --- a/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d +++ b/Task/Stable-marriage-problem/D/stable-marriage-problem-1.d @@ -2,7 +2,7 @@ import std.stdio, std.array, std.algorithm, std.string; string[string] matchmaker(string[][string] guyPrefers, - string[][string] girlPrefers) { + string[][string] girlPrefers) /*@safe*/ { string[string] engagedTo; string[] freeGuys = guyPrefers.keys; @@ -36,7 +36,7 @@ string[string] matchmaker(string[][string] guyPrefers, bool check(bool doPrint=false)(string[string] engagedTo, string[][string] guyPrefers, - string[][string] galPrefers) { + string[][string] galPrefers) @safe { enum MSG = "%s likes %s better than %s and %s " ~ "likes %s better than their current partner"; string[string] inverseEngaged; @@ -77,7 +77,7 @@ bool check(bool doPrint=false)(string[string] engagedTo, } -void main() { +void main() /*@safe*/ { auto guyData = "abe abi eve cath ivy jan dee fay bea hope gay bob cath hope abi dee eve fay bea jan ivy gay col hope eve abi dee bea fay ivy gay cath jan @@ -111,7 +111,7 @@ void main() { writeln("\nCouples:"); string[] parts; - foreach (k; engagedTo.keys.sort) + foreach (k; engagedTo.keys.sort()) writefln("%s is engagedTo to %s", k, engagedTo[k]); writeln(); @@ -119,7 +119,7 @@ void main() { writeln("Marriages are ", c ? "stable" : "unstable"); writeln("\n\nSwapping two fiances to introduce an error"); - auto gals = galPrefers.keys.sort; + auto gals = galPrefers.keys.sort(); swap(engagedTo[gals[0]], engagedTo[gals[1]]); foreach (gal; gals[0 .. 2]) writefln(" %s is now engagedTo to %s", gal, engagedTo[gal]); diff --git a/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d index cc957e4bba..d95d941176 100644 --- a/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d +++ b/Task/Stable-marriage-problem/D/stable-marriage-problem-2.d @@ -10,7 +10,7 @@ alias Couples = M[F]; immutable PrefMapF womenPref; immutable PrefMapM menPref; -pure nothrow static this() { +static this() pure nothrow @safe { with (F) with (M) { womenPref = [ abi: [bob, fred, jon, gav, ian, abe, dan, ed, col, hal], @@ -42,13 +42,15 @@ pure nothrow static this() { /// Does 'first' appear before 'second' in preference list? bool prefers(T)(in T[] preference, in T first, in T second) -pure nothrow if (is(T == F) || is(T == M)) { - const found = preference.findAmong([first, second]); +pure nothrow @safe @nogc if (is(T == F) || is(T == M)) { + //const found = preference.findAmong([first, second]); + immutable T[2] two = [first, second]; + const found = preference.findAmong(two[]); return !(found.empty || found.front == second); } void checkStability(in Couples engaged, in PrefMapM menPref, - in PrefMapF womenPref) { + in PrefMapF womenPref) @safe { "Stablility:".writeln; bool stable = true; foreach (immutable bride, immutable groom; engaged) { @@ -74,7 +76,7 @@ void checkStability(in Couples engaged, in PrefMapM menPref, "\t(all marriages stable)".writeln; } -void main() { +void main() /*@safe*/ { auto bachelors = menPref.keys.sort().release;// No queue in Phobos. Couples engaged; diff --git a/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m b/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m index 5183b06232..f18078e797 100644 --- a/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m +++ b/Task/Stable-marriage-problem/Objective-C/stable-marriage-problem.m @@ -10,10 +10,10 @@ @end @implementation Person -+ (Person *)named:(NSString *)name { - return [[Person alloc] initWithName:name]; ++ (instancetype)named:(NSString *)name { + return [[self alloc] initWithName:name]; } -- (id)initWithName:(NSString *)name { +- (instancetype)initWithName:(NSString *)name { if ((self = [super init])) { _name = name; _prefs = nil; @@ -98,7 +98,7 @@ void doMarriage() { ivy.prefs = @[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ]; jan.prefs = @[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ]; - NSArray *men = [NSArray arrayWithArray:abi.prefs]; + NSArray *men = abi.prefs; NSUInteger freeMenCount = men.count; while (freeMenCount > 0) { diff --git a/Task/Stable-marriage-problem/Perl-6/stable-marriage-problem.pl6 b/Task/Stable-marriage-problem/Perl-6/stable-marriage-problem.pl6 new file mode 100644 index 0000000000..ec095679ce --- /dev/null +++ b/Task/Stable-marriage-problem/Perl-6/stable-marriage-problem.pl6 @@ -0,0 +1,91 @@ +my %he-likes = + abe => < abi eve cath ivy jan dee fay bea hope gay >, + bob => < cath hope abi dee eve fay bea jan ivy gay >, + col => < hope eve abi dee bea fay ivy gay cath jan >, + dan => < ivy fay dee gay hope eve jan bea cath abi >, + ed => < jan dee bea cath fay eve abi ivy hope gay >, + fred => < bea abi dee gay eve ivy cath jan hope fay >, + gav => < gay eve ivy bea cath abi dee hope jan fay >, + hal => < abi eve hope fay ivy cath jan bea gay dee >, + ian => < hope cath dee gay bea abi fay ivy jan eve >, + jon => < abi fay jan gay eve bea dee cath ivy hope >, +; + +my %she-likes = + abi => < bob fred jon gav ian abe dan ed col hal >, + bea => < bob abe col fred gav dan ian ed jon hal >, + cath => < fred bob ed gav hal col ian abe dan jon >, + dee => < fred jon col abe ian hal gav dan bob ed >, + eve => < jon hal fred dan abe gav col ed ian bob >, + fay => < bob abe ed ian jon dan fred gav col hal >, + gay => < jon gav hal fred bob abe col ed dan ian >, + hope => < gav jon bob abe ian dan hal ed col fred >, + ivy => < ian col hal gav fred bob abe ed jon dan >, + jan => < ed hal gav abe bob jon col ian fred dan >, +; + +my \guys = %he-likes.keys; +my \gals = %she-likes.keys; + +my %fiancé; +my %fiancée; +my %proposed; + +sub she-prefers ($her, $hottie) { .index($hottie) < .index(%fiancé{$her}) given ~%she-likes{$her} } +sub he-prefers ($him, $hottie) { .index($hottie) < .index(%fiancée{$him}) given ~%he-likes{$him} } + +match'em; +check-stability; + +perturb'em; +check-stability; + +sub match'em { #' + say 'Matchmaking:'; + while unmatched-guy() -> $guy { + my $gal = preferred-choice($guy); + %proposed{"$guy $gal"} = '❤'; + if not %fiancé{$gal} { + engage($guy, $gal); + say "\t$gal and $guy"; + } + elsif she-prefers($gal, $guy) { + my $engaged-guy = %fiancé{$gal}; + engage($guy, $gal); + %fiancée{$engaged-guy} = ''; + say "\t$gal dumped $engaged-guy for $guy"; + } + } +} + +sub check-stability { + my @instabilities = gather for guys X gals -> $m, $w { + if he-prefers($m, $w) and she-prefers($w, $m) { + take "\t$w prefers $m to %fiancé{$w} and $m prefers $w to %fiancée{$m}"; + } + } + + say 'Stablility:'; + if @instabilities { + .say for @instabilities; + } + else { + say "\t(all marriages stable)"; + } +} + +sub unmatched-guy { guys.first: { not %fiancée{$_} } } + +sub preferred-choice($guy) { %he-likes{$guy}.first: { not %proposed{"$guy $_" } } } + +sub engage($guy, $gal) { + %fiancé{$gal} = $guy; + %fiancée{$guy} = $gal; +} + +sub perturb'em { #' + say 'Perturb:'; + say "\tengage abi with fred and bea with jon"; + engage('fred', 'abi'); + engage('jon', 'bea'); +} diff --git a/Task/Stack-traces/Clojure/stack-traces.clj b/Task/Stack-traces/Clojure/stack-traces.clj new file mode 100644 index 0000000000..4ccc224c80 --- /dev/null +++ b/Task/Stack-traces/Clojure/stack-traces.clj @@ -0,0 +1,2 @@ +(doall + (map println (.dumpAllThreads (java.lang.management.ManagementFactory/getThreadMXBean) false false))) diff --git a/Task/Stack-traces/Go/stack-traces.go b/Task/Stack-traces/Go/stack-traces.go index e7400efc7c..eb3fa7e2b6 100644 --- a/Task/Stack-traces/Go/stack-traces.go +++ b/Task/Stack-traces/Go/stack-traces.go @@ -2,13 +2,13 @@ package main import ( "fmt" - "runtime/debug" + "runtime" ) func main() { - // to print it to standard error - debug.PrintStack() - // alternately to get it in a variable: - stackTrace := debug.Stack() + stackTrace := make([]byte, 1024) + n := runtime.Stack(stackTrace, true) + stackTrace = stackTrace[:n] + fmt.Printf("%s\n", stackTrace) fmt.Printf("(%d bytes)\n", len(stackTrace)) } diff --git a/Task/Stack-traces/Ruby/stack-traces-3.rb b/Task/Stack-traces/Ruby/stack-traces-3.rb new file mode 100644 index 0000000000..575bc0e149 --- /dev/null +++ b/Task/Stack-traces/Ruby/stack-traces-3.rb @@ -0,0 +1 @@ +p Thread.current.backtrace diff --git a/Task/Stack/00DESCRIPTION b/Task/Stack/00DESCRIPTION index 14838d1cc9..3b32ab4375 100644 --- a/Task/Stack/00DESCRIPTION +++ b/Task/Stack/00DESCRIPTION @@ -1,5 +1,7 @@ {{data structure}}[[Category:Classic CS problems and programs]] -A '''stack''' is a container of elements with last in, first out access policy. Sometimes it also called '''LIFO'''. The stack is accessed through its '''top'''. The basic stack operations are: +A '''stack''' is a container of elements with last in, first out access policy. +Sometimes it also called '''LIFO'''. The stack is accessed through its '''top'''. +The basic stack operations are: * ''push'' stores a new element onto the stack top; * ''pop'' returns the last pushed stack element, while removing it from the stack; @@ -9,7 +11,12 @@ Sometimes the last pushed stack element is made accessible for immutable access * ''top'' (sometimes called ''peek'' to keep with the ''p'' theme) returns the topmost element without modifying the stack. -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. +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. diff --git a/Task/Stack/Babel/stack.pb b/Task/Stack/Babel/stack.pb index a4063c1adb..7406aa9eb8 100644 --- a/Task/Stack/Babel/stack.pb +++ b/Task/Stack/Babel/stack.pb @@ -15,7 +15,3 @@ check_foo! : {foo empty?) {nil} {"not " .} ifte "empty" . cr << } - -Output: -foo is not empty -foo is empty diff --git a/Task/Stack/JavaScript/stack-2.js b/Task/Stack/JavaScript/stack-2.js index 02c2e04d0b..c20bc05dd7 100644 --- a/Task/Stack/JavaScript/stack-2.js +++ b/Task/Stack/JavaScript/stack-2.js @@ -4,5 +4,5 @@ function Stack() { this.push = function(element) {this.data.push(element)} this.pop = function() {return this.data.pop()} this.empty = function() {return this.data.length == 0} - this.peek = function() {return this.data[0]} + this.peek = function() {return this.data[this.data.length - 1]} } diff --git a/Task/Stack/JavaScript/stack-3.js b/Task/Stack/JavaScript/stack-3.js new file mode 100644 index 0000000000..c106bda26f --- /dev/null +++ b/Task/Stack/JavaScript/stack-3.js @@ -0,0 +1,24 @@ +function makeStack() { + var stack = []; + + var popStack = function () { + return stack.pop(); + }; + var pushStack = function () { + return stack.push.apply(stack, arguments); + }; + var isEmpty = function () { + return stack.length === 0; + }; + var peekStack = function () { + return stack[stack.length-1]; + }; + + return { + pop: popStack, + push: pushStack, + isEmpty: isEmpty, + peek: peekStack, + top: peekStack + }; +} diff --git a/Task/Stack/Smalltalk/stack.st b/Task/Stack/Smalltalk/stack.st new file mode 100644 index 0000000000..aebe646b41 --- /dev/null +++ b/Task/Stack/Smalltalk/stack.st @@ -0,0 +1,6 @@ +s := Stack new. +s push: 1. +s push: 2. +s push: 3. +s pop. +s top. "2" diff --git a/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx index f3e3055369..5f61341680 100644 --- a/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx +++ b/Task/Stair-climbing-puzzle/REXX/stair-climbing-puzzle.rexx @@ -3,4 +3,4 @@ step_up: do while \step() end return -step_up: return random(0,1) /*randomly step up or fail to step up.*/ +step: return random(0,1) /*randomly step up or fail to step up.*/ diff --git a/Task/Stair-climbing-puzzle/SAS/stair-climbing-puzzle.sas b/Task/Stair-climbing-puzzle/SAS/stair-climbing-puzzle.sas new file mode 100644 index 0000000000..6f94fdfa23 --- /dev/null +++ b/Task/Stair-climbing-puzzle/SAS/stair-climbing-puzzle.sas @@ -0,0 +1,16 @@ +%macro step(); + %sysfunc(round(%sysfunc(ranuni(0)))) + %mend step; + +%macro step_up(); + + %if not %step %then %do; + %put Step Down; + %step_up; + %step_up; + %end; + %else %put Step Up; + + %mend step_up; + +%step_up; diff --git a/Task/Standard-deviation/00DESCRIPTION b/Task/Standard-deviation/00DESCRIPTION index 2ca0f3aca6..066841e733 100644 --- a/Task/Standard-deviation/00DESCRIPTION +++ b/Task/Standard-deviation/00DESCRIPTION @@ -1,5 +1,8 @@ -Write a stateful function, class, generator or coroutine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series. The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population. +Write a stateful function, class, generator or coroutine that takes a series of floating point numbers, ''one at a time'', and returns the running [[wp:Standard Deviation|standard deviation]] of the series. +The task implementation should use the most natural programming style of those listed for the function in the implementation language; the task ''must'' state which is being used. Do not apply [[wp:Bessel's correction|Bessel's correction]]; the returned standard deviation should always be computed as if the sample seen so far is the entire population. Use this to compute the standard deviation of this demonstration set, \{2, 4, 4, 4, 5, 5, 7, 9\}, which is 2. -See also: [[Moving Average]] +'''See also:''' +* [[Moving Average]] +* [[Random numbers]] diff --git a/Task/Standard-deviation/360-Assembly/standard-deviation.360 b/Task/Standard-deviation/360-Assembly/standard-deviation.360 new file mode 100644 index 0000000000..88237e5df7 --- /dev/null +++ b/Task/Standard-deviation/360-Assembly/standard-deviation.360 @@ -0,0 +1,102 @@ +******** Standard deviation of a population +STDDEV CSECT + USING STDDEV,R13 +SAVEAREA B STM-SAVEAREA(R15) + DC 17F'0' + DC CL8'STDDEV' +STM STM R14,R12,12(R13) + ST R13,4(R15) + ST R15,8(R13) + LR R13,R15 + SR R8,R8 s=0 + SR R9,R9 ss=0 + SR R4,R4 i=0 + LA R6,1 + LH R7,N +LOOPI BXH R4,R6,ENDLOOPI + LR R1,R4 i + BCTR R1,0 + SLA R1,1 + LH R5,T(R1) + ST R5,WW ww=t(i) + MH R5,=H'1000' w=ww*1000 + AR R8,R5 s=s+w + LR R15,R5 + MR R14,R5 w*w + AR R9,R15 ss=ss+w*w + LR R14,R8 s + SRDA R14,32 + DR R14,R4 /i + ST R15,AVG avg=s/i + LR R14,R9 ss + SRDA R14,32 + DR R14,R4 ss/i + LR R2,R15 ss/i + LR R15,R8 s + MR R14,R8 s*s + LR R3,R15 + LR R15,R4 i + MR R14,R4 i*i + LR R1,R15 + LA R14,0 + LR R15,R3 + DR R14,R1 (s*s)/(i*i) + SR R2,R15 + LR R10,R2 std=ss/i-(s*s)/(i*i) + LR R11,R10 std + SRA R11,1 x=std/2 + LR R12,R10 px=std +LOOPWHIL EQU * + CR R12,R11 while px<>=x + BE ENDWHILE + LR R12,R11 px=x + LR R15,R10 std + LA R14,0 + DR R14,R12 /px + LR R1,R12 px + AR R1,R15 px+std/px + SRA R1,1 /2 + LR R11,R1 x=(px+std/px)/2 + B LOOPWHIL +ENDWHILE EQU * + LR R10,R11 + CVD R4,P8 i + MVC C17,MASK17 + ED C17,P8 + MVC BUF+2(1),C17+15 + L R1,WW + CVD R1,P8 + MVC C17,MASK17 + ED C17,P8 + MVC BUF+10(1),C17+15 + L R1,AVG + CVD R1,P8 + MVC C18,MASK18 + ED C18,P8 + MVC BUF+17(5),C18+12 + CVD R10,P8 std + MVC C18,MASK18 + ED C18,P8 + MVC BUF+31(5),C18+12 + WTO MF=(E,WTOMSG) + B LOOPI +ENDLOOPI EQU * + L R13,4(0,R13) + LM R14,R12,12(R13) + XR R15,R15 + BR R14 + DS 0D +N DC H'8' +T DC H'2',H'4',H'4',H'4',H'5',H'5',H'7',H'9' +WW DS F +AVG DS F +P8 DS PL8 +MASK17 DC C' ',13X'20',X'2120',C'-' +MASK18 DC C' ',10X'20',X'2120',C'.',3X'20',C'-' +C17 DS CL17 +C18 DS CL18 +WTOMSG DS 0F + DC H'80',XL2'0000' +BUF DC CL80'N=1 ITEM=1 AVG=1.234 STDDEV=1.234 ' + YREGS + END STDDEV diff --git a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp index 79385886c9..21246166ae 100644 --- a/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp +++ b/Task/Standard-deviation/Common-Lisp/standard-deviation-1.lisp @@ -1,7 +1,7 @@ (defun std-dev (samples) (let* ((n (length samples)) (mean (/ (reduce #'+ samples) n)) - (tmp (mapcar (lambda (x) (sqr (- x mean))) samples))) + (tmp (mapcar (lambda (x) (expt (- x mean) 2)) samples))) (sqrt (/ (reduce #'+ tmp) n)))) (format t "~a" (std-dev '(2 4 4 4 5 5 7 9))) diff --git a/Task/Standard-deviation/Java/standard-deviation.java b/Task/Standard-deviation/Java/standard-deviation.java index dc26e4a768..8b49b32d1e 100644 --- a/Task/Standard-deviation/Java/standard-deviation.java +++ b/Task/Standard-deviation/Java/standard-deviation.java @@ -1,39 +1,22 @@ -import java.util.LinkedList; public class StdDev { - LinkedList nums; - public StdDev() { - nums = new LinkedList(); + int n = 0; + double sum = 0; + double sum2 = 0; + + public double sd(double x) { + n++; + sum += x; + sum2 += x*x; + + return Math.sqrt(sum2/n - sum*sum/n/n); } + public static void main(String[] args) { double[] testData = {2,4,4,4,5,5,7,9}; StdDev sd = new StdDev(); for (double x : testData) { - sd.newNum(x); - System.out.println(sd.getSD()); + System.out.println(sd.sd(x)); } } - - public void newNum(double num) { - nums.add(num); - } - - public double getAvg() { - if (nums.isEmpty()) return 0; - double ret = 0; - double sum = 0; - for (double num : nums) { - sum += num; - } - return sum / nums.size(); - } - - public double getSD() { - double sqDiffs = 0; - double avg = getAvg(); - for (double num : nums) { - sqDiffs += (num - avg) * (num - avg); - } - return Math.sqrt(sqDiffs / nums.size()); - } } diff --git a/Task/Standard-deviation/Lua/standard-deviation.lua b/Task/Standard-deviation/Lua/standard-deviation.lua new file mode 100644 index 0000000000..088bc0f89a --- /dev/null +++ b/Task/Standard-deviation/Lua/standard-deviation.lua @@ -0,0 +1,12 @@ +function stdev() + local sum, sumsq, k = 0,0,0 + return function(n) + sum, sumsq, k = sum + n, sumsq + n^2, k+1 + return math.sqrt((sumsq / k) - (sum/k)^2) + end +end + +ldev = stdev() +for i, v in ipairs{2,4,4,4,5,5,7,9} do + print(ldev(v)) +end diff --git a/Task/Standard-deviation/PL-I/standard-deviation.pli b/Task/Standard-deviation/PL-I/standard-deviation.pli index 9fe3ce0216..072d6fc244 100644 --- a/Task/Standard-deviation/PL-I/standard-deviation.pli +++ b/Task/Standard-deviation/PL-I/standard-deviation.pli @@ -1,23 +1,25 @@ -declare A(200) float; -declare ap fixed binary; -declare i fixed binary; - -ap = 0; -do i = 1 to 10; - ap = ap + 1; - get list ( A(ap) ); - put skip list ( std_dev (a, ap) ); -end; - -std_dev: procedure (A, ap) returns (float); - declare A(*) float, ap fixed binary nonassignable; +*process source attributes xref; + stddev: proc options(main); + declare a(10) float init(1,2,3,4,5,6,7,8,9,10); + declare stdev float; declare i fixed binary; - declare B(ap) float, average float; - do i = 1 to ap; - B(i) = A(i); - end; - average = sum(A) /ap; + stdev=std_dev(a); + put skip list('Standard deviation', stdev); - return ( sqrt (sum(B**2)/ap - average**2) ); -end std_dev; + std_dev: procedure(a) returns(float); + declare a(*) float, n fixed binary; + n=hbound(a,1); + begin; + declare b(n) float, average float; + declare i fixed binary; + do i=1 to n; + b(i)=a(i); + end; + average=sum(a)/n; + put skip data(average); + return( sqrt(sum(b**2)/n - average**2) ); + end; + end std_dev; + + end; diff --git a/Task/Standard-deviation/Pascal/standard-deviation.pascal b/Task/Standard-deviation/Pascal/standard-deviation.pascal new file mode 100644 index 0000000000..c41d3f5ea6 --- /dev/null +++ b/Task/Standard-deviation/Pascal/standard-deviation.pascal @@ -0,0 +1,28 @@ +program stddev; +uses math; +const + n=8; +var + arr: array[1..n] of real =(2,4,4,4,5,5,7,9); +function stddev(n: integer): real; +var + i: integer; + s1,s2,variance,x: real; +begin + for i:=1 to n do + begin + x:=arr[i]; + s1:=s1+power(x,2); + s2:=s2+x + end; + variance:=((n*s1)-(power(s2,2)))/(power(n,2)); + stddev:=sqrt(variance) +end; +var + i: integer; +begin + for i:=1 to n do + begin + writeln(i,' item=',arr[i]:2:0,' stddev=',stddev(i):18:15) + end +end. diff --git a/Task/Standard-deviation/REXX/standard-deviation.rexx b/Task/Standard-deviation/REXX/standard-deviation.rexx index 69da3a4d3a..991bca3c46 100644 --- a/Task/Standard-deviation/REXX/standard-deviation.rexx +++ b/Task/Standard-deviation/REXX/standard-deviation.rexx @@ -1,17 +1,17 @@ -/*REXX program to find the standard deviation of a given set of numbers.*/ -parse arg # /*let the user specify numbers. */ +/*REXX pgm finds & displays the standard deviation of a given set of #s.*/ +parse arg # /*any optional args on the C.L. ?*/ if #='' then #=2 4 4 4 5 5 7 9 /*None given? Then use default.*/ -w=words(#); s=0; ss=0 /*define: #items, a couple sums. */ +w=words(#); s=0; ss=0 /*define: #items; a couple sums.*/ - do j=1 for w; _=word(#,j); s=s+_; ss=ss+_*_ + do j=1 for w; _=word(#,j); s=s+_; ss=ss+_*_ say ' item' right(j,length(w))":" right(_,4), - ' average=' left(s/j,12), + ' average=' left(s/j,12), ' standard deviation=' left(sqrt( ss/j - (s/j)**2 ),15) end /*j*/ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────SQRT subroutine─────────────────────*/ -sqrt: procedure;parse arg x; if x=0 then return 0; d=digits(); numeric digits 11; g=.sqrtGuess() - 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 -.sqrtGuess: numeric form; m.=11; p=d+d%4+2 - parse value format(x,2,1,,0) 'E0' with g 'E' _ .; return g*.5'E'_%2 +sqrt: procedure; parse arg x; if x=0 then return 0; d=digits(); numeric digits 11 +numeric form; m.=11; p=d+d%4+2; parse value format(x,2,1,,0) 'E0' with g 'E' _ . +g=g*.5'E'_%2; 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 diff --git a/Task/Standard-deviation/Scala/standard-deviation.scala b/Task/Standard-deviation/Scala/standard-deviation.scala new file mode 100644 index 0000000000..3d9095e0f1 --- /dev/null +++ b/Task/Standard-deviation/Scala/standard-deviation.scala @@ -0,0 +1,24 @@ +import scala.math._ +import Numeric.Implicits._ + +object StddevCalc extends App { + + def avg[T](ts: Iterable[T])(implicit num: Fractional[T]): T = { + num.div(ts.sum, num.fromInt(ts.size)) // Leaving with type of function T + } + + def calcAvgAndStddev[T](ts: Iterable[T])(implicit num: Fractional[T]): (T, Double) = { + val mean = avg(ts) // Leave val type of T + val stdDev = // Root of mean diffs + sqrt(num.toDouble(ts.foldLeft(num.zero)((b, a) => num.plus(b, num.times(num.minus(a, mean), num.minus(a, mean))))) / ts.size) + (mean, stdDev) + } + + def calcAvgAndStddev(ts: Iterable[BigDecimal]): (Double, Double) = // Overloaded for BigDecimal + calcAvgAndStddev(ts.map(_.toDouble)) + + println(calcAvgAndStddev(List(2.0E0, 4.0, 4, 4, 5, 5, 7, 9))) + println(calcAvgAndStddev(Set(1.0, 2, 3, 4))) + println(calcAvgAndStddev(0.1 to 1.1 by 0.05)) + println(calcAvgAndStddev(List(BigDecimal(120), BigDecimal(1200)))) +} diff --git a/Task/Standard-deviation/Scilab/standard-deviation.scilab b/Task/Standard-deviation/Scilab/standard-deviation.scilab new file mode 100644 index 0000000000..ac0b36e539 --- /dev/null +++ b/Task/Standard-deviation/Scilab/standard-deviation.scilab @@ -0,0 +1,2 @@ +T=[2,4,4,4,5,5,7,9]; +stdev(T)*sqrt((length(T)-1)/length(T)) diff --git a/Task/Standard-deviation/Visual-Basic/standard-deviation.vb b/Task/Standard-deviation/Visual-Basic/standard-deviation.vb new file mode 100644 index 0000000000..d6ce338d17 --- /dev/null +++ b/Task/Standard-deviation/Visual-Basic/standard-deviation.vb @@ -0,0 +1,50 @@ +Function avg(what() As Variant) As Variant + 'treats non-numeric strings as zero + Dim L0 As Variant, total As Variant + For L0 = LBound(what) To UBound(what) + If IsNumeric(what(L0)) Then total = total + what(L0) + Next + avg = total / (1 + UBound(what) - LBound(what)) +End Function + +Function standardDeviation(fp As Variant) As Variant + Static list() As Variant + Dim av As Variant, tmp As Variant, L0 As Variant + + 'add to sequence if numeric + If IsNumeric(fp) Then + On Error GoTo makeArr 'catch undimensioned list + ReDim Preserve list(UBound(list) + 1) + On Error GoTo 0 + list(UBound(list)) = fp + End If + + 'get average + av = avg(list()) + + 'the actual work + For L0 = 0 To UBound(list) + tmp = tmp + ((list(L0) - av) ^ 2) + Next + tmp = Sqr(tmp / (UBound(list) + 1)) + + standardDeviation = tmp + + Exit Function +makeArr: + If 9 = Err.Number Then + ReDim list(0) + Else + 'something's wrong + Err.Raise Err.Number + End If + Resume Next +End Function + +Sub tester() + Dim x As Variant + x = Array(2, 4, 4, 4, 5, 5, 7, 9) + For L0 = 0 To UBound(x) + Debug.Print standardDeviation(x(L0)) + Next +End Sub diff --git a/Task/Start-from-a-main-routine/Ruby/start-from-a-main-routine.rb b/Task/Start-from-a-main-routine/Ruby/start-from-a-main-routine.rb new file mode 100644 index 0000000000..9bdad62d38 --- /dev/null +++ b/Task/Start-from-a-main-routine/Ruby/start-from-a-main-routine.rb @@ -0,0 +1,7 @@ +BEGIN { + # begin code +} + +END { + # end code +} diff --git a/Task/Start-from-a-main-routine/Scala/start-from-a-main-routine.scala b/Task/Start-from-a-main-routine/Scala/start-from-a-main-routine.scala new file mode 100644 index 0000000000..d0dee6a0b8 --- /dev/null +++ b/Task/Start-from-a-main-routine/Scala/start-from-a-main-routine.scala @@ -0,0 +1,7 @@ +object PrimaryMain extends App { +Console.println("Hello World: " + (args mkString ", ")) +} + +object MainTheSecond extends App { +Console.println("Goodbye, World: " + (args mkString ", ")) +} diff --git a/Task/Stem-and-leaf-plot/AWK/stem-and-leaf-plot.awk b/Task/Stem-and-leaf-plot/AWK/stem-and-leaf-plot.awk new file mode 100644 index 0000000000..d5dabe40b3 --- /dev/null +++ b/Task/Stem-and-leaf-plot/AWK/stem-and-leaf-plot.awk @@ -0,0 +1,47 @@ +# syntax: GAWK -f STEM-AND-LEAF_PLOT.AWK +# +# sorting: +# PROCINFO["sorted_in"] is used by GAWK +# SORTTYPE is used by Thompson Automation's TAWK +# +BEGIN { + 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" + data_points = split(data,data_arr," ") + for (i=1; i<=data_points; i++) { + x = data_arr[i] + stem = int(x / 10) + leaf = x % 10 + if (i == 1) { + lo = hi = stem + } + lo = min(lo,stem) + hi = max(hi,stem) + arr[stem][leaf]++ + } + PROCINFO["sorted_in"] = "@ind_str_asc" ; SORTTYPE = 1 + for (i=lo; i<=hi; i++) { + printf("%4d |",i) + arr[i][""] + for (j in arr[i]) { + for (k=1; k<=arr[i][j]; k++) { + printf(" %d",j) + leaves_printed++ + } + } + printf("\n") + } + if (data_points == leaves_printed) { + exit(0) + } + else { + printf("error: %d data points != %d leaves printed\n",data_points,leaves_printed) + exit(1) + } +} +function max(x,y) { return((x > y) ? x : y) } +function min(x,y) { return((x < y) ? x : y) } diff --git a/Task/Stem-and-leaf-plot/Maple/stem-and-leaf-plot.maple b/Task/Stem-and-leaf-plot/Maple/stem-and-leaf-plot.maple new file mode 100644 index 0000000000..f879f51897 --- /dev/null +++ b/Task/Stem-and-leaf-plot/Maple/stem-and-leaf-plot.maple @@ -0,0 +1,49 @@ +StemPlot := proc( datatable::{rtable,list,algebraic} ) + local i, j, k, tf, LeafStemTable, LeafStemIndices; + k:=0; + + LeafStemTable := ListTools:-Categorize( (x,y) -> iquo(x, 10) = iquo(y, 10), sort(datatable)); + + if LeafStemTable = NULL then + error "Empty List"; + elif nops( [ LeafStemTable ] ) = 1 or not( type( LeafStemTable[2], list) ) then + LeafStemTable := [ LeafStemTable ]; + end if; + + LeafStemIndices := { seq( iquo( LeafStemTable[i][1], 10 ), i = 1..nops( [ LeafStemTable ] ) ) }; + + for i from min( LeafStemIndices ) to max( LeafStemIndices ) do + + if i in LeafStemIndices then + k := k + 1; + + if i = 0 then + + if min( datatable ) >=0 then + printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1..nops( LeafStemTable[k] ) )], string ) ) ); + else + tf := ListTools:-Occurrences( true, (x->type(x,negative))~(LeafStemTable[k])); + printf( "%s%-4a%s%-s\n", "-", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1 .. tf )], string ) ) ); + printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = tf + 1 .. nops( LeafStemTable[k] ) )], string ) ) ); + end if; + + else + + printf( "%-4a%s%-s\n", i, " | ", StringTools:-Remove( "[],", convert( [seq( abs( irem( LeafStemTable[k][j], 10 ) ), j = 1..nops( LeafStemTable[k] ) )], string ) ) ); + + end if; + + else + + printf( "%-4a%s\n", i, " | " ); + + end if; + + end do; + + return NULL; +end proc: + +Y := [ 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]; + +StemPlot(Y); diff --git a/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml index 76b463dca8..c6baa66e5a 100644 --- a/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml +++ b/Task/Stem-and-leaf-plot/OCaml/stem-and-leaf-plot-2.ocaml @@ -9,11 +9,7 @@ let data = 34; 133; 45; 120; 30; 127; 31; 116; 146 ] let data = - List.map (fun d -> - let a = d / 10 in - let b = d mod 10 in - (a, b) - ) data + List.map (fun d -> (d / 10, d mod 10)) data let keys = List.sort compare (unique (List.map fst data)) diff --git a/Task/String-case/Elixir/string-case-1.elixir b/Task/String-case/Elixir/string-case-1.elixir new file mode 100644 index 0000000000..9c43ceb476 --- /dev/null +++ b/Task/String-case/Elixir/string-case-1.elixir @@ -0,0 +1,6 @@ +String.downcase("alphaBETA") +# => alphabeta +String.upcase("alphaBETA") +# => ALPHABETA +String.capitalize("alphaBETA") +# => Alphabeta diff --git a/Task/String-case/Elixir/string-case-2.elixir b/Task/String-case/Elixir/string-case-2.elixir new file mode 100644 index 0000000000..15ad0f5b8c --- /dev/null +++ b/Task/String-case/Elixir/string-case-2.elixir @@ -0,0 +1,6 @@ +String.downcase("αΒ") +# => αβ +String.upcase("αΒ") +# => ΑΒ +String.capitalize("αΒ") +# => Αβ diff --git a/Task/String-case/Rust/string-case.rust b/Task/String-case/Rust/string-case-1.rust similarity index 100% rename from Task/String-case/Rust/string-case.rust rename to Task/String-case/Rust/string-case-1.rust diff --git a/Task/String-case/Rust/string-case-2.rust b/Task/String-case/Rust/string-case-2.rust new file mode 100644 index 0000000000..7c714aebd2 --- /dev/null +++ b/Task/String-case/Rust/string-case-2.rust @@ -0,0 +1,5 @@ +// Rust 1.0 Alpha +fn main() { + let s = "jalapeño"; + println!("{}", s.chars().map(|c| c.to_uppercase()).collect::()); +} diff --git a/Task/String-comparison/00DESCRIPTION b/Task/String-comparison/00DESCRIPTION index 69ff9fc158..8586c1afca 100644 --- a/Task/String-comparison/00DESCRIPTION +++ b/Task/String-comparison/00DESCRIPTION @@ -1,5 +1,7 @@ -{{basic data operation}}[[Category:Basic language learning]]The task is to demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. The task should demonstrate: +{{basic data operation}} [[Category:Basic language learning]] [[Category:Simple]] +The task is to demonstrate how to compare two strings from within the language and how to achieve a lexical comparison. +The task should demonstrate: * Comparing two strings for exact equality * Comparing two strings for inequality (i.e., the inverse of exact equality) * Comparing two strings to see if one is lexically ordered before than the other @@ -12,4 +14,5 @@ Here "generic/polymorphic" comparison means that the function or operator you're '''See also:''' * [[Integer comparison]] -* [[Character matching]] +* [[String matching]] +* [[Compare a list of strings]] diff --git a/Task/String-comparison/AWK/string-comparison.awk b/Task/String-comparison/AWK/string-comparison.awk index d6c1bf8002..6975fce94f 100644 --- a/Task/String-comparison/AWK/string-comparison.awk +++ b/Task/String-comparison/AWK/string-comparison.awk @@ -4,8 +4,8 @@ BEGIN { if (a == b) { print "The strings are equal" } if (a != b) { print "The strings are not equal" } - if (a > b) { print "The first string is lexically after than the second" } - if (a < b) { print "The first string is lexically before than the second" } + if (a > b) { print "The first string is lexically after than the second" } + if (a < b) { print "The first string is lexically before than the second" } if (a >= b) { print "The first string is not lexically before than the second" } if (a <= b) { print "The first string is not lexically after than the second" } diff --git a/Task/String-comparison/Ada/string-comparison.ada b/Task/String-comparison/Ada/string-comparison.ada index cdb37d778e..47a855ef43 100644 --- a/Task/String-comparison/Ada/string-comparison.ada +++ b/Task/String-comparison/Ada/string-comparison.ada @@ -1,13 +1,15 @@ -with Ada.Text_IO, Ada.Characters.Handling; +with Ada.Text_IO, Ada.Strings.Equal_Case_Insensitive; procedure String_Compare is procedure Print_Comparison (A, B: String) is - use Ada.Text_IO, Ada.Characters.Handling; + use Ada.Text_IO; + Function eq(Left, Right : String) return Boolean + renames Ada.Strings.Equal_Case_Insensitive; begin Put_Line ( """" & A & """ and """ & B & """: " & - (if A = B then "equal, " elsif To_Lower(A) = To_Lower(B) + (if A = B then "equal, " elsif eq(A,B) then "case-insensitive-equal, " else "not equal at all, ") & (if A /= B then "/=, " else "") & (if A < B then "before, " else "") & diff --git a/Task/String-comparison/Aime/string-comparison.aime b/Task/String-comparison/Aime/string-comparison.aime new file mode 100644 index 0000000000..7f7c33918d --- /dev/null +++ b/Task/String-comparison/Aime/string-comparison.aime @@ -0,0 +1,16 @@ +text s, t; + +s = "occidental"; +t = "oriental"; + +# operator case sensitive comparison +o_form("~ vs ~ (==, !=, <, <=, >=, >): ~ ~ ~ ~ ~ ~\n", s, t, s == t, s != t, s < t, s <= t, s >= t, s > t); + +s = "Oriental"; +t = "oriental"; + +# case sensitive comparison +o_form("~ vs ~ (==, !=, <, >): ~ ~ ~ ~\n", s, t, !compare(s, t), compare(s, t), compare(s, t) < 0, 0 < compare(s, t)); + +# case insensitive comparison +o_form("~ vs ~ (==, !=, <, >): ~ ~ ~ ~\n", s, t, !icompare(s, t), icompare(s, t), icompare(s, t) < 0, 0 < icompare(s, t)); diff --git a/Task/String-comparison/Common-Lisp/string-comparison-1.lisp b/Task/String-comparison/Common-Lisp/string-comparison-1.lisp new file mode 100644 index 0000000000..e7c6d291dd --- /dev/null +++ b/Task/String-comparison/Common-Lisp/string-comparison-1.lisp @@ -0,0 +1,18 @@ +>(string= "foo" "foo") +T +> (string= "foo" "FOO") +NIL +> (string/= "foo" "bar") +0 +> (string/= "bar" "baz") +2 +> (string/= "foo" "foo") +NIL +> (string> "foo" "Foo") +0 +> (string< "foo" "Foo") +NIL +> (string>= "FOo" "Foo") +NIL +> (string<= "FOo" "Foo") +1 diff --git a/Task/String-comparison/Common-Lisp/string-comparison-2.lisp b/Task/String-comparison/Common-Lisp/string-comparison-2.lisp new file mode 100644 index 0000000000..1850fed88f --- /dev/null +++ b/Task/String-comparison/Common-Lisp/string-comparison-2.lisp @@ -0,0 +1,12 @@ +> (string-equal "foo" "FOo") +T +> (string-not-equal "foo" "FOO") +NIL +> (string-greaterp "foo" "Foo") +NIL +> (string-lessp "BAR" "foo") +0 +> (string-not-greaterp "foo" "Foo") +3 +> (string-not-lessp "baz" "bAr") +2 diff --git a/Task/String-comparison/Common-Lisp/string-comparison-3.lisp b/Task/String-comparison/Common-Lisp/string-comparison-3.lisp new file mode 100644 index 0000000000..3f240c80fd --- /dev/null +++ b/Task/String-comparison/Common-Lisp/string-comparison-3.lisp @@ -0,0 +1,4 @@ +> (string> "45" "12345") +0 +> (string> "45" "9") +NIL diff --git a/Task/String-comparison/Go/string-comparison.go b/Task/String-comparison/Go/string-comparison.go index e94e0c8885..768b24aa81 100644 --- a/Task/String-comparison/Go/string-comparison.go +++ b/Task/String-comparison/Go/string-comparison.go @@ -44,7 +44,7 @@ simple case folding rules.` // 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 + // the Go "sub repository" at golang.org/x/text. There is support // for Unicode normalization, collation tables, and locale sensitive // comparisons. } diff --git a/Task/String-comparison/Haskell/string-comparison.hs b/Task/String-comparison/Haskell/string-comparison.hs new file mode 100644 index 0000000000..09bca833aa --- /dev/null +++ b/Task/String-comparison/Haskell/string-comparison.hs @@ -0,0 +1,15 @@ +> "abc" == "abc" +True +> "abc" /= "abc" +False +> "abc" <= "abcd" +True +> "abc" <= "abC" +False +> "HELLOWORLD" == "HelloWorld" +False +> :m +Data.Char +> map toLower "ABC" +"abc" +> map toLower "HELLOWORLD" == map toLower "HelloWorld" +True diff --git a/Task/String-comparison/Java/string-comparison.java b/Task/String-comparison/Java/string-comparison.java new file mode 100644 index 0000000000..41dd990474 --- /dev/null +++ b/Task/String-comparison/Java/string-comparison.java @@ -0,0 +1,38 @@ +public class Compare +{ + public static void main (String[] args) + { + compare("Hello", "Hello"); + compare("5", "5.0"); + compare("java", "Java"); + compare("ĴÃVÁ", "ĴÃVÁ"); + compare("ĴÃVÁ", "ĵãvá"); + } + public static void compare (String A, String B) + { + if (A.equals(B)) + System.out.printf("'%s' and '%s' are lexically equal.", A, B); + else + System.out.printf("'%s' and '%s' are not lexically equal.", A, B); + System.out.println(); + + if (A.equalsIgnoreCase(B)) + System.out.printf("'%s' and '%s' are case-insensitive lexically equal.", A, B); + else + System.out.printf("'%s' and '%s' are not case-insensitive lexically equal.", A, B); + System.out.println(); + + if (A.compareTo(B) < 0) + System.out.printf("'%s' is lexically before '%s'.\n", A, B); + else if (A.compareTo(B) > 0) + System.out.printf("'%s' is lexically after '%s'.\n", A, B); + + if (A.compareTo(B) >= 0) + System.out.printf("'%s' is not lexically before '%s'.\n", A, B); + if (A.compareTo(B) <= 0) + System.out.printf("'%s' is not lexically after '%s'.\n", A, B); + + System.out.printf("The lexical relationship is: %d\n", A.compareTo(B)); + System.out.printf("The case-insensitive lexical relationship is: %d\n\n", A.compareToIgnoreCase(B)); + } +} diff --git a/Task/String-comparison/Mathematica/string-comparison.math b/Task/String-comparison/Mathematica/string-comparison.math new file mode 100644 index 0000000000..8e94d176fb --- /dev/null +++ b/Task/String-comparison/Mathematica/string-comparison.math @@ -0,0 +1,19 @@ +compare[x_, y_] := Module[{}, + If[x == y, + Print["Comparing for equality (case sensitive): " <> x <> " and " <> y <> " ARE equal"], + Print["Comparing for equality (case sensitive): " <> x <> " and " <> y <> " are NOT equal" ]] ; + If[x != y, + Print["Comparing for inequality (case sensitive): " <> x <> " and " <> y <> " are NOT equal"], + Print["Comparing for inequality (case sensitive): " <> x <> " and " <> y <> " ARE equal" ]] ; + Switch[Order[x, y], + 1, Print["Comparing for order (case sensitive): " <> x <> " comes before " <> y], + -1, Print["Comparing for order (case sensitive): " <> x <> " comes after " <> y], + 0, Print["Comparing for order (case sensitive): " <> x <> " comes in the same spot as " <> y]]; + If[ToLowerCase[x] == ToLowerCase[y], + Print["Comparing for equality (case insensitive): " <> x <> " and " <> y <> " ARE equal"], + Print["Comparing for equality (case insensitive): " <> x <> " and " <> y <> " are NOT equal" ]] ; + Print[]; + ] +compare["Hello", "Hello"] +compare["3.1", "3.14159"] +compare["mathematica", "Mathematica"] diff --git a/Task/String-comparison/PicoLisp/string-comparison.l b/Task/String-comparison/PicoLisp/string-comparison.l new file mode 100644 index 0000000000..3de9b9a255 --- /dev/null +++ b/Task/String-comparison/PicoLisp/string-comparison.l @@ -0,0 +1,18 @@ +(setq + str= = + str< < + str> > ) + +(println + (str= (lowc "Foo") (lowc "foo") (lowc "fOO")) + (str= "f" "foo") + (str= "foo" "foo" "foo") + (str= "" "") ) + +(println + (str< "abc" "def") + (str> "abc" "def") + (str< "" "") + (str< "12" "45") ) + +(bye) diff --git a/Task/String-comparison/R/string-comparison-1.r b/Task/String-comparison/R/string-comparison-1.r new file mode 100644 index 0000000000..ade613e821 --- /dev/null +++ b/Task/String-comparison/R/string-comparison-1.r @@ -0,0 +1,19 @@ +compare <- function(a, b) +{ + cat(paste(a, "is of type", class(a), "and", b, "is of type", class(b), "\n")) + + if (a < b) cat(paste(a, "is strictly less than", b, "\n")) + if (a <= b) cat(paste(a, "is less than or equal to", b, "\n")) + if (a > b) cat(paste(a, "is strictly greater than", b, "\n")) + if (a >= b) cat(paste(a, "is greater than or equal to", b, "\n")) + if (a == b) cat(paste(a, "is equal to", b, "\n")) + if (a != b) cat(paste(a, "is not equal to", b, "\n")) + + invisible() +} + +compare('YUP', 'YUP') +compare('BALL', 'BELL') +compare('24', '123') +compare(24, 123) +compare(5.0, 5) diff --git a/Task/String-comparison/R/string-comparison-2.r b/Task/String-comparison/R/string-comparison-2.r new file mode 100644 index 0000000000..3882fb1d2a --- /dev/null +++ b/Task/String-comparison/R/string-comparison-2.r @@ -0,0 +1,20 @@ +compare <- function(a, b) +{ + cat(paste(a, "is of type", class(a), "and", b, "is of type", class(b), "\n")) + + printer <- function(a, b, msg) cat(paste(a, msg, b, "\n")) + + op <- c(`<`, `<=`, `>`, `>=`, `==`, `!=`) + msgs <- c( + "is strictly less than", + "is less than or equal to", + "is strictly greater than", + "is greater than or equal to", + "is equal to", + "is not equal to" + ) + + sapply(1:length(msgs), function(i) if(op[[i]](a, b)) printer(a, b, msgs[i])) + + invisible() +} diff --git a/Task/String-comparison/Scala/string-comparison.scala b/Task/String-comparison/Scala/string-comparison.scala new file mode 100644 index 0000000000..dbe1b926d3 --- /dev/null +++ b/Task/String-comparison/Scala/string-comparison.scala @@ -0,0 +1,24 @@ +object Compare extends App { + def compare(a: String, b: String) { + if (a == b) println(s"'$a' and '$b' are lexically equal.") + else println(s"'$a' and '$b' are not lexically equal.") + + if (a.equalsIgnoreCase(b)) println(s"'$a' and '$b' are case-insensitive lexically equal.") + else println(s"'$a' and '$b' are not case-insensitive lexically equal.") + + if (a.compareTo(b) < 0) println(s"'$a' is lexically before '$b'.") + else if (a.compareTo(b) > 0) println(s"'$a' is lexically after '$b'.") + + if (a.compareTo(b) >= 0) println(s"'$a' is not lexically before '$b'.") + if (a.compareTo(b) <= 0) println(s"'$a' is not lexically after '$b'.") + + println(s"The lexical relationship is: ${a.compareTo(b)}") + println(s"The case-insensitive lexical relationship is: ${a.compareToIgnoreCase(b)}\n") + } + + compare("Hello", "Hello") + compare("5", "5.0") + compare("java", "Java") + compare("ĴÃVÁ", "ĴÃVÁ") + compare("ĴÃVÁ", "ĵãvá") +} diff --git a/Task/String-concatenation/00DESCRIPTION b/Task/String-concatenation/00DESCRIPTION index 50cbf8d676..c680e22562 100644 --- a/Task/String-concatenation/00DESCRIPTION +++ b/Task/String-concatenation/00DESCRIPTION @@ -1,4 +1,5 @@ -{{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}}[[Category:Simple]] +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/Ada/string-concatenation.ada b/Task/String-concatenation/Ada/string-concatenation.ada index 5a73b77657..8ecdec4cfa 100644 --- a/Task/String-concatenation/Ada/string-concatenation.ada +++ b/Task/String-concatenation/Ada/string-concatenation.ada @@ -3,7 +3,7 @@ with Ada.Text_IO; use Ada.Text_IO; procedure String_Concatenation is S : String := "Hello"; begin - Put_Line (S & " literal"); + Put_Line (S); declare S1 : String := S & " literal"; begin diff --git a/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net b/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net index 5fc0ad7eb5..f087449e93 100644 --- a/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net +++ b/Task/String-concatenation/Dylan.NET/string-concatenation.dylan.net @@ -1,4 +1,4 @@ -//to be compiled using dylan.NET v. 11.3.1.3 or later. +//to be compiled using dylan.NET v. 11.5.1.2 or later. #refstdasm mscorlib.dll import System @@ -6,7 +6,7 @@ import System assembly concatex exe ver 1.3.0.0 -class public auto ansi Module1 +class public Program method public static void main() var s as string = "hello" diff --git a/Task/String-concatenation/Elixir/string-concatenation.elixir b/Task/String-concatenation/Elixir/string-concatenation.elixir new file mode 100644 index 0000000000..329f354efa --- /dev/null +++ b/Task/String-concatenation/Elixir/string-concatenation.elixir @@ -0,0 +1,5 @@ +s = "hello" +t = s <> " literal" + +IO.puts s +IO.puts t diff --git a/Task/String-concatenation/Lua/string-concatenation.lua b/Task/String-concatenation/Lua/string-concatenation.lua new file mode 100644 index 0000000000..0687710a65 --- /dev/null +++ b/Task/String-concatenation/Lua/string-concatenation.lua @@ -0,0 +1,4 @@ +a = "hello " +print(a .. "world") +c = a .. "world" +print(c) diff --git a/Task/String-concatenation/NewLISP/string-concatenation.newlisp b/Task/String-concatenation/NewLISP/string-concatenation.newlisp new file mode 100644 index 0000000000..13f5184947 --- /dev/null +++ b/Task/String-concatenation/NewLISP/string-concatenation.newlisp @@ -0,0 +1,4 @@ +(let (str1 "foo") + (println str1) + (let (str2 (string str1 "bar")) + (println str2))) diff --git a/Task/String-concatenation/Rust/string-concatenation.rust b/Task/String-concatenation/Rust/string-concatenation.rust index f8387373e9..ec6f85fb50 100644 --- a/Task/String-concatenation/Rust/string-concatenation.rust +++ b/Task/String-concatenation/Rust/string-concatenation.rust @@ -1,20 +1,9 @@ -/* - * 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 +// rust 0.13 fn main() { - let s = ~"hello"; - println!("s={}", s + " world"); + let s = "hello".to_string(); + println!("{}", s); let s1 = s + " world"; - println!("s1={}", s1); - - let mut mutable_s = ~"hello"; - mutable_s.push_str(" world"); - println!("mutable_s={}", mutable_s); + println!("{}", s1); } diff --git a/Task/String-concatenation/Scilab/string-concatenation.scilab b/Task/String-concatenation/Scilab/string-concatenation.scilab new file mode 100644 index 0000000000..a1c3550d85 --- /dev/null +++ b/Task/String-concatenation/Scilab/string-concatenation.scilab @@ -0,0 +1,4 @@ +s1="Hello" +s1+" world!" +s2=s1+" world" +s2 diff --git a/Task/String-interpolation--included-/00META.yaml b/Task/String-interpolation--included-/00META.yaml index 3bdc51ea57..9ec0e0a94f 100644 --- a/Task/String-interpolation--included-/00META.yaml +++ b/Task/String-interpolation--included-/00META.yaml @@ -1,4 +1,5 @@ --- category: - String manipulation +- Simple note: Basic language learning diff --git a/Task/String-interpolation--included-/Delphi/string-interpolation--included-.delphi b/Task/String-interpolation--included-/Delphi/string-interpolation--included-.delphi new file mode 100644 index 0000000000..1833a78b3f --- /dev/null +++ b/Task/String-interpolation--included-/Delphi/string-interpolation--included-.delphi @@ -0,0 +1,36 @@ +program Project1; + +uses + System.SysUtils; + +var + Template : string; + Marker : string; + Description : string; + Value : integer; + Output : string; + +begin + // StringReplace can be used if you are definitely using strings + // http://docwiki.embarcadero.com/Libraries/XE7/en/System.SysUtils.StringReplace + Template := 'Mary had a X lamb.'; + Marker := 'X'; + Description := 'little'; + Output := StringReplace(Template, Marker, Description, [rfReplaceAll, rfIgnoreCase]); + writeln(Output); + + // You could also use format to do the same thing. + // http://docwiki.embarcadero.com/Libraries/XE7/en/System.SysUtils.Format + Template := 'Mary had a %s lamb.'; + Description := 'little'; + Output := format(Template,[Description]); + writeln(Output); + + // Unlike StringReplace, format is not restricted to strings. + Template := 'Mary had a %s lamb. It was worth $%d.'; + Description := 'little'; + Value := 20; + Output := format(Template,[Description, Value]); + writeln(Output); + +end. diff --git a/Task/String-interpolation--included-/Elixir/string-interpolation--included-.elixir b/Task/String-interpolation--included-/Elixir/string-interpolation--included-.elixir new file mode 100644 index 0000000000..8581ffd1e6 --- /dev/null +++ b/Task/String-interpolation--included-/Elixir/string-interpolation--included-.elixir @@ -0,0 +1,2 @@ +x = "little" +IO.puts "Mary had a #{x} lamb" diff --git a/Task/String-interpolation--included-/Frink/string-interpolation--included-.frink b/Task/String-interpolation--included-/Frink/string-interpolation--included-.frink new file mode 100644 index 0000000000..a98d11af97 --- /dev/null +++ b/Task/String-interpolation--included-/Frink/string-interpolation--included-.frink @@ -0,0 +1,2 @@ +x = "little" +println["Mary had a $x lamb."] diff --git a/Task/String-interpolation--included-/OOC/string-interpolation--included-.ooc b/Task/String-interpolation--included-/OOC/string-interpolation--included-.ooc new file mode 100644 index 0000000000..64ce30d3b4 --- /dev/null +++ b/Task/String-interpolation--included-/OOC/string-interpolation--included-.ooc @@ -0,0 +1,4 @@ +main: func { + X := "little" + "Mary had a #{X} lamb" println() +} diff --git a/Task/String-length/00DESCRIPTION b/Task/String-length/00DESCRIPTION index 2702bb034a..e2de335fec 100644 --- a/Task/String-length/00DESCRIPTION +++ b/Task/String-length/00DESCRIPTION @@ -1,5 +1,13 @@ -In this task, the goal is to find the character and byte length of a string. This means encodings like [[UTF-8]] need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters. By ''character'', we mean an individual Unicode ''code point'', not a user-visible ''grapheme'' containing combining characters. For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. +{{omit from|GUISS|Can use Microsoft Word document properties, but this might not be accurate}} +{{omit from|Openscad}} +In this task, the goal is to find the character and byte length of a string. +This means encodings like [[UTF-8]] need to be handled properly, as there is not necessarily a one-to-one relationship between bytes and characters.
    +By ''character'', we mean an individual Unicode ''code point'', not a user-visible ''grapheme'' containing combining characters. +For example, the character length of "møøse" is 5 but the byte length is 7 in UTF-8 and 10 in UTF-16. -Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, '''not''' 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. +Non-BMP code points (those between 0x10000 and 0x10FFFF) must also be handled correctly: answers should produce actual character counts in code points, not in code unit counts. +Therefore a string like "𝔘𝔫𝔦𝔠𝔬𝔡𝔢" (consisting of the 7 Unicode characters U+1D518 U+1D52B U+1D526 U+1D520 U+1D52C U+1D521 U+1D522) is 7 characters long, '''not''' 14 UTF-16 code units; and it is 28 bytes long whether encoded in UTF-8 or in UTF-16. -Please mark your examples with ===Character Length=== or ===Byte Length===. If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===. For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. +Please mark your examples with ===Character Length=== or ===Byte Length===. +If your language is capable of providing the string length in graphemes, mark those examples with ===Grapheme Length===.
    +For example, the string "J̲o̲s̲é̲" ("J\x{332}o\x{332}s\x{332}e\x{301}\x{332}") has 4 user-visible graphemes, 9 characters (code points), and 14 bytes when encoded in UTF-8. diff --git a/Task/String-length/00META.yaml b/Task/String-length/00META.yaml index 659c8686af..3bdc51ea57 100644 --- a/Task/String-length/00META.yaml +++ b/Task/String-length/00META.yaml @@ -1,2 +1,4 @@ --- +category: +- String manipulation note: Basic language learning diff --git a/Task/String-length/ColdFusion/string-length-1.cfm b/Task/String-length/ColdFusion/string-length-1.cfm index 1dca5aafb7..a90f279638 100644 --- a/Task/String-length/ColdFusion/string-length-1.cfm +++ b/Task/String-length/ColdFusion/string-length-1.cfm @@ -1 +1,6 @@ -#len("Hello World")# + + + + +

    #arrayLen(t)#

    +
    diff --git a/Task/String-length/Elixir/string-length-1.elixir b/Task/String-length/Elixir/string-length-1.elixir new file mode 100644 index 0000000000..a823e7278a --- /dev/null +++ b/Task/String-length/Elixir/string-length-1.elixir @@ -0,0 +1,3 @@ +name = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}" +byte_size(name) +# => 14 diff --git a/Task/String-length/Elixir/string-length-2.elixir b/Task/String-length/Elixir/string-length-2.elixir new file mode 100644 index 0000000000..d4d2c59f32 --- /dev/null +++ b/Task/String-length/Elixir/string-length-2.elixir @@ -0,0 +1,3 @@ +name = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}" +Enum.count(String.codepoints(name)) +# => 9 diff --git a/Task/String-length/Elixir/string-length-3.elixir b/Task/String-length/Elixir/string-length-3.elixir new file mode 100644 index 0000000000..bea49d1d16 --- /dev/null +++ b/Task/String-length/Elixir/string-length-3.elixir @@ -0,0 +1,3 @@ +name = "J\x{332}o\x{332}s\x{332}e\x{301}\x{332}" +String.length(name) +# => 4 diff --git a/Task/String-length/Java/string-length-1.java b/Task/String-length/Java/string-length-1.java index 6f41926d7f..b12bad7aa7 100644 --- a/Task/String-length/Java/string-length-1.java +++ b/Task/String-length/Java/string-length-1.java @@ -1,4 +1,4 @@ String s = "Hello, world!"; -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; +int byteCountUTF16 = s.getBytes("UTF-16").length; // Incorrect: it yields 28 (that is with the BOM) +int byteCountUTF16LE = s.getBytes("UTF-16LE").length; // Correct: it yields 26 +int byteCountUTF8 = s.getBytes("UTF-8").length; // yields 13 diff --git a/Task/String-length/Maple/string-length-1.maple b/Task/String-length/Maple/string-length-1.maple new file mode 100644 index 0000000000..438db73fa9 --- /dev/null +++ b/Task/String-length/Maple/string-length-1.maple @@ -0,0 +1 @@ +length("Hello world"); diff --git a/Task/String-length/Maple/string-length-2.maple b/Task/String-length/Maple/string-length-2.maple new file mode 100644 index 0000000000..4fc052bcce --- /dev/null +++ b/Task/String-length/Maple/string-length-2.maple @@ -0,0 +1 @@ +nops(convert("Hello world",bytes)); diff --git a/Task/String-length/Mercury/string-length-1.mercury b/Task/String-length/Mercury/string-length-1.mercury new file mode 100644 index 0000000000..8c5cc3dfed --- /dev/null +++ b/Task/String-length/Mercury/string-length-1.mercury @@ -0,0 +1,20 @@ +:- module string_byte_length. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list, string. + +main(!IO) :- + Words = ["møøse", "𝔘𝔫𝔦𝔠𝔬𝔡𝔢", "J\x332\o\x332\s\x332\e\x301\\x332\"], + io.write_list(Words, "", write_length, !IO). + +:- pred write_length(string::in, io::di, io::uo) is det. + +write_length(String, !IO):- + NumBytes = count_utf8_code_units(String), + io.format("%s: %d bytes\n", [s(String), i(NumBytes)], !IO). diff --git a/Task/String-length/Mercury/string-length-2.mercury b/Task/String-length/Mercury/string-length-2.mercury new file mode 100644 index 0000000000..70a8396fd7 --- /dev/null +++ b/Task/String-length/Mercury/string-length-2.mercury @@ -0,0 +1,20 @@ +:- module string_character_length. +:- interface. + +:- import_module io. + +:- pred main(io::di, io::uo) is det. + +:- implementation. + +:- import_module list, string. + +main(!IO) :- + Words = ["møøse", "𝔘𝔫𝔦𝔠𝔬𝔡𝔢", "J\x332\o\x332\s\x332\e\x301\\x332\"], + io.write_list(Words, "", write_length, !IO). + +:- pred write_length(string::in, io::di, io::uo) is det. + +write_length(String, !IO) :- + NumChars = count_codepoints(String), + io.format("%s: %d characters\n", [s(String), i(NumChars)], !IO). 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 index f8d67ab268..15d871b447 100644 --- 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 @@ -1,5 +1,5 @@ text -stripchars(text s, text w) +stripchars1(text s, text w) { integer p; data b; @@ -14,10 +14,24 @@ stripchars(text s, text w) return b_string(b); } +text +stripchars2(text s, text w) +{ + data b; + + b_cast(b, s); + b_drop(b, w); + + return b_string(b); +} + integer main(void) { - o_text(stripchars("She was a soul stripper. She took my heart!", "aei")); + o_text(stripchars1("She was a soul stripper. She took my heart!", "aei")); + o_newline(); + + o_text(stripchars2("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/C/strip-a-set-of-characters-from-a-string-2.c b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c index a6ec361cd2..f17590f532 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c +++ b/Task/Strip-a-set-of-characters-from-a-string/C/strip-a-set-of-characters-from-a-string-2.c @@ -16,7 +16,7 @@ char *strip(const char * str, const char *pat) int i = 0, tbl[128] = {0}; while (*pat != '\0') tbl[(int)*(pat++)] = 1; - char *ret = malloc(strlen(str)); + char *ret = malloc(strlen(str) + 1); do { if (!tbl[(int)*str]) ret[i++] = *str; diff --git a/Task/Strip-a-set-of-characters-from-a-string/ColdFusion/strip-a-set-of-characters-from-a-string.cfm b/Task/Strip-a-set-of-characters-from-a-string/ColdFusion/strip-a-set-of-characters-from-a-string.cfm new file mode 100644 index 0000000000..2e3afca5d3 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/ColdFusion/strip-a-set-of-characters-from-a-string.cfm @@ -0,0 +1,6 @@ + + + + + +#theString# diff --git a/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir new file mode 100644 index 0000000000..815803a0ce --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-1.elixir @@ -0,0 +1,3 @@ +str = "She was a soul stripper. She took my heart!" +String.replace(str, ~r/a|e|i/, "") +# => Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir new file mode 100644 index 0000000000..5218b98a2b --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/Elixir/strip-a-set-of-characters-from-a-string-2.elixir @@ -0,0 +1,10 @@ +defmodule RC do + def stripchars(str, chars) do + String.replace(str, ~r/#{Enum.join(String.split(chars, ""), "|")}/, "") + end +end + +str = "She was a soul stripper. She took my heart!" + +RC.stripchars(str, "aei") +# => Sh ws soul strppr. Sh took my hrt! diff --git a/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua index 1069a548cf..5d7809b879 100644 --- a/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua +++ b/Task/Strip-a-set-of-characters-from-a-string/Lua/strip-a-set-of-characters-from-a-string.lua @@ -1,9 +1,6 @@ -function stripchars( str, chr ) - local s = "" - for g in str:gmatch( "[^"..chr.."]" ) do - s = s .. g - end - return s +function stripchars(str, chrs) + local s = str:gsub("["..chrs.."]", '') + return s end print( stripchars( "She was a soul stripper. She took my heart!", "aei" ) ) diff --git a/Task/Strip-a-set-of-characters-from-a-string/NewLISP/strip-a-set-of-characters-from-a-string.newlisp b/Task/Strip-a-set-of-characters-from-a-string/NewLISP/strip-a-set-of-characters-from-a-string.newlisp new file mode 100644 index 0000000000..0c07cacba3 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/NewLISP/strip-a-set-of-characters-from-a-string.newlisp @@ -0,0 +1,2 @@ +(let (sentence "She was a soul stripper. She took my heart!") + (replace "[aei]" sentence "" 0)) diff --git a/Task/Strip-a-set-of-characters-from-a-string/ScriptBasic/strip-a-set-of-characters-from-a-string.scriptbasic b/Task/Strip-a-set-of-characters-from-a-string/ScriptBasic/strip-a-set-of-characters-from-a-string.scriptbasic new file mode 100644 index 0000000000..3893f10d71 --- /dev/null +++ b/Task/Strip-a-set-of-characters-from-a-string/ScriptBasic/strip-a-set-of-characters-from-a-string.scriptbasic @@ -0,0 +1,6 @@ +str1 = "She was a soul stripper. She took my heart!" +rmv = "aei" +FOR i = 1 TO LEN(rmv) + str1 = REPLACE(str1, MID(rmv, i, 1), "") +NEXT +PRINT str1,"\n" diff --git a/Task/Strip-block-comments/Scala/strip-block-comments-1.scala b/Task/Strip-block-comments/Scala/strip-block-comments-1.scala new file mode 100644 index 0000000000..6b370e379d --- /dev/null +++ b/Task/Strip-block-comments/Scala/strip-block-comments-1.scala @@ -0,0 +1,3 @@ +import java.util.regex.Pattern.quote +def strip1(x: String, s: String = "/*", e: String = "*/") = + x.replaceAll("(?s)"+quote(s)+".*?"+quote(e), "") diff --git a/Task/Strip-block-comments/Scala/strip-block-comments-2.scala b/Task/Strip-block-comments/Scala/strip-block-comments-2.scala new file mode 100644 index 0000000000..ade47387ab --- /dev/null +++ b/Task/Strip-block-comments/Scala/strip-block-comments-2.scala @@ -0,0 +1,6 @@ +def strip2(x: String, s: String = "/*", e: String = "*/"): String = { + val a = x indexOf s + val b = x indexOf (e, a + s.length) + if (a == -1 || b == -1) x + else strip2(x.take(a) + x.drop(b + e.length), s, e) +} diff --git a/Task/Strip-block-comments/Scala/strip-block-comments-3.scala b/Task/Strip-block-comments/Scala/strip-block-comments-3.scala new file mode 100644 index 0000000000..ea1334b13c --- /dev/null +++ b/Task/Strip-block-comments/Scala/strip-block-comments-3.scala @@ -0,0 +1,7 @@ +def strip3(x: String, s: String = "/*", e: String = "*/"): String = x.indexOf(s) match { + case -1 => x + case i => x.indexOf(e, i + s.length) match { + case -1 => x + case j => strip2(x.take(i) + x.drop(j + e.length), s, e) + } +} diff --git a/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go index 9b2ab7c5d9..70635e7806 100644 --- a/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go +++ b/Task/Strip-comments-from-a-string/Go/strip-comments-from-a-string.go @@ -1,26 +1,27 @@ package main import ( - "fmt" - "strings" + "fmt" + "strings" + "unicode" ) const commentChars = "#;" func stripComment(source string) string { - if cut := strings.IndexAny(source, commentChars); cut >= 0 { - return source[:cut] - } - return source + if cut := strings.IndexAny(source, commentChars); cut >= 0 { + return strings.TrimRightFunc(source[:cut], unicode.IsSpace) + } + return source } func main() { - for _, s := range []string{ - "apples, pears # and bananas", - "apples, pears ; and bananas", - "no bananas", - } { - fmt.Printf("source: %q\n", s) - fmt.Printf("stripped: %q\n", stripComment(s)) - } + for _, s := range []string{ + "apples, pears # and bananas", + "apples, pears ; and bananas", + "no bananas", + } { + fmt.Printf("source: %q\n", s) + fmt.Printf("stripped: %q\n", stripComment(s)) + } } diff --git a/Task/Strip-comments-from-a-string/Maple/strip-comments-from-a-string.maple b/Task/Strip-comments-from-a-string/Maple/strip-comments-from-a-string.maple new file mode 100644 index 0000000000..d5d04719ad --- /dev/null +++ b/Task/Strip-comments-from-a-string/Maple/strip-comments-from-a-string.maple @@ -0,0 +1,2 @@ +> use StringTools in map( Trim@Take, [ "\t\t apples, pears \t# and bananas", " apples, pears ; and bananas \t" ], "#;" ) end; + ["apples, pears", "apples, pears"] diff --git a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx index 301db52943..39c1839872 100644 --- a/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx +++ b/Task/Strip-comments-from-a-string/REXX/strip-comments-from-a-string.rexx @@ -13,29 +13,29 @@ new4=stripCom3(old2) ; say '4th version new ───►'new4"◄ exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────STRIPCOM1 subroutine────────────────*/ stripCom1: procedure; parse arg x /*get the argument (string). */ -x=translate(x,'#',";") /*translate semicolons to hash. */ -parse var x x '#' /*parse string, ending in hash. */ +x=translate(x, '#', ";") /*translate semicolons to hash. */ +parse var x x '#' /*parse string, ending in hash. */ return strip(x) /*return striped shortened string*/ /*──────────────────────────────────STRIPCOM2 subroutine────────────────*/ stripCom2: procedure; parse arg x /*get the argument (string). */ -d='#;' /*delimiter list to be used. */ +d = ';#' /*the delimiter list to be used. */ d1=left(d,1) /*get the 1st character in delim.*/ x=translate(x,copies(d1,length(d)),d) /*trans all delims ──► 1st delim.*/ -parse var x x (d1) /*parse string, ending in hash. */ +parse var x x (d1) /*parse string, ending in hash. */ return strip(x) /*return striped shortened string*/ /*──────────────────────────────────STRIPCOM3 subroutine────────────────*/ stripCom3: procedure; parse arg x /*get the argument (string). */ -d=';#' /*delimiter list to be used. */ - do j=1 for length(d) /*process each delimiter singly. */ +d = ';#' /*the delimiter list to be used. */ + do j=1 for length(d) /*process each delimiter singly. */ _=substr(d,j,1) /*use one delimiter at a time. */ - parse var x x (_) /*parse X string for each delim. */ + parse var x x (_) /*parse X string for each delim. */ end /*j*/ return strip(x) /*return striped shortened string*/ /*──────────────────────────────────STRIPCOM4 subroutine────────────────*/ stripCom4: procedure; parse arg x /*get the argument (string). */ -d=';#' /*delimiter list to be used. */ - do k=1 for length(d) /*process each delimiter singly. */ +d = ';#' /*the delimiter list to be used. */ + do k=1 for length(d) /*process each delimiter singly. */ p=pos(substr(d,k,1),x) /*see if a delimiter is in X. */ - if p\==0 then x=left(x,p-1) /*shorten the X string.*/ + if p\==0 then x=left(x,p-1) /*shorten the X string.*/ end /*k*/ return strip(x) /*return striped shortened string*/ diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Clojure/strip-control-codes-and-extended-characters-from-a-string.clj b/Task/Strip-control-codes-and-extended-characters-from-a-string/Clojure/strip-control-codes-and-extended-characters-from-a-string.clj new file mode 100644 index 0000000000..6d692c55fd --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Clojure/strip-control-codes-and-extended-characters-from-a-string.clj @@ -0,0 +1,8 @@ +; generate our test string of characters with control and extended characters +(def range-of-chars (apply str (map char (range 256)))) + +; filter out the control characters: +(apply str (filter #(not (Character/isISOControl %)) range-of-chars)) + +; filter to return String of characters that are between 32 - 126: +(apply str (filter #(<= 32 (int %) 126) range-of-chars)) diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go b/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go index 3abfa3ca63..57e92d913f 100644 --- a/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Go/strip-control-codes-and-extended-characters-from-a-string.go @@ -1,69 +1,90 @@ package main import ( - "fmt" - "strings" + "golang.org/x/text/transform" + "golang.org/x/text/unicode/norm" + "fmt" + "strings" ) // two byte-oriented functions identical except for operator comparing c to 127. func stripCtlFromBytes(str string) string { - b := make([]byte, len(str)) - var bl int - for i := 0; i < len(str); i++ { - c := str[i] - if c >= 32 && c != 127 { - b[bl] = c - bl++ - } - } - return string(b[:bl]) + b := make([]byte, len(str)) + var bl int + for i := 0; i < len(str); i++ { + c := str[i] + if c >= 32 && c != 127 { + b[bl] = c + bl++ + } + } + return string(b[:bl]) } func stripCtlAndExtFromBytes(str string) string { - b := make([]byte, len(str)) - var bl int - for i := 0; i < len(str); i++ { - c := str[i] - if c >= 32 && c < 127 { - b[bl] = c - bl++ - } - } - return string(b[:bl]) + b := make([]byte, len(str)) + var bl int + for i := 0; i < len(str); i++ { + c := str[i] + if c >= 32 && c < 127 { + b[bl] = c + bl++ + } + } + return string(b[:bl]) } // two UTF-8 functions identical except for operator comparing c to 127 func stripCtlFromUTF8(str string) string { - return strings.Map(func(r rune) rune { - if r >= 32 && r != 127 { - return r - } - return -1 - }, str) + return strings.Map(func(r rune) rune { + if r >= 32 && r != 127 { + return r + } + return -1 + }, str) } func stripCtlAndExtFromUTF8(str string) string { - return strings.Map(func(r rune) rune { - if r >= 32 && r < 127 { - return r - } - return -1 - }, str) + return strings.Map(func(r rune) rune { + if r >= 32 && r < 127 { + return r + } + return -1 + }, str) +} + +// Advanced Unicode normalization and filtering, +// see http://blog.golang.org/normalization and +// http://godoc.org/golang.org/x/text/unicode/norm for more +// details. +func stripCtlAndExtFromUnicode(str string) string { + isOk := func(r rune) bool { + return r < 32 || r >= 127 + } + // The isOk filter is such that there is no need to chain to norm.NFC + t := transform.Chain(norm.NFKD, transform.RemoveFunc(isOk)) + // This Transformer could also trivially be applied as an io.Reader + // or io.Writer filter to automatically do such filtering when reading + // or writing data anywhere. + str, _, _ = transform.String(t, str) + return str } const src = "déjà vu" + // precomposed unicode - "\n\000\037 \041\176\177\200\377\n" + // various boundary cases - "as⃝df̅" // unicode combining characters + "\n\000\037 \041\176\177\200\377\n" + // various boundary cases + "as⃝df̅" // unicode combining characters func main() { - fmt.Println("source text:") - fmt.Println(src, "\n") - fmt.Println("as bytes, stripped of control codes:") - fmt.Println(stripCtlFromBytes(src), "\n") - fmt.Println("as bytes, stripped of control codes and extended characters:") - fmt.Println(stripCtlAndExtFromBytes(src), "\n") - fmt.Println("as UTF-8, stripped of control codes:") - fmt.Println(stripCtlFromUTF8(src), "\n") - fmt.Println("as UTF-8, stripped of control codes and extended characters:") - fmt.Println(stripCtlAndExtFromUTF8(src)) + fmt.Println("source text:") + fmt.Println(src) + fmt.Println("\nas bytes, stripped of control codes:") + fmt.Println(stripCtlFromBytes(src)) + fmt.Println("\nas bytes, stripped of control codes and extended characters:") + fmt.Println(stripCtlAndExtFromBytes(src)) + fmt.Println("\nas UTF-8, stripped of control codes:") + fmt.Println(stripCtlFromUTF8(src)) + fmt.Println("\nas UTF-8, stripped of control codes and extended characters:") + fmt.Println(stripCtlAndExtFromUTF8(src)) + fmt.Println("\nas decomposed and stripped Unicode:") + fmt.Println(stripCtlAndExtFromUnicode(src)) } diff --git a/Task/Strip-control-codes-and-extended-characters-from-a-string/Java/strip-control-codes-and-extended-characters-from-a-string.java b/Task/Strip-control-codes-and-extended-characters-from-a-string/Java/strip-control-codes-and-extended-characters-from-a-string.java new file mode 100644 index 0000000000..05d9afc893 --- /dev/null +++ b/Task/Strip-control-codes-and-extended-characters-from-a-string/Java/strip-control-codes-and-extended-characters-from-a-string.java @@ -0,0 +1,15 @@ +import java.util.function.IntPredicate; + +public class StripControlCodes { + + public static void main(String[] args) { + String s = "\u0000\n abc\u00E9def\u007F"; + System.out.println(stripChars(s, c -> c > '\u001F' && c != '\u007F')); + System.out.println(stripChars(s, c -> c > '\u001F' && c < '\u007F')); + } + + static String stripChars(String s, IntPredicate include) { + return s.codePoints().filter(include::test).collect(StringBuilder::new, + StringBuilder::appendCodePoint, StringBuilder::append).toString(); + } +} diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/ALGOL-68/strip-whitespace-from-a-string-top-and-tail.alg b/Task/Strip-whitespace-from-a-string-Top-and-tail/ALGOL-68/strip-whitespace-from-a-string-top-and-tail.alg new file mode 100644 index 0000000000..91ce13e84f --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/ALGOL-68/strip-whitespace-from-a-string-top-and-tail.alg @@ -0,0 +1,54 @@ +# returns "text" with leading non-printing characters removed # +PROC trim leading whitespace = ( STRING text )STRING: +BEGIN + + INT pos := LWB text; + + WHILE + IF pos > UPB text + THEN + FALSE + ELSE + text[ pos ] <= " " + FI + DO + pos +:= 1 + OD; + + text[ pos : ] +END; # trim leading whitespace # + +# returns "text" with trailing non-printing characters removed # +PROC trim trailing whitespace = ( STRING text )STRING: +BEGIN + + INT pos := UPB text; + + WHILE + IF pos < LWB text + THEN + FALSE + ELSE + text[ pos ] <= " " + FI + DO + pos -:= 1 + OD; + + text[ : pos ] +END; # trim trailing whitespace # + +# returns "text" with leading and trailing non-printing characters removed # +PROC trim whitespace = ( STRING text )STRING: +BEGIN + trim trailing whitespace( trim leading whitespace( text ) ) +END; # trim whitespace # + + +main:( + STRING test = " leading and trailing spaces surrounded this text "; + + print( ( "trim leading: """ + trim leading whitespace ( test ) + """", newline ) ); + print( ( "trim trailing: """ + trim trailing whitespace( test ) + """", newline ) ); + print( ( "trim both: """ + trim whitespace ( test ) + """", newline ) ) +) diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Clojure/strip-whitespace-from-a-string-top-and-tail.clj b/Task/Strip-whitespace-from-a-string-Top-and-tail/Clojure/strip-whitespace-from-a-string-top-and-tail.clj new file mode 100644 index 0000000000..796197972e --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Clojure/strip-whitespace-from-a-string-top-and-tail.clj @@ -0,0 +1,7 @@ +(use 'clojure.string) +(triml " my string ") +=> "my string " +(trimr " my string ") +=> " my string" +(trim " \t\r\n my string \t\r\n ") +=> "my string" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir b/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir new file mode 100644 index 0000000000..c0f188035d --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/Elixir/strip-whitespace-from-a-string-top-and-tail.elixir @@ -0,0 +1,3 @@ +IO.puts "'" <> String.strip(" x ") <> "'" +IO.puts "'" <> String.rstrip(" x ") <> "'" +IO.puts "'" <> String.lstrip(" x ") <> "'" diff --git a/Task/Strip-whitespace-from-a-string-Top-and-tail/NewLISP/strip-whitespace-from-a-string-top-and-tail.newlisp b/Task/Strip-whitespace-from-a-string-Top-and-tail/NewLISP/strip-whitespace-from-a-string-top-and-tail.newlisp new file mode 100644 index 0000000000..d2831812ea --- /dev/null +++ b/Task/Strip-whitespace-from-a-string-Top-and-tail/NewLISP/strip-whitespace-from-a-string-top-and-tail.newlisp @@ -0,0 +1,10 @@ +(setq str " this is a string ") + +;; trim leading blanks +(trim str " " "") + +;; trim trailing blanks +(trim str "" " ") + +;; trim both leading and trailing blanks +(trim str) diff --git a/Task/Substring-Top-and-tail/Clojure/substring-top-and-tail.clj b/Task/Substring-Top-and-tail/Clojure/substring-top-and-tail.clj new file mode 100644 index 0000000000..8406eba9bb --- /dev/null +++ b/Task/Substring-Top-and-tail/Clojure/substring-top-and-tail.clj @@ -0,0 +1,15 @@ +; using substring: +user=> (subs "knight" 1) +"night" +user=> (subs "socks" 0 4) +"sock" +user=> (.substring "brooms" 1 5) +"room" + +; using rest and drop-last: +user=> (apply str (rest "knight")) +"night" +user=> (apply str (drop-last "socks")) +"sock" +user=> (apply str (rest (drop-last "brooms"))) +"room" diff --git a/Task/Substring-Top-and-tail/NewLISP/substring-top-and-tail.newlisp b/Task/Substring-Top-and-tail/NewLISP/substring-top-and-tail.newlisp new file mode 100644 index 0000000000..4437169562 --- /dev/null +++ b/Task/Substring-Top-and-tail/NewLISP/substring-top-and-tail.newlisp @@ -0,0 +1,7 @@ +(let (str "rosetta") + ;; strip first char + (println (1 str)) + ;; strip last char + (println (0 -1 str)) + ;; strip both first and last characters + (println (1 -1 str))) diff --git a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx index dcb6700b2c..e078d9fbb0 100644 --- a/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx +++ b/Task/Substring-Top-and-tail/REXX/substring-top-and-tail.rexx @@ -1,5 +1,4 @@ /*REXX program to show removal of 1st/last/1st&last chars from a string.*/ - z = 'abcdefghijk' say ' the original string =' z diff --git a/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb b/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb index 0435d87dcd..0e8acc4e47 100644 --- a/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb +++ b/Task/Substring-Top-and-tail/Ruby/substring-top-and-tail.rb @@ -2,3 +2,4 @@ puts "knight"[1..-1] # strip first character puts "socks"[0..-2] # strip last character puts "socks".chop # alternate way to strip last character puts "brooms"[1..-2] # strip both first and last characters +puts "与今令"[1..-2] # => 今 diff --git a/Task/Substring/00DESCRIPTION b/Task/Substring/00DESCRIPTION index 5eed4dc616..8465f453d9 100644 --- a/Task/Substring/00DESCRIPTION +++ b/Task/Substring/00DESCRIPTION @@ -1,4 +1,6 @@ -{{basic data operation}}In this task display a substring: +{{basic data operation}} +[[Category:String manipulation]] [[Category:Simple]] +In this task display a substring: * starting from n characters in and of m length; * starting from n characters in, up to the end of the string; @@ -6,4 +8,6 @@ * starting from a known character within the string and of m length; * starting from a known substring within the string and of m length. -If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, whether in the Basic Multilingual Plane or above it. The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. +If the program uses UTF-8 or UTF-16, it must work on any valid Unicode code point, +whether in the Basic Multilingual Plane or above it. +The program must reference logical characters (code points), not 8-bit code units for UTF-8 or 16-bit code units for UTF-16. Programs for other encodings (such as 8-bit ASCII, or EUC-JP) are not required to handle all Unicode characters. diff --git a/Task/Substring/00META.yaml b/Task/Substring/00META.yaml index 3bdc51ea57..659c8686af 100644 --- a/Task/Substring/00META.yaml +++ b/Task/Substring/00META.yaml @@ -1,4 +1,2 @@ --- -category: -- String manipulation note: Basic language learning diff --git a/Task/Substring/Go/substring-1.go b/Task/Substring/Go/substring-1.go new file mode 100644 index 0000000000..a8f8a66ca6 --- /dev/null +++ b/Task/Substring/Go/substring-1.go @@ -0,0 +1,26 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "ABCDEFGH" + n, m := 2, 3 + // for reference + fmt.Println("Index: ", "01234567") + fmt.Println("String:", s) + // starting from n characters in and of m length + fmt.Printf("Start %d, length %d: %s\n", n, m, s[n : n+m]) + // starting from n characters in, up to the end of the string + fmt.Printf("Start %d, to end: %s\n", n, s[n:]) + // whole string minus last character + fmt.Printf("All but last: %s\n", s[:len(s)-1]) + // starting from a known character within the string and of m length + dx := strings.IndexByte(s, 'D') + fmt.Printf("Start 'D', length %d: %s\n", m, s[dx : dx+m]) + // starting from a known substring within the string and of m length + sx := strings.Index(s, "DE") + fmt.Printf(`Start "DE", length %d: %s`+"\n", m, s[sx : sx+m]) +} diff --git a/Task/Substring/Go/substring-2.go b/Task/Substring/Go/substring-2.go new file mode 100644 index 0000000000..0fa28cfafb --- /dev/null +++ b/Task/Substring/Go/substring-2.go @@ -0,0 +1,29 @@ +package main + +import ( + "fmt" + "strings" +) + +func main() { + s := "αβγδεζηθ" + r := []rune(s) + n, m := 2, 3 + kc := 'δ' // known character + ks := "δε" // known string + // for reference + fmt.Println("Index: ", "01234567") + fmt.Println("String:", s) + // starting from n characters in and of m length + fmt.Printf("Start %d, length %d: %s\n", n, m, string(r[n:n+m])) + // starting from n characters in, up to the end of the string + fmt.Printf("Start %d, to end: %s\n", n, string(r[n:])) + // whole string minus last character + fmt.Printf("All but last: %s\n", string(r[:len(r)-1])) + // starting from a known character within the string and of m length + dx := strings.IndexRune(s, kc) + fmt.Printf("Start %q, length %d: %s\n", kc, m, string([]rune(s[dx:])[:m])) + // starting from a known substring within the string and of m length + sx := strings.Index(s, ks) + fmt.Printf("Start %q, length %d: %s\n", ks, m, string([]rune(s[sx:])[:m])) +} diff --git a/Task/Substring/Go/substring.go b/Task/Substring/Go/substring.go deleted file mode 100644 index 44d4b36023..0000000000 --- a/Task/Substring/Go/substring.go +++ /dev/null @@ -1,14 +0,0 @@ -package main -import "fmt" -import "strings" - -func main() { - s := "ABCDEFGH" - n, m := 2, 3 - - fmt.Println(s[n:n+m]) // "CDE" - fmt.Println(s[n:]) // "CDEFGH" - fmt.Println(s[0:len(s)-1]) // "ABCDEFG" - fmt.Println(s[strings.Index(s, "D"):strings.Index(s, "D")+m]) // "DEF" - fmt.Println(s[strings.Index(s, "DE"):strings.Index(s, "DE")+m]) // "DEF" -} diff --git a/Task/Substring/Maple/substring-1.maple b/Task/Substring/Maple/substring-1.maple new file mode 100644 index 0000000000..c980ca4754 --- /dev/null +++ b/Task/Substring/Maple/substring-1.maple @@ -0,0 +1,4 @@ +> n, m := 3, 5: +> s := "The Higher, The Fewer!": +> s[ n .. n + m - 1 ]; + "e Hig" diff --git a/Task/Substring/Maple/substring-2.maple b/Task/Substring/Maple/substring-2.maple new file mode 100644 index 0000000000..3f68d0b567 --- /dev/null +++ b/Task/Substring/Maple/substring-2.maple @@ -0,0 +1,5 @@ +> s[ n .. -1 ] = s[ n .. ]; + "e Higher, The Fewer!" = "e Higher, The Fewer!" + +> StringTools:-Drop( s, n - 1 ); + "e Higher, The Fewer!" diff --git a/Task/Substring/Maple/substring-3.maple b/Task/Substring/Maple/substring-3.maple new file mode 100644 index 0000000000..2c00c630af --- /dev/null +++ b/Task/Substring/Maple/substring-3.maple @@ -0,0 +1,5 @@ +> s[ 1 .. -2 ] = s[ .. -2 ]; +"The Higher, The Fewer" = "The Higher, The Fewer" + +> StringTools:-Chop( s ); + "The Higher, The Fewer" diff --git a/Task/Substring/Maple/substring-4.maple b/Task/Substring/Maple/substring-4.maple new file mode 100644 index 0000000000..dacb73ef2b --- /dev/null +++ b/Task/Substring/Maple/substring-4.maple @@ -0,0 +1,7 @@ +> pos := searchtext( ",", s ): +> s[ pos .. pos + m - 1 ]; + ", The" + +> pos := searchtext( "Higher", s ): +> s[ pos .. pos + m - 1 ]; + "Highe" diff --git a/Task/Substring/Prolog/substring-1.pro b/Task/Substring/Prolog/substring-1.pro new file mode 100644 index 0000000000..592f40aa07 --- /dev/null +++ b/Task/Substring/Prolog/substring-1.pro @@ -0,0 +1,17 @@ +substring_task(Str, N, M, Char, SubStr) :- + sub_string(Str, N, M, _, Span), + sub_string(Str, N, _, 0, ToEnd), + sub_string(Str, 0, _, 1, MinusLast), + string_from_substring_to_m(Str, Char, M, FromCharToMth), + string_from_substring_to_m(Str, SubStr, M, FromSubToM), + maplist( writeln, + [ 'from n to m ':Span, + 'from n to end ': ToEnd, + 'string minus last char ': MinusLast, + 'form known char to m ': FromCharToMth, + 'from known substring to m ': FromSubToM ]). + + +string_from_substring_to_m(String, Sub, M, FromSubToM) :- + sub_string(String, Before, _, _, Sub), + sub_string(String, Before, M, _, FromSubToM). diff --git a/Task/Substring/Prolog/substring-2.pro b/Task/Substring/Prolog/substring-2.pro new file mode 100644 index 0000000000..7f6691755e --- /dev/null +++ b/Task/Substring/Prolog/substring-2.pro @@ -0,0 +1,7 @@ +?- substring_task("abcdefghijk", 2, 4, "d", "ef"). +from n to m :cdef +from n to end :cdefghijk +string minus last char :abcdefghij +form known char to m :defg +from known substring to m :efgh +true diff --git a/Task/Substring/RPG/substring.rpg b/Task/Substring/RPG/substring.rpg new file mode 100644 index 0000000000..21aa3a531a --- /dev/null +++ b/Task/Substring/RPG/substring.rpg @@ -0,0 +1,25 @@ + * 1...5....1....5....2....5.. + D myString S 30 inz('Liebe bewegt das Universum!') + D output S 30 inz('') + D n S 2 0 inz(1) + D m S 2 0 inz(5) + D length S 2 0 inz(0) + D find S 2 0 inz(0) + + /free + *inlr = *on; + dsply %subst(myString:n:m); + dsply %subst(myString:7:20); + + length = %len(%trim(myString)); + dsply %subst(myString:1:length-1); + + find = %scan('U':myString); + dsply %subst(myString:find:9); + + find = %scan('bewegt':myString); + dsply %subst(myString:find:%len('bewegt')); + + output = ' *** end *** '; + dsply ' ' ' ' output; + /end-free diff --git a/Task/Substring/Scala/substring.scala b/Task/Substring/Scala/substring.scala index f4b3fee1b6..753f69bf41 100644 --- a/Task/Substring/Scala/substring.scala +++ b/Task/Substring/Scala/substring.scala @@ -6,14 +6,15 @@ object Substring { // 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)) + assert("life is one insp" == str.dropWhile(_ != '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) }) diff --git a/Task/Subtractive-generator/00DESCRIPTION b/Task/Subtractive-generator/00DESCRIPTION index 1077491747..6b0d9780fa 100644 --- a/Task/Subtractive-generator/00DESCRIPTION +++ b/Task/Subtractive-generator/00DESCRIPTION @@ -1,4 +1,5 @@ -A ''subtractive generator'' calculates a sequence of [[random number generator|random numbers]], where each number is congruent to the subtraction of two previous numbers from the sequence. The formula is +A ''subtractive generator'' calculates a sequence of [[random number generator|random numbers]], where each number is congruent to the subtraction of two previous numbers from the sequence.
    +The formula is * r_n = r_{(n - i)} - r_{(n - j)} \pmod m diff --git a/Task/Subtractive-generator/Fortran/subtractive-generator.f b/Task/Subtractive-generator/Fortran/subtractive-generator.f new file mode 100644 index 0000000000..b93c73dc48 --- /dev/null +++ b/Task/Subtractive-generator/Fortran/subtractive-generator.f @@ -0,0 +1,56 @@ +module subgenerator + implicit none + + integer, parameter :: modulus = 1000000000 + integer :: s(0:54), r(0:54) + +contains + +subroutine initgen(seed) + integer :: seed + integer :: n, rnum + + s(0) = seed + s(1) = 1 + + do n = 2, 54 + s(n) = mod(s(n-2) - s(n-1), modulus) + if (s(n) < 0) s(n) = s(n) + modulus + end do + + do n = 0, 54 + r(n) = s(mod(34*(n+1), 55)) + end do + + do n = 1, 165 + rnum = subrand() + end do + +end subroutine initgen + +integer function subrand() + integer, save :: p1 = 0 + integer, save :: p2 = 31 + + r(p1) = mod(r(p1) - r(p2), modulus) + if (r(p1) < 0) r(p1) = r(p1) + modulus + subrand = r(p1) + p1 = mod(p1 + 1, 55) + p2 = mod(p2 + 1, 55) + +end function subrand +end module subgenerator + +program subgen_test + use subgenerator + implicit none + + integer :: seed = 292929 + integer :: i + + call initgen(seed) + do i = 1, 10 + write(*,*) subrand() + end do + +end program diff --git a/Task/Subtractive-generator/REXX/subtractive-generator.rexx b/Task/Subtractive-generator/REXX/subtractive-generator.rexx index 01105e5289..44852b3dff 100644 --- a/Task/Subtractive-generator/REXX/subtractive-generator.rexx +++ b/Task/Subtractive-generator/REXX/subtractive-generator.rexx @@ -1,23 +1,23 @@ -/*REXX pgm uses a subtractive generator, creates a seq of random numbers*/ -numeric digits 20; billion = 10**9; s.0 = 292929; s.1 = 1 -cI = 55; cJ = 24; cP = 34 - do i=2 to cI-1 - s.i=mod(s(i-2)-s(i-1),billion) - end /*i*/ - do j=0 to cI-1 - r.j = s(mod(cP*(j+1),cI)) - end /*j*/ - -m=219; do k=cI to m; x=k//cI - r.x = mod(r(mod(k-cI,cI)) - r(mod(k-cJ,cI)),billion) - end /*m*/ - -t=235; do n=m+1 to t; y=n//cI - r.y = mod(r(mod(n-cI,cI)) - r(mod(n-cJ,cI)),billion) - say right(r.y,40) - end /*n*/ +/*REXX pgm uses a subtractive generator, creates a sequence of random #s*/ +numeric digits 20; s.0=292929; s.1=1; billion=10**9 +cI=55; cJ=24; cP=34; billion=1e9 /*same*/ + do i=2 to cI-1 + s.i=mod(s(i-2) - s(i-1), billion) + end /*i*/ + do j=0 to cI-1 + r.j=s(mod(cP*(j+1), cI)) + end /*j*/ +m=219 + do k=cI to m; x=k//cI + r.x=mod(r(mod(k-cI, cI)) - r(mod(k-cJ, cI)), billion) + end /*m*/ +t=235 + do n=m+1 to t; y=n//cI + r.y=mod(r(mod(n-cI, cI)) - r(mod(n-cJ, cI)), billion) + say right(r.y, 40) + end /*n*/ exit /*stick a fork in it, we're done.*/ -/*──────────────────────────────────subroutines─────────────────────────*/ -r: parse arg _; return r._ -s: parse arg _; return s._ -mod: procedure; arg a,b; return ((a // b) + b) // b +/*──────────────────────────────────one─liner subroutines───────────────*/ +mod: procedure; parse arg a,b; return ((a // b) + b) // b +r: parse arg _; return r._ +s: parse arg _; return s._ diff --git a/Task/Sudoku/00DESCRIPTION b/Task/Sudoku/00DESCRIPTION index 4bf99beaa5..0246fc119a 100644 --- a/Task/Sudoku/00DESCRIPTION +++ b/Task/Sudoku/00DESCRIPTION @@ -1 +1,2 @@ -Solve a partially filled-in normal 9x9 [[wp:Sudoku|Sudoku]] grid and display the result in a human-readable format. [[wp:Algorithmics_of_sudoku|Algorithmics of Sudoku]] may help implement this. +Solve a partially filled-in normal 9x9 [[wp:Sudoku|Sudoku]] grid and display the result in a human-readable format. +[[wp:Algorithmics_of_sudoku|Algorithmics of Sudoku]] may help implement this. diff --git a/Task/Sudoku/Clojure/sudoku-1.clj b/Task/Sudoku/Clojure/sudoku-1.clj index 492cdebe8a..98d6390eaa 100644 --- a/Task/Sudoku/Clojure/sudoku-1.clj +++ b/Task/Sudoku/Clojure/sudoku-1.clj @@ -1,41 +1,24 @@ -(ns sudoku - (:use [clojure.contrib.math :only (sqrt)])) +(ns rosettacode.sudoku + (:use [clojure.pprint :only (cl-format)])) -(defn print-grid [grid] - (doseq [y (range (count grid))] - (doseq [x (range (count grid))] - (print (retrieve grid x y) " ")) - (println)) - (println)) +(defn- compatible? [m x y n] + (let [n= #(= n (get-in m [%1 %2]))] + (or (n= y x) + (let [c (count m)] + (and (zero? (get-in m [y x])) + (not-any? #(or (n= y %) (n= % x)) (range c)) + (let [zx (* c (quot x c)), zy (* c (quot y c))] + (every? false? + (map n= (range zy (+ zy c)) (range zx (+ zx c)))))))))) -(defn retrieve [grid x y] - (get (get grid y) x)) - -(defn store [grid x y n] - (assoc grid y (assoc (get grid y) x n))) - -(defn coordinates [grid x y] - (let [n (sqrt (count grid)) - zx (* n (quot x n)) - zy (* n (quot y n))] - (for [x (range zx (+ zx n)) y (range zy (+ zy n))] - [x y]))) - -(defn compatible? [grid x y n] - (or - (= n (retrieve grid x y)) - (and - (zero? (retrieve grid x y)) - (every? #(and (not= n (retrieve grid % y)) (not= n (retrieve grid x %))) (range (count grid))) - (every? #(not= n (retrieve grid (first %) (second %))) (coordinates grid x y))))) - -(defn solve [grid x y] - (let [m (count grid)] - (if (= y m) - (print-grid grid) - (doseq [n (range 1 (inc m))] - (when (compatible? grid x y n) - (let [new-grid (store grid x y n)] - (if (= x (dec m)) - (solve new-grid 0 (inc y)) - (solve new-grid (inc x) y)))))))) +(defn solve [m] + (let [c (count m)] + (loop [m m, x 0, y 0] + (if (= y c) m + (let [ng (->> (range 1 c) + (filter #(compatible? m x y %)) + first + (assoc-in m [y x]))] + (if (= x (dec c)) + (recur ng 0 (inc y)) + (recur ng (inc x) y))))))) diff --git a/Task/Sudoku/Clojure/sudoku-2.clj b/Task/Sudoku/Clojure/sudoku-2.clj index 8f26b9a99e..5916955f3e 100644 --- a/Task/Sudoku/Clojure/sudoku-2.clj +++ b/Task/Sudoku/Clojure/sudoku-2.clj @@ -1,13 +1,13 @@ -sudoku> (solve [[3 9 4 0 0 2 6 7 0] - [0 0 0 3 0 0 4 0 0] - [5 0 0 6 9 0 0 2 0] - [0 4 5 0 0 0 9 0 0] - [6 0 0 0 0 0 0 0 7] - [0 0 7 0 0 0 5 8 0] - [0 1 0 0 6 7 0 0 8] - [0 0 9 0 0 8 0 0 0] - [0 2 6 4 0 0 7 3 5]] - 0 0) +sudoku>(cl-format true "~{~{~a~^ ~}~%~}" + (solve [[3 9 4 0 0 2 6 7 0] + [0 0 0 3 0 0 4 0 0] + [5 0 0 6 9 0 0 2 0] + [0 4 5 0 0 0 9 0 0] + [6 0 0 0 0 0 0 0 7] + [0 0 7 0 0 0 5 8 0] + [0 1 0 0 6 7 0 0 8] + [0 0 9 0 0 8 0 0 0] + [0 2 6 4 0 0 7 3 5]]) 3 9 4 8 5 2 6 7 1 2 6 8 3 7 1 4 5 9 5 7 1 6 9 4 8 2 3 diff --git a/Task/Sudoku/Curry/sudoku.curry b/Task/Sudoku/Curry/sudoku-1.curry similarity index 100% rename from Task/Sudoku/Curry/sudoku.curry rename to Task/Sudoku/Curry/sudoku-1.curry diff --git a/Task/Sudoku/Curry/sudoku-2.curry b/Task/Sudoku/Curry/sudoku-2.curry new file mode 100644 index 0000000000..9c0f6ac4ee --- /dev/null +++ b/Task/Sudoku/Curry/sudoku-2.curry @@ -0,0 +1,34 @@ +import CLPFD +import Constraint (allC) +import List (transpose) + + +sudoku :: [[Int]] -> Success +sudoku rows = + domain (concat rows) 1 9 + & different rows + & different (transpose rows) + & different blocks + & labeling [] (concat rows) + where + different = allC allDifferent + + blocks = [concat ys | xs <- each3 rows + , ys <- transpose $ map each3 xs + ] + each3 xs = case xs of + (x:y:z:rest) -> [x,y,z] : each3 rest + rest -> [rest] + + +test = [ [_,_,3,_,_,_,_,_,_] + , [4,_,_,_,8,_,_,3,6] + , [_,_,8,_,_,_,1,_,_] + , [_,4,_,_,6,_,_,7,3] + , [_,_,_,9,_,_,_,_,_] + , [_,_,_,_,_,2,_,_,5] + , [_,_,4,_,7,_,_,6,8] + , [6,_,_,_,_,_,_,_,_] + , [7,_,_,6,_,_,5,_,_] + ] +main | sudoku xs = xs where xs = test diff --git a/Task/Sudoku/D/sudoku.d b/Task/Sudoku/D/sudoku-1.d similarity index 82% rename from Task/Sudoku/D/sudoku.d rename to Task/Sudoku/D/sudoku-1.d index 67350729db..4ce4d8cc2d 100644 --- a/Task/Sudoku/D/sudoku.d +++ b/Task/Sudoku/D/sudoku-1.d @@ -1,21 +1,14 @@ import std.stdio, std.range, std.string, std.algorithm, std.array, - std.typetuple, std.ascii, std.typecons; - -template Range(size_t stop) { // For loop unrolling. - static if (stop == 0) - alias TypeTuple!() Range; - else - alias TypeTuple!(Range!(stop - 1), stop - 1) Range; -} + std.ascii, std.typecons; struct Digit { immutable char d; - this(in char d_) pure nothrow + this(in char d_) pure nothrow @safe @nogc in { assert(d_ >= '0' && d_ <= '9'); } body { this.d = d_; } - this(in int d_) pure nothrow + this(in int d_) pure nothrow @safe @nogc in { assert(d_ >= '0' && d_ <= '9'); } body { this.d = cast(char)d_; } // Required cast. @@ -34,30 +27,31 @@ pure nothrow { problem[].map!(c => c - '0').copy(grid[]); // DMD doesn't inline this function. Performance loss. - Tgrid access(in size_t x, in size_t y) nothrow { + Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc { return grid[y * sudokuSide + x]; } // DMD doesn't inline this function. If you want to retain // the same performance as the C++ entry and you use the DMD // compiler then this function must be manually inlined. - bool checkValidity(in Tgrid val, in size_t x, in size_t y) nothrow { - /*static*/ foreach (immutable i; Range!sudokuSide) + bool checkValidity(in Tgrid val, in size_t x, in size_t y) + pure nothrow @safe @nogc { + /*static*/ foreach (immutable i; staticIota!(0, sudokuSide)) if (access(i, y) == val || access(x, i) == val) return false; immutable startX = (x / sudokuUnitSide) * sudokuUnitSide; immutable startY = (y / sudokuUnitSide) * sudokuUnitSide; - /*static*/ foreach (immutable i; Range!sudokuUnitSide) - /*static*/ foreach (immutable j; Range!sudokuUnitSide) + /*static*/ foreach (immutable i; staticIota!(0, sudokuUnitSide)) + /*static*/ foreach (immutable j; staticIota!(0, sudokuUnitSide)) if (access(startX + j, startY + i) == val) return false; return true; } - bool canPlaceNumbers(in size_t pos=0) nothrow { + bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc { if (pos == SudokuTable.length) return true; if (grid[pos] > 0) @@ -87,7 +81,7 @@ pure nothrow { } string representSudoku(in ref SudokuTable sudo) -pure nothrow out(result) { +pure nothrow @safe out(result) { assert(result.countchars("1-9") == sudo[].count!q{a != '0'}); assert(result.countchars(".") == sudo[].count!q{a == '0'}); } body { diff --git a/Task/Sudoku/D/sudoku-2.d b/Task/Sudoku/D/sudoku-2.d new file mode 100644 index 0000000000..de1c3526bb --- /dev/null +++ b/Task/Sudoku/D/sudoku-2.d @@ -0,0 +1,34 @@ +import std.stdio, std.algorithm, std.range; + +const(int)[] solve(immutable int[] s) pure nothrow @safe { + immutable i = s.countUntil(0); + if (i == -1) + return s; + + enum B = (int i, int j) => i / 27 ^ j / 27 | (i%9 / 3 ^ j%9 / 3); + immutable c = iota(81) + .filter!(j => !((i - j) % 9 * (i/9 ^ j/9) * B(i, j))) + .map!(j => s[j]).array; + + foreach (immutable v; 1 .. 10) + if (!c.canFind(v)) { + const r = solve(s[0 .. i] ~ v ~ s[i + 1 .. $]); + if (!r.empty) + return r; + } + return null; +} + +void main() { + immutable problem = [ + 8, 5, 0, 0, 0, 2, 4, 0, 0, + 7, 2, 0, 0, 0, 0, 0, 0, 9, + 0, 0, 4, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 7, 0, 0, 2, + 3, 0, 5, 0, 0, 0, 9, 0, 0, + 0, 4, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 0, 0, 7, 0, + 0, 1, 7, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 3, 6, 0, 4, 0]; + writefln("%(%s\n%)", problem.solve.chunks(9)); +} diff --git a/Task/Sudoku/D/sudoku-3.d b/Task/Sudoku/D/sudoku-3.d new file mode 100644 index 0000000000..73bcb756eb --- /dev/null +++ b/Task/Sudoku/D/sudoku-3.d @@ -0,0 +1,42 @@ +import std.stdio, std.algorithm, std.range, std.typecons; + +Nullable!(const ubyte[81]) solve(in ubyte[81] s) pure nothrow @safe @nogc { + immutable i = s[].countUntil(0); + if (i == -1) + return typeof(return)(s); + + static immutable B = (in int i, in int j) pure nothrow @safe @nogc => + i / 27 ^ j / 27 | (i % 9 / 3 ^ j % 9 / 3); + + ubyte[81] c = void; + size_t len = 0; + foreach (immutable int j; 0 .. c.length) + if (!((i - j) % 9 * (i/9 ^ j/9) * B(i, j))) + c[len++] = s[j]; + + foreach (immutable ubyte v; 1 .. 10) + if (!c[0 .. len].canFind(v)) { + ubyte[81] s2 = void; + s2[0 .. i] = s[0 .. i]; + s2[i] = v; + s2[i + 1 .. $] = s[i + 1 .. $]; + const r = solve(s2); + if (!r.isNull) + return typeof(return)(r); + } + return typeof(return)(); +} + +void main() { + immutable ubyte[81] problem = [ + 8, 5, 0, 0, 0, 2, 4, 0, 0, + 7, 2, 0, 0, 0, 0, 0, 0, 9, + 0, 0, 4, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 1, 0, 7, 0, 0, 2, + 3, 0, 5, 0, 0, 0, 9, 0, 0, + 0, 4, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 0, 0, 7, 0, + 0, 1, 7, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 3, 6, 0, 4, 0]; + writefln("%(%s\n%)", problem.solve.get[].chunks(9)); +} diff --git a/Task/Sudoku/Delphi/sudoku-1.delphi b/Task/Sudoku/Delphi/sudoku-1.delphi index e5bb268c76..ff359fff55 100644 --- a/Task/Sudoku/Delphi/sudoku-1.delphi +++ b/Task/Sudoku/Delphi/sudoku-1.delphi @@ -9,7 +9,7 @@ type function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean; function ToString: string; reintroduce; - procedure PlaceNumber(pos: Integer); + function PlaceNumber(pos: Integer): Boolean; public constructor Create(s: string); @@ -79,15 +79,19 @@ begin Result := sb; end; -procedure TSudokuSolver.PlaceNumber(pos: Integer); +function TSudokuSolver.PlaceNumber(pos: Integer): Boolean; var n: Integer; begin + Result := False; if Pos = 81 then - raise Exception.Create('Finished!'); + begin + Result := True; + Exit; + end; if FGrid[pos] > 0 then begin - PlaceNumber(Succ(pos)); + Result := PlaceNumber(Succ(pos)); Exit; end; for n := 1 to 9 do @@ -95,8 +99,9 @@ begin if CheckValidity(n, pos mod 9, pos div 9) then begin FGrid[pos] := n; - PlaceNumber(Succ(pos)); - FGrid[pos] := 0; + Result := PlaceNumber(Succ(pos)); + if not Result then + FGrid[pos] := 0; end; end; end; @@ -112,11 +117,9 @@ end; procedure TSudokuSolver.Solve; begin - try - PlaceNumber(0); + if not PlaceNumber(0) then ShowMessage('Unsolvable'); - except - ShowMessage((ExceptObject as Exception).Message); - ShowMessage(ToString); + else + ShowMessage('Solved!'); end; end; diff --git a/Task/Sudoku/PL-I/sudoku-1.pli b/Task/Sudoku/PL-I/sudoku-1.pli new file mode 100644 index 0000000000..6d1be3be4b --- /dev/null +++ b/Task/Sudoku/PL-I/sudoku-1.pli @@ -0,0 +1,83 @@ +sudoku: procedure options (main); /* 27 July 2014 */ + + declare grid (9,9) fixed (1) static initial ( + 0, 0, 3, 0, 2, 0, 6, 0, 0, + 9, 0, 0, 3, 0, 5, 0, 0, 1, + 0, 0, 1, 8, 0, 6, 4, 0, 0, + 0, 0, 8, 1, 0, 2, 9, 0, 0, + 7, 0, 0, 0, 0, 0, 0, 0, 8, + 0, 0, 6, 7, 0, 8, 2, 0, 0, + 0, 0, 2, 6, 0, 9, 5, 0, 0, + 8, 0, 0, 2, 0, 3, 0, 0, 9, + 0, 0, 5, 0, 1, 0, 3, 0, 0 ); + + declare grid_solved (9,9) fixed (1); + + call print_sudoku (grid); + call solve (1, 1); + put skip (2); + call print_sudoku (grid_solved); + +solve: procedure (i, j) recursive options (reorder); + declare (i, j) fixed binary; + declare (n, n_tmp) fixed binary; + + if i > 9 then + grid_solved = grid; + else + do n = 1 to 9; + if is_safe (i, j, n) then + do; + n_tmp = grid (i, j); + grid (i, j) = n; + if j = 9 then + call solve (i + 1, 1); + else + call solve (i, j + 1); + grid (i, j) = n_tmp; + end; + end; + + end solve; + +is_safe: procedure (i, j, n) returns (bit(1) aligned) options (reorder); + declare (i, j, n) fixed binary; + declare (true value ('1'b), false value ('0'b) ) bit (1); + declare (i_min, j_min, ii, jj) fixed binary; + declare kk bit(1) aligned; + + if grid (i, j) = n then return (true); + if grid (i, j) ^= 0 then return (false); + if any (grid (i, *) = n) then return (false); + if any (grid (*, j) = n) then return (false); + + /* i_min and j_min are the co-ordinates of the top left-hand corner */ + /* of 3 x 3 grid in which element (i,j) exists. */ + i_min = 1 + 3 * trunc((i - 1) / 3); + j_min = 1 + 3 * trunc((j - 1) / 3); + + begin; + declare sub_grid(3,3) fixed (1) defined grid(1sub+i_min-1,2sub+j_min-1); + + kk = true; + if any(sub_grid = n) then kk = false; + end; + return (kk); + end is_safe; + +print_sudoku: procedure (grid); + declare grid (*,*) fixed (1); + declare ( i, j, ii) fixed binary; + declare bar character (19) initial ( '+-----+-----+-----+' ); + declare frame (9) character (1) initial (' ', ' ', '|', ' ', ' ', '|', ' ', ' ', '|' ); + + put skip list (bar); + do i = 1 to 7 by 3; + do ii = i to i + 2; + put skip edit ( '|', (grid (ii, j), frame(j) do j = 1 to 9) ) (a, f(1)); + end; + put skip list (bar); + end; + end print_sudoku; + +end sudoku; diff --git a/Task/Sudoku/PL-I/sudoku-2.pli b/Task/Sudoku/PL-I/sudoku-2.pli new file mode 100644 index 0000000000..67e83aa032 --- /dev/null +++ b/Task/Sudoku/PL-I/sudoku-2.pli @@ -0,0 +1,138 @@ +*PROCESS MARGINS(1,120) LIBS(SINGLE,STATIC); +*PROCESS OPTIMIZE(2) DFT(REORDER); + + + sudoku: proc(parms) options(main); + dcl parms char (100) var; + + define alias bits bit (9) aligned; + dcl total (81) type bits; + dcl matrix (9, 9) type bits based(addr(total)); + dcl box (9, 3, 3) type bits defined (total(trunc((1sub-1) /3) * 27 + mod(1sub-1, 3) * 3 + (2sub-1) * 9 + 3sub)); + + dcl posbit (0:9) type bits init('000000000'b, '100000000'b, '010000000'b, '001000000'b, + '000100000'b, '000010000'b, '000001000'b, '000000100'b, + '000000010'b, '000000001'b); + + dcl (i, j, k) fixed bin(31); + dcl (start, finish) float(18); + dcl result fixed dec(5,3); + + dcl buffer char(81); + dcl in file; + + /* ON UNIT for the Sudoku data conversion */ + on conversion + begin; + put skip + list('Sudoku data not valid.'); + stop; + end; + + /* ON UNIT to display info about the usage */ + on undefinedfile(in) + begin; + put skip + list('Usage: ' || procedurename() || ' /filename'); + stop; + end; + + open file(in) + title ('/'||parms||',type(fixed), recsize(81)') record input; + + /* Ignore the endfile condition */ + on endfile(in); + + /* Read the Sudoku data into buffer as one record */ + read file(in) into(buffer); + close file(in); + + /* Convert numbers -> position bit presentation and assign into the Sudoku board */ + do k = 1 to 81; + total(k) = posbit(substr(buffer, k, 1)); + end; + + /* Start solving the Sudoku */ + start = secs(); + if solve() then + do; + finish = secs(); + result = finish - start + 0.0005; + put skip list('Sudoku solved! Time: ' || trim(result) || ' seconds'); + put skip(2); + + /* display the solved Sudoku if solution exist */ + do i = 1 to 9; + do j = 1 to 9; + put edit(trim(index(matrix(i, j), '1'b))) (a(3)); + end; + put skip(2); + end; + end; + else put skip list('Impossible!'); + + + /*************************************/ + /* Simple backtracking sudoku solver */ + /*************************************/ + solve: proc recursive returns(bit(1)); + dcl (i, j, k) fixed bin(31); + dcl result type bits; + + /* find free cell */ + do i = 1 to 9; + do j = 1 to 9; + if matrix(i, j) = posbit(0) then goto skip; + end; + end; + + /* No more free cells. Check if the completed Sudoku is valid. */ + /* Number in the cell is valid if the matching position bit is set. */ + do i = 1 to 9; + do j = 1 to 9; + k = index(matrix(i, j), '1'b); + matrix(i, j) = posbit(0); + result = ^(any(matrix(i, *)) | any(matrix(*, j)) | any(box(numbox(i, j), *, *))); + if substr(result, k, 1) = '0'b then return('0'b); + matrix(i, j) = posbit(k); + end; + end; + + return('1'b); + skip: + + /* Go through and test possible values for the free cell untill the Sudoku is completed */ + result = ^(any(matrix(i, *)) | any(matrix(*, j)) | any(box(numbox(i, j), *, *))); + k = 0; + do forever; + k = search(result, '1'b, k+1); + if k = 0 then leave; + matrix(i, j) = posbit(k); + if solve() then return('1'b); + else matrix(i, j) = posbit(0); + end; + + return('0'b); + end solve; + + + /********************************************/ + /* Returns box number for the sudoku coords */ + /********************************************/ + numbox: proc(i, j) returns(fixed bin(31)); + dcl (i, j) fixed bin(31); + + dcl lookup (9, 9) fixed bin(31) static init( (3)1, (3)2, (3)3, + (3)1, (3)2, (3)3, + (3)1, (3)2, (3)3, + (3)4, (3)5, (3)6, + (3)4, (3)5, (3)6, + (3)4, (3)5, (3)6, + (3)7, (3)8, (3)9, + (3)7, (3)8, (3)9, + (3)7, (3)8, (3)9 ); + + return(lookup(i, j)); + end numbox; + + end sudoku; diff --git a/Task/Sudoku/Perl-6/sudoku.pl6 b/Task/Sudoku/Perl-6/sudoku-1.pl6 similarity index 100% rename from Task/Sudoku/Perl-6/sudoku.pl6 rename to Task/Sudoku/Perl-6/sudoku-1.pl6 diff --git a/Task/Sudoku/Perl-6/sudoku-2.pl6 b/Task/Sudoku/Perl-6/sudoku-2.pl6 new file mode 100644 index 0000000000..687997ca38 --- /dev/null +++ b/Task/Sudoku/Perl-6/sudoku-2.pl6 @@ -0,0 +1,224 @@ +#!/usr/bin/env perl6 +use v6; +# +# In this code, a sudoku puzzle is represented as a two-dimentional +# array. The cells that are not yet solved are represented by yet +# another array of all the possible values. +# +# This implementation is not a simple brute force evaluation of all +# the options, but rather makes four extra attempts to guide the +# solution: +# +# 1) For every change in the grid, usually made by an attempt at a +# solution, we will reduce the search space of the possible values +# in all the other cells before going forward. +# +# 2) When a cell that is not yet resolved is the only one that can +# hold a specific value, resolve it immediately instead of +# performing the regular search. +# +# 3) Instead of trying from cell 1,1 and moving in sequence, this +# implementation will start trying on the cell that is the closest +# to being solved already. +# +# 4) Instead of trying all possible values in sequence, start with +# the value that is the most unique. I.e.: If the options for this +# cell are 1,4,6 and 6 is only a candidate for two of the +# competing cells, we start with that one. +# + +# keep a list with all the cells, handy for traversal +my @cells = do for 0..8 X 0..8 -> $x, $y { [ $x, $y ] }; + +# +# Try to solve this puzzle and return the resolved puzzle if it is at +# all solvable in this configuration. +sub solve($sudoku, Int $level) { + # cleanup the impossible values first, + if (cleanup-impossible-values($sudoku, $level)) { + # try to find implicit answers + while (find-implicit-answers($sudoku, $level)) { + # and every time you find some, re-do the cleanup and try again + cleanup-impossible-values($sudoku, $level); + } + # Now let's actually try to solve a new value. But instead of + # going in sequence, we select the cell that is the closest to + # being solved already. This will reduce the overall number of + # guesses. + for sort { solution-complexity-factor($sudoku, $_[0], $_[1]) }, + grep { $sudoku[$_[0]][$_[1]] ~~ Array }, + @cells -> $cell + { + my Int ($x, $y) = @($cell); + # Now let's try the possible values in the order of + # uniqueness. + for sort { matches-in-competing-cells($sudoku, $x, $y, $_) }, @($sudoku[$x][$y]) -> $val { + trace $level, "Trying $val on "~($x+1)~","~($y+1)~" "~$sudoku[$x][$y].perl; + my $solution = clone-sudoku($sudoku); + $solution[$x][$y] = $val; + my $solved = solve($solution, $level+1); + if $solved { + trace $level, "Solved... ($val on "~($x+1)~","~($y+1)~")"; + return $solved; + } + } + # if we fell through, it means that we found no valid + # value for this cell + trace $level, "Backtrack, path unsolvable... (on "~($x+1)~" "~($y+1)~")"; + return 0; + } + # all cells are already solved. + return $sudoku; + } else { + # if the cleanup failed, it means this is an invalid grid. + return False; + } +} + +# This function reduces the search space from values that are already +# assigned to competing cells. +sub cleanup-impossible-values($sudoku, Int $level = 1) { + my Bool $resolved; + repeat { + $resolved = False; + for grep { $sudoku[$_[0]][$_[1]] ~~ Array }, + @cells -> $cell { + my Int ($x, $y) = @($cell); + # which block is this cell in + my Int $bx = Int($x / 3); + my Int $by = Int($y / 3); + + # A unfilled cell is not resolved, so it shouldn't match + my multi match-resolved-cell(Array $other, Int $this) { + return 0; + } + my multi match-resolved-cell(Int $other, Int $this) { + return $other == $this; + } + + # Reduce the possible values to the ones that are still + # valid + my @r = + grep { !match-resolved-cell($sudoku[any(0..2)+3*$bx][any(0..2)+3*$by], $_) }, # same block + grep { !match-resolved-cell($sudoku[any(0..8)][$y], $_) }, # same line + grep { !match-resolved-cell($sudoku[$x][any(0..8)], $_) }, # same column + @($sudoku[$x][$y]); + if (@r.elems == 1) { + # if only one element is left, then make it resolved + $sudoku[$x][$y] = @r[0]; + $resolved = True; + } elsif (@r.elems == 0) { + # This is an invalid grid + return 0; + } else { + $sudoku[$x][$y] = @r; + } + } + } while $resolved; # repeat if there was any change + return 1; +} + +sub solution-complexity-factor($sudoku, Int $x, Int $y) { + my Int $bx = Int($x / 3); # this block + my Int $by = Int($y / 3); + my multi count-values(Array $val) { + return $val.elems; + } + my multi count-values(Int $val) { + return 1; + } + # the number of possible values should take precedence + my Int $f = 1000 * count-values($sudoku[$x][$y]); + for 0..2 X 0..2 -> $lx, $ly { + $f += count-values($sudoku[$lx+$bx*3][$ly+$by*3]) + } + for 0..^($by*3), (($by+1)*3)..8 -> $ly { + $f += count-values($sudoku[$x][$ly]) + } + for 0..^($bx*3), (($bx+1)*3)..8 -> $lx { + $f += count-values($sudoku[$lx][$y]) + } + return $f; +} + +sub matches-in-competing-cells($sudoku, Int $x, Int $y, Int $val) { + my Int $bx = Int($x / 3); # this block + my Int $by = Int($y / 3); + # Function to decide which possible value to try first + my multi cell-matching(Int $cell) { + return $val == $cell ?? 1 !! 0; + } + my multi cell-matching(Array $cell) { + return $cell.grep({ $val == $_ }) ?? 1 !! 0; + } + my Int $c = 0; + for 0..2 X 0..2 -> $lx, $ly { + $c += cell-matching($sudoku[$lx+$bx*3][$ly+$by*3]) + } + for 0..^($by*3), (($by+1)*3)..8 -> $ly { + $c += cell-matching($sudoku[$x][$ly]) + } + for 0..^($bx*3), (($bx+1)*3)..8 -> $lx { + $c += cell-matching($sudoku[$lx][$y]) + } + return $c; +} + +sub find-implicit-answers($sudoku, Int $level) { + my Bool $resolved = False; + for grep { $sudoku[$_[0]][$_[1]] ~~ Array }, + @cells -> $cell { + my Int ($x, $y) = @($cell); + for @($sudoku[$x][$y]) -> $val { + # If this is the only cell with this val as a possibility, + # just make it resolved already + if (matches-in-competing-cells($sudoku, $x, $y, $val) == 1) { + $sudoku[$x][$y] = $val; + $resolved = True; + } + } + } + return $resolved; +} + +my $puzzle = + map { [ map { $_ == 0 ?? [1..9] !! $_+0 }, @($_) ] }, + [ 0,0,0,0,3,7,6,0,0 ], + [ 0,0,0,6,0,0,0,9,0 ], + [ 0,0,8,0,0,0,0,0,4 ], + [ 0,9,0,0,0,0,0,0,1 ], + [ 6,0,0,0,0,0,0,0,9 ], + [ 3,0,0,0,0,0,0,4,0 ], + [ 7,0,0,0,0,0,8,0,0 ], + [ 0,1,0,0,0,9,0,0,0 ], + [ 0,0,2,5,4,0,0,0,0 ]; + +my $solved = solve($puzzle, 0); +if $solved { + print-sudoku($solved,0); +} else { + say "unsolvable."; +} + +# Utility functions, not really part of the solution + +sub trace(Int $level, Str $message) { + say '.' x $level, $message; +} + +sub clone-sudoku($sudoku) { + my $clone; + for 0..8 X 0..8 -> $x, $y { + $clone[$x][$y] = $sudoku[$x][$y]; + } + return $clone; +} + +sub print-sudoku($sudoku, Int $level = 1) { + trace $level, '-' x 5*9; + for @($sudoku) -> $row { + trace $level, join " ", do for @($row) -> $cell { + $cell ~~ Array ?? "#{$cell.elems}#" !! " $cell " + } + } +} diff --git a/Task/Sudoku/Prolog/sudoku.pro b/Task/Sudoku/Prolog/sudoku-1.pro similarity index 100% rename from Task/Sudoku/Prolog/sudoku.pro rename to Task/Sudoku/Prolog/sudoku-1.pro diff --git a/Task/Sudoku/Prolog/sudoku-2.pro b/Task/Sudoku/Prolog/sudoku-2.pro new file mode 100644 index 0000000000..8f35989082 --- /dev/null +++ b/Task/Sudoku/Prolog/sudoku-2.pro @@ -0,0 +1,54 @@ +:- initialization(main). + + +solve(Rows) :- + maplist(domain_1_9, Rows) + , different(Rows) + , transpose(Rows,Cols), different(Cols) + , blocks(Rows,Blocks) , different(Blocks) + , maplist(fd_labeling, Rows) + . + +domain_1_9(Rows) :- fd_domain(Rows,1,9). +different(Rows) :- maplist(fd_all_different, Rows). + +blocks(Rows,Blocks) :- + maplist(split3,Rows,Xs), transpose(Xs,Ys) + , concat(Ys,Zs), concat_map(split3,Zs,Blocks) + . % where + split3([X,Y,Z|L],[[X,Y,Z]|R]) :- split3(L,R). + split3([],[]). + + +% utils/list +concat_map(F,Xs,Ys) :- call(F,Xs,Zs), maplist(concat,Zs,Ys). + +concat([],[]). +concat([X|Xs],Ys) :- append(X,Zs,Ys), concat(Xs,Zs). + +transpose([],[]). +transpose([[X]|Col], [[X|Row]]) :- transpose(Col,[Row]). +transpose([[X|Row]], [[X]|Col]) :- transpose([Row],Col). +transpose([[X|Row]|Xs], [[X|Col]|Ys]) :- + maplist(bind_head, Row, Ys, YX) + , maplist(bind_head, Col, Xs, XY) + , transpose(XY,YX) + . % where + bind_head(H,[H|T],T). + bind_head([],[],[]). + + +% tests +test([ [_,_,3,_,_,_,_,_,_] + , [4,_,_,_,8,_,_,3,6] + , [_,_,8,_,_,_,1,_,_] + , [_,4,_,_,6,_,_,7,3] + , [_,_,_,9,_,_,_,_,_] + , [_,_,_,_,_,2,_,_,5] + , [_,_,4,_,7,_,_,6,8] + , [6,_,_,_,_,_,_,_,_] + , [7,_,_,6,_,_,5,_,_] + ]). + +main :- test(T), solve(T), maplist(show,T), halt. +show(X) :- write(X), nl. diff --git a/Task/Sudoku/Ruby/sudoku.rb b/Task/Sudoku/Ruby/sudoku.rb index 1f148019fc..8f955aaf77 100644 --- a/Task/Sudoku/Ruby/sudoku.rb +++ b/Task/Sudoku/Ruby/sudoku.rb @@ -1,39 +1,28 @@ -def read_matrix(fh) - matrix = [] - - (0..8).each { |i| - l = fh.readline - matrix[i] = [] - (0..8).each { |j| - matrix[i][j] = l[j..j].to_i - } - } - matrix +def read_matrix(data) + lines = data.each_line.to_a # ver 2.0 later data.lines + 9.times.collect { |i| 9.times.collect { |j| lines[i][j].to_i } } end def permissible(matrix, i, j) - ok = [true] * 9 + ok = [nil, *1..9] # Same as another in the column isn't permissible... - (0..8).each { |i2| - next if matrix[i2][j] == 0 - ok[matrix[i2][j] - 1] = false - } + 9.times do |i2| + ok[matrix[i2][j]] = nil if matrix[i2][j].nonzero? + end # Same as another in the row isn't permissible... - (0..8).each { |j2| - next if matrix[i][j2] == 0 - ok[matrix[i][j2] - 1] = false - } + 9.times do |j2| + ok[matrix[i][j2]] = nil if matrix[i][j2].nonzero? + end # Same as another in the 3x3 block isn't permissible... - igroup = (i / 3) * 3 - jgroup = (j / 3) * 3 - (igroup..(igroup + 2)).each { |i2| - (jgroup..(jgroup + 2)).each { |j2| - next if matrix[i2][j2] == 0 - ok[matrix[i2][j2] - 1] = false - } - } - # Convert to the array format... - (1..9).select { |i2| ok[i2-1] } + irange = (ig = (i / 3) * 3) .. ig + 2 + jrange = (jg = (j / 3) * 3) .. jg + 2 + irange.each do |i2| + jrange.each do |j2| + ok[matrix[i2][j2]] = nil if matrix[i2][j2].nonzero? + end + end + # Gathering only permitted one + ok.compact end def deep_copy_sudoku(matrix) @@ -43,63 +32,55 @@ end def solve_sudoku(matrix) loop do options = [] - (0..8).each { |i| - (0..8).each { |j| - next if matrix[i][j] != 0 + 9.times do |i| + 9.times do |j| + next if matrix[i][j].nonzero? p = permissible(matrix, i, j) # If nothing is permissible, there is no solution at this level. - return nil if p.length == 0 - options.push({:i => i, :j => j, :permissible => p}) - } - } + return if p.empty? # return nil + options << [i, j, p] + end + end # If the matrix is complete, we have a solution... - return matrix if options.length == 0 + return matrix if options.empty? - omin = options.min_by { |x| x[:permissible].length } + i, j, permissible = options.min_by { |x| x.last.length } # If there is an option with only one solution, set it and re-check permissibility - if omin[:permissible].length == 1 - matrix[omin[:i]][omin[:j]] = omin[:permissible][0] + if permissible.length == 1 + matrix[i][j] = permissible[0] next end # We have two or more choices. We need to search both... - omin[:permissible].each { |v| + permissible.each do |v| mtmp = deep_copy_sudoku(matrix) - mtmp[omin[:i]][omin[:j]] = v + mtmp[i][j] = v ret = solve_sudoku(mtmp) return ret if ret - } + end # We did an exhaustive search on this branch and nothing worked out. - return nil + return end end def print_matrix(matrix) - if not matrix - puts "Impossible" - return - end + puts "Impossible" or return unless matrix border = "+-----+-----+-----+" - (0..8).each { |i| + 9.times do |i| puts border if i%3 == 0 - (0..8).each { |j| - print(j%3 == 0 ? "|" : " ") - print(matrix[i][j] == 0 ? "." : matrix[i][j]) - } - print "|\n" - } + 9.times do |j| + print j%3 == 0 ? "|" : " " + print matrix[i][j] == 0 ? "." : matrix[i][j] + end + puts "|" + end puts border end -matrix = read_matrix(DATA) -print_matrix(matrix) -puts -print_matrix(solve_sudoku(matrix)) - -__END__ +data = < 9 Then + 'exit with gridSolved = Grid + For r = 1 To 9 + For c = 1 To 9 + gridSolved(r, c) = grid(r, c) + Next 'c + Next 'r + Exit Sub + End If + For n = 1 To 9 + If isSafe(i, j, n) Then + nTmp = grid(i, j) + grid(i, j) = n + If j = 9 Then + Solve i + 1, 1 + Else + Solve i, j + 1 + End If + grid(i, j) = nTmp + End If + Next 'n +End Sub 'Solve + +Public Function isSafe(i, j, n) + If grid(i, j) <> 0 Then + isSafe = (grid(i, j) = n) + Exit Function + End If + 'grid(i,j) is an empty cell. Check if n is OK + 'first check the row i + For c = 1 To 9 + If grid(i, c) = n Then + isSafe = False + Exit Function + End If + Next 'c + 'now check the column j + For r = 1 To 9 + If grid(r, j) = n Then + isSafe = False + Exit Function + End If + Next 'r + 'finally, check the 3x3 subsquare containing grid(i,j) + iMin = 1 + 3 * Int((i - 1) / 3) + jMin = 1 + 3 * Int((j - 1) / 3) + For r = iMin To iMin + 2 + For c = jMin To jMin + 2 + If grid(r, c) = n Then + isSafe = False + Exit Function + End If + Next 'c + Next 'r + 'all tests were OK + isSafe = True +End Function 'isSafe + +Public Sub Sudoku() + 'main routine + Dim s(9) + s(1) = "001005070" + s(2) = "920600000" + s(3) = "008000600" + s(4) = "090020401" + s(5) = "000000000" + s(6) = "304080090" + s(7) = "007000300" + s(8) = "000007069" + s(9) = "010800700" + For i = 1 To 9 + For j = 1 To 9 + grid(i, j) = Int(Mid(s(i), j, 1)) + Next 'j + Next 'j + 'print problem + Wscript.echo "Problem:" + For i = 1 To 9 + c="" + For j = 1 To 9 + c=c & grid(i, j) & " " + Next 'j + Wscript.echo c + Next 'i + 'solve it! + Solve 1, 1 + 'print solution + Wscript.echo "Solution:" + For i = 1 To 9 + c="" + For j = 1 To 9 + c=c & gridSolved(i, j) & " " + Next 'j + Wscript.echo c + Next 'i +End Sub 'Sudoku + +Call sudoku diff --git a/Task/Sum-and-product-of-an-array/Bracmat/sum-and-product-of-an-array.bracmat b/Task/Sum-and-product-of-an-array/Bracmat/sum-and-product-of-an-array.bracmat new file mode 100644 index 0000000000..4676488503 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Bracmat/sum-and-product-of-an-array.bracmat @@ -0,0 +1,16 @@ +( ( sumprod + = sum prod num + . 0:?sum + & 1:?prod + & ( !arg + : ? + ( #%?num ? + & !num+!sum:?sum + & !num*!prod:?prod + & ~ + ) + | (!sum.!prod) + ) + ) +& out$sumprod$(2 3 5 7 11 13 17 19) +); diff --git a/Task/Sum-and-product-of-an-array/CoffeeScript/sum-and-product-of-an-array.coffee b/Task/Sum-and-product-of-an-array/CoffeeScript/sum-and-product-of-an-array.coffee new file mode 100644 index 0000000000..7a4b25235a --- /dev/null +++ b/Task/Sum-and-product-of-an-array/CoffeeScript/sum-and-product-of-an-array.coffee @@ -0,0 +1,5 @@ +sum = (array) -> + array.reduce (x, y) -> x + y + +product = (array) -> + array.reduce (x, y) -> x * y diff --git a/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e b/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e new file mode 100644 index 0000000000..48f2835064 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Eiffel/sum-and-product-of-an-array.e @@ -0,0 +1,64 @@ +note + description : "project application root class" + date : "$Date$" + revision : "$Revision$" + +class + APPLICATION + +inherit + ARGUMENTS + +create + make + +feature {NONE} + + array : ARRAY[INTEGER] + + make + do + create array.make_filled (0, 0, 4) + array.put (2, 0) + array.put (4, 1) + array.put (6, 2) + array.put (8, 3) + array.put (10, 4) + + print("%NSum of the elements of the array: ") + print(sum(array)) + print("%NProduct of the elements of the array: ") + print(product(array)) + end + + sum(ar : ARRAY[INTEGER]):INTEGER + local + s, i: INTEGER + do + from + i := 0 + until + i > 4 + loop + s := s + ar[i] + i := i + 1 + end + Result := s + end + + product(ar : ARRAY [INTEGER]):INTEGER + local + prod, i: INTEGER + do + prod := 1 + from + i := 0 + until + i > 4 + loop + prod := prod * ar[i] + i := i + 1 + end + Result := prod + end +end diff --git a/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array.java b/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-1.java similarity index 100% rename from Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array.java rename to Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-1.java diff --git a/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-2.java b/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-2.java new file mode 100644 index 0000000000..195387aff7 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Java/sum-and-product-of-an-array-2.java @@ -0,0 +1,12 @@ +import java.util.Arrays; + +public class SumProd +{ + public static void main(final String[] args) + { + int[] arg = {1,2,3,4,5}; + System.out.printf("sum = %d\n", Arrays.stream(arg).sum()); + System.out.printf("sum = %d\n", Arrays.stream(arg).reduce(0, (a, b) -> a + b)); + System.out.printf("product = %d\n", Arrays.stream(arg).reduce(1, (a, b) -> a * b)); + } +} diff --git a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia index 37d817e8c5..0481d49ae1 100644 --- a/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia +++ b/Task/Sum-and-product-of-an-array/Julia/sum-and-product-of-an-array.julia @@ -1,5 +1,5 @@ -julia> sum(1:5) -15 +julia> sum([4,6,8]) +18 -julia> prod(1:5) -120 +julia> prod([4,6,8]) +192 diff --git a/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.newlisp b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.newlisp new file mode 100644 index 0000000000..a85307e564 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/NewLISP/sum-and-product-of-an-array.newlisp @@ -0,0 +1,3 @@ +(setq a '(1 2 3 4 5)) +(apply + a) +(apply * a) diff --git a/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl index 030d1ba1bc..0a6f37c087 100644 --- a/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl +++ b/Task/Sum-and-product-of-an-array/Perl/sum-and-product-of-an-array-2.pl @@ -1,6 +1,5 @@ -use List::Util qw( sum reduce ); -my @list = ( 1, 2, 3 ); +use List::Util qw/sum0 product/; +my @list = (1..9); -my $sum1 = sum 0, @list; # 0 identity to allow empty list -my $sum2 = reduce { $a + $b } 0, @list; -my $product = reduce { $a * $b } 1, @list; +say "Sum: ", sum0(@list); # sum0 returns 0 for an empty list +say "Product: ", product(@list); diff --git a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb index bb4912d55c..8a08b027d4 100644 --- a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb +++ b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-1.rb @@ -1,5 +1,5 @@ arr = [1,2,3,4,5] # or ary = *1..5, or ary = (1..5).to_a -sum = arr.inject(0) { |sum, item| sum + item } +p sum = arr.inject(0) { |sum, item| sum + item } # => 15 -product = arr.inject(1) { |prod, element| prod * element } +p product = arr.inject(1) { |prod, element| prod * element } # => 120 diff --git a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb index 38a3db68e5..5bce13fdfc 100644 --- a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb +++ b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-2.rb @@ -1,5 +1,8 @@ arr = [1,2,3,4,5] -sum = arr.inject(0, :+) -# => 15 -product = arr.inject(1, :*) -# => 120 +p sum = arr.inject(0, :+) #=> 15 +p product = arr.inject(1, :*) #=> 120 + +# If you do not explicitly specify an initial value for memo, +# then the first element of collection is used as the initial value of memo. +p sum = arr.inject(:+) #=> 15 +p product = arr.inject(:*) #=> 120 diff --git a/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-3.rb b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-3.rb new file mode 100644 index 0000000000..7c23e9d389 --- /dev/null +++ b/Task/Sum-and-product-of-an-array/Ruby/sum-and-product-of-an-array-3.rb @@ -0,0 +1,5 @@ +arr = [] +p arr.inject(0, :+) #=> 0 +p arr.inject(1, :*) #=> 1 +p arr.inject(:+) #=> nil +p arr.inject(:*) #=> nil diff --git a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust index 03dfb16a13..559ce77b3e 100644 --- a/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust +++ b/Task/Sum-and-product-of-an-array/Rust/sum-and-product-of-an-array.rust @@ -1,7 +1,7 @@ use std::iter::{AdditiveIterator, MultiplicativeIterator}; fn main() { - let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; + let arr = [1i, 2, 3, 4, 5, 6, 7, 8, 9]; // using fold let sum = arr.iter().fold(0, |a, &b| a + b); diff --git a/Task/Sum-digits-of-an-integer/00DESCRIPTION b/Task/Sum-digits-of-an-integer/00DESCRIPTION index 12b6381441..ec72247229 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   [[http://en.wikipedia.org/wiki/Natural_number]]   in a given Base and return the sum of its digits: +This task is to take a [[wp:Natural_number|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/ALGOL-68/sum-digits-of-an-integer.alg b/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer.alg new file mode 100644 index 0000000000..c52b6161dd --- /dev/null +++ b/Task/Sum-digits-of-an-integer/ALGOL-68/sum-digits-of-an-integer.alg @@ -0,0 +1,45 @@ +# operator to return the sum of the digits of an integer value in the # +# specified base # +PRIO SUMDIGITS = 1; +OP SUMDIGITS = ( INT value, INT base )INT: + IF base < 2 + THEN + # invalid base # + print( ( "Base for digit sum must be at least 2", newline ) ); + stop + ELSE + # the base is OK # + INT result := 0; + INT rest := ABS value; + + WHILE rest /= 0 + DO + result PLUSAB ( rest MOD base ); + rest OVERAB base + OD; + + result + FI; # SUMDIGITS # + +# additional operator so we can sum the digits of values expressed in # +# other than base 10, e.g. 16ra is a hex lteral with value 10 # +# (Algol 68 allows bases 2, 4, 8 and 16 for non-base 10 literals) # +# however as such literals are BITS values, not INTs, we need this # +# second operator # +OP SUMDIGITS = ( BITS value, INT base )INT: ABS value SUMDIGITS base; + +main:( + + # test the SUMDIGITS operator # + + print( ( "value\base base digit-sum", newline ) ); + print( ( " 1\10 10 ", whole( 1 SUMDIGITS 10, -9 ), newline ) ); + print( ( " 1234\10 10 ", whole( 1234 SUMDIGITS 10, -9 ), newline ) ); + print( ( " fe\16 16 ", whole( 16rfe SUMDIGITS 16, -9 ), newline ) ); + print( ( " f0e\16 16 ", whole( 16rf0e SUMDIGITS 16, -9 ), newline ) ); + + # of course, we don't have to express the number in the base we sum # + # the digits in... # + print( ( " 73\10 71 ", whole( 73 SUMDIGITS 71, -9 ), newline ) ) + +) diff --git a/Task/Sum-digits-of-an-integer/ATS/sum-digits-of-an-integer.ats b/Task/Sum-digits-of-an-integer/ATS/sum-digits-of-an-integer.ats new file mode 100644 index 0000000000..a4d15438a4 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/ATS/sum-digits-of-an-integer.ats @@ -0,0 +1,54 @@ +(* ****** ****** *) +// +// How to compile: +// patscc -DATS_MEMALLOC_LIBC -o SumDigits SumDigits.dats +// +(* ****** ****** *) +// +#include +"share/atspre_staload.hats" +// +(* ****** ****** *) + +extern +fun{a:t@ype} +SumDigits(n: a, base: int): a + +implement +{a}(*tmp*) +SumDigits(n, base) = let +// +val base = gnumber_int(base) +// +fun +loop (n: a, res: a): a = + if gisgtz_val
    (n) + then loop (gdiv_val(n, base), gadd_val(res, gmod_val(n, base))) + else res +// +in + loop (n, gnumber_int(0)) +end // end of [SumDigits] + +(* ****** ****** *) + +val SumDigits_int = SumDigits + +(* ****** ****** *) + +implement +main0 () = +{ +// +val n = 1 +val () = println! ("SumDigits(1, 10) = ", SumDigits_int(n, 10)) +val n = 12345 +val () = println! ("SumDigits(12345, 10) = ", SumDigits_int(n, 10)) +val n = 123045 +val () = println! ("SumDigits(123045, 10) = ", SumDigits_int(n, 10)) +val n = 0xfe +val () = println! ("SumDigits(0xfe, 16) = ", SumDigits_int(n, 16)) +val n = 0xf0e +val () = println! ("SumDigits(0xf0e, 16) = ", SumDigits_int(n, 16)) +// +} (* end of [main0] *) diff --git a/Task/Sum-digits-of-an-integer/Clojure/sum-digits-of-an-integer.clj b/Task/Sum-digits-of-an-integer/Clojure/sum-digits-of-an-integer.clj new file mode 100644 index 0000000000..1c825bdbdc --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Clojure/sum-digits-of-an-integer.clj @@ -0,0 +1,3 @@ +(defn sum-digits [n base] + (let [number (if-not (string? n) (Long/toString n base) n)] + (reduce + (map #(Long/valueOf (str %) base) number)))) diff --git a/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d index 3860ffe4c7..1c86b4ba44 100644 --- a/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d +++ b/Task/Sum-digits-of-an-integer/D/sum-digits-of-an-integer.d @@ -1,6 +1,6 @@ import std.stdio, std.bigint; -uint sumDigits(T)(T n, in uint base=10) pure /*nothrow*/ +uint sumDigits(T)(T n, in uint base=10) pure nothrow in { assert(base > 1); } body { diff --git a/Task/Sum-digits-of-an-integer/Factor/sum-digits-of-an-integer.factor b/Task/Sum-digits-of-an-integer/Factor/sum-digits-of-an-integer.factor new file mode 100644 index 0000000000..7ecd678f18 --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Factor/sum-digits-of-an-integer.factor @@ -0,0 +1,3 @@ +: sum-digits ( base n -- sum ) 0 swap [ dup zero? ] [ pick /mod swapd + swap ] until drop nip ; + +{ 10 10 16 16 } { 1 1234 0xfe 0xf0e } [ sum-digits ] 2each diff --git a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go index 58aa050361..c50de9efc1 100644 --- a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go +++ b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-1.go @@ -1,26 +1,41 @@ +// File digit.go + package digit import ( - "errors" - "strconv" + "math/big" + "strconv" ) -func Sum(n string, base int) (int64, error) { - if base < 2 || base > 36 { - return 0, errors.New("base must be from 2 to 36") - } - i, err := strconv.ParseInt(n, base, 64) - if err != nil { - return 0, err - } - if i < 0 { - return 0, errors.New("number must be non-negative") - } - b64 := int64(base) - var sum int64 - for i > 0 { - sum += i % b64 - i /= b64 - } - return sum, nil +func SumString(n string, base int) (int, error) { + i, ok := new(big.Int).SetString(n, base) + if !ok { + return 0, strconv.ErrSyntax + } + if i.Sign() < 0 { + return 0, strconv.ErrRange + } + if i.BitLen() <= 64 { + return Sum(i.Uint64(), base), nil + } + return SumBig(i, base), nil +} + +func Sum(i uint64, base int) (sum int) { + b64 := uint64(base) + for ; i > 0; i /= b64 { + sum += int(i % b64) + } + return +} + +func SumBig(n *big.Int, base int) (sum int) { + i := new(big.Int).Set(n) + b := new(big.Int).SetUint64(uint64(base)) + r := new(big.Int) + for i.BitLen() > 0 { + i.DivMod(i, b, r) + sum += int(r.Uint64()) + } + return } diff --git a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go index 770c380b58..bdf2115835 100644 --- a/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go +++ b/Task/Sum-digits-of-an-integer/Go/sum-digits-of-an-integer-2.go @@ -1,32 +1,51 @@ -package digit_test +// File digit_test.go -import ( - "testing" +package digit - "digit" -) +import "testing" type testCase struct { - n string - base int - dSum int64 + n string + base int + dSum int } var testData = []testCase{ - {"1", 10, 1}, - {"1234", 10, 10}, - {"fe", 16, 29}, - {"f0e", 16, 29}, + {"1", 10, 1}, + {"1234", 10, 10}, + {"fe", 16, 29}, + {"f0e", 16, 29}, + {"18446744073709551615", 10, 87}, + {"abcdefghijklmnopqrstuvwzuz0123456789", 36, 628}, } -func testSum(t *testing.T) { - for _, tc := range testData { - ds, err := digit.Sum(tc.n, tc.base) - if err != nil { - t.Fatal("test case", tc, err) - } - if ds != tc.dSum { - t.Fatal("test case", tc, "got", ds, "expected", tc.dSum) - } - } +func TestSumString(t *testing.T) { + for _, tc := range testData { + ds, err := SumString(tc.n, tc.base) + if err != nil { + t.Error("test case", tc, err) + continue + } + if ds != tc.dSum { + t.Error("test case", tc, "got", ds, "expected", tc.dSum) + } + } +} + +func TestErrors(t *testing.T) { + for _, tc := range []struct { + n string + base int + }{ + {"1234", 37}, + {"0", 1}, + {"1234", 4}, + {"-123", 10}, + } { + _, err := SumString(tc.n, tc.base) + if err == nil { + t.Error("expected error for", tc) + } + t.Log("got expected error:", err) + } } diff --git a/Task/Sum-digits-of-an-integer/Logo/sum-digits-of-an-integer.logo b/Task/Sum-digits-of-an-integer/Logo/sum-digits-of-an-integer.logo new file mode 100644 index 0000000000..f8fd54344f --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Logo/sum-digits-of-an-integer.logo @@ -0,0 +1,11 @@ +make "digits "0123456789abcdefghijklmnopqrstuvwxyz + +to digitvalue :digit + output difference find [equal? :digit item ? :digits] iseq 1 count :digits 1 +end + +to sumdigits :number [:base 10] + output reduce "sum map.se "digitvalue :number +end + +foreach [1 1234 fe f0e] [print (se ? "-> sumdigits ?)] diff --git a/Task/Sum-digits-of-an-integer/Lua/sum-digits-of-an-integer.lua b/Task/Sum-digits-of-an-integer/Lua/sum-digits-of-an-integer.lua new file mode 100644 index 0000000000..74eeddc84e --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Lua/sum-digits-of-an-integer.lua @@ -0,0 +1,15 @@ +function sum_digits(n, base) + sum = 0 + while n > 0.5 do + m = math.floor(n / base) + digit = n - m * base + sum = sum + digit + n = m + end + return sum +end + +print(sum_digits(1, 10)) +print(sum_digits(1234, 10)) +print(sum_digits(0xfe, 16)) +print(sum_digits(0xf0e, 16)) diff --git a/Task/Sum-digits-of-an-integer/Pascal/sum-digits-of-an-integer.pascal b/Task/Sum-digits-of-an-integer/Pascal/sum-digits-of-an-integer.pascal new file mode 100644 index 0000000000..13cfce009c --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Pascal/sum-digits-of-an-integer.pascal @@ -0,0 +1,27 @@ +Program SumOFDigits; + +function SumOfDigitBase(n:UInt64;base:LongWord): LongWord; +var + tmp: Uint64; + digit,sum : LongWord; +Begin + digit := 0; + sum := 0; + While n > 0 do + Begin + tmp := n div base; + digit := n-base*tmp; + n := tmp; + inc(sum,digit); + end; + SumOfDigitBase := sum; +end; +Begin + writeln(' 1 sums to ', SumOfDigitBase(1,10)); + writeln('1234 sums to ', SumOfDigitBase(1234,10)); + writeln(' $FE sums to ', SumOfDigitBase($FE,16)); + writeln('$FOE sums to ', SumOfDigitBase($F0E,16)); + + writeln('18446744073709551615 sums to ', SumOfDigitBase(High(Uint64),10)); + +end. diff --git a/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer.py b/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-1.py similarity index 100% rename from Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer.py rename to Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-1.py diff --git a/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-2.py b/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-2.py new file mode 100644 index 0000000000..c267c4ceaf --- /dev/null +++ b/Task/Sum-digits-of-an-integer/Python/sum-digits-of-an-integer-2.py @@ -0,0 +1,8 @@ +def sumDigits(num, base=10): + return sum([int(x, base) for x in list(str(num))]) + +print sumDigits(1) +print sumDigits(12345) +print sumDigits(123045) +print sumDigits('fe', 16) +print sumDigits("f0e", 16) diff --git a/Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r b/Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r new file mode 100644 index 0000000000..759b872eea --- /dev/null +++ b/Task/Sum-digits-of-an-integer/R/sum-digits-of-an-integer.r @@ -0,0 +1,27 @@ +change.base <- function(n, base) +{ + ret <- integer(as.integer(logb(x=n, base=base))+1L) + + for (i in 1:length(ret)) + { + ret[i] <- n %% base + n <- n %/% base + + } + + return(ret) +} + +sum.digits <- function(n, base=10) +{ + if (base < 2) + stop("base must be at least 2") + + return(sum(change.base(n=n, base=base))) +} + +sum.digits(1) +sum.digits(12345) +sum.digits(123045) +sum.digits(0xfe, 16) +sum.digits(0xf0e, 16) diff --git a/Task/Sum-of-a-series/00DESCRIPTION b/Task/Sum-of-a-series/00DESCRIPTION index c888e53f4d..9c2e94c85a 100644 --- a/Task/Sum-of-a-series/00DESCRIPTION +++ b/Task/Sum-of-a-series/00DESCRIPTION @@ -1,4 +1,4 @@ -Compute the ''n''-th term of a [[wp:Series (mathematics)|series]], i.e. the sum of the ''n'' first terms of the corresponding [[wp:sequence|sequence]]. Informally, it is also called the ''sum of the series'', thus the title of this task. +Compute the ''n''-th term of a [[wp:Series (mathematics)|series]], i.e. the sum of the ''n'' first terms of the corresponding [[wp:sequence|sequence]]. Informally this value, or its limit when n tends to infinity, is also called the ''sum of the series'', thus the title of this task. For this task, use: diff --git a/Task/Sum-of-a-series/D/sum-of-a-series-1.d b/Task/Sum-of-a-series/D/sum-of-a-series-1.d index 3adf4247ba..ba87cc8aa1 100644 --- a/Task/Sum-of-a-series/D/sum-of-a-series-1.d +++ b/Task/Sum-of-a-series/D/sum-of-a-series-1.d @@ -1,12 +1,13 @@ import std.stdio, std.traits; -ReturnType!TF series(TF)(TF func, int end, int start=1) pure nothrow { +ReturnType!TF series(TF)(TF func, int end, int start=1) +pure nothrow @safe @nogc { typeof(return) sum = 0; - foreach (i; start .. end + 1) + foreach (immutable i; start .. end + 1) sum += func(i); return sum; } void main() { - writeln("Sum: ", series((int n) => 1.0L / (n ^^ 2), 1_000)); + writeln("Sum: ", series((in int n) => 1.0L / (n ^^ 2), 1_000)); } diff --git a/Task/Sum-of-a-series/D/sum-of-a-series-2.d b/Task/Sum-of-a-series/D/sum-of-a-series-2.d index 9c5c1df2e2..621f896e49 100644 --- a/Task/Sum-of-a-series/D/sum-of-a-series-2.d +++ b/Task/Sum-of-a-series/D/sum-of-a-series-2.d @@ -1,7 +1,7 @@ import std.stdio, std.algorithm, std.range; -enum series(alias F) = (in int end, in int start=1) /*pure*/ => - iota(start, end + 1).map!F.sum; +enum series(alias F) = (in int end, in int start=1) + pure nothrow @nogc => iota(start, end + 1).map!F.sum; void main() { writeln("Sum: ", series!q{1.0L / (a ^^ 2)}(1_000)); diff --git a/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi b/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi index cef8620898..eddf1b9f9a 100644 --- a/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi +++ b/Task/Sum-of-a-series/Delphi/sum-of-a-series.delphi @@ -37,7 +37,7 @@ end; procedure TFormSumOfASeries.B_CalcClick(Sender: TObject); begin try - M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1,trunc(sqrt($7FFFFFFFFFFFFFFF-1))))); + M_Log.Lines.Add(FloatToStr(Sum_Of_A_Series(1, 1000))); except M_Log.Lines.Add('Error'); end; diff --git a/Task/Sum-of-a-series/NewLISP/sum-of-a-series.newlisp b/Task/Sum-of-a-series/NewLISP/sum-of-a-series.newlisp new file mode 100644 index 0000000000..454b2952e0 --- /dev/null +++ b/Task/Sum-of-a-series/NewLISP/sum-of-a-series.newlisp @@ -0,0 +1,4 @@ +(let (s 0) + (for (i 1 1000) + (inc s (div 1 (* i i)))) + (println s)) diff --git a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 index ae20eb890b..05c2bee1c7 100644 --- a/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 +++ b/Task/Sum-of-a-series/Perl-6/sum-of-a-series-7.pl6 @@ -1,2 +1,2 @@ -sub ζ($s) { (state %){$s} //= [\+] map * **-$s, 1..* } +sub ζ($s) is cached { [\+] 1..* X** -$s } say ζ(2)[1000]; diff --git a/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb b/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb index ece9cda47c..cc776a9218 100644 --- a/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb +++ b/Task/Sum-of-a-series/Ruby/sum-of-a-series.rb @@ -1 +1,2 @@ -puts (1..1000).inject(0) {|sum, x| sum + 1.0 / x ** 2} +puts (1..1000).inject{|sum, x| sum + 1.0 / x ** 2} +#=> 1.64393456668156 diff --git a/Task/Sum-of-a-series/Rust/sum-of-a-series.rust b/Task/Sum-of-a-series/Rust/sum-of-a-series.rust new file mode 100644 index 0000000000..c221b0dc7f --- /dev/null +++ b/Task/Sum-of-a-series/Rust/sum-of-a-series.rust @@ -0,0 +1,8 @@ +use std::iter::range_inclusive; +use std::iter::AdditiveIterator; + +fn main() { + let series = range_inclusive(1f64, 1000f64); + let sum = series.map(|a| 1f64 / (a * a)).sum(); + println!("{}", sum); +} diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr index e77e480dc7..cc21412201 100644 --- a/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-1.txr @@ -1,2 +1,2 @@ -txr -c '@(bind sum @[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0])' -sum="1.64393456668156" +txr -p '[reduce-left + (let ((i 0)) (gen (< i 1000) (/ 1.0 (* (inc i) i)))) 0]' +1.64393456668156 diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr index 44552ce771..45968008b8 100644 --- a/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-2.txr @@ -1,2 +1,2 @@ -txr -c '@(bind sum @[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0])' -sum="1.64393456668156" +txr -p '[reduce-left + [(let ((i 0)) (gen t (/ 1.0 (* (inc i) i)))) 0..999] 0]' +1.64393456668156 diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr index c6fc9896f4..c1a968c4c1 100644 --- a/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-3.txr @@ -1,2 +1,2 @@ -txr -c '@(bind sum @[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000])' -sum="1.64393456668156" +txr -p '[[chain range (op mapcar (op / 1.0 (* @1 @1))) (op reduce-left + @1 0)] 1 1000]' +1.64393456668156 diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr index e0eaa1cad4..abe56a81e7 100644 --- a/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-4.txr @@ -1,2 +1,2 @@ -txr -c '@(bind sum @[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0])' -sum="1.64393456668156" +txr -p '[reduce-left + (mapcar (op / 1.0 (* @1 @1)) (range 1 1000)) 0]' +1.64393456668156 diff --git a/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr b/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr index 06570640cb..98f6dcd8dd 100644 --- a/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr +++ b/Task/Sum-of-a-series/TXR/sum-of-a-series-5.txr @@ -1,2 +1,2 @@ -txr -c '@(bind sum @[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0])' -sum="1.64393456668156" +txr -p '[reduce-left (op + @1 (/ 1.0 (* @2 @2))) (range 1 1000) 0]' +1.64393456668156 diff --git a/Task/Sum-of-squares/00DESCRIPTION b/Task/Sum-of-squares/00DESCRIPTION index 81ec00542f..ba1d9faf46 100644 --- a/Task/Sum-of-squares/00DESCRIPTION +++ b/Task/Sum-of-squares/00DESCRIPTION @@ -1,3 +1,4 @@ -Write a program to find the sum of squares of a numeric vector. The program should work on a zero-length vector (with an answer of 0). +Write a program to find the sum of squares of a numeric vector.
    +The program should work on a zero-length vector (with an answer of 0). See also [[Mean]]. diff --git a/Task/Sum-of-squares/Aime/sum-of-squares.aime b/Task/Sum-of-squares/Aime/sum-of-squares.aime new file mode 100644 index 0000000000..66e117f0a9 --- /dev/null +++ b/Task/Sum-of-squares/Aime/sum-of-squares.aime @@ -0,0 +1,28 @@ +real +squaredsum(list l) +{ + integer i; + real s; + + s = 0; + i = -l_length(l); + while (i) { + s += sq(l[i += 1]); + } + + return s; +} + +integer +main(void) +{ + list l; + + l = l_effect(0, 1, 2, 3); + + o_form("~\n", squaredsum(l)); + o_form("~\n", squaredsum(l_effect())); + o_form("~\n", squaredsum(l_effect(.5, -.5, 2))); + + return 0; +} diff --git a/Task/Sum-of-squares/Bracmat/sum-of-squares.bracmat b/Task/Sum-of-squares/Bracmat/sum-of-squares.bracmat new file mode 100644 index 0000000000..0252876cb1 --- /dev/null +++ b/Task/Sum-of-squares/Bracmat/sum-of-squares.bracmat @@ -0,0 +1,13 @@ +( ( sumOfSquares + = sum component + . 0:?sum + & whl + ' ( !arg:%?component ?arg + & !component^2+!sum:?sum + ) + & !sum + ) +& out$(sumOfSquares$(3 4)) +& out$(sumOfSquares$(3 4 i*5)) +& out$(sumOfSquares$(a b c)) +); diff --git a/Task/Sum-of-squares/D/sum-of-squares-1.d b/Task/Sum-of-squares/D/sum-of-squares-1.d index 9acd560df2..c2fa9a14ef 100644 --- a/Task/Sum-of-squares/D/sum-of-squares-1.d +++ b/Task/Sum-of-squares/D/sum-of-squares-1.d @@ -1,6 +1,4 @@ -import std.stdio: writeln; - -T sumSquares(T)(T[] a) { +T sumSquares(T)(T[] a) pure nothrow @safe @nogc { T sum = 0; foreach (e; a) sum += e ^^ 2; @@ -8,6 +6,7 @@ T sumSquares(T)(T[] a) { } void main() { - auto items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0]; - writeln(sumSquares(items)); + import std.stdio: writeln; + + [3.1, 1.0, 4.0, 1.0, 5.0, 9.0].sumSquares.writeln; } diff --git a/Task/Sum-of-squares/D/sum-of-squares-2.d b/Task/Sum-of-squares/D/sum-of-squares-2.d index d1648d34c0..b83847b4f8 100644 --- a/Task/Sum-of-squares/D/sum-of-squares-2.d +++ b/Task/Sum-of-squares/D/sum-of-squares-2.d @@ -1,11 +1,11 @@ import std.stdio, std.algorithm, std.traits, std.range; -auto sumSquares(Range)(Range data) { - return reduce!q{a + b ^^ 2}(cast(ForeachType!Range)0, data); +auto sumSquares(Range)(Range data) pure nothrow @safe @nogc { + return reduce!q{a + b ^^ 2}(ForeachType!Range(0), data); } void main() { - auto items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0]; - writeln(sumSquares(items)); - writeln(sumSquares(iota(10))); + immutable items = [3.1, 1.0, 4.0, 1.0, 5.0, 9.0]; + items.sumSquares.writeln; + 10.iota.sumSquares.writeln; } diff --git a/Task/Sum-of-squares/Java/sum-of-squares.java b/Task/Sum-of-squares/Java/sum-of-squares.java index 88789318c5..250c3937ac 100644 --- a/Task/Sum-of-squares/Java/sum-of-squares.java +++ b/Task/Sum-of-squares/Java/sum-of-squares.java @@ -4,7 +4,7 @@ public class SumSquares { double sum = 0; int[] nums = {1,2,3,4,5}; - for (int i : sum) + for (int i : nums) sum += i * i; System.out.println("The sum of the squares is: " + sum); } diff --git a/Task/Sum-of-squares/MOO/sum-of-squares.moo b/Task/Sum-of-squares/MOO/sum-of-squares.moo index 99fe2cc427..8ac53aad9a 100644 --- a/Task/Sum-of-squares/MOO/sum-of-squares.moo +++ b/Task/Sum-of-squares/MOO/sum-of-squares.moo @@ -8,7 +8,7 @@ endfor player:tell(toliteral(list), " => ", sum); . -Output: +{{out}} ;#100:sum_squares({3,1,4,1,5,9}) {3, 1, 4, 1, 5, 9} => 133 ;#100:sum_squares({}) diff --git a/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx b/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx index f9425a5c0c..39ccc78554 100644 --- a/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx +++ b/Task/Sum-of-squares/NetRexx/sum-of-squares.netrexx @@ -5,7 +5,7 @@ **********************************************************************/ numeric digits 50 /*allow 50-digit # (default is 9)*/ v='-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12' /* vector with some #s. */ -n=words(v) +n=v.words() x='' sum=0 /*initialize SUM to zero. */ /*if vector is empty, sum = zero.*/ diff --git a/Task/Sum-of-squares/Python/sum-of-squares.py b/Task/Sum-of-squares/Python/sum-of-squares-1.py similarity index 100% rename from Task/Sum-of-squares/Python/sum-of-squares.py rename to Task/Sum-of-squares/Python/sum-of-squares-1.py diff --git a/Task/Sum-of-squares/Python/sum-of-squares-2.py b/Task/Sum-of-squares/Python/sum-of-squares-2.py new file mode 100644 index 0000000000..82c7c9248d --- /dev/null +++ b/Task/Sum-of-squares/Python/sum-of-squares-2.py @@ -0,0 +1 @@ +sum(map(lambda x: x*x, [1, 2, 3, 4, 5])) diff --git a/Task/Sum-of-squares/REXX/sum-of-squares.rexx b/Task/Sum-of-squares/REXX/sum-of-squares.rexx index 315727bc14..461693c923 100644 --- a/Task/Sum-of-squares/REXX/sum-of-squares.rexx +++ b/Task/Sum-of-squares/REXX/sum-of-squares.rexx @@ -1,4 +1,4 @@ -/*REXX program to sum the squares of a vector of fifteen numbers. */ +/*REXX program sums the squares of a vector which contains 15 numbers.*/ numeric digits 50 /*allow 50-digit # (default is 9)*/ v=-100 9 8 7 6 0 3 4 5 2 1 .5 10 11 12 /*define a vector with some #s. */ sum=0 /*initialize SUM to zero. */ @@ -7,5 +7,6 @@ sum=0 /*initialize SUM to zero. */ sum=sum + word(v,k)**2 /*add squared element to the sum.*/ end /*k*/ -say 'The sum of ' words(v) " elements for the V vector is: " sum +say 'The sum of ' words(v) " squared elements for the V vector is: " sum + /*stick a fork in it, we're done.*/ /*stick a fork in it, we're done.*/ diff --git a/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb index 3b4e8f15ca..8a87a51388 100644 --- a/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb +++ b/Task/Sum-of-squares/Ruby/sum-of-squares-2.rb @@ -1 +1 @@ -[3,1,4,1,5,9].map { |x| x**2 }.reduce(:+) +[3,1,4,1,5,9].map { |x| x**2 }.reduce(0, :+) diff --git a/Task/Sum-of-squares/Rust/sum-of-squares.rust b/Task/Sum-of-squares/Rust/sum-of-squares.rust new file mode 100644 index 0000000000..58e648ae53 --- /dev/null +++ b/Task/Sum-of-squares/Rust/sum-of-squares.rust @@ -0,0 +1,17 @@ +fn sqsum(v: Vec) -> f64 { + let mut s = 0.0; + + for i in v.iter() { + s += *i * *i; + } + + return s; +} + +fn main() { + let v = vec!(3.0, 1.0, 4.0, 1.0, 5.0, 9.0); + println!("{}", sqsum(v)); + + let u : Vec = vec!(); + println!("{}", sqsum(u)); +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-1.cs b/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-1.cs new file mode 100644 index 0000000000..7fa51f2dc5 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-1.cs @@ -0,0 +1,237 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Windows; + +namespace Sutherland +{ + public static class SutherlandHodgman + { + #region Class: Edge + + /// + /// This represents a line segment + /// + private class Edge + { + public Edge(Point from, Point to) + { + this.From = from; + this.To = to; + } + + public readonly Point From; + public readonly Point To; + } + + #endregion + + /// + /// This clips the subject polygon against the clip polygon (gets the intersection of the two polygons) + /// + /// + /// Based on the psuedocode from: + /// http://en.wikipedia.org/wiki/Sutherland%E2%80%93Hodgman + /// + /// Can be concave or convex + /// Must be convex + /// The intersection of the two polygons (or null) + public static Point[] GetIntersectedPolygon(Point[] subjectPoly, Point[] clipPoly) + { + if (subjectPoly.Length < 3 || clipPoly.Length < 3) + { + throw new ArgumentException(string.Format("The polygons passed in must have at least 3 points: subject={0}, clip={1}", subjectPoly.Length.ToString(), clipPoly.Length.ToString())); + } + + List outputList = subjectPoly.ToList(); + + // Make sure it's clockwise + if (!IsClockwise(subjectPoly)) + { + outputList.Reverse(); + } + + // Walk around the clip polygon clockwise + foreach (Edge clipEdge in IterateEdgesClockwise(clipPoly)) + { + List inputList = outputList.ToList(); // clone it + outputList.Clear(); + + if (inputList.Count == 0) + { + // Sometimes when the polygons don't intersect, this list goes to zero. Jump out to avoid an index out of range exception + break; + } + + Point S = inputList[inputList.Count - 1]; + + foreach (Point E in inputList) + { + if (IsInside(clipEdge, E)) + { + if (!IsInside(clipEdge, S)) + { + Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To); + if (point == null) + { + throw new ApplicationException("Line segments don't intersect"); // may be colinear, or may be a bug + } + else + { + outputList.Add(point.Value); + } + } + + outputList.Add(E); + } + else if (IsInside(clipEdge, S)) + { + Point? point = GetIntersect(S, E, clipEdge.From, clipEdge.To); + if (point == null) + { + throw new ApplicationException("Line segments don't intersect"); // may be colinear, or may be a bug + } + else + { + outputList.Add(point.Value); + } + } + + S = E; + } + } + + // Exit Function + return outputList.ToArray(); + } + + #region Private Methods + + /// + /// This iterates through the edges of the polygon, always clockwise + /// + private static IEnumerable IterateEdgesClockwise(Point[] polygon) + { + if (IsClockwise(polygon)) + { + #region Already clockwise + + for (int cntr = 0; cntr < polygon.Length - 1; cntr++) + { + yield return new Edge(polygon[cntr], polygon[cntr + 1]); + } + + yield return new Edge(polygon[polygon.Length - 1], polygon[0]); + + #endregion + } + else + { + #region Reverse + + for (int cntr = polygon.Length - 1; cntr > 0; cntr--) + { + yield return new Edge(polygon[cntr], polygon[cntr - 1]); + } + + yield return new Edge(polygon[0], polygon[polygon.Length - 1]); + + #endregion + } + } + + /// + /// Returns the intersection of the two lines (line segments are passed in, but they are treated like infinite lines) + /// + /// + /// Got this here: + /// http://stackoverflow.com/questions/14480124/how-do-i-detect-triangle-and-rectangle-intersection + /// + private static Point? GetIntersect(Point line1From, Point line1To, Point line2From, Point line2To) + { + Vector direction1 = line1To - line1From; + Vector direction2 = line2To - line2From; + double dotPerp = (direction1.X * direction2.Y) - (direction1.Y * direction2.X); + + // If it's 0, it means the lines are parallel so have infinite intersection points + if (IsNearZero(dotPerp)) + { + return null; + } + + Vector c = line2From - line1From; + double t = (c.X * direction2.Y - c.Y * direction2.X) / dotPerp; + //if (t < 0 || t > 1) + //{ + // return null; // lies outside the line segment + //} + + //double u = (c.X * direction1.Y - c.Y * direction1.X) / dotPerp; + //if (u < 0 || u > 1) + //{ + // return null; // lies outside the line segment + //} + + // Return the intersection point + return line1From + (t * direction1); + } + + private static bool IsInside(Edge edge, Point test) + { + bool? isLeft = IsLeftOf(edge, test); + if (isLeft == null) + { + // Colinear points should be considered inside + return true; + } + + return !isLeft.Value; + } + private static bool IsClockwise(Point[] polygon) + { + for (int cntr = 2; cntr < polygon.Length; cntr++) + { + bool? isLeft = IsLeftOf(new Edge(polygon[0], polygon[1]), polygon[cntr]); + if (isLeft != null) // some of the points may be colinear. That's ok as long as the overall is a polygon + { + return !isLeft.Value; + } + } + + throw new ArgumentException("All the points in the polygon are colinear"); + } + + /// + /// Tells if the test point lies on the left side of the edge line + /// + private static bool? IsLeftOf(Edge edge, Point test) + { + Vector tmp1 = edge.To - edge.From; + Vector tmp2 = test - edge.To; + + double x = (tmp1.X * tmp2.Y) - (tmp1.Y * tmp2.X); // dot product of perpendicular? + + if (x < 0) + { + return false; + } + else if (x > 0) + { + return true; + } + else + { + // Colinear points; + return null; + } + } + + private static bool IsNearZero(double testValue) + { + return Math.Abs(testValue) <= .000000001d; + } + + #endregion + } +} diff --git a/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-2.cs b/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-2.cs new file mode 100644 index 0000000000..41bd3b8c74 --- /dev/null +++ b/Task/Sutherland-Hodgman-polygon-clipping/C-sharp/sutherland-hodgman-polygon-clipping-2.cs @@ -0,0 +1,20 @@ + + + + + + + + + + + + +